Slides · Deep learning and transformers
Training deep networks: normalisation, regularisation, AdamW and debugging
1 / 22
Training deep networks
Normalisation, regularisation, AdamW with a schedule, gradient clipping, and a checklist for NaN and flat losses.
Concept
Why this is worth 70 minutes
- A network that trains can still fail quietly: validation loss rising, results that change with batch size, a model that behaves differently in serving than in testing, a late NaN.
- Each has a short mechanism, and the questions are standard in interviews (common industry pattern).
- This lesson finishes threads from earlier ones: AdamW, schedules, clipping and early stopping.
Three things you will be able to do:
- Compare batch and layer norm and explain train versus eval mode.
- Explain dropout, weight decay, early stopping and AdamW, and read an experiment honestly.
- Set up a warmup-plus-cosine schedule with clipping, and debug NaN and flat losses.
Compare
Batch norm versus layer norm
| Batch norm | Layer norm | |
|---|---|---|
| Statistics over | Batch, per feature | Features, per example |
| Depends on other examples | Yes | No |
| Train and eval | Differ (running estimates) | Same |
| Small batches | Noisy | Fine |
- Row 0 under batch norm: (−0.447,0.447,−1.183), then (−0.576,0.798,−1.069) after another row changes. Layer norm: (−1.225,0,1.225) both times.
- Batch mean spread: 0.701, 0.358, 0.178, 0.089 at batch sizes 2, 8, 32, 128.
Sources[1] torch.nn.BatchNorm1d[2] torch.nn.LayerNorm[3] Layer Normalization[4] Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
Concept
Train mode versus eval mode
- Dropout: zero with probability p and scale survivors by 1/(1−p) in training; identity in eval. Mean of a dropped 3.0: 3.005 at p=0.2.
- Batch norm: batch statistics in training, running estimates in eval.
- Layer norm: the same in both.
model.eval()switches the layers that behave differently;torch.no_grad()only stops gradient tracking.
Sources[5] torch.nn.Module (train and eval)[6] torch.no_grad[7] torch.nn.Dropout[8] Dive into Deep Learning, Dropout
Check yourself
Check: batch-dependent scores
At serving time the score for one request changes with the other requests in its batch. A teammate proposes retraining with layer norm. What do you check first?
Answer
Whether the served model is in eval mode: a batch norm model in training mode normalises with the current batch. Layer norm would also remove the dependence, but only after retraining; calling eval() is the cheap first check.
Concept
Dropout, weight decay, early stopping
- Dropout: training-time noise. Why it works is debated; the mechanics are not.
- Weight decay: L2 adds λW to the gradient. Equivalent to decay for SGD, not for Adam.
- Early stopping: keep the weights from the best validation epoch; report on a separate test set, since the epoch was picked on validation.
Sources[7] torch.nn.Dropout[8] Dive into Deep Learning, Dropout[9] Dropout: A Simple Way to Prevent Neural Networks from Overfitting[10] Dive into Deep Learning, Forward propagation, backward propagation and computational graphs[11] Decoupled Weight Decay Regularization[12] A Recipe for Training Neural Networks
Worked example
Two moons, 30 training points, 8 seeds
| Setting | Test loss | Test accuracy | At best-validation epoch |
|---|---|---|---|
| None | 0.616 | 0.826 | 0.380 |
| Weight decay 0.01 | 0.417 | 0.828 | 0.382 |
| Dropout 0.3 | 0.595 | 0.822 | 0.382 |
- Weight decay won on 7 of 8 seeds (0.417 against 0.616); dropout on only 3 of 8 (0.595).
- Accuracy barely moved: weight decay improved the probabilities; dropout changed neither noticeably (within noise for 8 seeds).
- Early stopping beat the last epoch on 8 of 8 seeds; best epochs ranged from 2 to 188.
Math
Adam with L2 versus AdamW
AdamW: θ←θ−γλθ before the moment updates| Loss gradient scale | Extra shrinkage per step, Adam+L2 | AdamW |
|---|---|---|
| 0 | 1.0×10−3 | 1.0×10−5 |
| 0.001 | 9.95×10−4 | 1.0×10−5 |
| 0.01 | 7.07×10−4 | 1.0×10−5 |
| 0.1 | 9.95×10−5 | 1.0×10−5 |
| 1 | 1.0×10−5 | 1.0×10−5 |
| 100 | 1.0×10−7 | 1.0×10−5 |
- w=1, decay 0.01, rate 0.001; a stylised case with the gradient alternating ±G.
- Adam+L2 extra step ≈γλw/G2+(λw)2: a full rate where G≪λw, about γλw/G where G≫λw. It meets AdamW near G=1 only because of these units.
- PyTorch AdamW defaults: rate 0.001, betas 0.9 and 0.999, epsilon 10−8, decay 0.01.
Sources[13] torch.optim.AdamW[11] Decoupled Weight Decay Regularization
Check yourself
Check: which decay?
You switch from Adam with an L2 penalty to AdamW and keep the same number, 0.01. Why might the best value change?
Answer
The two shrink weights differently: with L2 the effective decay depends on each parameter’s gradient scale, while AdamW applies the same fraction of the weight everywhere. The paper reports that decoupling makes the best decay value largely independent of the learning rate, so re-tune it rather than carrying the number over.
Worked example
Warmup then cosine
| Step | 0 | 99 | 325 | 550 | 775 | 999 |
|---|---|---|---|---|---|---|
| Rate (peak 10−3) | 10−5 | 10−3 | 8.54×10−4 | 5×10−4 | 1.46×10−4 | 3×10−9 |
- 100 warmup steps, 1,000 in total. A quarter of the way down, cosine is at 85% of the peak, a line at 75%.
- Warmup is established practice; why it helps for Adam is still studied. The older alternative is step decay (divide by a factor, often 10, at chosen epochs; common practice).
- The original transformer: 4,000 warmup steps, β2=0.98, inverse-square-root decay.
Sources[14] torch.optim.lr_scheduler.CosineAnnealingLR[15] Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour[16] Attention Is All You Need[17] On the Variance of the Adaptive Learning Rate and Beyond
Concept
Gradient clipping by global norm
- One norm over all parameter gradients; if it exceeds the limit, multiply every gradient by limit over norm.
- (3,4) has norm 5; with limit 1 it becomes (0.6,0.8). Direction kept, length capped.
- Norm 0.5: untouched.
- Toy case w4, start 3, rate 0.1: unclipped iterates −7.8, 182, −2.41×106; clipped: 2.9, 2.8, 2.7, 2.6, 2.5, 2.4.
- A guard against rare spikes. If it fires on nearly every step of a small model, check the rate and the init.
Sources[18] torch.nn.utils.clip_grad_norm_[19] On the difficulty of training Recurrent Neural Networks
Diagram
Debugging a NaN loss
Concept
A flat loss
- Initial loss against lnC (0.693 for two balanced classes).
- Can it overfit four examples? If not, suspect the data, the loss or the backward pass.
- The learning rate, including a schedule that already decayed to zero.
- The initial weight scale: tiny init or dead units.
- The classic slip: softmax before a loss that expects logits.
Sources[20] torch.nn.CrossEntropyLoss[12] A Recipe for Training Neural Networks
Compare
Bugs that look like a hard problem
| Bug | Check |
|---|---|
| Softmax before the loss | Pass raw logits |
| Evaluating in train mode | Call eval() |
| Data not shuffled | Shuffle each epoch (common practice) |
| Validation data in normalisation statistics | Fit on training data only |
| Wrong inputs | Visualise what goes into the network |
Sources[20] torch.nn.CrossEntropyLoss[21] Cross-validation: evaluating estimator performance[12] A Recipe for Training Neural Networks
Check yourself
Check: a late NaN
A run is healthy for 5,000 steps. The loss climbs for about 20 steps, then turns NaN. What is the first suspect and the first change?
Answer
A rise before the NaN points to an unstable step, usually a learning rate that is too high for the current point (a hard batch, or a schedule that is still near its peak). Lower the peak rate or lengthen warmup, and add global-norm clipping. Save the batch that preceded the spike and replay it.
Code
Clipping and the schedule in a few lines
Python
import math
def clip(grads, max_norm):
norm = math.sqrt(sum(g * g for g in grads))
scale = max_norm / norm if norm > max_norm else 1.0
return [g * scale for g in grads]
def lr_at(step, total, warmup, peak):
if step < warmup:
return peak * (step + 1) / warmup
c = (step - warmup) / (total - warmup)
return 0.5 * peak * (1 + math.cos(math.pi * c))- The homework adds the L2 penalty and a single Adam step with either an L2 penalty or decoupled decay.
Summary
Recap
- Batch norm depends on the batch and on train or eval mode; layer norm does not.
- Dropout and weight decay are training-time regularisers; use AdamW; stop early on validation and report on test; in the experiment weight decay helped the loss, not the accuracy, and dropout changed little.
- Warmup then cosine; clip by global norm to keep the direction and cap the length.
- NaN: find the first bad step, data and loss code at step 0, learning rate if it rose first. Flat: initial loss, overfit four examples, learning rate, initial scale.
References
References & Sources (1 of 5)
torch.nn.BatchNorm1d (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.BatchNorm1d.html
Used for Batch norm formula, statistics per dimension over the mini-batch, evaluation uses running estimates updated with default momentum 0.1, default eps 1e-5, biased variance for normalisation.
torch.nn.LayerNorm (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.LayerNorm.html
Used for Layer norm computes mean and standard deviation over the last D dimensions of each example, uses the same statistics-from-input computation in training and evaluation, default eps 1e-5.
Layer Normalization (opens in a new tab)
Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton2016arXiv:1607.06450Paper
https://arxiv.org/abs/1607.06450
Used for Batch normalisation's effect depends on the mini-batch size and is not obvious to apply to recurrent networks; layer normalisation computes statistics from all summed inputs of one training case (abstract).
Sergey Ioffe, Christian Szegedy2015ICML 2015 (arXiv:1502.03167)Paper
https://arxiv.org/abs/1502.03167
Used for Batch normalisation allows much higher learning rates, reduces sensitivity to initialisation, can act as a regulariser that sometimes removes the need for dropout; the authors attribute the benefit to reducing internal covariate shift (abstract).
torch.nn.Module (train and eval) (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.Module.html
Used for eval() and train() set the mode; the change has an effect only on certain modules such as Dropout and BatchNorm.
References
References & Sources (2 of 5)
torch.no_grad (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.no_grad.html
Used for no_grad disables gradient calculation, which reduces memory consumption for inference.
torch.nn.Dropout (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.Dropout.html
Used for Dropout zeroes elements with probability p during training, scales outputs by 1/(1-p), and is the identity in evaluation; default p 0.5.
Dive into Deep Learning, Dropout (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_multilayer-perceptrons/dropout.html
Used for Dropout zeroes an activation with probability p and divides survivors by 1-p so the expectation is unchanged; it is used only in training; the co-adaptation justification is described as up for debate.
Dropout: A Simple Way to Prevent Neural Networks from Overfitting (opens in a new tab)
Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, et al.2014JMLR 15(56):1929-1958Paper
https://jmlr.org/papers/v15/srivastava14a.html
Used for Dropout randomly drops units in training, prevents units from co-adapting too much, and at test time one unthinned network with scaled-down weights approximates averaging many thinned networks (abstract).
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_multilayer-perceptrons/backprop.html
Used for The weight decay term (lambda/2)||W||^2 adds lambda*W to the gradients.
References
References & Sources (3 of 5)
Decoupled Weight Decay Regularization (opens in a new tab)
Ilya Loshchilov, Frank Hutter2019ICLR 2019 (arXiv:1711.05101)Paper
https://arxiv.org/abs/1711.05101
Used for L2 regularisation and weight decay are equivalent for SGD (with the decay scaled by the learning rate) but not for adaptive methods such as Adam; decoupling weight decay makes the best decay value largely independent of the learning rate and improves Adam's generalisation (abstract).
A Recipe for Training Neural Networks (opens in a new tab)
Andrej Karpathy2019Article
https://karpathy.github.io/2019/04/25/recipe/
Used for Adam at 3e-4 as a safe baseline; dropout used sparingly and not combined well with batch norm; early stopping on validation loss; do not trust learning-rate decay defaults (the rate can reach zero too early); visualise exactly what goes into the network; a well-tuned SGD almost always slightly outperforms Adam for ConvNets, while Adam is much more forgiving.
torch.optim.AdamW (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.optim.AdamW.html
Used for AdamW applies weight decay to the parameters before the moment updates so decay does not accumulate in the momentum or variance; defaults lr 0.001, betas (0.9, 0.999), eps 1e-8, weight_decay 0.01.
torch.optim.lr_scheduler.CosineAnnealingLR (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.optim.lr_scheduler.CosineAnnealingLR.html
Used for The closed form eta_t = eta_min + 0.5 (eta_max - eta_min)(1 + cos(T_cur pi / T_max)) from SGDR; PyTorch implements a recursive approximation of it, without restarts; the page says nothing about warmup.
Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (opens in a new tab)
Priya Goyal, Piotr Dollar, Ross Girshick, Pieter Noordhuis, et al.2017arXiv:1706.02677Preprint
https://arxiv.org/abs/1706.02677
Used for A learning-rate scaling rule and a warmup scheme that overcomes optimisation challenges early in training with large minibatches (abstract; the warmup details are in the full paper).
References
References & Sources (4 of 5)
Attention Is All You Need (opens in a new tab)
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, et al.2017Advances in Neural Information Processing Systems 30 (NIPS 2017)Paper
arXiv 1706.03762 (opens in a new tab)https://arxiv.org/abs/1706.03762
Used for The original transformer trained with Adam (beta1 0.9, beta2 0.98, epsilon 1e-9), warmup_steps 4000, and a learning rate rising linearly then decaying with the inverse square root of the step (section 5.3, read on the HTML version).
On the Variance of the Adaptive Learning Rate and Beyond (opens in a new tab)
Liyuan Liu, Haoming Jiang, Pengcheng He, Weizhu Chen, et al.2020ICLR 2020 (arXiv:1908.03265)Paper
https://arxiv.org/abs/1908.03265
Used for The adaptive learning rate has problematically large variance early in training and the authors propose that warmup works as a variance reduction technique (abstract).
torch.nn.utils.clip_grad_norm_ (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.utils.clip_grad_norm_.html
Used for The gradient norm is computed over all parameters as if concatenated into one vector, gradients are modified in place, and error_if_nonfinite (default False) raises an error when the total norm is nan or inf.
On the difficulty of training Recurrent Neural Networks (opens in a new tab)
Razvan Pascanu, Tomas Mikolov, Yoshua Bengio2013ICML 2013 (arXiv:1211.5063)Paper
https://arxiv.org/abs/1211.5063
Used for Proposes a gradient norm clipping strategy to deal with exploding gradients in recurrent networks (abstract).
torch.nn.CrossEntropyLoss (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.CrossEntropyLoss.html
Used for The input to CrossEntropyLoss is expected to contain the unnormalised logits for each class.
References
References & Sources (5 of 5)
Cross-validation: evaluating estimator performance (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/cross_validation.html
Used for Preprocessing such as scaling should be learned from the training set only and applied to held-out data, so validation statistics do not leak into the model.
Keys: ← → move, Home End first and last, F full screen.