5 Pre-training 1 / 5
  1. In this chapter
  2. The LLM Training Pipeline
  3. Pretraining Data Engineering
  4. Scaling Laws
  5. The Compute and Memory Ledger of Training
  6. Distributed Training
All chapters →

Chapter 5 · Pre-training 5.1

The LLM Training Pipeline: From Data to Deployment

A map of the pipeline from data preparation, pretraining, SFT and preference alignment to evaluation and release, with the public data scale of each stage, plus a 0.86M-parameter byte-level GPT that trains on a laptop CPU to test data mixture, resuming and leakage.

Intermediate 34 min read Updated Companion code ↓

After this page you will be able to

  • Name the six stages from data to deployment, and for each stage its input, output, training objective and the first metric to watch.
  • Use the numbers in public technical reports to build an order-of-magnitude intuition for how much data pretraining, SFT and preference alignment use.
  • Train a small byte-level GPT on your own laptop and use it to verify three things: how the data mixture changes the loss of each domain, what happens when you resume without the optimizer state or the step counter, and how much a leaked validation set inflates the score.
  • When offline scores and online experience disagree, diagnose by stage instead of reflexively adding more alignment.
On this page
  1. Overview: from raw data to a deployable model
  2. The stages at a glance: inputs, outputs, objectives and data scale
  3. Stage 1: data preparation is the foundation of the whole pipeline
  4. A minimal instruction-data format
  5. Stage 2: pretraining learns world knowledge and language structure
  6. What to watch during pretraining
  7. Pitfalls that show up most often
  8. Hands-on: shrinking pretraining to fit a laptop
  9. Data: two domains, read as bytes
  10. Model: a 0.86M-parameter byte-level GPT
  11. The training loop
  12. A health check before training
  13. Baseline: 2000 steps and a checkpoint
  14. Reading the monitoring curves
  15. Experiment 1: the data mixture decides what the model is good at
  16. Experiment 2: a resume goes wrong and the score does not show it
  17. Experiment 3: validation leakage makes the score look better than it is
  18. Stage 3: SFT turns a model that continues text into one that follows instructions
  19. Stage 4: preference alignment goes from “can answer” to “answers the way people want”
  20. The basic RLHF recipe
  21. Why DPO is lighter
  22. Stage 5: evaluation must be independent of the training set
  23. Stage 6: release is not the end but the start of the next data loop
  24. Compare training pipelines under a fixed budget
  25. A minimal workable process for a small team
  26. Summary and exercises
  27. Quick self-test
  28. Further reading
  29. FAQ

Think of LLM training as a production line. The model weights are only the final product; what decides success is whether the whole line runs smoothly. This page first draws the global map, then runs an experiment that fits on a laptop to do the most easily overlooked steps by hand.

The experiments ran on the CPU of an Apple M2 Max laptop (Python 3.14, PyTorch 2.10, 8 threads, fp32); one 2000-step run takes about three and a half minutes. Seeds and data order are fixed, so rerunning on the same machine with the same number of threads gives bit-identical results (with a different thread count the order of floating-point sums changes and the results are no longer bit-identical; see the end of Experiment 1). The model is about 1/470,000 the size of Llama 3 405B, so absolute numbers do not transfer to large models. What transfers is the method: how to evaluate per domain, which states must be restored together when resuming, and how to detect leakage. The public data scales quoted here all come from the original papers.

Overview: from raw data to a deployable model

A typical LLM training project splits into six segments:

  1. Data preparation: collecting, cleaning, deduplicating, filtering, mixing and splitting.
  2. Pretraining: predicting the next token over a huge number of tokens to learn general language modeling.
  3. Supervised fine-tuning (SFT): turning a model that continues text into one that answers as asked.
  4. Preference alignment (RLHF or DPO): making the model closer to human preferences, refusal policy and product style.
  5. Evaluation and safety review: confirming that capability, safety and stability meet the release bar.
  6. Deployment and feedback: feeding online signals back into the data loop to drive the next iteration.

The six segments are not strictly linear. Mature teams evaluate while they train and feed data back while they serve, so the pipeline behaves like a loop rather than a one-off waterfall. Here is the main line in one picture:

The LLM training pipeline as a closed loop Data preparation leads to pretraining, SFT, preference alignment, evaluation and deployment, and logs and failure cases from deployment flow back into data preparation. The offline training line After release, back into the data loop Data prep clean / dedupe Pretraining next-token loss SFT instructions Alignment RLHF / DPO Evaluation skills / safety Deployment feedback loop Logs, failure cases and new data re-enter data prep
Training is not a one-way line but a continuous loop of training, evaluation, deployment and feedback.

The stages at a glance: inputs, outputs, objectives and data scale

The table quotes only numbers stated in public technical reports. Pretraining is counted in tokens, SFT and preference alignment in examples; the units differ, so the numbers are not directly comparable.

StageInput → outputTraining objectiveData scale in public sourcesFirst metric to watch
Data preparationraw web pages, books, code → cleaned, deduplicated, mixed token sequencesnone (data engineering)Llama 3: about 15T tokens, mixed roughly 50% general knowledge, 25% math and reasoning, 17% code, 8% multilingualdedup rate, share of each source, pass rate of the quality classifier
Pretrainingtoken sequences → base modelcross-entropy of the next tokenLlama 3 405B: 15.6T tokens; DeepSeek-V3: 14.8T tokensper-domain validation loss, gradient norm, throughput
SFT(instruction, response) pairs → instruction-tuned modelcross-entropy on response tokens onlyInstructGPT: about 13k prompts; LIMA: 1,000 examples; DeepSeek-V3: 1.5M instancesformat validity, instruction following, held-out loss
Preference alignmentpreference pairs or reward signal → aligned modelRLHF: maximize reward under a KL constraint to a reference model; DPO: classification-style loss on preference pairsInstructGPT: about 33k prompts for the reward model, about 31k for PPOwin rate, refusal rate, KL to the reference model
Evaluation and reviewcandidate model + independent eval sets → ship or notnone (judgment)depends on the productcapability, behavior and safety metrics
Deployment and feedbackproduction logs, failure cases → new data and new eval setsnone (loop)depends on the productonline metrics, how fast failures enter the data set

The scales differ enormously. LIMA fine-tuned a 65B LLaMA on only 1,000 examples, about 750,000 tokens in total (Zhou et al., 2023), while Llama 3 405B was pretrained on 15.6T tokens, so the former is roughly one twenty-millionth of the latter. The LIMA authors proposed the “superficial alignment hypothesis” on this basis: almost all knowledge is learned in pretraining, and alignment mainly teaches the model which style to answer in. It is a hypothesis, not a settled fact (InstructGPT’s SFT set is 13 times larger and DeepSeek-V3’s is 1,500 times larger), but it is one reason SFT work emphasizes data quality over quantity.

Stage 1: data preparation is the foundation of the whole pipeline

Many newcomers think of training as “architecture plus number of GPUs”, yet the ceiling is usually set by data. Data preparation has at least six steps:

StepWhat it doesWhy it matters
Collectionweb pages, books, code, papers, Q&A, dialogue, domain documentscoverage decides what the model can learn
Cleaningremove garbled text and boilerplate, extract the main contentnoise gets learned as if it were a pattern
Deduplicationexact plus near-duplicate removal (for example MinHash)less memorization and waste, and the first line of defense against eval leakage
Quality filteringrules, classifiers or small-model scoringspend the limited token budget on content worth learning
Mixingchoose the sampling weight of each sourceshapes what the model is good at; see Experiment 1 below
Splittingkeep training, validation and evaluation separate by document or sourceprevents leakage; see Experiment 3 below

What the cleaning, deduplication and quality-filtering steps each drop and on what evidence (the public recipes of C4, Gopher, FineWeb and DCLM), and how to set the parameters of MinHash near-duplicate removal and where it is blind, are in Pretraining Data Engineering.

Quality often matters more than quantity. Once the data is already large, adding low-quality samples is rarely a pure gain; it brings style drift, amplified noise, more safety risk and a token budget diluted by low-value content. In practice many teams spend most of their effort on data scoring, sampling weights and mixture strategy rather than on simply adding tokens.

