ELLMEngineering Large
Language Models
Download PDF

Chapter 08

Designing a Training Recipe

On this page

A training recipe specifies the data, objectives, stages, budget, and tests for improving a capability. It must also say when to stop: a promising pilot is not enough evidence to spend the remaining compute on scale-up.

The recipe canvas

Use Part I's model-invocation path, workload estimates, and evaluation method; Part III expands that invocation into a serving lifecycle. Use these to state the task and serving limits. Add the training-specific choices: source datasets, supervision, stages, token and compute budgets, evaluation checkpoints, and stop conditions. The worked recipe below records these choices for a reasoning model.

Serving failures become curated examples, evaluation updates, and the next training stage.
Open full diagram ↗

Serving failures become curated examples, evaluation updates, and the next training stage.

Work backward from serving

If the product needs high-volume interactive decode, architecture and tokenizer choices should reflect KV-cache and output-length costs. If the product needs code completion, data freshness, exact syntax, repository context, and executable verification matter more than generic preference labels. If the product needs a speculative draft, target-distribution agreement and acceptance speed matter more than standalone benchmark leadership.

A common failure is to train the most capable model that fits the training cluster and discover later that it cannot meet the serving SLO. Compare total training and serving cost subject to explicit quality, latency, memory, and failure constraints. A candidate that misses a required quality threshold is infeasible even if its training run is cheap. The compute model below estimates one term of this comparison.

Budget the program, not only the final run

The nominal training run is only one consumer of compute. A credible budget includes data ablations, architecture pilots, hyperparameter sweeps, failed runs, checkpoint evaluation, teacher inference, safety testing, and the reserve needed to repeat a result. Spending nearly all available compute on one scale-up removes the ability to diagnose or correct it.

Partition the budget into three envelopes:

  • learning budget: small experiments that estimate response to data, model, and schedule changes;
  • commitment budget: the selected training run and its planned continuations;
  • assurance budget: evaluation, red-teaming, reproducibility, rollback preparation, and one credible recovery path.

For dense transformer training, a first-order compute model is proportional to parameters times training tokens:

2026-10-12T12:02:55.045990 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The constant k depends on architecture, forward-backward accounting, sparsity, and implementation.

The estimate is useful for comparing candidate scales, not for purchasing a cluster. Convert it into wall-clock time using measured utilization from representative pilots, then add evaluation and checkpoint overhead. A model that fits the arithmetic budget can still miss its deadline because of input stalls, collectives, failures, or poor local matrix shapes.

For a concrete teaching estimate, set k=6, P=7e9, and T=1e12, giving 4.2e22 FLOPs. If 256 accelerators each sustain 300 TFLOP/s of useful model work during training, the compute interval is 4.2e22/(256*300e12) = 546875 seconds, about 6.33 days. Adding overhead equal to 20% of that interval gives 7.60 days. These are assumed sustained rates, not hardware peak rates or measurements. Do not apply another utilization factor to a rate that already accounts for it; separately list evaluation, checkpoint, and recovery time.

Allocate a fixed compute budget between model size and data

Scaling Laws for Neural Language Models and Training Compute-Optimal Large Language Models are empirical allocation studies, not universal constants. The latter revisits how a fixed training budget is divided between parameters and tokens. Serving cost, data quality, and reuse can change the economic optimum.

Empirical scaling laws often approximate reducible loss with power-law relationships over a bounded regime. A schematic form is:

2026-10-12T12:02:55.051887 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Loss decreases with model parameters N and training tokens D within the fitted regime.

If dense training compute is approximately proportional to ND, a fixed compute budget creates a constrained allocation between model size and data. For example, a larger model must see fewer training tokens if ND stays fixed. The fitted loss terms estimate which allocation gives lower loss within the measured regime.

To solve the toy allocation, write the fixed budget as ND = K, substitute D=K/N, and differentiate A N^(-α) + B K^(-β) N^β with respect to N. At its interior optimum, α A N^(-α) = β B D^(-β): marginal returns to model size and data balance under the constraint. For positive fitted coefficients and exponents, N* = (α A / (β B))^(1/(α+β)) * K^(β/(α+β)), then D*=K/N*. Thus parameter and token counts grow with equal exponents in the budget only when α=β; their absolute ratio still depends on the fitted constants and units.

