Skip to content

Chapter 7.8 — Post-training in production: data, objectives and evaluation

🎯 Objective

Give a team that consumes open models what it needs to decide, produce data, measure and operate light post-training (SFT or DPO with LoRA) without confusing three things that usually arrive mixed together: the data that goes in, the objective the training optimizes and the mechanism that updates the weights. Ch. 7.6 answers whether training is worth it (three independent axes; what weights do and do not give you in knowledge). This chapter starts after the "yes": what changes in each phase, what SFT really optimizes, what DPO and RLHF add, how to produce and document data, and how to evaluate without fooling yourself.

What stays out: RL algorithms (PPO, GRPO, advantage estimation), distributed training (Ch. 7.7) and RL infrastructure at scale. A production team needs to know what these stages do to the model and which data they require, not how to implement them.

⚠️ Maturity. Public post-training recipes change with every model generation, and much of the evidence comes from the labs' own technical reports, not from independent replication. This chapter uses those recipes as evidence that the phases combine, not as a prescription of rounds or proportions.

🧠 Phases and boundaries

"Post-training" today names a sequence of stages, often iterated in rounds, not a single fine-tuning run. Each stage optimizes a different signal, consumes a different data format and fails in a different way:

Phase Training signal Data What changes in the model Typical risk
Pretraining Next-token prediction (cross-entropy) Web-scale corpus: web, code, papers Language, general knowledge, latent capabilities Out of reach for teams that consume models; you inherit biases and contamination you do not control
Mid-training / continued pretraining The same cross-entropy, over a curated mix or a domain corpus Billions of high-quality, synthetic or domain tokens Vocabulary and conventions of a domain; "patches" to capabilities On an already post-trained model, breaks instruction following; mitigated by chat data in the mix and a restoration step; typical LoRA falls behind full FT in this regime (Ch. 7.6)
SFT (instruction tuning) Likelihood of the demonstrations' target tokens Prompt-response pairs, multi-turn conversations, trajectories with tool calls Format, style, instruction following, tool use Memorizes style, not task; for facts, learns slowly and increases hallucination (Ch. 7.6)
Preference optimization (RLHF, DPO and variants, RLAIF) Margin between preferred and rejected answer relative to a reference, or a reward model's reward Chosen/rejected pairs; binary labels; human or LLM judgments Which of two plausible answers the model prefers: tone, helpfulness, safety, concision Learns the proxy (length, confidence) instead of the criterion; exploitable reward model
RL with verifiable rewards (RLVR) Scalar reward from a verifier: tests, gold answer, constraint check Prompts with a verifier Correctness on checkable tasks: math, code, format constraints An incomplete verifier becomes a reward-hacking target; online sampling cost
Evaluation as a phase None: it is the phase that decides A development split and a sealed ("unseen") split; decontamination against training Nothing in the model; everything in the promotion decision Dev -> test leakage; iterating against the holdout until you beat it

