Slides · Deep learning and transformers

CNNs, ResNets, transfer learning and recurrent networks, with RMSNorm and label smoothing

CNNs, ResNets and recurrent networks

Convolution, skip connections, transfer learning, LSTM and GRU gates, RMSNorm and label smoothing.

Concept

Why this is worth 75 minutes

  • Counting parameters, shapes and receptive fields, and explaining why skip connections and LSTM gates work, are standard interview questions (common industry pattern).
  • Both architectures save parameters by sharing weights, and both pay for it in how gradients behave.
  • It adds two pieces commonly used with these architectures: RMSNorm and label smoothing.

Four things you will be able to do:

  1. Compute output size, parameters and receptive field for a conv stack.
  2. Explain skip connections, transfer learning and augmentation.
  3. Explain gradients through time and write the LSTM and GRU updates.
  4. Compare RMSNorm with layer norm and write the label-smoothed loss.

Math

Shapes and parameters

nout=⌊n+2p−ks⌋+1,params=khkwcincout+coutn_{\text{out}}=\left\lfloor\frac{n+2p-k}{s}\right\rfloor+1,\qquad \text{params}=k_hk_wc_{\text{in}}c_{\text{out}}+c_{\text{out}}
  • Height and width are separate calculations. An input of 10, kernel 3, stride 2, padding 1 gives 5: the window past the edge is dropped.
  • A 3 by 3 conv from 3 to 64 channels: 1,792 parameters, whatever the image size.
  • A dense layer to the same 32 by 32 by 64 output would need 201,326,592 weights: weight sharing is the saving.

Sources1 Dive into Deep Learning, From Fully Connected Layers to Convolutions2 Dive into Deep Learning, Padding and Stride3 CS231n: Convolutional Neural Networks for Visual Recognition, Convolutional Networks4 Dive into Deep Learning, Multiple Input and Multiple Output Channels5 torch.nn.Conv2d

Worked example

Pooling and the receptive field

Track rr (start 1) and the jump jj (start 1). Per layer: r←r+(k−1)jr\leftarrow r+(k-1)j, then j←jsj\leftarrow js.

StackReceptive field
three 3 by 3, stride 17
three 3 by 3, stride 215
3 by 3 conv, then 2 by 2 pool (stride 2)4
2 by 2 pool (stride 2), then 3 by 3 conv6
  • Three 3 by 3 layers match one 7 by 7 with 27C227C^2 weights against 49C249C^2.
  • Pooling has no parameters and is invariant only to shifts inside a window.

Sources6 Dive into Deep Learning, Pooling3 CS231n: Convolutional Neural Networks for Visual Recognition, Convolutional Networks

Check yourself

Check: two strided layers

An image is 224 by 224. Two 3 by 3 convolutions, each with stride 2 and padding 1, are applied one after the other. What is the output size, and what does one output unit see?

Answer

224 gives ⌊(224+2−3)/2⌋+1=112\lfloor(224+2-3)/2\rfloor+1=112 after the first layer and 56 after the second. The receptive field is 3+(3−1)⋅2=73+(3-1)\cdot2=7 input pixels along each axis, even though two stride-1 layers would see 5.

Diagram

A residual block

Diagram: The input takes two routes, through the layers and across the shortcut, and the two are added.

gradient: g + J_F^T g

x

F(x): conv, norm, ReLU, conv, norm

+

y = x + F(x)

Diagram summary: The input takes two routes, through the layers and across the shortcut, and the two are added. Backward, the gradient takes both routes too, so the gradient reaching the input always contains the incoming gradient itself plus whatever returns through the layers.

Sources7 Deep Residual Learning for Image Recognition8 Dive into Deep Learning, Residual Networks (ResNet) and ResNeXt

Concept

Why it trains deeper

  • Degradation: deeper plain networks reach higher training error, and the paper says this is not overfitting.
  • Reformulation: fit F(x)=H(x)−xF(x)=H(x)-x. Doing nothing means F≈0F\approx0, which is easy to reach.
  • Gradient: ∂y/∂x=I+∂F/∂x\partial y/\partial x=I+\partial F/\partial x, so the stack contains an identity path (derived here).
  • ImageNet validation top-1: plain-34 28.54, ResNet-34 25.03.
  • It does not cap the gradient: an unscaled residual stack returned a gradient norm of 22.6 at depth 50, against 0.0183 for the plain stack.

Sources7 Deep Residual Learning for Image Recognition8 Dive into Deep Learning, Residual Networks (ResNet) and ResNeXt

Check yourself

Check: what a block can do

A residual block’s layers are initialised so that F(x)F(x) is close to zero for every input. What function does the block compute at the start of training, and why is that a useful start?

Answer

Approximately the identity, y≈xy\approx x. Adding the block therefore does not make the network worse at the start, and the layers only have to learn a correction. A plain block would have to learn the identity from scratch.