For a dimensionless toy problem, let n and d be parameter and token counts divided by fixed reference scales. Minimize 4/n + 1/d with n*d=16. The optimum is n=8, d=2, giving loss contribution 1; choosing n=d=4 gives 1.25. Equal exponents do not imply equal counts. With equal exponents the optimum balances the two reducible-loss contributions, not necessarily raw parameters and tokens. This derivation does not justify a universal tokens-per-parameter ratio.

Extrapolation is dangerous. The fitted data distribution, architecture family, tokenizer, optimization recipe, and evaluation metric define the regime. Data exhaustion, repeated examples, context changes, and capability thresholds can break the curve. Always retain uncertainty bands and validate intermediate scales before committing a frontier run.

The compute-optimal training point may also differ from the lifetime product optimum. Serving a model billions of times can dominate its one-time training cost. A smaller model trained on more tokens may cost more to create but far less to operate. A frontier capability project may rationally prefer a larger model even when it is not the lowest-loss allocation under a simple compute constraint.

Stage design

Pretraining builds broad representations from next-token prediction or a related self-supervised objective. Continued pretraining shifts domain, language, freshness, or context distribution while protecting general capability. Supervised fine-tuning teaches response formats and high-quality trajectories. Preference optimization shifts behavior among plausible outputs. Distillation transfers a distribution or capability into a smaller serving envelope.

Choose stages by the missing signal. Continued pretraining supplies domain text; SFT supplies desired responses; preference optimization supplies an ordering among responses. Use interaction-based optimization when exploration and delayed outcomes are necessary. Check broad capability after each stage to detect forgetting.

Use an experiment ladder

Training evidence should become more expensive only as uncertainty falls:

  1. pipeline proof: hundreds of steps establish data, loss, checkpoint, and metric correctness;
  2. overfit test: a tiny dataset verifies that the model can drive the intended objective down;
  3. small-scale pilot: alternative mixtures, schedules, or losses are compared at matched tokens;
  4. scaling pilot: two or more scales test whether the observed gain persists and estimate utilization;
  5. confirmation run: the selected recipe is repeated or validated on a protected dataset;
  6. production run: the full budget is committed with predeclared review points;
  7. release qualification: immutable checkpoints pass capability, safety, and serving gates.

Do not let the ladder become ritual. A deterministic code change may need correctness and performance tests but no statistical pilot. A new data mixture needs controlled training evidence because its effect cannot be inferred from the pipeline alone.

Curriculum and mixture

Data mixture weights determine the gradient distribution. Sampling every source in proportion to raw size lets abundant low-value sources dominate. Equal sampling overweights tiny domains and can cause memorization. Temperature sampling interpolates between these extremes.

Curriculum can mean ordering by difficulty, capability, context length, quality, or domain. It is useful when later data assumes skills learned earlier or when expensive long sequences should be introduced after the model is stable. It is harmful when the sequence creates catastrophic forgetting or a distribution cliff.

Mixture control loop

  1. Define capability slices with leading metrics.
  2. Estimate source-to-slice influence through ablations or data attribution proxies.
  3. Choose a baseline mixture that covers product distribution.
  4. Train small pilots across a sparse set of mixture changes.
  5. Fit a response model only as complex as the evidence supports.
  6. Update the mixture and preserve held-out confirmation data.

Schedules and stop conditions

Warmup protects early training when moment estimates and activation scales are unstable. Cosine or linear decay then reduces update size as the run approaches a local basin. Restart schedules can help exploration but complicate reproducibility and interpretation.

Stopping only when training loss plateaus wastes compute. Use a portfolio of signals: validation loss, target capability, data-slice trends, gradient noise, checkpoint-to-checkpoint improvement, projected value of more tokens, and schedule milestones. A predeclared review point makes it easier to stop a prestigious run whose marginal return has collapsed.

Compare checkpoints by tokens and wall-clock, not by step number alone. Track the marginal gain between evaluation points:

2026-10-12T12:02:55.062366 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

A declining marginal gain supports an explicit continue, change, or stop decision.

