Contents
Key concepts
Losses come from likelihoods
Cross-entropy is the negative log-likelihood of a categorical model and binary cross-entropy of a Bernoulli; MSE is the negative log-likelihood under Gaussian noise. With a sigmoid output, MSE gives vanishing gradients when the model is confidently wrong, whereas BCE’s gradient with respect to the logit is simply (p − y). For asymmetric costs, such as late deliveries hurting more than early ones, use a quantile (pinball) loss at the matching quantile rather than reweighting MSE.
SGD, momentum, Adam and AdamW
Momentum averages gradients to damp oscillation and speed progress along consistent directions. Adam keeps exponential averages of the gradient (m, β1 ≈ 0.9) and squared gradient (v, β2 ≈ 0.95– 0.999), bias-corrects both because they start at zero, and steps by m̂/(√v̂ + ε), so step size is roughly invariant to gradient scale. AdamW applies weight decay directly to the weights instead of adding it to the gradient, where Adam’s normalisation would weaken it for parameters with large gradients. Typical LLM settings: β2 0.95, weight decay 0.1, gradient clipping at 1.0. Muon became the main challenger in 2025: it takes the momentum update of each hidden weight matrix and orthogonalises it with five Newton–Schulz iterations (embeddings, the output head and vector parameters stay on AdamW). With weight decay and update-scale matching added, Moonshot reported about twice AdamW’s compute efficiency, and it has since trained Kimi K2 (1T parameters) and DeepSeek-V4.
Flow · 3 stepsDecoupled weight decay in AdamW
- Moments The gradient feeds exponential averages m and v.
- Step Bias-corrected m̂ and v̂ set the step, which moves the weight.
- Decay Weight decay is subtracted directly from the weight, not added to the gradient.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Moments | The gradient feeds exponential averages m and v. |
| 2 | Step | Bias-corrected m̂ and v̂ set the step, which moves the weight. |
| 3 | Decay | Weight decay is subtracted directly from the weight, not added to the gradient. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| gradient g | Input | one step |
| m, v | Compute | β1 ≈ 0.9, β2 ≈ 0.95–0.999 |
| bias-corrected step | Compute | m̂ / (√v̂ + ε) |
| weight w | Memory | fp32 master |
| decoupled decay | Compute | subtract lr × λ × w |
| updated weight | Output | w after step and decay |
Source: This page's text
Learning-rate schedules and warmup
Warmup (often 0.5–2% of steps) avoids huge early updates while Adam’s second-moment estimates are noisy and activations are not yet well scaled; it is particularly important for post-norm and large-batch training. Cosine or linear decay to about 10% of peak improves final loss; warmup-stable- decay schedules keep a constant rate and decay at the end, which makes continuing training easier. Choose the peak rate by short sweeps on small proxies and transfer with care across width and batch. Recent open recipes are also staged by data: Olmo 3 follows about 5.9T tokens of broad pretraining with a 100B-token mid-training mix of math, code, QA, instructions and thinking traces, then a long-context stage, before SFT, DPO and RL with verifiable rewards.
Regularisation
L2 shrinks weights smoothly (a Gaussian prior); L1 drives many to exactly zero (a Laplace prior) because its subgradient does not vanish near zero. Dropout zeroes activations at rate p and scales the survivors by 1/(1 − p) during training, so it must be off in eval mode; it acts like an ensemble over subnetworks. Early stopping, augmentation and weight decay matter for small data; single-epoch LLM pretraining usually uses no dropout because there is little overfitting.
Initialisation, normalisation and gradient flow
Repeated multiplication through depth makes gradients vanish or explode. Xavier and He initialisation keep activation variance roughly constant (He uses variance 2/fan_in for ReLU). Residual connections give gradients an identity path; layer norm or RMSNorm, placed before each sublayer (pre-LN), stabilises deep transformers. Gradient clipping caps rare large updates.
Mixed precision numerics
fp16 has 5 exponent bits (largest value 65,504, smallest normal about 6.1e-5), so small gradients underflow and loss scaling is needed. bf16 keeps fp32’s 8 exponent bits (range up to about 3.4e38) but only 8 significant bits, so it rarely needs scaling but cannot represent small updates to large weights. Hence fp32 master weights and optimiser state, and fp32 accumulation in matmuls and reductions. FP8 training adds fine-grained scaling: DeepSeek-V3 scaled activations per 1×128 tile and weights per 128×128 block, promoted partial sums to fp32 every 128 elements, kept embeddings, the output head, normalisation and attention in higher precision, and stayed within 0.25% relative loss of bf16. NVFP4 stores 4-bit E2M1 values in 16-element blocks with an FP8 scale plus a per-tensor fp32 scale; NVIDIA’s pretraining recipe adds random Hadamard transforms, 2-D weight scaling, stochastic rounding of gradients and a few bf16 layers, and Nemotron 3 Super was pretrained this way on 25T tokens.
Stack · 6 layersMixed-precision Adam memory per parameter
bf16 weights are stored at 2 bytes per parameter.
Gradients are also kept in bf16 at 2 bytes per parameter.
An fp32 master copy keeps small updates from rounding away.
Exponential average of the gradient, kept in fp32.
Exponential average of the squared gradient, kept in fp32.
About 16 bytes per parameter; 70B parameters need about 1.1 TB before activations.
Memory and distributed training
Mixed-precision Adam needs about 16 bytes per parameter: 2 (bf16 weights) + 2 (gradients) + 4 (fp32 master) + 4 + 4 (Adam m and v), so 70B parameters need about 1.1 TB before activations. Activation checkpointing trades recomputation for memory. Data parallelism replicates the model; ZeRO and FSDP shard optimiser state, gradients and weights across data-parallel ranks; tensor and pipeline parallelism split the model itself. Ring all-reduce sends about 2(N−1)/N times the gradient size per GPU, nearly independent of N.
Debugging training
First overfit a single small batch to near-zero loss; if you cannot, the bug is in the model, loss or data pipeline, not in the hyperparameters. Classic PyTorch bugs: no optimizer.zero_grad() (gradients accumulate across steps), evaluating in train mode (dropout on, batch-norm statistics updated), forgetting torch.no_grad() or inference_mode during evaluation, softmax applied before a loss that expects logits, and causal masks or label shifts off by one. For loss spikes in large runs, check data (bad shards), LR and warmup, attention-logit growth and output-logit drift (qk-norm and z-loss help), then roll back and skip the offending batches. Muon made logit growth worse at scale; Kimi K2’s QK-Clip rescales a head’s query and key weights after any step where its largest attention logit exceeds a threshold (τ = 100), and the 15.5T-token run reported no loss spikes.
Flow · 5 stepsDiagnosing loss spikes in large runs
- Spot the spike A loss spike appears in a large run.
- Check data and schedule Check data for bad shards, then LR and warmup.
- Check logit growth Check attention-logit growth and output-logit drift.
- Mitigate Use qk-norm or z-loss; Muon can worsen logit growth, so QK-Clip rescales query and key weights above τ = 100.
- Recover Roll back and skip the offending batches.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Spot the spike | A loss spike appears in a large run. |
| 2 | Check data and schedule | Check data for bad shards, then LR and warmup. |
| 3 | Check logit growth | Check attention-logit growth and output-logit drift. |
| 4 | Mitigate | Use qk-norm or z-loss; Muon can worsen logit growth, so QK-Clip rescales query and key weights above τ = 100. |
| 5 | Recover | Roll back and skip the offending batches. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Loss spike | Detect | large run |
| Check data | Check | bad shards |
| Check LR and warmup | Check | |
| Check logit growth | Check | attention and output logits |
| Mitigate | Mitigate | qk-norm, z-loss, QK-Clip τ = 100 |
| Roll back | Recover | skip offending batches |
Source: This page's text
Worked examples
Adam versus AdamW for one parameter, by hand
A weight w = 2.0 receives gradient g = 0.5 on step 1. Adam uses lr = 1e-3, β1 = 0.9, β2 = 0.999, ε = 1e-8. Compute the step with and without bias correction. Then add weight decay λ = 0.1, first as L2 inside Adam, then decoupled as in AdamW, and compare.
1. Moments. m₁ = (1 − 0.9) × 0.5 = 0.05. v₁ = (1 − 0.999) × 0.5² = 0.00025.
2. Bias correction. m̂ = 0.05 / (1 − 0.9) = 0.5. v̂ = 0.00025 / (1 − 0.999) = 0.25.
3. Step. lr × m̂ / (√v̂ + ε) = 1e-3 × 0.5 / 0.5 = 1e-3, so w = 1.999.
4. Without bias correction. 0.05 / √0.00025 = 0.05 / 0.0158 = 3.16, so the step would be 3.16e-3, more than three times too large at the start, which is one reason early steps are unstable without warmup.
5. Scale invariance. If g were 50 instead of 0.5, m̂ = 50 and √v̂ = 50, and the step is still 1e-3. Adam’s step size is set by the learning rate, not by gradient magnitude.
6. L2 inside Adam. The gradient becomes g + λw = 0.5 + 0.1 × 2.0 = 0.7. The normalised step is still 1e-3 × 0.7 / 0.7 = 1e-3, so w = 1.999. The decay has been absorbed by the normalisation; parameters with large historical gradients are effectively regularised less.
7. AdamW (decoupled). Adam step as in (3), then subtract lr × λ × w = 1e-3 × 0.1 × 2.0 = 2e-4. w = 2.0 − 0.001 − 0.0002 = 1.9988. Every weight decays at the same relative rate whatever its gradient history, which is the behaviour weight decay was meant to have.
Why fp16 needs loss scaling and bf16 needs fp32 master weights
A gradient element is 1e-8. A weight is 1.0 and its update is −1e-4. Show what happens in fp16 and in bf16, and the standard fixes.
1. fp16 underflow. The smallest positive fp16 value (subnormal) is about 5.96e-8, so 1e-8 rounds to 0 and that gradient is lost.
2. Loss scaling. Multiply the loss by S = 2^16 = 65,536 before backward. The gradient becomes 1e-8 × 65,536 = 6.6e-4, comfortably above fp16’s smallest normal number (6.1e-5). Unscale in fp32 before the optimiser step. Dynamic loss scaling halves S and skips the step whenever an inf or NaN appears, and doubles S after, say, 2,000 clean steps.
3. bf16 range is fine. bf16 shares fp32’s exponent range (smallest normal about 1.2e-38), so 1e-8 is representable and loss scaling is usually unnecessary.
4. bf16 precision is the problem. With 8 significant bits, representable numbers just below 1.0 are 2^-8 ≈ 0.0039 apart (and 2^-7 ≈ 0.0078 just above). 1.0 − 0.0001 = 0.9999 is far closer to 1.0 than to the next value down, so it rounds back to 1.0: the update vanishes. Thousands of small updates are lost the same way, and training stalls.
5. Fix. Keep an fp32 master copy of the weights (spacing near 1.0 is about 1.2e-7), apply the update there, and cast to bf16 for the next forward pass; also accumulate matmul sums and reductions in fp32.
6. Memory consequence. bf16 weights (2 B) + bf16 gradients (2 B) + fp32 master (4 B) + Adam m and v (8 B) = 16 B per parameter, which is why a 7B model needs about 112 GB of training state before activations and must be sharded across GPUs.
All-reduce cost and keeping convergence when the batch grows 8×
You train a 7B model with data parallelism on 64 GPUs, each with 400 Gb/s (50 GB/s) of network bandwidth, at a global batch of 4M tokens. Estimate gradient all-reduce time against compute time. Then the global batch must grow from 0.5M to 4M tokens (8×): how do you keep convergence?
1. Gradient size. 7e9 parameters × 2 B (bf16) = 14 GB.
2. Ring all-reduce traffic per GPU. 2(N − 1)/N × S = 2 × 63/64 × 14 GB = 27.6 GB. Time ≈ 27.6 / 50 GB/s = 0.55 s per step. The bandwidth term barely changes with N; a latency term grows with the 2(N − 1) ring steps, which matters for small messages.
3. Compute per step. 4M tokens / 64 GPUs = 65,536 tokens per GPU. FLOPs ≈ 6 × 7e9 × 65,536 = 2.75e15. At an effective 400 TFLOP/s, that takes about 6.9 s.
4. Ratio. Communication is about 8% of compute and can be overlapped with the backward pass by bucketing gradients, so it is mostly hidden. In practice NCCL uses fast NVLink inside a node and the network between nodes; FSDP or ZeRO-3 replace all-reduce with reduce-scatter plus all-gather at about 1.5× the traffic.
5. Growing the batch 8×. There are 8× fewer optimiser steps for the same tokens, so the learning rate must rise.
- SGD: the linear scaling rule (LR × 8) with a gradual warmup is the usual starting point.
- Adam: square-root scaling (LR × √8 ≈ 2.8) is a common starting point; confirm with a short sweep.
- Re-express warmup and decay in tokens, not steps, and compare loss against tokens seen with the old run.
- Above the critical batch size, extra batch gives diminishing returns per token, so check that the larger batch actually reduces time to target loss.
- If memory limits the per-GPU batch, use gradient accumulation; it is equivalent for most layers but not for batch normalisation statistics.
What changed recently
Flow · 4 stepsOlmo 3 staged pipeline
- Pretraining About 5.9T tokens of broad pretraining.
- Mid-training A 100B-token mix of math, code, QA, instructions and thinking traces.
- Long-context Extend the window from 8k to about 65k.
- Post-training SFT, then DPO, then RL with verifiable rewards.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Pretraining | About 5.9T tokens of broad pretraining. |
| 2 | Mid-training | A 100B-token mix of math, code, QA, instructions and thinking traces. |
| 3 | Long-context | Extend the window from 8k to about 65k. |
| 4 | Post-training | SFT, then DPO, then RL with verifiable rewards. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Pretraining | Pretraining | ~5.9T tokens |
| Mid-training | Pretraining | 100B-token mix |
| Long-context stage | Pretraining | 8k to ~65k |
| SFT | Post-training | |
| DPO | Post-training | |
| RL with verifiable rewards | Post-training |
Source: This page's text
Nemotron 3 Super is pretrained on 25T tokens in NVFP4
NVIDIA pretrained Nemotron 3 Super, a 120B-total, 12B-active hybrid Mamba-attention MoE, on 25 trillion tokens in 4-bit NVFP4, then post-trained it with SFT and RL and released checkpoints and datasets. It moves 4-bit training from a research result to a production recipe, so interviewers now ask what must stay in higher precision and how you would spot quantisation damage during a run.
DeepSeek-V4 trains a 1.6T MoE with Muon and hyper-connections
DeepSeek-V4-Pro (1.6T total, 49B active) was pretrained on more than 32T tokens with the Muon optimiser, which DeepSeek credits with faster convergence and greater stability, and with manifold-constrained hyper-connections that strengthen the residual path. After Kimi K2, it confirms that Muon is no longer a small-model curiosity, and candidates are expected to explain what it changes relative to AdamW.
Olmo 3 publishes a complete multi-stage model flow
Ai2’s fully open Olmo 3 (7B and 32B) released every stage, checkpoint and dataset: about 5.9T tokens of pretraining, a 100B-token mid-training mix aimed at math, code, QA and thinking traces, a long-context stage that extends the window from 8k to about 65k, then SFT, DPO and RL with verifiable rewards for the Think models. It is the clearest public map of the modern pipeline, and interviewers use it to ask what each stage is for and how you would evaluate and decontaminate between them.
NVFP4 pretraining matches FP8 on a 10T-token run
NVIDIA trained a 12B model on 10T tokens in NVFP4 with loss and downstream accuracy comparable to FP8, using random Hadamard transforms on weight-gradient inputs, 16×16 block scaling for weights, stochastic rounding of gradients, roughly a sixth of linear layers kept in bf16, and a switch to higher precision shortly before learning-rate decay. FP4 tensor cores offer 2–3× FP8’s math throughput on GB200 and GB300, which is why numerics questions now go well beyond bf16 versus fp16.
Kimi K2: MuonClip trains a 1T MoE without loss spikes
Moonshot pretrained Kimi K2 (1T total, 32B active) on 15.5T tokens with MuonClip: Muon plus QK-Clip, which rescales a head’s query and key weights whenever its largest attention logit exceeds a threshold, curing the logit explosions Muon caused at scale. The run reported no loss spikes, and the team also rephrased pretraining text synthetically to get more learning signal per token, which makes it the standard example for optimiser choice and data-constrained training.
Pitfalls
- Saying Adam’s bias correction is a minor detail; without it early steps are several times too large.
- Implementing weight decay as L2 inside Adam and calling it AdamW.
- Claiming bf16 needs loss scaling like fp16, or that bf16 is ‘more precise’ than fp16 (it has more range, less precision).
- Forgetting model.eval() and torch.no_grad() in evaluation, or zero_grad() in the training loop.
- Tuning hyperparameters before confirming the model can overfit a single batch.
- Scaling batch size without changing learning rate and warmup, then concluding that large batches hurt.
How interviewers probe it
- Explain momentum, Adam’s moment estimates and bias correction, and why AdamW decouples weight decay. What does Muon do differently, and which parameters does it leave to AdamW?
- Why do transformer recipes use warmup then cosine or linear decay? How would you choose a learning rate for a new model?
- What does mixed precision change, why does fp16 need loss scaling, and why is bf16 often preferred? What extra machinery do FP8 and NVFP4 pretraining need?
- How does ring all-reduce scale with workers, and how do you keep convergence when the global batch grows 8×?
- Midway through a large run the loss spikes and sometimes diverges: how do you diagnose and mitigate it, including attention-logit growth under Muon?
- Debugging round: a notebook’s loss plateaus high and evaluation numbers look wrong; find the bugs.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Explain momentum, Adam’s moment estimates and bias correction, and why AdamW decouples weight decay.
Model answer, written in a candidate's voice
- Momentum averages past gradients to smooth noise and reinforce consistent directions.
- Adam keeps EMAs of gradients and squared gradients, corrects early bias, and scales each parameter by its own adaptive denominator.
- Bias correction divides the EMAs by 1 - beta^t because they start at zero.
- AdamW applies weight decay directly to the weights instead of folding L2 into the gradient, avoiding rescaling by the adaptive denominator.
- SGD with momentum can generalise better in some vision settings; Adam is the default for transformers.
Compare SGD, SGD with momentum and Adam. Why was AdamW introduced, and which settings (schedule, warmup, β values) matter most when training large models?
Model answer, written in a candidate's voice
- SGD uses raw gradient steps; momentum averages gradients exponentially and damps oscillation.
- Adam keeps first and second moment estimates, applies bias correction, and scales each parameter adaptively.
- Adam costs two extra state tensors per parameter (m and v).
- AdamW decouples weight decay from the adaptive scaling so regularisation is not distorted by per-parameter step sizes.
- For large models, warmup plus cosine/linear decay and beta2 are the most sensitive settings; lower beta2 can stabilise runs.
Why do transformer recipes use warmup followed by cosine or linear decay? How would you choose a learning rate for a new model?
Model answer, written in a candidate's voice
- Warmup ramps LR up gradually so Adam’s noisy first/second-moment estimates and unnormalised activations settle before large steps are taken.
- Cosine or linear decay shrinks steps late in training, letting the model settle into the wide low-loss region found at high LR.
- Choose LR via a short LR range test, then scale it with batch size (roughly linear for SGD, closer to square root for Adam).
- Monitor loss spikes and instability; back off LR or extend warmup if they appear.
- Learned or adaptive schedules exist — e.g. MetaGradients, used in DeepMind’s published Google Maps ETA GNN work to adapt the LR for stability — rather than relying only on hand-tuned curves.
You have finished this topic.
Reading
- Optimization Algorithms (Dive into Deep Learning, chapter 12)Free, runnable explanations of SGD, momentum, Adam and learning-rate scheduling.
- A Recipe for Training Neural NetworksA disciplined debugging process: know the data, overfit a batch, add complexity one step at a time.
- Adam: A Method for Stochastic OptimizationThe original algorithm, including the bias-correction derivation.
- Decoupled Weight Decay Regularization (AdamW)Shows why L2 regularisation and weight decay differ under adaptive optimisers.
- Mixed Precision TrainingIntroduces fp32 master weights, loss scaling and fp32 accumulation.
- Muon is Scalable for LLM TrainingShows the weight-decay and update-scale fixes that let Muon scale, with about 2× AdamW’s compute efficiency in scaling-law runs.
- Pretraining Large Language Models with NVFP4The 4-bit pretraining recipe (Hadamard transforms, 2-D scaling, stochastic rounding, bf16 layers) behind a 12B, 10T-token run that matched FP8.
- The Ultra-Scale Playbook: Training LLMs on GPU ClustersA long, practical guide to data, tensor, pipeline, context and expert parallelism with measurements.
Practise this topic
- Explain momentum, Adam’s moment estimates and bias correction, and why AdamW decouples weight decay.
- Compare SGD, SGD with momentum and Adam. Why was AdamW introduced, and which settings (schedule, warmup, β values) matter most when training large models?
- Why do transformer recipes use warmup followed by cosine or linear decay? How would you choose a learning rate for a new model?
- What does mixed-precision training change, why does fp16 need loss scaling, and why is bf16 often preferred?
- How does ring all-reduce scale with the number of workers? How do you keep convergence when the global batch grows 8×?
- Midway through a large pretraining run, the loss suddenly spikes and sometimes diverges. How do you diagnose the cause, and which mitigations would you consider?
- Why can gradients vanish or explode in deep networks, and how do Xavier/He initialisation, residual connections and normalisation address this?
- A PyTorch notebook trains a small transformer, but the loss plateaus high and evaluation numbers look wrong. Find the bugs. Follow-up: add a KV cache to its generation loop and prove it matches full recomputation.
- Explain what dropout does during training and inference, why it regularises, and how it interacts with batch normalisation.
- Derive binary cross-entropy from a Bernoulli likelihood and the gradient of logistic regression. Why is MSE a poor loss for classification?
- You lead a team training a 7B open model. Leadership asks why the plan has separate pretraining, mid-training, long-context and RL stages instead of just pretraining for longer. Using Olmo 3’s published model flow, justify the budget split and the gates between stages.
- Your GRPO run generates rollouts with a fast inference engine and computes gradients in a separate FSDP trainer, partly asynchronously. Reward climbs for a few hundred steps and then training collapses, although the same weights are loaded in both places. Explain training–inference mismatch, how you would confirm it is the cause, and what you would change.
- You are asked to move a pretraining run from FP8 to NVFP4 on Blackwell GPUs. Explain the NVFP4 format, what can go wrong numerically, and the recipe changes and monitoring you would put in place.
- Google’s VaultGemma (2025) was trained from scratch with sequence-level differential privacy at ε ≤ 2 and ended up roughly as capable as GPT-2 1.5B. Explain what ‘sequence-level’ protects and what it does not, why DP scaling laws favour smaller models with larger batches, and when you would use DP training rather than deduplication and PII filtering for a model fine-tuned on customer messages.
- During a pre-training run on thousands of accelerators you see occasional loss spikes with no NaNs and no hardware errors reported. How do you decide whether silent data corruption is the cause, and what would you build to detect and contain it?
- Muon has gone from small-scale experiments to training Kimi K2 and DeepSeek-V4. Explain what Muon computes and for which parameters, why it needed weight decay and update-scale matching to scale, and what instability Kimi K2 hit and how QK-Clip fixes it.
- The NeurIPS 2025 best paper on gated attention adds a head-specific sigmoid gate after scaled dot-product attention. Where exactly does the gate sit, why could such a small change stabilise training and remove attention sinks, and how would you test it on your own model?