Concept

Transfer learning and augmentation

  1. Pretrain on a large source task. 2. Copy everything but the output layer. 3. Random-initialise a new output layer. 4. Train the new layer from scratch (larger rate, 10 times in the book) and fine-tune the rest (small rate).
  • Hot dog task, same architecture, d2l’s PyTorch run: 0.940 fine-tuned against 0.850 from scratch; its MXNet run: 0.944 against 0.860 (single runs).
  • Freeze the backbone with little data, fine-tune with more (common practice).
  • Augmentation: random flips, crops, colour changes that keep the label, on training data only. A left-right flip is wrong for digits or text.

Sources9 Dive into Deep Learning, Fine-Tuning10 Dive into Deep Learning, Image Augmentation

Math

Gradients through time

∂hT∂h0=∏t=1Tdiag⁡(1−ht2) Wh\frac{\partial h_T}{\partial h_0}=\prod_{t=1}^{T}\operatorname{diag}(1-h_t^2)\,W_h
  • Near zero state: the factor is ww. w=0.9w=0.9: 0.349 at 10 steps, 0.00515 at 50. w=1.5w=1.5: 57.7 at 10 steps, 6.38×1086.38\times10^{8} at 50.
  • Near zero state needs zero input. With constant input 0.1 the state settles at h≈0.894h\approx0.894 (w=1.5w=1.5) or 0.9960.996 (w=3w=3), where w(1−h2)=0.302w(1-h^2)=0.302 or 0.0250.025: 7.55×10−247.55\times10^{-24} and 6.55×10−756.55\times10^{-75} at 50 steps. The large weight causes the saturation.
  • Clipping caps the exploding side only. It cannot raise a vanished gradient.

Sources11 Dive into Deep Learning, Backpropagation Through Time12 On the difficulty of training Recurrent Neural Networks

Diagram

The LSTM cell

Diagram: The old cell state is scaled by the forget gate and added to the candidate scaled by the input gate.

c(t-1)

x f

forget gate f

input gate i

x i

candidate g = tanh

+

c(t)

tanh

output gate o

x o

h(t)

Diagram summary: The old cell state is scaled by the forget gate and added to the candidate scaled by the input gate. The hidden state is tanh of the new cell state scaled by the output gate. The cell state path has one multiplication and one addition per step and no squashing.

Sources13 Dive into Deep Learning, Long Short-Term Memory (LSTM)14 torch.nn.LSTM

Compare

LSTM versus GRU, and the parameter count

LSTMGRU
Statectc_t and hth_thth_t only
Gatesinput, forget, outputreset, update
Updatect=f⊙ct−1+i⊙gc_t=f\odot c_{t-1}+i\odot ght=(1−z)⊙n+z⊙ht−1h_t=(1-z)\odot n+z\odot h_{t-1}
Blocks43
Params (d=10d=10, H=20H=20, PyTorch)2,5601,920
  • Direct gradient path: diag⁡(ft)\operatorname{diag}(f_t). A product of 0.99 over 100 steps is 0.366; 0.5 gives 7.89×10−317.89\times10^{-31}.
  • The full derivative has extra terms through the gates, so this is the direct path only.
  • PyTorch keeps two bias vectors per gate, so the textbook counts (2,480 and 1,860) are lower. So does nn.RNN (640 against 620).

Sources13 Dive into Deep Learning, Long Short-Term Memory (LSTM)15 Dive into Deep Learning, Gated Recurrent Units (GRU)16 torch.nn.GRU14 torch.nn.LSTM17 torch.nn.RNN

Check yourself

Check: forgetting over ten and fifty steps

All forget gates equal 0.9, over 10 steps and then over 50 steps. Roughly how much of the direct gradient path survives, and what would you change in the model?

Answer

0.910≈0.3490.9^{10}\approx0.349 and 0.950≈0.005150.9^{50}\approx0.00515. To keep information longer, the forget gates must sit closer to 1 on the relevant units. That is a learned quantity, which a high initial forget bias can encourage, as the script’s forget bias of 3 does, and Jozefowicz et al. report that a forget bias of 1 closes the gap between LSTM and GRU. It is a possibility, not a guarantee.

Source18 An Empirical Exploration of Recurrent Network Architectures

Compare

RMSNorm versus layer norm

Layer normRMSNorm
Subtracts the meanYesNo
Divides bystandard deviationroot mean square, ϵ+1n∑xi2\sqrt{\epsilon+\tfrac1n\sum x_i^2}
x→10xx\to10xunchangedunchanged
x→x+5x\to x+5unchangedchanges
  • On (1,2,3,6)(1,2,3,6): layer norm gives (−1.069,−0.535,0,1.604)(-1.069,-0.535,0,1.604), RMSNorm (0.283,0.566,0.849,1.697)(0.283,0.566,0.849,1.697).
  • Paper: re-centring is dispensable; comparable quality, 7% to 64% less running time on its models. LLaMA uses RMSNorm.