The data mixture has to be answered by experiments. The final Llama 3 mixture is roughly 50% general knowledge, 25% math and reasoning, 17% code and 8% multilingual (Dubey et al., 2024). To choose it, the team trained a batch of small models on different mixtures, extrapolated with scaling laws how a large model would do on each mixture, and then trained large models on the candidates. Research also tries to automate this: DoReMi uses a 280M proxy model to set domain weights for an 8B model, and RegMix treats “mixture to performance” as a regression problem fitted on 512 models of 1M parameters before training a 1B model (Xie et al., 2023; Liu et al., 2024). Experiment 1 on this page is the smallest version of that idea: change the mixture on a small model and watch how each domain’s loss moves.

A minimal instruction-data format

A single-turn conversation in the SFT stage typically looks like this:

{
  "messages": [
    { "role": "system", "content": "You are a careful AI assistant." },
    { "role": "user", "content": "Explain what a KV cache is." },
    {
      "role": "assistant",
      "content": "A KV cache stores the keys and values of earlier tokens..."
    }
  ]
}

In a real project a single consistent format matters a great deal, because once templates get messy, both training and evaluation develop faults that are hard to localize.

Stage 2: pretraining learns world knowledge and language structure

The pretraining objective is autoregressive next-token prediction: given the context, minimize the cross-entropy of the true next token.

L(θ)=−1N∑t=1Nlog⁡pθ(xt∣x<t)\mathcal{L}(\theta) = -\frac{1}{N}\sum_{t=1}^{N}\log p_\theta(x_t \mid x_{<t})

The objective looks simple, but it is powerful because grammar, facts, patterns, style and reasoning cues all get compressed into this one prediction task (see Next-token prediction).

Token-level losses of models with different tokenizers cannot be compared directly: with a larger vocabulary, each token carries more bytes. The comparable metric is bits per byte (BPB): convert the total loss into bits and divide by the number of bytes BB in the text.

BPB=1B∑t(−log⁡2pθ(xt∣x<t))\text{BPB} = \frac{1}{B}\sum_{t}\left(-\log_2 p_\theta(x_t \mid x_{<t})\right)

The denominator is the text itself, independent of the tokenizer, so models with different vocabularies and domains with different content can be put on the same ruler (for how cross-entropy relates to information theory, see Information theory refresher). The experiments below use a byte-level model, where each token is exactly one byte, so BPB is simply the mean loss in base 2.

What to watch during pretraining

MetricWhat to look atSuspect first when abnormal
Training lossoverall downward trend (single steps are noisy, use a moving average)unstable data mixture, learning rate too high
Per-domain validation losseach domain’s curve on held-out datamixture imbalance, a source suddenly got worse
Gradient normglobal norm before clipping, and how often clipping triggersa norm spike: learning rate too high, outlier samples, numerical overflow; clipping on most steps: updates are cut by the threshold, like a smaller learning rate
Learning ratewhether warmup and decay follow the planthe step counter was not restored when resuming (Experiment 2)
Throughput and utilizationtokens/s, GPU utilization, memorydata loading or communication became the bottleneck
Checkpointcan it be restored to match uninterrupted trainingoptimizer state or step counter was not saved (Experiment 2)

Pitfalls that show up most often

  • An unstable data mixture makes the loss curve fluctuate wildly.
  • A bad learning rate or warmup makes early training diverge outright; for spikes or NaNs in the middle of a run, the order of checks is in Optimizers and training stability.
  • Wrong initialization: the loss at step 0 should be about log⁡2V\log_2 V bits (VV is the vocabulary size); if it is far off, do not start training yet (see “A health check before training” below).
  • Looking only at the overall loss and not at per-domain curves: the average looks fine while the scenario you care about is poor (Experiment 1).
  • Resuming with weights only, or forgetting to restore the step counter (Experiment 2).
  • Overlap between the validation and training sets inflates the score (Experiment 3).
  • A tokenizer that does not fit the task wastes tokens.

To see why scaling follows regular laws, read Scaling laws; the compute and memory ledger is in The compute and memory ledger of training, and what to do when a model does not fit on one GPU is in Distributed training.

Hands-on: shrinking pretraining to fit a laptop

Real pretraining needs thousands of GPUs, but the steps where pipelines most often go wrong (how to split the data, how to set the mixture, how to resume after a crash, whether anything leaked) can all be reproduced on a toy model. The code blocks below share one Python session (Jupyter cells or python -i both work) and run in order. You need torch, numpy, pandas and huggingface_hub; the first run downloads about 6 MB of WikiText-2.

Data: two domains, read as bytes

import glob
import math
import re
import sysconfig
import time

import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import hf_hub_download

torch.set_num_threads(8)

# prose: WikiText-2 train split (English Wikipedia); an article that starts
# with a level-1 heading counts as one document
path = hf_hub_download("Salesforce/wikitext",
                       "wikitext-2-raw-v1/train-00000-of-00001.parquet",
                       repo_type="dataset")
text = "".join(pd.read_parquet(path)["text"])
articles = [a.encode() for a in re.split(r"(?m)^(?= = [^=])", text) if a]

# code: the .py files of the Python stdlib without tests, one file = one doc
root = sysconfig.get_paths()["stdlib"]
paths = sorted(glob.glob(f"{root}/**/*.py", recursive=True))
paths = [p for p in paths if "/test" not in p and "site-packages" not in p]
files = [open(p, "rb").read() for p in paths]

as_array = lambda docs: np.frombuffer(b"".join(docs), np.uint8)


def split(docs, frac=0.05):
    """Split by document: the last documents (about 5%) become validation."""
    ends = np.cumsum([len(d) for d in docs])
    k = int(np.searchsorted(ends, ends[-1] * (1 - frac)))
    return docs[:k], docs[k:]


TRAIN, VAL, VAL_DOCS = {}, {}, {}
for name, docs in [("prose", articles), ("code", files)]:
    train_docs, VAL_DOCS[name] = split(docs)
    TRAIN[name], VAL[name] = as_array(train_docs), as_array(VAL_DOCS[name])
    n_train, n_val = len(TRAIN[name]), len(VAL[name])
    print(f"{name}: {len(docs)} documents, train {n_train / 1e6:.2f} MB, "
          f"validation {n_val / 1e3:.0f} KB")

Output:

prose: 629 documents, train 10.33 MB, validation 586 KB
code: 662 documents, train 11.12 MB, validation 590 KB

Three design decisions are in this block:

  • Read bytes, no tokenizer. The vocabulary is the 256 byte values, which keeps the code shortest. Each byte is one prediction, and dividing the loss by ln⁡2\ln 2 gives BPB, so two domains and two models can be compared directly.
  • Two domains. Prose is the training split of WikiText-2 (English Wikipedia, Merity et al., 2016); code is the .py files of the Python standard library without tests. Their statistics differ a lot, which is exactly what is needed to watch the mixture trade-offs.
  • Split by document, not by random bytes. For prose a document is an article, for code a file, and the last documents (about 5%) become the validation set. The validation content has never been seen during training, and no file has its first half in training and its second half in validation. Randomly splitting byte windows or sentences puts neighboring, overlapping content on both sides, and the validation score stops measuring generalization (Experiment 3 quantifies this).

Model: a 0.86M-parameter byte-level GPT

