Training data is the collection of examples a machine learning model learns from. Each example typically consists of one or more input features and, in supervised settings, a corresponding target or label. During training, an optimization algorithm—most commonly stochastic gradient descent (SGD) or a variant such as AdamW—adjusts the model's internal parameters to minimize a loss function that measures the discrepancy between predictions and targets.
For large language models (LLMs), training data is predominantly unstructured natural language text. A single training example might be a document, a web page, a code file, or a conversation transcript. The model learns to predict the next token in a sequence, which implicitly teaches grammar, facts, reasoning patterns, and style. The breadth and depth of this data determines what the model can know and do.
| Dataset | Purpose | Used During | Exposed to Model? |
|---|---|---|---|
| Training set | Learn parameters (weights, biases) | Gradient descent / backpropagation | Yes — directly |
| Validation set | Tune hyperparameters, early stopping | Periodic evaluation between epochs | No — gradients not computed |
| Test set | Estimate generalization performance | Final evaluation only | No — touched once |
A model can only learn patterns that exist in its training data. If the data contains biases, factual errors, or narrow perspectives, the model will inherit all of them. The architecture and optimization procedure determine how efficiently patterns are extracted, but the data determines what patterns are available to extract. This is why dataset engineering is often the highest-leverage activity in an ML project.
A persistent myth in machine learning holds that more data is always better. In practice, the relationship between dataset size and model quality is highly non-linear, and the quality of each example dominates the marginal value of additional examples once a corpus reaches a certain scale.
Multiple lines of evidence support the primacy of quality:
| Evidence | Source / Study | Implication |
|---|---|---|
| Phi-series models trained on “textbook quality” synthetic data punch far above their parameter count | Microsoft Research (Phi-1, Phi-1.5, Phi-2) | Curated high-quality data can substitute for raw scale |
| FineWeb-Edu filtering by educational content score dramatically improves benchmark results | HuggingFace FineWeb (2024) | Quality classifiers are a powerful filtering tool |
| Deduplication alone yields measurable perplexity reductions | Lee et al., “Deduplicating Training Data Makes Language Models Better” (2022) | Even accidental repetition degrades learning |
| Stable cascade of quality filters (language ID, perplexity, heuristics) used in RefinedWeb | Penedo et al. (2023) | Systematic pipeline filtering outperforms raw dumps |
Quantity is not irrelevant. For models with billions or trillions of parameters, a minimum volume of tokens is required to avoid underfitting and to expose the model to enough linguistic diversity to generalize. The Chinchilla scaling laws (discussed in Section 12) quantify this relationship precisely. The point is that quantity without quality is wasted compute—and quality with insufficient quantity starves the model.
Partitioning data into separate sets is the single most important practice for honest model evaluation. Without it, you cannot distinguish between a model that has learned generalizable patterns and one that has memorized specific examples.
| Ratio | Train | Validation | Test | Best For |
|---|---|---|---|---|
| 60 / 20 / 20 | 60% | 20% | 20% | Small datasets where test set needs statistical power |
| 70 / 15 / 15 | 70% | 15% | 15% | Medium datasets; balanced compromise |
| 80 / 10 / 10 | 80% | 10% | 10% | Large datasets where 10% is still many examples |
| 90 / 5 / 5 | 90% | 5% | 5% | Very large datasets (millions+ of examples) |
| 98 / 1 / 1 | 98% | 1% | 1% | Web-scale LLM pretraining (billions of tokens) |
The validation and test sets must be large enough to produce a statistically stable estimate of performance. If your test set contains only 50 examples, a single misclassified sample swings accuracy by 2%. As a heuristic, aim for at least 1,000 examples in each evaluation set for classification tasks. For LLM evaluation, held-out validation loss on a few hundred million tokens is usually sufficient because the metric is an average over many predictions.
A random split assigns each example to a partition by drawing from a uniform distribution. This works well when classes are balanced. When classes are imbalanced, a stratified split preserves the class distribution in each partition, ensuring that rare classes appear in both validation and test sets.
For temporal data, random splitting causes leakage because future information can leak into the training set. Use a chronological split: train on the oldest data, validate on the next period, and test on the most recent period. Walk-forward validation (expanding or rolling window) is the gold standard for time-series evaluation.
When data is scarce, k-fold cross-validation extracts maximum value. The data is divided into k equally sized folds. The model is trained k times, each time holding out a different fold as the validation set and training on the remaining k−1 folds. Performance is averaged across folds. Common values are k=5 and k=10. For very small datasets, leave-one-out cross-validation (k = n) is used.
Overfitting occurs when a model learns patterns specific to the training data that do not generalize to unseen data. The model effectively memorizes noise, outliers, and idiosyncratic features rather than discovering the underlying signal. Symptoms include training loss continuing to decrease while validation loss plateaus or increases.
| Symptom | Overfitted Model | Underfitted Model |
|---|---|---|
| Training loss | Very low | High |
| Validation loss | Higher than training loss (gap) | High, close to training loss |
| Training accuracy | Near 100% | Below target |
| Validation accuracy | Significantly lower | Below target |
| Model behavior | Memorizes specifics | Fails to capture patterns |
Underfitting is the opposite failure mode: the model is too simple or trained too briefly to capture the patterns in the data. Both training and validation loss remain high. The model has high bias and low variance. Remedies include increasing model capacity, training longer, reducing regularization, or improving feature engineering.
The expected prediction error of a model can be decomposed into three components: bias, variance, and irreducible error. Understanding this decomposition clarifies why overfitting and underfitting happen and how to balance them.
| Component | Definition | High Value Means | Remedy |
|---|---|---|---|
| Bias | Systematic error from wrong assumptions (e.g., linear model for nonlinear data) | Underfitting | Increase model complexity |
| Variance | Sensitivity to fluctuations in the training set | Overfitting | More data, regularization, simpler model |
| Irreducible error | Inherent noise in the data that no model can eliminate | Bayes-optimal error floor | Clean data; cannot be reduced by modeling |
The total expected error is approximately:
As model complexity increases, bias tends to decrease (the model can represent more nuanced functions) while variance tends to increase (the model becomes more sensitive to the specific training sample). The optimal complexity minimizes the sum of bias and variance. This is the bias-variance tradeoff.
Data leakage occurs when information from outside the training set—typically from the validation or test set—unintentionally influences the training process. The result is an optimistically biased evaluation that collapses when the model is deployed on truly unseen data. Leakage is one of the most common and insidious errors in applied machine learning.
| Leakage Type | Description | Example |
|---|---|---|
| Feature leakage | A feature in the training data encodes the target | “Days until churn” as a feature for churn prediction |
| Train-test contamination | Same or near-duplicate examples appear in both train and test | Duplicate documents across web crawl shards |
| Temporal leakage | Future data is used to train a model that should only see past data | Random shuffle of time-series data before splitting |
| Preprocessing leakage | Normalization or feature selection is fit on the full dataset before splitting | Computing mean/std on all data, then splitting |
| Group leakage | Examples from the same group (patient, user, session) span train and test | Splitting by row instead of by patient ID in medical data |
| Benchmark leakage | Test benchmark questions are included in pretraining data | MMLU questions scraped into Common Crawl |
Raw data is almost never ready for training. Preprocessing transforms messy, heterogeneous inputs into a clean, consistent, numeric representation that a model can consume efficiently. The preprocessing pipeline is a first-class engineering artifact—it must be reproducible, versioned, and applied identically at training and inference time.
Cleaning removes or repairs content that would mislead the model. For text corpora, typical cleaning steps include:
Normalization standardizes the numeric or textual representation so that the model sees consistent inputs. For tabular features, this means scaling. For text, it includes case folding, punctuation normalization, and whitespace cleanup.
| Technique | Formula / Action | When to Use |
|---|---|---|
| Standardization (Z-score) | (x − mean) / std | Features with Gaussian-ish distribution |
| Min-Max scaling | (x − min) / (max − min) | Bounded features; neural network inputs |
| Robust scaling | (x − median) / IQR | Features with outliers |
| Log transformation | log(x + 1) | Heavy-tailed distributions (counts, prices) |
| Case folding (text) | lowercase all characters | When case is not semantically meaningful |
| Unicode normalization (text) | NFKC or NFC | Unify equivalent character representations |
Tokenization converts raw text into a sequence of discrete tokens, each mapped to an integer ID in the model's vocabulary. The choice of tokenizer affects vocabulary size, sequence lengths, handling of rare words, and multilingual coverage.
| Tokenizer | Type | Used By | Vocab Size (typical) |
|---|---|---|---|
| Byte-Pair Encoding (BPE) | Subword | GPT-2, GPT-3, LLaMA | 32,000 – 50,000 |
| SentencePiece (Unigram) | Subword | T5, ALBERT, XLNet | 32,000 – 128,000 |
| WordPiece | Subword | BERT, DistilBERT | 30,000 – 100,000 |
| Byte-level | Character/byte | GPT-2 (byte-level BPE) | 256 base + merges |
| Tiktoken | Byte-level BPE (fast impl) | GPT-4, GPT-4o | 100,000 – 200,000 |
Data augmentation artificially increases the effective size and diversity of a training set by applying label-preserving transformations to existing examples. It is one of the most effective regularizers, particularly when labeled data is scarce.
| Technique | Description | Preserves Label? |
|---|---|---|
| Synonym replacement | Replace words with WordNet or embedding-based synonyms | Usually |
| Random word deletion | Drop a fraction of words randomly | Yes (for classification) |
| Back-translation | Translate to another language and back; yields paraphrase | Yes |
| Random word swap | Swap adjacent word pairs | Usually |
| Masked language modeling | Mask random tokens; model predicts them (self-supervised) | N/A (pretraining) |
| Instruction paraphrasing | Use an LLM to rewrite instructions in different styles | Yes (for instruction tuning) |
| Response augmentation | Generate additional correct responses for the same prompt | Yes |
The storage format of a dataset affects disk usage, I/O throughput, random access speed, and interoperability with training frameworks. The right choice depends on dataset size, access patterns, and the toolchain.
| Format | Human-Readable | Compression | Columnar | Best For |
|---|---|---|---|---|
| JSONL (JSON Lines) | Yes | None (can gzip) | No (row-based) | NLP examples, instruction tuning, debugging |
| CSV | Yes | None (can gzip) | No (row-based) | Tabular data, small datasets, interchange |
| Parquet | No | Snappy / Zstd (built-in) | Yes | Large-scale LLM pretraining, analytics |
| HuggingFace Datasets (Arrow) | No | Memory-mapped | Yes | Integration with transformers, streaming |
| TFRecord | No | Built-in | No (record-based) | TensorFlow pipelines |
| WebDataset / Sharded tar | No | Per-file | No | Distributed training over object stores |
JSONL (JSON Lines) stores one JSON object per line. It is the de facto standard for instruction tuning datasets because each line is a self-contained example that can be streamed, shuffled, or sampled independently.
HuggingFace datasets library wraps Arrow as its underlying storage format and provides a unified API for loading, streaming, transforming, and pushing datasets to the Hub. It supports lazy loading via memory-mapping, which allows datasets larger than RAM to be processed efficiently.
The following corpora are the backbone of most open-source and many proprietary LLM pretraining runs. Each has distinct characteristics in terms of scale, composition, and licensing.
| Dataset | Approx. Size (tokens) | Composition | Notes |
|---|---|---|---|
| Common Crawl | ~100T+ (raw) | Web pages scraped from the internet since 2007 | Raw, noisy; requires heavy filtering and dedup |
| Wikipedia | ~4B (English) | Encyclopedia articles, high quality, multilingual | Gold-standard quality; small but dense |
| RedPajama | ~1.2T (v2) | Reproduction of LLaMA training mix: CC, C4, GitHub, Books, Wiki, ArXiv, StackExchange | Open replication of LLaMA's data composition |
| FineWeb | ~15T (English) | Filtered Common Crawl (2013–2024) | State-of-the-art web filtering pipeline by HuggingFace |
| FineWeb-Edu | ~1.3T | FineWeb subset filtered for educational content | Quality classifier trained on LLM-rated educational value |
| OpenWebText | ~8B | Open-source replication of WebText (Reddit outbound links, karma >= 3) | Used for GPT-2 reproduction; now largely superseded |
| C4 (Colossal Clean Crawled Corpus) | ~750B | Filtered Common Crawl (April 2019 snapshot) | Used for T5; aggressive heuristic filtering |
| The Stack v2 | ~67B (code) | Permissively licensed source code from GitHub | Used for Code Llama, StarCoder2; per-file dedup |
| Books3 / Books1 | ~100B | Book-length text (novels, nonfiction) | Copyright concerns; Books3 was taken down |
| ArXiv | ~100B | Scientific papers (math, physics, CS) | High-quality academic prose; LaTeX source |
LLM pretraining corpora are rarely a single source. They are a carefully weighted mixture. A representative mix (inspired by LLaMA and RedPajama) might look like:
| Source | Share | Rationale |
|---|---|---|
| Filtered web crawl | ~67% | Breadth and diversity of topics and styles |
| Books / long-form | ~4.5% | Coherent long-context reasoning, narrative |
| Wikipedia | ~4.5% | Factual, encyclopedic knowledge |
| GitHub code | ~4.5% | Programming ability, logical reasoning |
| ArXiv / scientific | ~2.5% | Technical and mathematical content |
| StackExchange | ~2% | Q&A format, practical reasoning |
| News / other | ~15% | Current events, formal writing |
Pretraining on raw text produces a base model that can predict the next token but does not follow instructions. Instruction tuning (also called supervised fine-tuning, or SFT) teaches the model to respond to human prompts in a helpful, structured way. The datasets for this phase are smaller, higher-cost, and more carefully curated than pretraining corpora.
| Dataset | Size | Source | Format | Notes |
|---|---|---|---|---|
| Alpaca (52K) | 52,000 examples | Self-instruct with text-davinci-003 | instruction / input / output | Stanford; open-sourced March 2023 |
| Dolly 15K | 15,000 examples | Human-written by Databricks employees | instruction / response / category | Truly human-generated; open license |
| OpenAssistant (OASST1) | 161,000 messages | Crowdsourced conversation trees | Multi-turn conversation | LAION; 35+ languages; human-ranked |
| ShareGPT | ~90,000 conversations | User-shared ChatGPT conversations | Multi-turn, user/assistant roles | Collected from sharegpt.com; license uncertain |
| FLAN Collection | ~1.8M examples | 1,800+ tasks reformatted as instructions | Mixed task formats | Google; largest open instruction-tuning set |
| OpenOrca | ~4.2M examples | GPT-3.5/GPT-4 responses to FLAN prompts | instruction / response | Distilled from proprietary models |
| Lima | 1,000 examples | Curated community Q&A and wikiHow | instruction / response | Shows 1K high-quality examples suffice |
| WizardLM Evol-Instruct | ~250K examples | Evolutionary instruction generation | instruction / response | Progressively more complex instructions |
The LIMA paper (Zhou et al., 2023) demonstrated that fine-tuning on just 1,000 carefully curated, high-quality instruction-response pairs can produce a model that rivals chatbots trained on millions of examples. This reinforced the central theme: quality dominates quantity in instruction tuning.
Beyond SFT, modern alignment uses preference data for RLHF (Reinforcement Learning from Human Feedback) or DPO (Direct Preference Optimization). Each example contains a prompt and two responses, labeled by a human as “chosen” and “rejected.”
The Chinchilla paper (Hoffmann et al., DeepMind, 2022) established that previous large models were “under-trained”—they had too many parameters for the amount of data they were trained on. The optimal allocation of compute balances model size (N, parameters) and data size (D, tokens) so that both scale proportionally.
For compute-optimal training, the number of training tokens should scale approximately linearly with the number of parameters:
That is, a 10-billion-parameter model should be trained on roughly 200 billion tokens, and a 70-billion-parameter model should be trained on roughly 1.4 trillion tokens. The earlier GPT-3 (175B parameters, 300B tokens) was significantly under-trained by this criterion; Chinchilla (70B parameters, 1.4T tokens) matched or exceeded GPT-3's performance with far fewer parameters but more data.
| Model Size (params) | Optimal Tokens (≈20N) | Optimal Tokens (newer ≈30–40N) | Example Models |
|---|---|---|---|
| 1B | 20B | 30–40B | TinyLlama, Phi-1 |
| 7B | 140B | 210–280B | LLaMA-1 7B (trained on 1T, over-trained) |
| 13B | 260B | 390–520B | LLaMA-1 13B |
| 70B | 1.4T | 2.1–2.8T | Chinchilla, LLaMA-2 70B |
| 175B | 3.5T | 5.25–7T | GPT-3 (under-trained at 300B) |
| 540B | 10.8T | 16–21T | PaLM (trained on 780B, under-trained) |
Data contamination occurs when a model's training data contains examples from an evaluation benchmark. This inflates benchmark scores and makes reported performance unreliable. As LLM pretraining corpora grow to tens of trillions of tokens scraped from the web, contamination has become a systemic concern.
| Type | Description | Detection Difficulty |
|---|---|---|
| Exact match | Benchmark questions appear verbatim in training data | Easy (string matching) |
| Near-duplicate | Questions with minor paraphrasing or formatting changes | Medium (n-gram overlap) |
| Semantic overlap | Same concept or fact is present, rephrased substantially | Hard (requires semantic comparison) |
| Output leakage | Answer choices or gold answers appear in training data independently | Hard |
The following command-line examples use common tools for dataset inspection, splitting, and format conversion. They assume a Linux environment with Python and standard ML libraries installed.
Use this checklist before committing a dataset to a training run. Each item prevents a common failure mode that can silently degrade model quality or invalidate evaluation results.
Datasets are the most consequential component of any machine learning system. The best models are built on data that is clean, diverse, well-split, properly preprocessed, and rigorously decontaminated. The key takeaways from this reference:
Mastering dataset engineering is the highest-leverage skill in the modern AI stack. The model architecture can be copied from a paper; the dataset cannot.