Sources19 Root Mean Square Layer Normalization20 torch.nn.RMSNorm21 LLaMA: Open and Efficient Foundation Language Models

Worked example

Label smoothing

Target qk=(1−ε)1[k=y]+ε/Kq_k=(1-\varepsilon)\mathbb 1[k=y]+\varepsilon/K. With K=10K=10, ε=0.1\varepsilon=0.1: 0.910.91 and 0.010.01.

  • Gradient wrt the logits is p−qp-q, zero when p=qp=q: the best logit gap is ln⁡(0.91/0.01)=4.511\ln(0.91/0.01)=4.511.
  • Loss floor is the entropy of qq: 0.5003, not 0.
  • Logit gap 2, 4.51, 8, 12: smoothed loss 0.9766, 0.5003, 0.7230, 1.0801; hard loss 0.7966, 0.0943, 0.0030, 0.0001.
  • The paper used ε=0.1\varepsilon=0.1 and reports a gain of about 0.2 percentage points on ILSVRC 2012. Loss values are not comparable across smoothing settings.

Sources22 Rethinking the Inception Architecture for Computer Vision23 torch.nn.CrossEntropyLoss

Check yourself

Check: a different setting

With 5 classes and smoothing 0.2, what is the target, and what logit gap is the loss minimised at?

Answer

True class 0.8+0.2/5=0.840.8+0.2/5=0.84, each other class 0.2/5=0.040.2/5=0.04 (they sum to 1). The loss is minimised when the prediction matches, a gap of ln⁡(0.84/0.04)=ln⁡21≈3.04\ln(0.84/0.04)=\ln21\approx3.04 between the true logit and each other logit. Derived here from the formula in the lesson.

Code

Shapes and receptive field in a few lines

Python

def conv_out(n, k, s=1, p=0):
    return (n + 2 * p - k) // s + 1

def receptive_field(layers):
    r, jump = 1, 1
    for k, s in layers:
        r += (k - 1) * jump
        jump *= s
    return r
  • The homework adds the parameter count, a 2-D convolution, one LSTM step, RMSNorm and label-smoothed cross-entropy.

Summary

Recap

  • Conv output ⌊(n+2p−k)/s⌋+1\lfloor(n+2p-k)/s\rfloor+1; parameters do not depend on the image size; receptive field grows with kernel and stride, and order matters.
  • A skip connection gives an identity path and an easy “do nothing” start; it does not cap the gradient. Fine-tune with a new head at a larger rate; augmentation is training-only and label-preserving.
  • RNN gradients are a product of per-step factors; clipping handles only the exploding side. The LSTM cell path f⊙ct−1+i⊙gf\odot c_{t-1}+i\odot g and the GRU interpolation let information and gradient persist.
  • RMSNorm drops the mean and is not shift-invariant. Label smoothing has a finite best logit gap and a loss floor above zero.

References

References & Sources (1 of 5)

  1. Dive into Deep Learning, From Fully Connected Layers to Convolutions (opens in a new tab)

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

    Used for Translation invariance or equivariance and locality motivate convolution; the kernel is shared across positions and the parameter count drops sharply; the cost is an inductive bias that helps only if it matches the data.

  2. Dive into Deep Learning, Padding and Stride (opens in a new tab)

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

    Used for The output-shape formula with padding and stride, written with total padding and rounding down, and the padding and stride examples.

  3. CS231n: Convolutional Neural Networks for Visual Recognition, Convolutional Networks (opens in a new tab)

    Stanford CS231n2026Book

    Used for The output-size formula (W - F + 2P)/S + 1, the AlexNet first-layer example (55x55x96, 105,705,600 parameters without sharing, 34,944 with it), pooling with zero parameters, and three stacked 3x3 layers having a 7x7 view with 27C^2 against 49C^2 weights.

  4. Dive into Deep Learning, Multiple Input and Multiple Output Channels (opens in a new tab)

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

    Used for The kernel shape c_o x c_i x k_h x k_w, outputs summed over input channels, and a 1x1 convolution as a per-pixel dense layer that matches a matrix multiplication.

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

    PyTorch2026Documentation

    Used for The Conv2d output-height formula and weight shape; padding 'same' does not support strides other than 1; bias on by default.

References