Recent public recipes show that the phases combine and repeat, each in a role:

  • Llama 3: six rounds of SFT followed by DPO; the SFT data combines answers picked by rejection sampling (K between 10 and 30 answers per prompt, the best one according to a reward model), capability-targeted synthetic data and a small human-curated share, with no published proportion; DPO was preferred over PPO because it required less compute at scale and did better on instruction following.
  • Tülu 3: prompt curation and decontamination -> SFT -> DPO -> RLVR; 8-gram decontamination (a training dataset counts as contaminated when it overlaps more than 2% of the instances of any evaluation; it is dropped or stripped of the matching instances); an "unseen" split never consulted during development; PPO on preferences cost ~28 h on two nodes versus ~4 h on one node for DPO, with a slightly lower score, so it was reserved for RLVR.
  • Qwen3: a minimal supervised cold start with long-reasoning examples -> reasoning RL over a few thousand question-verifier pairs -> fusion of the "think" and "answer" modes through SFT -> general RL with more than twenty tasks and rule-based, reference-based and reward-model rewards.
  • DeepSeek-R1: the R1-Zero variant ran pure RL on the base model with rule-based rewards (accuracy and format), without SFT; the authors avoided a neural reward model on reasoning tasks as "susceptible to reward hacking" (in R1's final RL stage, general data goes back to reward models); the final version reintroduced a supervised cold start and a rejection sampling + SFT stage, and the small models were obtained by SFT alone on the large model's outputs, which beat applying RL to them directly.

Three boundaries remain in dispute and depend on context: DPO versus online RL for preferences (labs chose differently according to budget and task verifiability); whether the supervised cold start is necessary (R1-Zero shows it is not; R1 brings it back for readability, language mixing and convergence; Qwen3 uses a minimal cold start to instill reasoning patterns before RL); and how much RL "teaches" versus "elicits" what already exists in the model. For a team that consumes models, the practical consequence is the same: the data format you can produce and verify determines the phase you can use.

🧩 What SFT really optimizes

SFT maximizes the probability of the demonstrations' target tokens. What counts as "target" is a recipe decision, not the library's:

  • In a dialogue, the target is usually only what the assistant produces (answers and tool calls). System instructions, user turns and tool results are masked: the model should not learn to "write" a tool's output. Libraries expose this as an option (loss only on the completion, or only on assistant turns); check the default of the version you use, because it changes between dataset formats.
  • The chat template defines roles, delimiters, end of turn and the syntax of tool calls. Training with one template and serving with another produces a model that looks good on loss and fails on the first tool call.
  • Truncation drops the end of long examples; if the end is the answer, the example is left with no target tokens (with masking) or only with easy-to-predict prompt tokens (without masking), and the mean loss stops measuring the answer without any warning.

Before training, inspect three tokenized batches: rebuild the tokens that receive loss, check masks and truncation, and run a conversation with a tool call and a tool result through it. This smoke test costs minutes and prevents a frequent class of "we trained and nothing changed".

Lower loss does not mean better performance on the task. It can be memorization, dev-to-train leakage or a more predictable style. The only acceptable evidence is evaluation on a sealed holdout, per case family, compared against the initial checkpoint and with regressions (Ch. 2.11, 5.7). And SFT is not the place for mutable facts: what it does well is format, style and tool use; what weights do and do not give you in knowledge is in the table in Ch. 7.6.

⚖️ Preferences, DPO and RLHF in one page

SFT teaches imitating demonstrations. Preferences teach choosing between plausible answers, which matters when there is no single correct answer: tone, concision, an appropriate refusal, which of two tool calls is safer.

Classic RLHF (the InstructGPT recipe): demonstrations feed an SFT; human comparisons between answers train a reward model; an RL algorithm updates the policy to maximize that reward with a penalty that limits the deviation from the SFT model. Three models, online sampling and a reward model that can be exploited.

DPO removes the separate reward model and the online loop: it optimizes the chosen/rejected pairs directly, with a classification loss, relative to a reference policy:

L_DPO = - E_{(x, y_w, y_l) ~ D} [ log σ( β · ( log[π(y_w|x) / π_ref(y_w|x)] - log[π(y_l|x) / π_ref(y_l|x)] ) ) ]

x      prompt;  y_w preferred answer (chosen);  y_l rejected answer (rejected)
D      preference dataset;  σ  logistic function
π      policy being trained;  π_ref  reference policy (the same policy before DPO)
β      controls how far the policy may move away from the reference

In words: training widens the margin between the probability ratio of the preferred answer and that of the rejected one, measuring both relative to what the model already did. The reference anchors training and β is the brake (higher β, less deviation), but the anchor is only measured on the pairs' answers: it does not protect capabilities the pairs do not exercise (that is what the maintenance mix and the regression eval are for). In practice the margin tends to come more from pushing the rejected answer down than from raising the preferred one; track both log-probabilities. With adapters, the reference does not require a second model in memory: with a new adapter, disabling it returns the base; if DPO continues an adapter that came from SFT, the reference is a frozen copy of it; and the reference log-probabilities can be precomputed. Large labs report preferring DPO over PPO for preferences on cost, with comparable or better results (Llama 3, Tülu 3); the reference-free or unpaired-label variants (KTO, ORPO, SimPO) trade one assumption for another, results depend on data and model, and Tülu 3 dropped SimPO and standard DPO in favor of length-normalized DPO.

RLAIF replaces the human annotator with an LLM that produces the preferences from a rubric or from principles. It makes annotation cheaper and scalable, but inherits the judge's biases (Ch. 2.11) and requires calibration against a human sample.

RLVR replaces the reward model with a programmatic verifier: the policy is rewarded only when the answer is verifiably correct (tests that pass, an answer equal to the gold one, a format constraint satisfied). It applies where correctness is checkable and is the phase that most depends on a question from Ch. 5.7: does the verifier cover what you want, or only what is easy to check? An incomplete verifier is a target, and models optimized against it find the holes. This book's position: a production team rarely needs RLVR; it does need the data with a verifier, because that data serves evaluation even when it never goes into training.

📦 Data and supervision

The data format defines the possible objective. The four formats that matter for a production team:

Format Schema example Objective it enables What to record per example
Demonstrations {"messages": [...]} or {"prompt", "completion"} SFT Origin (human, synthetic, redacted trace), generator and version, filters applied
Preference pairs {"prompt", "chosen", "rejected"} DPO and variants; reward model label_source (human, LLM judge with model and version, verifier, heuristic), criterion, preference strength, ties discarded or not
Trajectories with tool calls Messages with tool_calls, messages with the tool role, a tools column with the schemas SFT and DPO for agents Tool schema version, real or simulated result, mask applied to the results
Data with a verifier Prompt + gold answer, tests or a verification function RLVR; evaluation Verifier version, positive and no-op controls, solvability (Ch. 5.7)

Synthetic generation and curation. In recent pipelines, most post-training data is synthetic and filtered: in Nemotron-4 340B, more than 98% of the alignment data was generated; Llama 3 produced SFT data through rejection sampling filtered by a reward model; DeepSeek-R1 assembled ~800 thousand SFT samples: ~600 thousand reasoning samples by rejection sampling from the RL checkpoint, keeping only correct answers (rule-checked or judged by DeepSeek-V3 against the ground truth), and ~200 thousand non-reasoning samples reused from DeepSeek-V3's SFT dataset. The technique families you will meet: Self-Instruct (the model generates instructions and answers from seeds and filters out invalid and near-duplicate items), Evol-Instruct (rewrites instructions into progressively harder versions), Magpie (the pre-query template makes an aligned model emit instructions from scratch) and rejection sampling / best-of-n (generate K answers and keep the best one according to a judge, reward model or verifier). The bottleneck is not volume, it is prompt diversity: in Cosmopedia (synthetic pre-training data), rewording the prompt did not contain duplicates, and the authors turned to varying audience and style, on top of topic and seeds; deduplicating near-duplicates is mandatory.

Collapse. Training generation after generation on model-generated data degrades the distribution (the tails disappear) when synthetic data replaces real data. When data accumulates (each synthetic generation added to the original real data), test error stays bounded instead of diverging in Gerstgrasser et al.'s experiments (small LMs, diffusion, VAEs) and in their linear-regression analysis. Bounded is not free: in the VAEs error still rises and diversity drops, and another theoretical analysis (Dohmatob et al., ICLR 2025) concludes that even a small fraction of synthetic data can keep more data from improving the model. The operational rule: never discard the real data; synthetic data enters as a filtered, measured addition.

Decontamination. Before training, compare the training set against the entire evaluation suite. Three published practices: exact match of each benchmark's prompts against the post-training data (Llama 3); 8-gram overlap (Tülu 3: a training dataset counts as contaminated when it overlaps more than 2% of the instances of any evaluation, and is then dropped or stripped of the matching instances); three random 50-character substrings per evaluation example (the GPT-4 report, which estimated 25% of HumanEval as contaminated). None is conclusive: literal matching misses paraphrases (the GPT-4 report acknowledges false negatives and false positives), and on code and multiple choice n-grams err the other way: in the Llama 3 analysis (8-grams against the pre-training corpus), MBPP, HumanEval, MMLU and MMLU-Pro scored so high that the authors concluded that "other contamination detection methods may be needed". Passing the n-gram check is not being clean.

Provenance and licenses. In a 2023 audit of more than 1,800 text datasets, the license was omitted in about 70% of cases on the hubs (GitHub, Hugging Face, Papers with Code), with error rates above 50%; check at the original source, not on the hub. Treat synthetic data as if it carried the generator's terms and the seeds' licenses: the terms bind whoever accepted them (their reach over third parties who merely reuse the dataset is disputed), and whether the seeds' license extends to the outputs is an open question. The current terms of two major providers (Anthropic, commercial terms; Google, Gemini API additional terms) prohibit using the services to develop or train competing models; the interpretation of "competing" is legal and unsettled. Before using an API's outputs as training data, check your provider's terms in their current version and record the decision in the dataset card.

Splits by family, before variants. If you generate paraphrases, translations or variations of the same seed case, decide the seed's split before generating: all variants go to the same side. Otherwise, the holdout contains siblings of the training set and measures memorization. The sealed split is not consulted during development, not even "for a quick look".

Dataset card. Each version of the post-training dataset has a card with: origin and legal basis; the license of each source and the generator's terms; generator and judge model and version; filters, dedup and decontamination applied (with the suite used); distribution per family and per language; PII treatment; aggregate label_source; known biases; what is not covered. Without the card, the eval in the next section has nothing to explain when it regresses.

🏗️ In production

The minimum pipeline is not a training script; it is a chain with gates:

versioned data -> training -> independent evaluation (holdout + regression) -> registry -> canary -> defined rollback

Five artifacts versioned together, because any of them changes the result:

  • Dataset (content hash, card, splits) and the mix (proportion of each source, including "maintenance" data for capabilities you do not want to lose).
  • Chat template and tokenizer version: record the template actually used in training (the library may swap it for a "training template"; TRL does so with assistant_only_loss=True) and confirm, by rendering the same conversations on both sides, that training and serving produce the expected token sequence; every difference must be known and intentional.
  • Adapter with the exact identifier of the base (checkpoint hash, not just the model name) and the hyperparameters.
  • DPO reference (which checkpoint; adapter disabled or a "ref" adapter).
  • Evaluator: version of the suite, of the verifiers, of the judge and of the seeds.

Memory, as an order of magnitude:

training memory ≈ base weights
                + (trainable weights + gradients + optimizer states)   -> only for the parameters being trained
                + activations                                          -> grows with batch × sequence length
                + reference (DPO)                                      -> zero with the adapter disabled or precomputed log-probs

With full fine-tuning, the second term exists for every parameter; with LoRA, only for the adapter (in the original paper, ~10,000× fewer trainable parameters and ~3× less GPU memory on GPT-3 175B); with QLoRA, the frozen base sits in 4 bits (65B on a single 48 GB GPU in the authors' experiments). In full fine-tuning the trainable weights are the base weights themselves: count them once. The bytes-per-parameter arithmetic for the weights is in Ch. 6.3; the rest is what makes "does it fit on the GPU" a question of batch and sequence length, not only of model size.

Three LoRA settings with published evidence (one lab report, repeated in the TRL documentation, and Biderman et al.): a learning rate ~10× that of full fine-tuning (an empirical rule measured with α = 32, with no theoretical explanation; ~15× for short runs), all linear layers, including the MLPs (attention-only LoRA falls behind even at the same parameter count), and a rank that fits the dataset (in Biderman et al., with ~110 thousand code examples, r=16 and r=64 fall behind and only r=256 closes the gap; TRL recommends 256 for SFT). Under these conditions LoRA tends to match full fine-tuning on small and medium datasets; where it loses is in Ch. 7.6.

🚨 Failure modes

Failure How it shows up Why it happens
Loss drops and the task does not improve Pretty curves, eval equal to the baseline Wrong mask, divergent template, truncation, style memorization
Regression on an uncovered capability Format improves; tool calling, a secondary language or refusals get worse The mix does not contain the capability; in a published experiment (Qwen3-8B), mid-training on 100% internal documents raised internal QA from 18% to 43% and dropped IF-eval from 85% to 45%; with 30% chat data in the mix the result was 36% and 79%, and an on-policy distillation step, with the original model as teacher, took that variant to 41% and 83%
Dev -> test leakage Great holdout, production unchanged Variants of the same seed in both splits; iteration against the holdout
A preference that teaches only concision (or verbosity) Shorter answers, not better ones In the pairs, the chosen answer is systematically shorter or longer; the model learns length, and labs mitigate this with length-normalized DPO variants
Memorized PII The model reproduces personal data from a training trace Traces without redaction in the dataset; no extraction test before promotion
Adapter on a different base Silent degradation after "updating the model" Adapter trained on one checkpoint and served on another (including another quantization)
API data without permission Contractual risk discovered after deployment A provider's outputs used as training data without checking the current terms

🛡️ Controls

  • Sealed holdout, split by family before variants are generated, never consulted during development; its result is read once per candidate.
  • Regression eval covering what the training did not target: tool calling, already-stable formats, languages, refusals, safety (Ch. 2.11). Compare against the initial checkpoint and against the cheapest alternative (prompt + structured outputs), not only against the previous version.
  • Predefined seeds, recorded for training, sampling and evaluation; with budget, more than one seed, to know whether the difference survives the variance (Ch. 1.3).
  • Three-batch smoke test and a short run on a subset before the full training.
  • A report even with a null result: dataset, mix, hyperparameters, metrics per family with intervals, regressions and what was not covered. "It did not improve" is a result that saves repeating the experiment.
  • Separate "dataset quality" from "measured gain in the model": the card describes the first; only the independent eval asserts the second. An excellent dataset that does not move the metric is information, not failure.
  • Memorization and PII extraction test on a sample of the dataset before promotion; adapter pinned to the base hash in the registry (Ch. 7.2).

🏢 Hermes Logística — wave 6

The cargo-divergence report had a fixed format (fields, order, vocabulary) that prompt and structured outputs stabilized in ~90% of cases; the remaining 10% cost human rework. The team trained an SFT with LoRA on the open model that already served wave 3, with 1,200 redacted and reviewed reports, splits per tenant and per occurrence type, and a dataset card. The format gain was clear: schema validity from 90% to 99% on the sealed holdout. The promotion almost went through — until the regression eval, which had existed since wave 5, showed that the same agent's tool calling accuracy had dropped from 94% to 81%: the training mix did not contain a single trajectory with a tool call, and the adapter "forgot" the syntax the serving template expected. The rollback was pointing the @stable alias back to the previous version, in minutes, because the adapter was a versioned artifact in the registry. The second round mixed 30% tool-calling trajectories (data that already existed for evaluation) into the reports: format at 98%, tool calling at 93%, and this time the canary ran for a week before the alias moved. The lesson: the regression eval is not a cost of the fine-tuning project; it is what makes it possible.

📌 Checklist

  • [ ] Does the data you can produce and verify (demonstrations, pairs, trajectories, verifiers) match the phase you intend to use?
  • [ ] Were three tokenized batches inspected (masks, template, truncation, tool call with result)?
  • [ ] Was the template actually used in training (including any "training template" the library applied) compared, by rendering, with the serving one, and is the adapter pinned to the exact base hash?
  • [ ] Were the splits decided by family before generating variants, and was the sealed holdout never consulted during development?
  • [ ] Was training decontaminated against the entire evaluation suite, and is the method used (n-gram, substrings) recorded with its limits?
  • [ ] Does the dataset card record licenses at the source, the provider terms for the outputs used, generator and judge with version, PII treatment and label_source?
  • [ ] Does the regression eval cover capabilities the training did not target, and was the candidate compared against the initial checkpoint and the cheapest alternative?
  • [ ] Are dataset, mix, template, adapter, reference and evaluator versioned together, with rollback by alias defined before the canary?

📚 References