Slides · Deep learning and transformers
CNNs, ResNets, transfer learning and recurrent networks, with RMSNorm and label smoothing
1 / 23
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:
- Compute output size, parameters and receptive field for a conv stack.
- Explain skip connections, transfer learning and augmentation.
- Explain gradients through time and write the LSTM and GRU updates.
- Compare RMSNorm with layer norm and write the label-smoothed loss.
Math
Shapes and parameters
nout=⌊sn+2p−k⌋+1,params=khkwcincout+cout- 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.
Sources[1] Dive into Deep Learning, From Fully Connected Layers to Convolutions[2] Dive into Deep Learning, Padding and Stride[3] CS231n: Convolutional Neural Networks for Visual Recognition, Convolutional Networks[4] Dive into Deep Learning, Multiple Input and Multiple Output Channels[5] torch.nn.Conv2d
Worked example
Pooling and the receptive field
Track r (start 1) and the jump j (start 1). Per layer: r←r+(k−1)j, then j←js.
| Stack | Receptive field |
|---|---|
| three 3 by 3, stride 1 | 7 |
| three 3 by 3, stride 2 | 15 |
| 3 by 3 conv, then 2 by 2 pool (stride 2) | 4 |
| 2 by 2 pool (stride 2), then 3 by 3 conv | 6 |
- Three 3 by 3 layers match one 7 by 7 with 27C2 weights against 49C2.
- Pooling has no parameters and is invariant only to shifts inside a window.
Sources[6] Dive into Deep Learning, Pooling[3] 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 after the first layer and 56 after the second. The receptive field is 3+(3−1)⋅2=7 input pixels along each axis, even though two stride-1 layers would see 5.
Diagram
A residual block
Sources[7] Deep Residual Learning for Image Recognition[8] 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)−x. Doing nothing means F≈0, which is easy to reach.
- Gradient: ∂y/∂x=I+∂F/∂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.
Sources[7] Deep Residual Learning for Image Recognition[8] 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) 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≈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
- 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.
Sources[9] Dive into Deep Learning, Fine-Tuning[10] Dive into Deep Learning, Image Augmentation
Math
Gradients through time
∂h0∂hT=t=1∏Tdiag(1−ht2)Wh- Near zero state: the factor is w. w=0.9: 0.349 at 10 steps, 0.00515 at 50. w=1.5: 57.7 at 10 steps, 6.38×108 at 50.
- Near zero state needs zero input. With constant input 0.1 the state settles at h≈0.894 (w=1.5) or 0.996 (w=3), where w(1−h2)=0.302 or 0.025: 7.55×10−24 and 6.55×10−75 at 50 steps. The large weight causes the saturation.
- Clipping caps the exploding side only. It cannot raise a vanished gradient.
Sources[11] Dive into Deep Learning, Backpropagation Through Time[12] On the difficulty of training Recurrent Neural Networks
Diagram
The LSTM cell
Sources[13] Dive into Deep Learning, Long Short-Term Memory (LSTM)[14] torch.nn.LSTM
Compare
LSTM versus GRU, and the parameter count
| LSTM | GRU | |
|---|---|---|
| State | ct and ht | ht only |
| Gates | input, forget, output | reset, update |
| Update | ct=f⊙ct−1+i⊙g | ht=(1−z)⊙n+z⊙ht−1 |
| Blocks | 4 | 3 |
| Params (d=10, H=20, PyTorch) | 2,560 | 1,920 |
- Direct gradient path: diag(ft). A product of 0.99 over 100 steps is 0.366; 0.5 gives 7.89×10−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).
Sources[13] Dive into Deep Learning, Long Short-Term Memory (LSTM)[15] Dive into Deep Learning, Gated Recurrent Units (GRU)[16] torch.nn.GRU[14] torch.nn.LSTM[17] 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.349 and 0.950≈0.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.
Source[18] An Empirical Exploration of Recurrent Network Architectures
Compare
RMSNorm versus layer norm
| Layer norm | RMSNorm | |
|---|---|---|
| Subtracts the mean | Yes | No |
| Divides by | standard deviation | root mean square, ϵ+n1∑xi2 |
| x→10x | unchanged | unchanged |
| x→x+5 | unchanged | changes |
- On (1,2,3,6): layer norm gives (−1.069,−0.535,0,1.604), RMSNorm (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.
Sources[19] Root Mean Square Layer Normalization[20] torch.nn.RMSNorm[21] LLaMA: Open and Efficient Foundation Language Models
Worked example
Label smoothing
Target qk=(1−ε)1[k=y]+ε/K. With K=10, ε=0.1: 0.91 and 0.01.
- Gradient wrt the logits is p−q, zero when p=q: the best logit gap is ln(0.91/0.01)=4.511.
- Loss floor is the entropy of q: 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 and reports a gain of about 0.2 percentage points on ILSVRC 2012. Loss values are not comparable across smoothing settings.
Sources[22] Rethinking the Inception Architecture for Computer Vision[23] 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.84, each other class 0.2/5=0.04 (they sum to 1). The loss is minimised when the prediction matches, a gap of ln(0.84/0.04)=ln21≈3.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; 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⊙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)
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
https://d2l.ai/chapter_convolutional-neural-networks/why-conv.html
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.
Dive into Deep Learning, Padding and Stride (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_convolutional-neural-networks/padding-and-strides.html
Used for The output-shape formula with padding and stride, written with total padding and rounding down, and the padding and stride examples.
Stanford CS231n2026Book
https://cs231n.github.io/convolutional-networks/
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.
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
https://d2l.ai/chapter_convolutional-neural-networks/channels.html
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.
torch.nn.Conv2d (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.Conv2d.html
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)
Dive into Deep Learning, Pooling (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_convolutional-neural-networks/pooling.html
Used for Pooling has no parameters, works on each channel separately, reduces sensitivity to location and downsamples; max pooling is usually preferred.
Deep Residual Learning for Image Recognition (opens in a new tab)
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun2015arXiv:1512.03385Paper
https://arxiv.org/abs/1512.03385
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).
Dive into Deep Learning, Residual Networks (ResNet) and ResNeXt (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_convolutional-modern/resnet.html
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.
Dive into Deep Learning, Fine-Tuning (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_computer-vision/fine-tuning.html
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).
Dive into Deep Learning, Image Augmentation (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_computer-vision/image-augmentation.html
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)
Dive into Deep Learning, Backpropagation Through Time (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_recurrent-neural-networks/bptt.html
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.
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 Analysis of why recurrent networks are difficult to train, with a gradient norm clipping strategy for exploding gradients (abstract).
Dive into Deep Learning, Long Short-Term Memory (LSTM) (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_recurrent-modern/lstm.html
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.
torch.nn.LSTM (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.LSTM.html
Used for The LSTM equations, weight_ih shape (4H, input), weight_hh shape (4H, H), and two bias vectors of length 4H per layer.
Dive into Deep Learning, Gated Recurrent Units (GRU) (opens in a new tab)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_recurrent-modern/gru.html
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)
torch.nn.GRU (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.GRU.html
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.
torch.nn.RNN (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.RNN.html
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).
An Empirical Exploration of Recurrent Network Architectures (opens in a new tab)
Rafal Jozefowicz, Wojciech Zaremba, Ilya Sutskever2015ICML 2015 (PMLR 37:2342-2350)Paper
https://proceedings.mlr.press/v37/jozefowicz15.html
Used for Adding a bias of 1 to the LSTM's forget gate closes the gap between the LSTM and the GRU (abstract).
Root Mean Square Layer Normalization (opens in a new tab)
Biao Zhang, Rico Sennrich2019NeurIPS 2019 (arXiv:1910.07467)Paper
https://arxiv.org/abs/1910.07467
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).
torch.nn.RMSNorm (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.RMSNorm.html
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)
LLaMA: Open and Efficient Foundation Language Models (opens in a new tab)
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Guillaume Lample2023arXiv:2302.13971Paper
https://arxiv.org/abs/2302.13971
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).
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
https://arxiv.org/abs/1512.00567
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).
torch.nn.CrossEntropyLoss (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.CrossEntropyLoss.html
Used for The label_smoothing argument, described as mixing the ground truth with a uniform distribution, with default 0.0.
Keys: ← → move, Home End first and last, F full screen.