References & Sources (2 of 5)

  1. Dive into Deep Learning, Pooling (opens in a new tab)

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

    Used for Pooling has no parameters, works on each channel separately, reduces sensitivity to location and downsamples; max pooling is usually preferred.

  2. Deep Residual Learning for Image Recognition (opens in a new tab)

    Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun2015arXiv:1512.03385Paper

    Used for The residual reformulation, the degradation problem not being overfitting, vanishing gradients being largely addressed by normalised initialisation and normalisation layers, identity shortcuts adding no parameters, and the ImageNet top-1 errors 27.94, 28.54, 27.88 and 25.03 (10-crop validation).

  3. Dive into Deep Learning, Residual Networks (ResNet) and ResNeXt (opens in a new tab)

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

    Used for The residual mapping, why the identity is easier to learn, the 1x1 convolution on the shortcut when the shape changes, and conv, batch norm, ReLU ordering.

  4. Dive into Deep Learning, Fine-Tuning (opens in a new tab)

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

    Used for The four-step fine-tuning recipe, a small rate for pretrained layers and a larger one (10 times) for the new output layer, and the hot dog accuracies from d2l's PyTorch run (0.940 fine-tuned at base rate 5e-5, 0.850 from scratch at 5e-4) and its MXNet run (0.944 at 0.01, 0.860 at 0.1).

  5. Dive into Deep Learning, Image Augmentation (opens in a new tab)

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

    Used for Augmentation produces similar but distinct training examples, flips, crops and colour changes, is applied to training examples only, and the book's CIFAR-10 run included no un-augmented comparison.

References

References & Sources (3 of 5)

  1. Dive into Deep Learning, Backpropagation Through Time (opens in a new tab)

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

    Used for Backpropagation through time on the unrolled network, shared parameters with summed gradients, matrix powers with eigenvalues below 1 vanishing and above 1 diverging, and truncation as an approximation.

  2. 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 Analysis of why recurrent networks are difficult to train, with a gradient norm clipping strategy for exploding gradients (abstract).

  3. Dive into Deep Learning, Long Short-Term Memory (LSTM) (opens in a new tab)

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

    Used for The LSTM equations, the purposes of the three gates, hidden state in (-1, 1), the self-connected edge of weight 1 letting the gradient pass many steps, and the shapes of the weights.

  4. torch.nn.LSTM (opens in a new tab)

    PyTorch2026Documentation

    Used for The LSTM equations, weight_ih shape (4H, input), weight_hh shape (4H, H), and two bias vectors of length 4H per layer.

  5. Dive into Deep Learning, Gated Recurrent Units (GRU) (opens in a new tab)

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

    Used for The GRU equations with reset and update gates, the update gate as an interpolation between old state and candidate, and the GRU as a lighter alternative to the LSTM.

References

References & Sources (4 of 5)

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

    PyTorch2026Documentation

    Used for The GRU equations with h_t = (1 - z) n + z h_(t-1), shapes of 3H, and the note that n_t applies the reset gate after the W_hn multiplication, differing from the original paper.

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

    PyTorch2026Documentation

    Used for nn.RNN stores bias_ih and bias_hh, each of length hidden_size, with the update h_t = tanh(x_t W_ih^T + b_ih + h_(t-1) W_hh^T + b_hh).

  3. An Empirical Exploration of Recurrent Network Architectures (opens in a new tab)

    Rafal Jozefowicz, Wojciech Zaremba, Ilya Sutskever2015ICML 2015 (PMLR 37:2342-2350)Paper

    Used for Adding a bias of 1 to the LSTM's forget gate closes the gap between the LSTM and the GRU (abstract).

  4. Root Mean Square Layer Normalization (opens in a new tab)

    Biao Zhang, Rico Sennrich2019NeurIPS 2019 (arXiv:1910.07467)Paper

    Used for RMSNorm drops mean-centring, keeps re-scaling invariance, performs comparably to LayerNorm and reduces running time by 7% to 64% on different models (abstract).

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

    PyTorch2026Documentation

    Used for The RMSNorm formula with RMS = sqrt(eps + mean of squares), default eps of None meaning the machine epsilon of the computation type, a per-element weight and no documented bias.

References

References & Sources (5 of 5)

  1. LLaMA: Open and Efficient Foundation Language Models (opens in a new tab)

    Hugo Touvron, Thibaut Lavril, Gautier Izacard, Guillaume Lample2023arXiv:2302.13971Paper

    Used for LLaMA normalises the input of each transformer sub-layer and uses the RMSNorm function introduced by Zhang and Sennrich 2019 (section 2.2, read on the ar5iv HTML).

  2. Rethinking the Inception Architecture for Computer Vision (opens in a new tab)

    Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, et al.2016arXiv:1512.00567Paper

    Used for Label smoothing as a mixture of the one-hot target and a uniform distribution, epsilon 0.1 on ImageNet, the overconfidence motive, and a gain of about 0.2 percentage points in top-1 and top-5 error (ar5iv text of section 7).

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

    PyTorch2026Documentation

    Used for The label_smoothing argument, described as mixing the ground truth with a uniform distribution, with default 0.0.