class Block(nn.Module):
    def __init__(self, d, heads):
        super().__init__()
        self.heads = heads
        self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.qkv, self.proj = nn.Linear(d, 3 * d), nn.Linear(d, d)
        self.fc1, self.fc2 = nn.Linear(d, 4 * d), nn.Linear(4 * d, d)

    def forward(self, x):
        B, T, D = x.shape
        qkv = self.qkv(self.ln1(x)).view(B, T, 3, self.heads, D // self.heads)
        q, k, v = qkv.permute(2, 0, 3, 1, 4)
        a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        x = x + self.proj(a.transpose(1, 2).reshape(B, T, D))
        return x + self.fc2(F.gelu(self.fc1(self.ln2(x))))


class GPT(nn.Module):
    """Byte-level GPT: the vocabulary is the 256 byte values, no tokenizer."""

    def __init__(self, d=128, layers=4, heads=4, ctx=256):
        super().__init__()
        self.tok, self.pos = nn.Embedding(256, d), nn.Embedding(ctx, d)
        self.blocks = nn.ModuleList(Block(d, heads) for _ in range(layers))
        self.ln = nn.LayerNorm(d)
        self.head = nn.Linear(d, 256, bias=False)
        self.head.weight = self.tok.weight  # tie input and output embeddings
        for m in self.modules():  # GPT-2 style init: weights N(0, 0.02^2)
            if isinstance(m, (nn.Linear, nn.Embedding)):
                nn.init.normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.zeros_(m.bias)

    def forward(self, x):
        h = self.tok(x) + self.pos(torch.arange(x.shape[1]))
        for block in self.blocks:
            h = block(h)
        return self.head(self.ln(h))


model = GPT()
print(f"parameters {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")

Output:

parameters 0.86M

This is the structure from The Transformer block: pre-norm (Pre-LN), multi-head causal attention (via scaled_dot_product_attention) and a GELU feed-forward layer four times as wide, with 4 layers, d=128d=128, 4 heads, context length 256 and 858,880 parameters. Positions use the simplest learned embeddings, and the input embedding and the output layer share weights (weight tying), so the vocabulary costs only 256×128256\times128 parameters.

The initialization lines are not decoration. The first version of this lab did not have them: PyTorch’s nn.Embedding initializes from a standard normal (standard deviation 1), and the output layer shares its weights, so at every position the logit of the byte that was just read averaged 84.8 while the true next byte got only 9.9. The loss at step 0 was 108.0 bits against 8 bits for a uniform guess. Training still works, but the loss only dropped below 8 bits at step 23, so the first 22 steps were worse than guessing, and the gradient norm exceeded the clipping threshold in all of the first 50 steps. GPT-2 style initialization (weights from N(0,0.022)\mathcal{N}(0, 0.02^2)) keeps the initial logits near 0, so training starts where it should, at log⁡2256=8\log_2 256 = 8.

The training loop

T, B = 256, 32  # sequence length and batch size: 8192 bytes per step


def get_batch(step, mix, seed=0):
    """Batch for a step: depends only on (seed, step), so data order resumes."""
    rng = np.random.default_rng((seed, step))
    names = rng.choice(list(mix), size=B, p=list(mix.values()))
    rows = []
    for name in names:
        data = TRAIN[name]
        i = int(rng.integers(0, len(data) - T - 1))
        rows.append(data[i:i + T + 1])
    rows = torch.from_numpy(np.stack(rows).astype(np.int64))
    return rows[:, :-1], rows[:, 1:]


def lr_at(step, total, peak=6e-3, warmup=50):
    """Linear warmup, then cosine decay to 10% of the peak."""
    if step < warmup:
        return peak * (step + 1) / warmup
    t = (step - warmup) / (total - warmup)
    return peak * (0.1 + 0.45 * (1 + math.cos(math.pi * t)))


@torch.no_grad()
def val_bpb(model, data, windows=256):
    """Validation bits per byte: comparable across domains."""
    windows = min(windows, len(data) // T)
    stride = (len(data) - T - 1) // windows
    rows = [data[j * stride:j * stride + T + 1] for j in range(windows)]
    rows = torch.from_numpy(np.stack(rows).astype(np.int64))
    losses = [F.cross_entropy(model(r[:, :-1]).reshape(-1, 256),
                              r[:, 1:].reshape(-1))
              for r in rows.split(64)]
    return torch.stack(losses).mean().item() / math.log(2)


def make(seed=0):
    torch.manual_seed(seed)
    model = GPT()
    decay = [p for p in model.parameters() if p.ndim >= 2]
    rest = [p for p in model.parameters() if p.ndim < 2]
    opt = torch.optim.AdamW(
        [{"params": decay, "weight_decay": 0.1},
         {"params": rest, "weight_decay": 0.0}], betas=(0.9, 0.95))
    return model, opt


def train(model, opt, start, end, total, mix, eval_every=100, lr_shift=0):
    """Train steps [start, end) and return the log."""
    log, t0 = [], time.time()
    for step in range(start, end):
        for group in opt.param_groups:
            group["lr"] = lr_at(step + lr_shift, total)
        x, y = get_batch(step, mix)
        loss = F.cross_entropy(model(x).reshape(-1, 256), y.reshape(-1))
        loss.backward()
        norm = nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        opt.zero_grad()
        row = dict(step=step + 1, loss=loss.item() / math.log(2),
                   norm=norm.item())
        if (step + 1) % eval_every == 0 or step + 1 == end:
            row |= {f"val_{n}": val_bpb(model, VAL[n]) for n in VAL}
            row["bytes_per_s"] = (step + 1 - start) * B * T / (time.time() - t0)
        log.append(row)
    return log

A few points deserve explanation:

  • The batch at each step depends only on (seed, step). The random generator is seeded with (seed, step), so knowing the step is enough to get exactly the batch an uninterrupted run would have used, and resuming does not need the data loader’s random state. Real systems use “dataset position plus random seed”, which is the same idea.
  • The learning rate warms up linearly for 50 steps and then decays along a cosine to 10% of the peak. After warmup:
ηt=ηmax⁡[0.1+0.45(1+cos⁡π (t−50)S−50)],S=2000\eta_t = \eta_{\max}\left[0.1 + 0.45\left(1+\cos\frac{\pi\,(t-50)}{S-50}\right)\right],\qquad S=2000

The peak is ηmax⁡=6×10−3\eta_{\max}=6\times10^{-3}. It was not tuned carefully and was compared with 3×10−33\times10^{-3} only once, under the same seed: at steps 500, 1000 and 1500 the validation BPB of both domains is lower with 6×10−36\times10^{-3}; at step 2000 the mean BPB is 2.096 against 2.113, and on prose 3×10−33\times10^{-3} is actually 0.008 lower. This gap is much smaller than the fluctuation between seeds (see the baseline below), so all we can say is that the two are about equally good. Exercise 6 asks you to run it yourself.

  • AdamW with β2=0.95\beta_2=0.95, weight decay 0.1 applied only to matrices (two or more dimensions), none to biases and LayerNorm parameters, and gradient clipping at 1.0. These defaults and their reasons are in Optimizers and training stability.
  • The log records the training loss and the pre-clipping gradient norm at every step, and the per-domain validation BPB every 100 steps. The monitoring figure below is drawn from this log.

A health check before training

Two almost free checks catch most bugs in training code: the loss at step 0 should be about log⁡2V\log_2 V, and training on one fixed batch should drive the loss close to 0.

# Sanity checks: the loss at step 0 should be about log2(256) = 8 bits;
# training on one fixed batch should drive the loss to almost 0
# (if it cannot overfit, the code is broken)
model, opt = make()
x, y = get_batch(0, {"prose": 0.5, "code": 0.5})
for i in range(301):
    loss = F.cross_entropy(model(x).reshape(-1, 256), y.reshape(-1))
    if i % 50 == 0:
        print(f"step {i:3d} loss {loss.item() / math.log(2):.2f} bits")
    loss.backward()
    opt.step()
    opt.zero_grad()

Output:

step   0 loss 8.04 bits
step  50 loss 4.12 bits
step 100 loss 3.20 bits
step 150 loss 2.08 bits
step 200 loss 0.98 bits
step 250 loss 1.45 bits
step 300 loss 0.07 bits

The initial loss is 8.04 bits, matching the 8 bits of a uniform guess. After 300 steps on the same batch it drops to 0.07 bits (there is no schedule here, only AdamW’s default learning rate of 10−310^{-3}, and the curve is not monotonic: it rises back to 1.45 at step 250). So the model, backpropagation and optimizer all work. Only after the check passes is it worth spending a few minutes on the full run.

Baseline: 2000 steps and a checkpoint

The three experiments below share one baseline: 50% prose and 50% code, 2000 steps, 16.38 million training bytes in total. The code saves the full state of the model and the optimizer as the checkpoint mid.pt at step 1000; Experiment 2 uses it.

STEPS, HALF = 2000, 1000
BASE = {"prose": 0.5, "code": 0.5}


def report(tag, model):
    s = [val_bpb(model, VAL[name]) for name in ("prose", "code")]
    print(f"{tag}\n  validation bpb: prose {s[0]:.3f}, code {s[1]:.3f}, "
          f"mean {sum(s) / 2:.3f}")


def weight_gap(a, b):
    pairs = zip(a.state_dict().values(), b.state_dict().values())
    return max((x - y).abs().max().item() for x, y in pairs)


def early_loss(rows):  # mean training loss of the first 20 steps (bits/byte)
    return sum(r["loss"] for r in rows[:20]) / 20


# Baseline: train 2000 steps, save a full checkpoint at step 1000
model, opt = make()
log = train(model, opt, 0, HALF, STEPS, BASE)
torch.save({"model": model.state_dict(), "opt": opt.state_dict()}, "mid.pt")
log += train(model, opt, HALF, STEPS, STEPS, BASE)
base_model = model
report("Baseline (50% prose + 50% code)", base_model)
print(f"  steps 1001-1020 mean loss {early_loss(log[HALF:]):.3f}\n")

Output:

Baseline (50% prose + 50% code)
  validation bpb: prose 2.346, code 1.847, mean 2.096
  steps 1001-1020 mean loss 2.309

Prose has a BPB 0.5 bits higher than code, so it is harder to predict: for the same model and the same amount of data, code contains more repeated patterns (indentation, keywords, identifiers). These numbers are the reference for every experiment that follows.

This is the result for seed 0. Changing the seed changes both the initialization and the data order. We also ran seeds 1 and 2 (replace make() above with make(seed) and replace the global get_batch with functools.partial(get_batch, seed=seed) to reproduce them):

SeedProse BPBCode BPBMeanLargest pre-clipping gradient norm
0 (this page’s baseline)2.3461.8472.09659.0
12.4181.9832.2006.7
22.4181.9632.1917.1

Of the three seeds, seed 0 is the best, about 0.1 bits lower than the other two, and it is also the only run with a gradient spike like the one at step 19; whether the two are related was not tested. Now look at the start of training: the model first learns byte frequencies, and once the loss is down to 3.7 to 3.9 bits it falls only slowly for a few hundred steps, until the model learns to use context. Take the first step at which the mean validation BPB (evaluated every 100 steps) drops below 3.0 as the moment a run leaves this plateau: step 500 for seed 0 and step 700 for seeds 1 and 2, and the two seeds that leave the plateau later also end about 0.1 higher. The point is: the difference between seeds (about 0.1) is noise that cannot be ignored. So every experiment below is a paired comparison under the same seed that changes one factor only; numbers from different seeds must not be subtracted from each other.

Reading the monitoring curves

A training run should record at least four things: the training loss, per-domain validation metrics, the pre-clipping gradient norm and the learning rate. The figure below is the complete record of this baseline run.

Monitoring curves of a 2000-step byte-level GPT run Three side-by-side charts, all with training steps 0 to 2000 on the x axis. Left: the 20-step moving average of the training loss falls from about 8 bits; validation BPB for prose and code is logged every 100 steps and code stays below prose. Middle: the gradient norm before clipping on a log scale peaks near 60 in the first 100 steps and then settles; the dashed line is the clip threshold 1.0. Right: the learning rate warms up linearly for 50 steps to 6×10⁻³ and then decays along a cosine to 6×10⁻⁴. A dashed line at step 1000 marks where the checkpoint was saved. A healthy run: loss falls, gradient norm settles, LR follows plan Training loss and validation BPB 2 4 6 8 bits / byte Gradient norm (before clipping) 0.1 1 10 100 clip threshold 1.0 Learning rate η (×10⁻³) 0 2 4 6 0 1000 2000 training step 0 1000 2000 training step 0 1000 2000 training step checkpoint train loss validation: prose validation: code
Monitoring curves of the baseline run (drawn from the log above). Left: 20-step moving average of the training loss and the validation BPB of the two domains. Middle: gradient norm before clipping, geometric mean over every 10 steps, logarithmic axis. Right: learning rate. The vertical dashed line marks step 1000, where the checkpoint is saved.

How to read the three panels:

  • Loss and validation BPB. The training loss falls from 8.04 bits at step 1 (a uniform guess is 8) to a mean of 2.01 over the last 20 steps. Validation BPB is evaluated every 100 steps and ends at 2.346 for prose and 1.847 for code, a mean of 2.096, only 0.08 bits above the training loss, so there is no sign of overfitting.
  • Gradient norm. In the first 100 steps, 37 steps exceed the clipping threshold of 1.0. The largest norm of the whole run, 59.0, occurs at step 19: the training loss jumps from 4.76 to 7.30 on that step, and on the next step the norm is back to 2.6 and the loss to 4.61. After step 100 the norm stays around 0.4 to 0.5 (segment medians 0.42, 0.50 and 0.45), and only 39 steps (1.95%) were clipped in the whole run. The share of clipped steps is a number to watch: when it is high, the updates are being cut by the threshold, which quietly amounts to a smaller learning rate. The run with a peak learning rate of 3×10−33\times10^{-3} in Exercise 6 is an example: its median norm in the second half is 1.3 to 1.4 and 1602 of the 2000 steps were clipped, yet training is healthy, only somewhat slower than this run. So read the clipped share together with the threshold and the loss curve; on its own it is not a fault signal.
  • Learning rate. It warms up over 50 steps to 6×10−36\times10^{-3} and then follows a cosine down to 6×10−46\times10^{-4}. At step 1000, where the checkpoint is saved, it is 3.4×10−33.4\times10^{-3} and still decaying, which matters for Experiment 2.

Matching curves to questions: a loss that does not move from about 8 bits points at initialization or the learning rate; a spike in the middle calls for the gradient norm and the data batch of that step; a validation curve that stops falling while the training curve keeps falling is a sign of overfitting; per-domain curves that move differently point at the data mixture (Experiment 1 below). A more systematic checklist is in Optimizers and training stability.

Experiment 1: the data mixture decides what the model is good at

Change one thing: how many windows are drawn from each domain during training. The seed, steps, learning rate and model stay the same, and the validation sets are the same two.

print()
for p in (0.9, 0.1):  # share of prose
    model, opt = make()
    train(model, opt, 0, STEPS, STEPS, {"prose": p, "code": 1 - p})
    report(f"Mixture: {p:.0%} prose + {1 - p:.0%} code", model)

Output:

Mixture: 90% prose + 10% code
  validation bpb: prose 2.205, code 2.263, mean 2.234
Mixture: 10% prose + 90% code
  validation bpb: prose 2.576, code 1.605, mean 2.090

Together with the 50:50 baseline (seed 0, lower BPB is better):

Prose : codeProse BPBCode BPBMean of the two
90 : 102.2052.2632.234
50 : 50 (baseline)2.3461.8472.096
10 : 902.5761.6052.090

A conclusion from a single seed is not reliable, so each mixture was run again with seeds 1 and 2 (everything else unchanged) and put into one table. The last column is the “step at which the run leaves the plateau” defined in the previous section:

Prose : codeSeedProse BPBCode BPBMean of the twoStep leaving the plateau
90 : 1002.2052.2632.234600†
90 : 1012.1902.2312.210600
90 : 1022.4472.6472.5471100
50 : 5002.3461.8472.096500
50 : 5012.4181.9832.200700
50 : 5022.4181.9632.191700
10 : 9002.5761.6052.090500†
10 : 9012.6621.7172.190600
10 : 9022.7031.7472.225700

† For these two seed-0 rows the step is taken from a rerun with 4 threads, for the reason given in the last paragraph of this section.

Three conclusions:

  1. The mixture is a knob, and its direction is mostly consistent across the three seeds. Raising the code share from 10% to 50% and then to 90% lowers the code BPB monotonically in all three seeds (seed 0: 2.263, 1.847, 1.605; seed 1: 2.231, 1.983, 1.717; seed 2: 2.647, 1.963, 1.747). Raising the prose share from 10% to 50% lowers the prose BPB by 0.23 to 0.29 in all three seeds; going on to 90% lowers it by another 0.14 and 0.23 in seeds 0 and 1, but raises it by 0.03 in seed 2, which is exactly the run that left the plateau last.
  2. The mean hides the trade-off, and the ranking by mean is unstable. The means of 50:50 and 10:90 differ by only 0.006, 0.010 and 0.034 in the three seeds; 10:90 is slightly better in the first two seeds and 50:50 in the third, so from the mean of a single seed you can reach any conclusion. Per domain the trade-off is stable: the prose of 10:90 is always 0.23 to 0.29 worse, and its code is always 0.22 to 0.27 better. This is why per-domain evaluation is a must for pretraining monitoring, not a nicety.
  3. The differences between seeds are mostly about when the run leaves the plateau. Eight of the nine runs leave the plateau between step 500 and step 700; only seed 2 of 90:10 drags on until step 1100 and ends with a mean BPB of 2.547, 0.31 and 0.34 higher than the other two runs of the same mixture. Within every mixture, the later a run leaves the plateau, the higher it ends. This is a correspondence seen in nine runs and was not tested for causation. So when comparing two settings, pair them under the same seed, run several seeds if you can, and look at the curves rather than only the end point.

This experiment answers “how does the mixture change the loss of each domain”, not “which mixture is best”. Which one is best depends on the weight of each domain in the target use, and the usual approach is the small-model experiments plus extrapolation (Llama 3) or proxy models (DoReMi, RegMix) mentioned above. Two limitations apply as well: the model has only 0.86M parameters and a fixed training budget, so the numbers hold only for this setup; and each mixture has only three seeds, enough to see a direction but not to give confidence intervals.

The thread count is a source of noise too. The seed-0 rows of the table and the baselines of seeds 1 and 2 used 8 CPU threads; the mixtures of seeds 1 and 2 used 4. A different thread count changes the order of floating-point sums, and the training trajectory is no longer bit-identical: rerunning the seed-0 mixtures 90:10 and 10:90 with 4 threads gives mean BPBs of 2.231 and 2.121, against 2.234 and 2.090 in the table, differences of 0.003 and 0.031. This is pure numerical noise with the same seed and the same data, of the same size as the “means differ by 0.006 to 0.034” above, which is why the regression test of Exercise 4 requires the same device and thread count.

Experiment 2: a resume goes wrong and the score does not show it

Resuming from a checkpoint after an interruption is something every training pipeline does. A checkpoint needs at least three things: the model weights, the optimizer state (the first and second moments of AdamW) and the number of steps already taken (it determines the learning rate and the next batch). Starting from the step-1000 checkpoint, we resume to step 2000 in four ways and compare with the uninterrupted baseline:

  1. Restore all three.
  2. Restore the weights only; the optimizer is re-initialized.
  3. Forget the step count: the data and the learning rate both restart from step 0.
  4. The data is right (batches from step 1000), but the learning-rate schedule restarts from the beginning.
def resume(keep_opt=True, data_from=HALF, lr_from=HALF):
    """Resume 1000 steps from the checkpoint. data_from and lr_from are the
    step numbers used for the data order and the learning rate."""
    state = torch.load("mid.pt", weights_only=True)
    model, opt = make()
    model.load_state_dict(state["model"])
    if keep_opt:
        opt.load_state_dict(state["opt"])
    shift = lr_from - data_from
    rows = train(model, opt, data_from, data_from + HALF, STEPS, BASE,
                 lr_shift=shift)
    return model, rows


cases = [("Resume: weights + optimizer + step", {}),
         ("Resume: weights only", dict(keep_opt=False)),
         ("Resume: forgot the step (data and LR restart)",
          dict(data_from=0, lr_from=0)),
         ("Resume: right data, LR restarts", dict(lr_from=0))]
for tag, kwargs in cases:
    model, rows = resume(**kwargs)
    report(tag, model)
    print(f"  max weight gap to baseline {weight_gap(model, base_model):.2e}, "
          f"first-20-step mean loss {early_loss(rows):.3f}")

Output:

Resume: weights + optimizer + step
  validation bpb: prose 2.346, code 1.847, mean 2.096
  max weight gap to baseline 0.00e+00, first-20-step mean loss 2.309
Resume: weights only
  validation bpb: prose 2.347, code 1.848, mean 2.098
  max weight gap to baseline 3.41e-01, first-20-step mean loss 2.400
Resume: forgot the step (data and LR restart)
  validation bpb: prose 2.374, code 1.804, mean 2.089
  max weight gap to baseline 6.64e-01, first-20-step mean loss 2.307
Resume: right data, LR restarts
  validation bpb: prose 2.371, code 1.799, mean 2.085
  max weight gap to baseline 8.88e-01, first-20-step mean loss 2.278
Resume modeProse BPBCode BPBMeanMax weight gap to the uninterrupted runMean loss, first 20 steps
Uninterrupted (baseline)2.3461.8472.09602.309
All three restored2.3461.8472.09602.309
Weights only2.3471.8482.0980.342.400
Forgot the step2.3741.8042.0890.662.307
Right data, schedule restarted2.3711.7992.0850.892.278

The widget below makes this table switchable: pick a resume mode to see which of the checkpoint’s three parts came back, how much the score moved versus the weights, with two side-by-side bars sharing one scale — the score gap is invisible, the weight gap unmistakable; the learning-rate curves below explain why the two “forgot the step count” modes even score slightly lower.

  1. With all three restored the result is bit-for-bit identical to the uninterrupted run: the maximum weight gap is exactly 0, not “very small”. This depends on two conditions: the checkpoint contains the optimizer state, and the batch depends only on (seed, step). If the data reader carries random state that cannot be restored, the data order changes, the runs cannot be bit-identical, and you cannot turn this into a regression test.
  2. The other three all “succeed”. There is no error, the loss looks normal, and the mean BPB is within 0.011 of the baseline, so nobody would get suspicious, yet their weights already differ from the uninterrupted run. With weights only, the mean loss over the first 20 steps is 0.09 bits higher: both AdamW moments start from zero, and the first few updates are larger than in the steady state. The end point is almost unaffected.
  3. The last two share an offset in their scores: code is 0.04 to 0.05 better and prose is about 0.03 worse. What they have in common is the end of the learning-rate schedule: at step 2000 the learning rate is still 3.4×10−33.4\times10^{-3} instead of 6×10−46\times10^{-4}. Whether this offset is stable and why it points this way is not tested here with more controls, so we draw no conclusion. Note also that the first-20-step loss of the schedule restarts (2.307 and 2.278) is not high: re-warming starts the learning rate at 1.2×10−41.2\times10^{-4}, far below the 3.4×10−33.4\times10^{-3} of the baseline at that point, so “the loss looks normal after resuming” does not prove the resume was correct.

So the criterion for accepting a resume is not the score but the state: what the checkpoint holds, and whether the step count and learning rate in the resumed log continue where the interruption happened. The strongest check is the first row above: training for 2N steps and training for N steps, saving, loading and training N more must give bit-identical weights. If you can do that, make it an automated test; if you cannot, be clear about which part of the state cannot be restored.

Experiment 3: validation leakage makes the score look better than it is

When the training and validation sets overlap, the validation score measures memorization, not generalization. In real projects leakage is mostly unintentional: scraped web pages carry evaluation questions, synthetic data paraphrases an evaluation set, files of the same repository land on both sides. Here we simulate the simplest case: a small piece of the validation set is mixed into the training data.

Take the first few files of the validation set until they reach 32 KB; in fact that is 6 files totaling 59.7 KB (wsgiref/validate.py and 5 files of the xml/ package) and it is the “leaked chunk”. The other 30 validation files, 531 KB in total, never take part in training. Then train 2000 steps each:

  1. Baseline: no extra data.
  2. Control: 5% of the training samples come from a piece of training-set code of the same size.
  3. Leaked: 5% of the training samples come from the leaked chunk, so each byte is seen about 14 times on average.

The control removes the change that merely comes from “seeing 5% more code samples”.

vfiles = VAL_DOCS["code"]  # the validation files, sorted by path
k = 0
while sum(map(len, vfiles[:k])) < 32768:  # take leading files up to 32 KB
    k += 1
chunk, rest = as_array(vfiles[:k]), as_array(vfiles[k:])
print(f"leaked part: first {k} validation files, {len(chunk) / 1e3:.1f} KB")
print(f"rest of validation: {len(rest) / 1e3:.0f} KB, never trained on")


def leak_scores(tag, model):
    print(f"{tag}\n  leaked part {val_bpb(model, chunk):.3f}, "
          f"rest of validation {val_bpb(model, rest):.3f} bpb")


def retrain_with(extra):
    """5% of the training samples come from extra, the rest 47.5% + 47.5%."""
    TRAIN["extra"] = extra.copy()
    mix = {"prose": 0.475, "code": 0.475, "extra": 0.05}
    model, opt = make()
    train(model, opt, 0, STEPS, STEPS, mix)
    del TRAIN["extra"]
    return model


control = retrain_with(TRAIN["code"][:len(chunk)])
leaked = retrain_with(chunk)
leak_scores("Baseline: no extra data", base_model)
leak_scores("Control: the same amount of training-set code", control)
leak_scores("Leak: the leaked part", leaked)

# Among the other validation files, which gain most: bpb of the control
# model minus bpb of the leaked model
names = [p.removeprefix(root + "/") for p in paths[-len(vfiles):]][k:]
gain = {}
for name, f in zip(names, vfiles[k:]):
    if len(f) >= 4096:
        data = np.frombuffer(f, np.uint8)
        gain[name] = val_bpb(control, data) - val_bpb(leaked, data)
print("Extra bpb gained by these files because of the leak:")
for name in sorted(gain, key=gain.get, reverse=True)[:5]:
    print(f"  {name:<28} {gain[name]:.3f} bpb")

Output:

leaked part: first 6 validation files, 59.7 KB
rest of validation: 531 KB, never trained on
Baseline: no extra data
  leaked part 1.944, rest of validation 1.874 bpb
Control: the same amount of training-set code
  leaked part 1.930, rest of validation 1.876 bpb
Leak: the leaked part
  leaked part 1.352, rest of validation 1.771 bpb
Extra bpb gained by these files because of the leak:
  xml/dom/minidom.py           0.359 bpb
  xml/dom/pulldom.py           0.357 bpb
  xml/sax/expatreader.py       0.274 bpb
  xml/dom/xmlbuilder.py        0.237 bpb
  xml/sax/saxutils.py          0.193 bpb
ModelLeaked-chunk BPBRest-of-validation BPB
Baseline (no extra data)1.9441.874
Control (same amount of training-set code mixed in)1.9301.876
Leaked (leaked chunk mixed in)1.3521.771
  1. The score on the leaked chunk itself is hugely inflated. It falls from the control’s 1.930 to 1.352, by 0.58 bits (30%), yet the model’s coding ability did not improve by 30%; it simply memorized these 60 KB. The control hardly changed (leaked chunk 1.944 to 1.930, rest 1.874 to 1.876), so the change comes from the leak and not from seeing 5% more code samples.
  2. Leakage spills over to similar content. The rest of the validation set, which never entered training, also drops from 1.876 to 1.771 BPB. The five files that improved the most are all in the xml/ package, siblings of the leaked xml/dom/expatbuilder.py and its neighbors: minidom.py improved by 0.36, pulldom.py by 0.36, expatreader.py by 0.27, xmlbuilder.py by 0.24 and saxutils.py by 0.19. So “these files were not seen during training” does not mean “there is no leakage”: paraphrases, translations and near-duplicates from the same source can all inflate an evaluation score.
  3. Splitting by document is necessary, not sufficient. Splitting by file avoids “the first half of a file in training and the second half in validation”, but the result above shows that when similar files of one package land on both sides, the validation score is inflated as well. In this page’s data the whole xml/ package happens to sit in the validation set, so the baseline does not have this problem; a safer rule is to split by source (repository, website, author).

This is exactly what to watch for in real evaluations. The Llama 3 report estimates how contaminated its evaluation sets are by the pretraining corpus with 8-gram overlap, notes that any detection method can produce false negatives and false positives and that how to run contamination analysis is still an open research question; contamination matters a lot for some datasets (PiQA, HellaSwag) and hardly at all for others (Natural Questions is estimated at 52% contaminated yet shows almost no gain) (Dubey et al., 2024, Section 5.1.4). Next to an evaluation score, state which method was used to detect contamination and what it found.

Stage 3: SFT turns a model that continues text into one that follows instructions

With pretraining alone, a model behaves more like a text-completion system. SFT teaches it to follow the user’s intent, produce more stable formats and fit the interaction style of the product. The training procedure is almost the same as pretraining; what differs is the data and the loss. The data are (instruction, response) pairs, and the loss is computed only on the response tokens, not on the prompt (Llama 3 describes this as masking loss on prompt tokens, Dubey et al., 2024):

LSFT=−1∣R∣∑t∈Rlog⁡pθ(yt∣y<t)\mathcal{L}_{\text{SFT}} = -\frac{1}{|R|}\sum_{t\in R}\log p_\theta(y_t \mid y_{<t})

where RR is the set of response-token positions.

SFT data usually comes from four kinds of sources: high-quality instructions written by people, domain Q&A annotated by experts, cleaned-up customer-service or business conversations, and synthetic data distilled from a stronger model. Four things matter most at this stage:

  1. Whether the answer style is consistent.
  2. Whether the output structure is stable, for example JSON, Markdown or tool-call formats.
  3. Whether the model learned to refuse requests beyond its ability or that are high-risk.
  4. Whether domain data damaged general ability.

Many teams discover at this step that a small amount of high-quality data often beats a large batch of low-quality instructions, and LIMA’s 1,000 examples are an extreme case.

Stage 4: preference alignment goes from “can answer” to “answers the way people want”

SFT teaches the model the task format, but it does not guarantee that style, risk appetite, helpfulness and safety all match the product goals. That is where preference alignment comes in. The formulas, a small runnable experiment and the trade-off between the two methods are in Preference Optimization: From RLHF to DPO; here we only look at where they sit in the pipeline.

The basic RLHF recipe

RLHF can be roughly split into three steps:

  1. Have annotators rank several answers by preference.
  2. Train a reward model on those preferences.
  3. Update the main model with reinforcement learning so that it tends to produce high-reward answers.

InstructGPT did exactly this: about 13k prompts for SFT, about 33k for the reward model and about 31k for PPO (Ouyang et al., 2022; see the paper breakdown). RLHF is expressive and models “which answer people prefer” explicitly; the price is a complex pipeline, high cost and demanding stability requirements.

Why DPO is lighter

DPO (Direct Preference Optimization) skips the explicit reward model and the reinforcement-learning loop and updates the model directly from preference pairs. Its appeal:

  • The implementation path is shorter.
  • Training is closer to ordinary supervised learning.
  • Experiment turnaround is usually faster.

DPO is not a cure-all either. If the preference data itself is poor, or the product goal is very complex, DPO is limited as well. A pragmatic approach is:

  • While still iterating quickly, start with SFT plus DPO to establish basic alignment.
  • When you need finer control over behavioral boundaries, consider the fuller RLHF pipeline.

Condensing this into a roadmap makes it clearer why a small team should not start with the heaviest alignment chain:

Choosing between SFT, DPO and RLHF in the training pipeline First decide whether the goal is a usable assistant, a quick correction of answer style, or fine-grained control of behavior, and choose between SFT, SFT plus DPO and full RLHF accordingly. Choose the alignment stage by what is missing, not by prestige What is missing right now? Be a usable assistant Stable format and tone come first SFT write the basic task space Typical: first product version,domain assistants, format tasks, Q&A Style still unstable Fix preferences and trade-offs fast SFT + DPO shorter path, fast iteration Typical: preference pairs exist,you want answers people prefer, fast Fine-grained control Can afford a reward model and PPO Full RLHF more expressive, but costlier Typical: high-value alignment,complex boundaries, tunable behavior For most teams the safer default order is SFT first, then DPO if needed, full RLHF last.
A good decision in the training pipeline is rarely to jump to the heaviest RLHF: first judge whether you lack usability, stable preferences or fine-grained behavior control.

Stage 5: evaluation must be independent of the training set

The most dangerous illusion in a training pipeline is “the loss went down, so the model got better”. The loss only tells you how good the model is at the next token of the training distribution; it does not tell you whether it can finish the task or whether it will cause trouble. Evaluation has to cover at least three kinds of questions:

TypeWhat it testsExamples
Capabilitycan the model do itgeneral Q&A, code generation, math reasoning, domain tasks
Behaviordoes it do it reliablyinstruction following, structured-output stability, long-context use, tool-call success rate
Safetywill it cause troublehandling of harmful requests, hallucination rate, leaking unauthorized information, refusal policy in sensitive areas

A mature evaluation system has both automatic benchmarks and human spot checks: automatic metrics are fast, human review is closer to real experience. Evaluation sets must also be isolated from training data, otherwise the score no longer reflects generalization, which is exactly what Experiment 3 quantifies. The Llama 3 report estimates how much the evaluation sets are contaminated by the pretraining corpus with 8-gram overlap, and admits that every detection method can produce false positives and false negatives, so how best to do it remains an open question (Dubey et al., 2024, Section 5.1.4). The details of evaluation methodology are in LLM Evaluation Methodology.

The hard part is not reciting “pretraining, SFT, alignment, evaluation” but, when online quality becomes unstable, quickly judging which layer is the likely cause. Many teams react to worse user feedback by doing more alignment, yet the problem may come from a weak base model, SFT data that did not explain the task, or an evaluation set that never covered the real distribution. Translating common symptoms into a stage diagnosis table helps avoid piling effort onto the wrong step:

SymptomStage more likely at faultFirst review action
Weak common sense and weak continuationThe base model or data coverage is insufficient; do not blame SFT firstLook at base evaluations and the pretraining data distribution to check whether the base ceiling is simply too low
Answers somewhat, but format and instructions are unstableSFT data did not define the task space; templates, boundary cases and format constraints are lackingAdd high-quality instructions, paraphrased samples and structured-output checks instead of just training longer
Answers sound human but flatter users or over-refuseThe alignment objective is unbalanced, preference pairs are noisy, or the weights of safety and helpfulness are skewedLook at helpfulness, refusal rate and hallucination rate separately instead of chasing one total score or a single subjective impression
Good offline scores, frequent failures onlineUsually the evaluation set is detached from the real distribution, or online tool chains and scenario constraints were never covered offlineCollect failure cases and rebuild the evaluation set first, then decide whether you really need to go back to training

Locate the layer of the symptom first, then decide whether to fix the base, SFT, alignment or evaluation.

Stage 6: release is not the end but the start of the next data loop

After deployment you will see many problems that training could never reveal:

  • Users phrase questions differently from the offline data.
  • Tool-call chains are more fragile on real networks.
  • Some refusal policies are too strict and hurt normal use.
  • Hot scenarios have stricter format requirements than expected.

So production logs, failure cases, user feedback and human review all become important sources for the next round of training and evaluation. A mature team runs a continuous loop rather than a single training run.

Compare training pipelines under a fixed budget

The Berkeley Scalable AI spring pretraining assignment caps compute and connects data preparation, training, and evaluation. A small team can borrow that design. Fix the hardware and GPU-hour budget, reserve time for evaluation and reruns, then compare candidates.

To test a new filtering rule, freeze the model, tokenizer, validation set, and baseline training configuration. Compare validation loss at the same number of training tokens, then compare how far each version gets in the same wall-clock budget. If filtering shifts average sample length, the same number of steps may contain different numbers of non-padding tokens. Report useful training tokens, data preparation time, device utilization, and loss by validation slice. This lets you distinguish data utility from a change in tokens processed per hour.

A minimal workable process for a small team

If you are not training a base model with tens of billions of parameters but want a workable process for a product, this scaled-down version is a reasonable start:

  1. Pick an open-source base model.
  2. Prepare a small batch of high-quality domain SFT data.
  3. Build a basic automatic evaluation set and a human review checklist, and keep the evaluation set separated from training data by document.
  4. Do SFT first, then see whether DPO is needed.
  5. Keep feeding online failure cases back into the data set and the evaluation set.

The process is simple, but it is more effective than “pile on data and train blindly” and closer to the rhythm of real projects.

Summary and exercises

Key points:

  1. The training pipeline has six stages: data preparation, pretraining, SFT, preference alignment, evaluation and review, and release with feedback. It is a loop, not a waterfall: failure cases from production become the next round of data and evaluation sets. The data sizes of the stages differ by orders of magnitude: pretraining is on the order of 101310^{13} tokens (15.6T for Llama 3 405B), SFT ranges from 10310^3 examples (LIMA) to 10610^6 (DeepSeek-V3), and InstructGPT’s preference data is on the order of 10410^4.
  2. Monitor pretraining per domain; BPB is the metric that can be compared across tokenizers. Run two checks before training: the loss at step 0 should be about log⁡2V\log_2 V, and one fixed batch should be overfit to nearly 0. Monitor four things: training loss, per-domain validation, the pre-clipping gradient norm and the learning rate.
  3. Experiment 1: the mixture is a knob. In all three seeds a larger code share gives a lower code BPB, and raising the prose share from 10% to 50% lowers the prose BPB by 0.23 to 0.29. The means of 50:50 and 10:90 differ by only 0.006 to 0.034, and which is better changes with the seed, while the domains differ steadily by 0.22 to 0.29, so evaluate per domain and do not draw conclusions from a single seed.
  4. Experiment 2: a resume must restore the weights, the optimizer state and the step count together. With all three the run is bit-identical to the uninterrupted one; the other modes raise no error and end within 0.011 of the baseline mean BPB, yet their weights already differ. Accept a resume by its state, not by its score.
  5. Experiment 3: mixing 60 KB of validation text into the training set lowers the BPB of that chunk from 1.930 to 1.352; the rest of the validation set, never trained on, also drops from 1.876 to 1.771, most of all for sibling files of the same package. Split validation data by document, better by source, and isolate it from the training data.
  6. SFT computes the loss on response tokens only; preference alignment has two routes, RLHF and DPO; the evaluation set must be isolated from the training data. When something goes wrong, locate the stage first and then decide what to fix, instead of reflexively adding more alignment.

Quick self-test

1. Offline evaluation scores are high, but after launch users complain that “the format is always unstable and it often ignores what I asked”. What is the most reasonable first step?

  • Run another round of preference alignment
  • Double the number of pretraining tokens
  • Collect failure cases from production, check whether the evaluation set covers the real distribution, and check whether the SFT data defines the task format clearly
  • Switch to a larger vocabulary

High offline scores with poor online behavior first suggest an evaluation set detached from the real distribution; an unstable format usually means the SFT data did not spell out the task space. Piling on alignment or pretraining before locating the stage spends resources on a step that may be unrelated.

2. Why compare models with different vocabularies by BPB rather than token-level cross-entropy?

  • BPB is always a smaller number
  • The denominator of BPB is the number of bytes of text, independent of the tokenizer, so models can be placed on the same scale
  • Token-level cross-entropy cannot be computed
  • BPB only works for byte-level models

A model with a larger vocabulary packs more bytes into each token, so token-level losses are not comparable. BPB is total bits divided by total bytes and can be computed for a model with any tokenizer.

3. When resuming, only the model weights were loaded and the optimizer was re-initialized. What is the most likely symptom?

  • An immediate error because the states do not match
  • The model falls back to random initialization
  • No error; the loss is briefly higher at the start of the resumed run and the final score is almost unchanged
  • The validation score drops permanently by more than 0.5 bits

In this page’s experiment, the mean loss over the first 20 steps is 2.400 with weights only against 2.309 with all three restored; the final mean BPB is 2.098 against 2.096. So looking at the final score alone does not reveal the problem.

4. Which kind of split is most likely to inflate the validation score?

  • Split by file, using the last 5% of files as the validation set
  • Cut all the text into overlapping windows and draw 5% of them at random as the validation set
  • Training and validation sets come from different websites
  • Use the validation set only for the final evaluation

Overlapping or adjacent windows land on both sides, so the model has already seen most of the validation text during training, and the validation score measures memorization. Only a split by document guarantees that not a single character of the validation text was seen.

5. Why is the SFT loss usually computed on response tokens only?

  • To save memory
  • The goal is to learn how to respond to an instruction; the prompt is the condition, not the output to imitate
  • Because prompts are always short
  • Because pretraining has already learned the prompts

The Llama 3 report describes this as masking the loss on prompt tokens. Masking does not save memory: the forward and backward passes still go through all tokens, only the loss on prompt positions is left out of the average.

6. In Experiment 1 the mean BPB of the 10:90 mixture is almost the same as that of 50:50 (2.090 and 2.096 for seed 0; across the three seeds they differ by only 0.006 to 0.034, and which is better changes with the seed). What should you conclude?

  • The two mixtures are equally good, so pick either
  • The mean hides a trade-off: the prose of 10:90 is steadily 0.23 to 0.29 worse and its code steadily 0.22 to 0.27 better, and the choice depends on the weight of each domain in the target use
  • Code data is of no use to the model
  • The evaluation code has a bug

This is why pretraining has to be evaluated per domain: the same average can hide completely different capability profiles, and the ranking by average is not even stable across seeds.

Exercises:

  1. With the Llama 3 mixture (50% general knowledge, 25% math and reasoning, 17% code, 8% multilingual) and about 15T pretraining tokens, how many T tokens does each category get?
  2. A tokenizer averages 4 bytes per token, and the model’s token-level cross-entropy on the validation set is 2.8 nats. What is its BPB?
  3. This page’s run used N=858,880N=858{,}880 parameters and 2000 steps × 32 × 256 bytes. Estimate the total training FLOPs with C≈6NDC\approx6ND. At the measured speed of about 77K bytes per second, what is the average compute rate? How many times is the roughly 3.8×10253.8\times10^{25} FLOPs of Llama 3 405B pretraining larger?
  4. How would you write a regression test for “resume”? What conditions does it need?
  5. Given a batch of SFT data and an evaluation set, how do you check that there is no leakage between them?
  6. Change the peak learning rate of the baseline from 6×10−36\times10^{-3} to 3×10−33\times10^{-3} (only the peak of lr_at) and rerun 2000 steps. First predict how the validation BPB (midway and at the end), the largest gradient norm and the number of clipped steps change, then run it to check.
Reference answers
  1. General knowledge 15×50%=7.515\times50\%=7.5T, math and reasoning 3.753.75T, code 2.552.55T, multilingual 1.21.2T, 15T in total.
  2. Convert to bits first: 2.8/ln⁡2≈4.042.8/\ln2\approx4.04 bits per token, then divide by the bytes per token: 4.04/4≈1.014.04/4\approx1.01 BPB. On the same text it is much better than this page’s 2.1; but 2.8 and 2.1 are in different units and cannot be compared directly.
  3. D=2000×32×256=16,384,000D=2000\times32\times256=16{,}384{,}000 and C≈6×858,880×16,384,000≈8.44×1013C\approx6\times858{,}880\times16{,}384{,}000\approx8.44\times10^{13} FLOPs. At 77K bytes per second the run takes about 213 seconds, an average of about 4×10114\times10^{11} FLOP/s, or 0.4 TFLOP/s. The compute of Llama 3 405B is about 4.5×10114.5\times10^{11} times larger. Note that 6ND6ND is only an estimate and leaves out the part of attention that depends on sequence length.
  4. Train for 2N2N steps; on a second path train for NN steps, save a checkpoint, load it and train NN more; assert that the maximum weight gap between the two is 0. Conditions: the checkpoint holds weights, optimizer state and step count; the batch depends only on (seed, step); both runs use the same device, thread count and deterministic kernels. When bit-identical results are impossible, compare at least whether the step count, learning rate and loss curves connect across the resume, and be clear about which part of the state cannot be restored.
  5. Split by document or source, not by random windows; run n-gram overlap detection between the training data and the evaluation set before training (Llama 3 uses 8-grams and admits that every detection method has false negatives and false positives); deduplicate the training data approximately (for example MinHash), also covering paraphrased and translated questions; use the evaluation set only for the final evaluation; report the detection method and result together with the scores.
  6. At steps 500, 1000 and 1500 the validation BPB with 3×10−33\times10^{-3} is higher in both domains (step 1000: prose 2.689 against 2.643, code 2.250 against 2.201). At step 2000 the mean is 2.113 against 2.096, with prose actually 0.008 lower (2.338 against 2.346) and code 0.041 higher (1.888 against 1.847). The largest gradient norm is 6.0 against 59.0, so there is no spike like the one at step 19; but the number of clipped steps is 1602 against 39: in the second half its median gradient norm is 1.3 to 1.4, while that of the 6×10−36\times10^{-3} run is only 0.45 to 0.50, so the clipping threshold is active almost all the time. Read the clipped share together with the learning rate, the threshold and the loss curve; on its own it is not a fault signal.

Further reading

FAQ

What stages does an LLM training pipeline have?
A typical pipeline runs through data preparation, pretraining, supervised fine-tuning (SFT), preference alignment (RLHF or DPO), independent evaluation and review, and deployment, and what is learned from deployment becomes the next round of data. Pretraining learns world knowledge and language structure, SFT teaches the model to follow instructions, alignment makes answers closer to what people want, and evaluation decides whether the model ships.
What problems do pretraining, SFT and preference alignment each solve?
Pretraining predicts the next token on a huge corpus and learns world knowledge and language structure. SFT uses instruction and answer pairs to turn a model that continues text into one that follows instructions. Preference alignment uses human or AI preference data to move answers from merely correct to what people actually prefer. The three use different objectives and differ in data volume by orders of magnitude.
How do RLHF and DPO differ?
RLHF first trains a reward model on preference data and then optimizes the policy with reinforcement learning such as PPO, which makes the pipeline long and requires several models at once. DPO rewrites preference optimization as a classification-style loss on preference pairs, so it needs neither an explicit reward model nor online sampling. It is lighter and easier to reproduce.
How many tokens does pretraining use, and how much data do SFT and alignment need?
Public technical reports differ by orders of magnitude: Llama 3 405B was pretrained on 15.6T tokens and DeepSeek-V3 on 14.8T tokens. SFT sets range from about 13k prompts for InstructGPT and 1,000 curated examples for LIMA to 1.5M instances for DeepSeek-V3. InstructGPT's reward model used about 33k prompts and PPO about 31k. The units differ (tokens versus examples), and data quality, mixture and model size all change the requirement, so treat these numbers as orders of magnitude only.
What must a checkpoint contain to resume training after an interruption?
At least three things: the model weights, the optimizer state (the first and second moments of AdamW) and the number of steps already taken, which determines the learning rate and the next batch. In this page's byte-level GPT experiment, a resume that restores all three is bit-identical to the uninterrupted run; restoring weights only raises the mean loss of the first 20 steps by about 0.09 bits; forgetting the step count or restarting the learning-rate schedule raises no error and ends within 0.011 of the baseline mean validation BPB, yet the model is no longer the same. So accept a resume by its state, not by its score.
How do you avoid validation leakage and keep evaluation scores trustworthy?
Split by document or source rather than by random windows; before training, run n-gram overlap detection between the training data and the evaluation set (Llama 3 uses 8-grams) and deduplicate the training data approximately; use the evaluation set only for the final evaluation; report which contamination-detection method was used. In this page's experiment, mixing 60 KB of validation text into the training set lowers the BPB of that chunk from 1.930 to 1.352, and similar files that were never trained on improve by up to 0.36, so 'not seen' does not mean 'not leaked'.