The metric in this calculation must be tied to the program objective. Validation loss can guide broad pretraining, while executable pass rate or calibrated task success may be more appropriate for a capability-specific continuation. Guardrails remain constraints rather than terms that can be averaged away.

Matrix-aware updates: what Muon changes

For diagonal momentum diag(100, 1), an unnormalized momentum step is dominated by the first direction. Muon's idealized orthogonalization yields diag(1, 1) before the chosen overall scale. This balances directions, but also discards magnitude information that might be useful. The method is not equivalent to normalizing the whole matrix by its norm.

AdamW scales gradient coordinates using elementwise moment estimates. Muon instead uses a momentum matrix and approximately orthogonalizes its update direction for selected matrix-shaped parameters. Using a compact singular-value decomposition over the nonzero singular directions, M=UΣV^T, the idealized direction UV^T removes their relative magnitudes. This produces orthonormal columns for a full-column-rank tall matrix, or rows for a full-row-rank wide matrix, not necessarily a square orthogonal matrix. Rank-deficient directions need a convention; this idealization leaves zero directions at zero, including an all-zero update. Practical matrix iterations approximate the transformation rather than computing a full SVD each step. Update scale, momentum, and numerical precision all matter.

Muon is Scalable for LLM Training studies weight decay and update-scale choices for large-model use. It does not establish one universal optimizer setting for every architecture. Embeddings, output heads, vectors, and matrix parameters need an explicit optimizer assignment; a hybrid optimizer configuration is not an implementation error.

Compare optimizers at matched data, model, validation targets, and compute accounting. Include matrix-iteration time and any momentum all-gathers needed by sharded training. A lower number of tokens to reach a loss can coexist with a more expensive optimizer step. Checkpoint the optimizer assignment and states, and rerun learning-rate/decay sweeps rather than copying an AdamW recipe unchanged.

Checkpointing and recovery

Before the expensive run, restore a checkpoint and verify that the next batch and optimizer step resume correctly. Budget checkpoint pauses, storage traffic, and lost work between durable saves. Distributed Checkpoints, Recovery, and Elasticity in Part V specifies the required state, atomic publication, and resharded restore protocol.

Worked recipe: a reasoning model

For a reasoning model, start with a strong base model and define the target beyond “longer reasoning.” Separate mathematical derivation, code execution, structured planning, evidence synthesis, and tool use because they have different verification surfaces.

Construct tasks with independently verifiable answers and retain diverse solution trajectories rather than only the teacher's preferred style. Use supervised training to establish tool syntax, decomposition patterns, and termination behavior. Add outcome- or process-based optimization only where the reward remains reliable under policy improvement.

A staged program might proceed as follows:

Stage Training signal Entry evidence Exit gate
Capability pilot Verified demonstrations Base model can solve a measurable fraction Gain persists on protected task families
SFT Correct and diverse trajectories Format and verifier are stable Better success without excessive length growth
Verifiable optimization Hidden executable outcomes Reward resists simple exploit probes Independent evaluation improves with bounded divergence
Distillation Teacher distributions and selected traces Serving target is defined Cost-adjusted task success beats the baseline
Release No additional gradient updates Immutable candidate checkpoint Quality, safety, latency, and rollback gates pass

Prevent reward hacking with hidden tests, adversarial cases, generator-verifier separation, and audits of suspiciously short or repetitive traces. Track answer accuracy, pass@k, calibration, token efficiency, tool validity, and a taxonomy of failure mechanisms. A reasoning program succeeds when the model solves more valuable tasks reliably, not when it merely emits more intermediate tokens.

Design Exercises

  1. Design a recipe for a code model that must run on a fixed single-GPU serving tier.
  2. When would continued pretraining be safer than changing the base mixture from the start?
  3. How would you decide whether to spend the next budget increment on data, model size, or more steps?
  4. What belongs in a resumable checkpoint for a sharded optimizer?
  5. How do you prevent a reasoning model from learning to exploit its verifier?

Use the staged reasoning example above for the recipe questions. The checkpoint protocol in Distributed Checkpoints, Recovery, and Elasticity develops the recovery answer; Applied Data-System Casework supplies the data-lineage and verifier checks.