---
title: "Training neural networks: losses, optimisers, numerics and scale"
url: https://gurkanozkan.ai/learn/topics/training/
markdown: https://gurkanozkan.ai/learn/topics/training.md
kind: topic
tracks:
  - ML engineering
  - Research
  - Applied LLM
json: https://gurkanozkan.ai/api/learn/topics/training.json
---

# Training neural networks: losses, optimisers, numerics and scale

Training questions check that you understand what actually happens inside a training loop: which loss follows from which likelihood, how SGD, momentum, Adam and AdamW differ, why transformer recipes use warmup and decay, how regularisation and initialisation keep optimisation well behaved, and what mixed precision changes numerically. At scale they move on to memory per parameter, all-reduce cost, large-batch learning rates and diagnosing loss spikes. Since 2025 they also probe the new frontier defaults: FP8 and even 4-bit (NVFP4) pretraining, matrix-aware optimisers such as Muon, and multi-stage recipes that add mid-training, long-context extension and RL with verifiable rewards after pretraining. Debugging rounds hand you a PyTorch loop with missing zero_grad, train/eval mode errors or no_grad misuse; the fastest candidates reason from first principles and check with tiny experiments, such as overfitting one batch.

## 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.

### 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.

### 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.

## 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.

**Solution**

**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.

**Solution**

**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?

**Solution**

**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

- **Apr 2026: 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. [Source](https://arxiv.org/abs/2604.12374)
- **Apr 2026: 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. [Source](https://arxiv.org/abs/2606.19348)
- **Dec 2025: 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. [Source](https://arxiv.org/html/2512.13961v2)
- **Sep 2025: 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. [Source](https://arxiv.org/html/2509.25149v2)
- **Jul 2025: 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. [Source](https://arxiv.org/abs/2507.20534)

## 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.

## Reading

- [Optimization Algorithms (Dive into Deep Learning, chapter 12)](https://d2l.ai/chapter_optimization/index.html) (Book, 150 min, Intro): Free, runnable explanations of SGD, momentum, Adam and learning-rate scheduling.
- [A Recipe for Training Neural Networks](https://karpathy.github.io/2019/04/25/recipe/) (Blog, 25 min, Core): A disciplined debugging process: know the data, overfit a batch, add complexity one step at a time.
- [Adam: A Method for Stochastic Optimization](https://arxiv.org/abs/1412.6980) (Paper, 40 min, Core): The original algorithm, including the bias-correction derivation.
- [Decoupled Weight Decay Regularization (AdamW)](https://arxiv.org/abs/1711.05101) (Paper, 40 min, Core): Shows why L2 regularisation and weight decay differ under adaptive optimisers.
- [Mixed Precision Training](https://arxiv.org/abs/1710.03740) (Paper, 30 min, Core): Introduces fp32 master weights, loss scaling and fp32 accumulation.
- [Muon is Scalable for LLM Training](https://arxiv.org/abs/2502.16982) (Paper, 40 min, Core): Shows 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 NVFP4](https://arxiv.org/abs/2509.25149) (Paper, 45 min, Deep): The 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 Clusters](https://huggingface.co/spaces/nanotron/ultrascale-playbook) (Book, 300 min, Deep): A 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.](https://gurkanozkan.ai/learn/questions/mle-sgd-momentum-adam-and-adamw-10.md)
- [Compare SGD, SGD with momentum and Adam. Why was AdamW introduced, and which settings (schedule, warmup, β values) matter most when training large models?](https://gurkanozkan.ai/learn/questions/research-optimisers-sgd-momentum-adam-020.md)
- [Why do transformer recipes use warmup followed by cosine or linear decay? How would you choose a learning rate for a new model?](https://gurkanozkan.ai/learn/questions/mle-learning-rate-schedules-and-warmup-11.md)
- [What does mixed-precision training change, why does fp16 need loss scaling, and why is bf16 often preferred?](https://gurkanozkan.ai/learn/questions/mle-mixed-precision-fp16-vs-bf16-58.md)
- [How does ring all-reduce scale with the number of workers? How do you keep convergence when the global batch grows 8×?](https://gurkanozkan.ai/learn/questions/mle-all-reduce-gradient-accumulation-and-large-batch-training-56.md)
- [Midway through a large pretraining run, the loss suddenly spikes and sometimes diverges. How do you diagnose the cause, and which mitigations would you…](https://gurkanozkan.ai/learn/questions/research-loss-spikes-in-a-large-run-046.md)
- [Why can gradients vanish or explode in deep networks, and how do Xavier/He initialisation, residual connections and normalisation address this?](https://gurkanozkan.ai/learn/questions/research-vanishing-exploding-gradients-026.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-10.md)
- [Explain what dropout does during training and inference, why it regularises, and how it interacts with batch normalisation.](https://gurkanozkan.ai/learn/questions/mle-why-dropout-works-04.md)
- [Derive binary cross-entropy from a Bernoulli likelihood and the gradient of logistic regression. Why is MSE a poor loss for classification?](https://gurkanozkan.ai/learn/questions/mle-deriving-cross-entropy-from-maximum-likelihood-14.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-training-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-reinforcement-learning-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-training-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-privacy-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-systems-reliability-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-training-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-transformers-02.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
