Slides · Deep learning and transformers

Training deep networks: normalisation, regularisation, AdamW and debugging

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:

  1. Compare batch and layer norm and explain train versus eval mode.
  2. Explain dropout, weight decay, early stopping and AdamW, and read an experiment honestly.
  3. Set up a warmup-plus-cosine schedule with clipping, and debug NaN and flat losses.

Compare

Batch norm versus layer norm

Batch normLayer norm
Statistics overBatch, per featureFeatures, per example
Depends on other examplesYesNo
Train and evalDiffer (running estimates)Same
Small batchesNoisyFine
  • Row 0 under batch norm: (−0.447,0.447,−1.183)(-0.447,0.447,-1.183), then (−0.576,0.798,−1.069)(-0.576,0.798,-1.069) after another row changes. Layer norm: (−1.225,0,1.225)(-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.

Sources1 torch.nn.BatchNorm1d2 torch.nn.LayerNorm3 Layer Normalization4 Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift

Concept

Train mode versus eval mode

  • Dropout: zero with probability pp and scale survivors by 1/(1−p)1/(1-p) in training; identity in eval. Mean of a dropped 3.0: 3.005 at p=0.2p=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.

Sources5 torch.nn.Module (train and eval)6 torch.no_grad7 torch.nn.Dropout8 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\lambda 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.

Sources7 torch.nn.Dropout8 Dive into Deep Learning, Dropout9 Dropout: A Simple Way to Prevent Neural Networks from Overfitting10 Dive into Deep Learning, Forward propagation, backward propagation and computational graphs11 Decoupled Weight Decay Regularization12 A Recipe for Training Neural Networks

Worked example

Two moons, 30 training points, 8 seeds

SettingTest lossTest accuracyAt best-validation epoch
None0.6160.8260.380
Weight decay 0.010.4170.8280.382
Dropout 0.30.5950.8220.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\text{AdamW: }\ \theta\leftarrow\theta-\gamma\lambda\theta\ \text{ before the moment updates}
Loss gradient scaleExtra shrinkage per step, Adam+L2AdamW
01.0×10−31.0\times10^{-3}1.0×10−51.0\times10^{-5}
0.0019.95×10−49.95\times10^{-4}1.0×10−51.0\times10^{-5}
0.017.07×10−47.07\times10^{-4}1.0×10−51.0\times10^{-5}
0.19.95×10−59.95\times10^{-5}1.0×10−51.0\times10^{-5}
11.0×10−51.0\times10^{-5}1.0×10−51.0\times10^{-5}
1001.0×10−71.0\times10^{-7}1.0×10−51.0\times10^{-5}
  • w=1w=1, decay 0.01, rate 0.001; a stylised case with the gradient alternating ±G\pm G.
  • Adam+L2 extra step ≈γλw/G2+(λw)2\approx\gamma\lambda w/\sqrt{G^2+(\lambda w)^2}: a full rate where G≪λwG\ll\lambda w, about γλw/G\gamma\lambda w/G where G≫λwG\gg\lambda w. It meets AdamW near G=1G=1 only because of these units.
  • PyTorch AdamW defaults: rate 0.001, betas 0.9 and 0.999, epsilon 10−810^{-8}, decay 0.01.

Sources13 torch.optim.AdamW11 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

Step099325550775999
Rate (peak 10−310^{-3})10−510^{-5}10−310^{-3}8.54×10−48.54\times10^{-4}5×10−45\times10^{-4}1.46×10−41.46\times10^{-4}3×10−93\times10^{-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\beta_2=0.98, inverse-square-root decay.

Sources14 torch.optim.lr_scheduler.CosineAnnealingLR15 Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour16 Attention Is All You Need17 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)(3,4) has norm 5; with limit 1 it becomes (0.6,0.8)(0.6,0.8). Direction kept, length capped.
  • Norm 0.5: untouched.
  • Toy case w4w^4, start 3, rate 0.1: unclipped iterates −7.8, 182, −2.41×106-7.8,\ 182,\ -2.41\times10^{6}; 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.

Sources18 torch.nn.utils.clip_grad_norm_19 On the difficulty of training Recurrent Neural Networks

Diagram

Debugging a NaN loss

Diagram: NaN at step 0 points to the data or the loss code, since no update has happened.

yes

no, after some steps

yes

no, sudden

Loss is NaN or inf

Is it NaN at step 0?

Check data and labels for NaN or inf,
then the loss code: log(0), softmax overflow

Did the loss rise first?

Learning rate too high:
lower it, add warmup, add clipping

Bad batch, division by zero,
exploding activations: check inputs and init

Overfit 4 examples;
run a gradient check

Diagram summary: NaN at step 0 points to the data or the loss code, since no update has happened. NaN after a rise points to the learning rate. A sudden NaN points to a bad batch or a numerical hazard. In every case the next step is to overfit a handful of examples and gradient-check.

Concept

A flat loss

  1. Initial loss against ln⁡C\ln C (0.693 for two balanced classes).
  2. Can it overfit four examples? If not, suspect the data, the loss or the backward pass.
  3. The learning rate, including a schedule that already decayed to zero.
  4. The initial weight scale: tiny init or dead units.
  5. The classic slip: softmax before a loss that expects logits.

Sources20 torch.nn.CrossEntropyLoss12 A Recipe for Training Neural Networks

Compare

Bugs that look like a hard problem

BugCheck
Softmax before the lossPass raw logits
Evaluating in train modeCall eval()
Data not shuffledShuffle each epoch (common practice)
Validation data in normalisation statisticsFit on training data only
Wrong inputsVisualise what goes into the network

Sources20 torch.nn.CrossEntropyLoss21 Cross-validation: evaluating estimator performance12 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)

  1. torch.nn.BatchNorm1d (opens in a new tab)

    PyTorch2026Documentation

    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.

  2. torch.nn.LayerNorm (opens in a new tab)

    PyTorch2026Documentation

    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.

  3. Layer Normalization (opens in a new tab)

    Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton2016arXiv:1607.06450Paper

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

  4. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift (opens in a new tab)

    Sergey Ioffe, Christian Szegedy2015ICML 2015 (arXiv:1502.03167)Paper

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

  5. torch.nn.Module (train and eval) (opens in a new tab)

    PyTorch2026Documentation

    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)

  1. torch.no_grad (opens in a new tab)

    PyTorch2026Documentation

    Used for no_grad disables gradient calculation, which reduces memory consumption for inference.

  2. torch.nn.Dropout (opens in a new tab)

    PyTorch2026Documentation

    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.

  3. Dive into Deep Learning, Dropout (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    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.

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

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

  5. Dive into Deep Learning, Forward propagation, backward propagation and computational graphs (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    Used for The weight decay term (lambda/2)||W||^2 adds lambda*W to the gradients.

References

References & Sources (3 of 5)

  1. Decoupled Weight Decay Regularization (opens in a new tab)

    Ilya Loshchilov, Frank Hutter2019ICLR 2019 (arXiv:1711.05101)Paper

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

  2. A Recipe for Training Neural Networks (opens in a new tab)

    Andrej Karpathy2019Article

    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.

  3. torch.optim.AdamW (opens in a new tab)

    PyTorch2026Documentation

    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.

  4. torch.optim.lr_scheduler.CosineAnnealingLR (opens in a new tab)

    PyTorch2026Documentation

    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.

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

    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)

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

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

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

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

  3. torch.nn.utils.clip_grad_norm_ (opens in a new tab)

    PyTorch2026Documentation

    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.

  4. On the difficulty of training Recurrent Neural Networks (opens in a new tab)

    Razvan Pascanu, Tomas Mikolov, Yoshua Bengio2013ICML 2013 (arXiv:1211.5063)Paper

    Used for Proposes a gradient norm clipping strategy to deal with exploding gradients in recurrent networks (abstract).

  5. torch.nn.CrossEntropyLoss (opens in a new tab)

    PyTorch2026Documentation

    Used for The input to CrossEntropyLoss is expected to contain the unnormalised logits for each class.

References

References & Sources (5 of 5)

  1. Cross-validation: evaluating estimator performance (opens in a new tab)

    scikit-learn2026Documentation

    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.