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

  • Intermediate
  • 1 h 15 min
  • Lesson 3 of 4 in Deep learning and transformers
  • Last verified

Open slides(23 slides)

Before you start

You will be able to

  • Compute the output size, parameter count and receptive field of a stack of convolution and pooling layers with padding and stride, and explain what weight sharing buys compared with a dense layer.
  • Explain why a skip connection y = x + F(x) keeps a gradient path through a deep stack, and describe how transfer learning and data augmentation reuse a pretrained model or enlarge the effective training set.
  • Explain vanishing and exploding gradients through time as a product of per-step factors, write the LSTM and GRU updates, say why the additive cell path helps, and count their parameters.
  • Compare RMSNorm with layer norm, and write the label-smoothed target and loss, including the loss floor and the logit gap it asks for.

Concept

The previous lesson kept a dense network stable and well generalised. This lesson covers the two architectures built on a different assumption about the data, plus two extra pieces commonly used with these architectures, RMSNorm and label smoothing. Convolutional networks assume the input has local structure that repeats across positions (images). Recurrent networks assume the input is a sequence and reuse one set of weights at every step. Both save parameters by sharing weights, and both pay for it in how gradients behave.

IdeaWhat it assumes or fixesWhere it is used
ConvolutionThe same local pattern matters at every positionImages, audio, any grid
PoolingSmall shifts should not change the answerAfter convolutions
Skip connection (ResNet)Very deep stacks are hard to optimiseAlmost every deep vision model
Transfer learningFeatures learned on a big task help a small oneSmall labelled datasets
RNN, LSTM, GRUOrder matters and sequences vary in lengthOlder sequence models
RMSNormRe-centring in layer norm is not neededNormalisation inside large models
Label smoothingHard 0 and 1 targets push logits without limitClassification losses
Data augmentationSome changes to the input keep the labelTraining-time regularisation

Why It Matters

Convolution, residual blocks and gated recurrence are the standard vocabulary of deep learning, and the questions are standard in interviews (common industry pattern): count the parameters of a layer, say what a receptive field is, explain why ResNets train deeper than plain stacks, say why an LSTM does not forget as fast as an RNN. The two extra pieces matter in practice because label smoothing is one argument to a loss function and RMSNorm is a one-line swap in a transformer block. Recurrent networks are mostly replaced by transformers, but the vanishing-gradient argument behind gating is the cleanest example of a mechanism you will use again.

Mental Model

Keep the relay from the earlier lessons: a message passed along a line of people, each multiplying it by a number. In a plain deep stack each person transforms the message and hands it on. A skip connection lets each person also pass the original message straight through, so the line always has a channel that carries the message unchanged. A recurrent network is one person standing in a loop, applying the same transformation at every tick: after 100 ticks the message has been multiplied by that person’s factor 100 times, so it either fades or shouts. A gate is a dial that lets the person say “keep what I held” at nearly 1 each tick, which makes the dial’s setting the thing that decides how long a message survives. A convolution is one small stamp pressed at every position of the picture, instead of a different stamp for each position.

Convolution: weight sharing, shapes and parameters

A dense layer connects every input to every output. A convolution layer slides one small kernel over the input and computes a weighted sum at each position. Two assumptions produce the saving: the output at a position depends only on a small window (locality), and the same weights are used at every position, so a pattern is detected the same way wherever it appears (Dive into Deep Learning, from fully connected layers to convolutions). That second property is weight sharing. It makes the layer translation equivariant: shift the input and the output shifts by the same amount. The book notes that the price is an inductive bias that helps only if it matches the data.

Deep learning libraries compute cross-correlation and call it convolution: the kernel is not flipped. In the script, an asymmetric Sobel-like kernel on an 8 by 8 image gives the same 6 by 6 output pattern one row lower when the input is shifted down one row (section 2 prints True).

Shapes: padding and stride

Along one axis, with input length nn, kernel size kk, padding pp zeros on each side and stride ss:

nout=⌊n+2p−ks⌋+1n_{\text{out}}=\left\lfloor \frac{n+2p-k}{s}\right\rfloor+1

The book writes the same quantity with total padding (Dive into Deep Learning, padding and stride) and CS231n gives the version above for symmetric padding (CS231n). Height and width are separate calculations, so a non-square image or kernel gives a different size on each axis. The script reproduces the examples: a 7 input with a 3 kernel gives 5 at stride 1 and 3 at stride 2, and 227 with an 11 kernel at stride 4 gives 55 (the CS231n AlexNet example). It also shows what rounding does. An input of 10 with kernel 3, stride 2 and padding 1 gives ⌊9/2⌋+1=5\lfloor 9/2\rfloor+1=5: the window that would start past the edge is dropped. An image 8 high and 6 wide with a 3 by 5 kernel and padding (1, 2) keeps its shape, 8 by 6. PyTorch’s padding='same' does the same for you but is not supported with a stride other than 1 (PyTorch, Conv2d).

Parameters

With cinc_{\text{in}} input channels, each output channel has one kernel of shape kh×kw×cink_h\times k_w\times c_{\text{in}} (Dive into Deep Learning, channels), so the count does not depend on the image size:

params=kh kw cin cout+cout\text{params}=k_h\,k_w\,c_{\text{in}}\,c_{\text{out}}+c_{\text{out}}

A 3 by 3 convolution from 3 to 64 channels has 27⋅64+64=1,79227\cdot 64+64=1{,}792 parameters, a 5 by 5 from 16 to 32 has 12,832 and a 1 by 1 from 256 to 64 has 16,448. A 1 by 1 convolution mixes channels at each pixel and is a per-pixel dense layer; the book verifies that it matches a matrix multiplication. To see what sharing saves, take a dense layer from a 32 by 32 by 3 image to a 32 by 32 by 64 map: 3072×65536=201,326,5923072\times 65536=201{,}326{,}592 weights and 65,536 biases, against 1,792 for the convolution with the same output shape (about 112,384 times fewer, derived here). CS231n gives the real-network version: AlexNet’s first layer would need 105,705,600 parameters without sharing and has 34,944 with it.

Pooling and the receptive field

Pooling slides a window and outputs the maximum or average of each region. It has no parameters, works on each channel separately so the channel count is unchanged, and halves the height and width for a 2 by 2 window at stride 2 (Dive into Deep Learning, pooling; CS231n). The book says it reduces sensitivity to location and downsamples. The sensitivity reduction is partial. In the script a single bright pixel at position 2 or 3 gives the same max-pooled output, while moving it from 3 to 4 changes it: pooling is invariant to shifts inside a window, not to every shift.

The receptive field of a unit is the part of the input that can affect it. For a stack described by (kernel, stride) pairs, track the receptive field rr (starting at 1) and the jump jj, the distance in input pixels between neighbouring positions of the current layer (starting at 1). Each layer does r←r+(k−1)jr\leftarrow r+(k-1)j and then j←j sj\leftarrow j\,s. This recurrence is derived here. It reproduces the CS231n statement that a neuron in the third of three stacked 3 by 3 layers sees 7 by 7 of the input, and shows that stride makes the field grow faster: three 3 by 3 layers at stride 2 reach 15. Order matters: a 3 by 3 convolution followed by a 2 by 2 pool at stride 2 sees 4 pixels, but the pool first and then the convolution sees 6.

The small-filter argument follows. One 7 by 7 layer and three 3 by 3 layers have the same 7 by 7 field, but with CC channels the first has 49C249C^2 weights and the stack 27C227C^2 (CS231n). For C=64C=64 that is 200,704 against 110,592 (biases ignored). The stack also has two extra non-linearities, and CS231n notes that it may need more memory for intermediate results during backpropagation.

Residual connections: why gradients flow

Stacking more layers should not make a network worse, since the extra layers could copy their input. In practice He et al. report degradation: deeper plain networks reach higher training error, and “such degradation is not caused by overfitting” (He et al., introduction). They also say vanishing and exploding gradients “have been largely addressed by normalized initialization and intermediate normalization layers”. The fix is a reformulation: if the desired mapping is H(x)H(x), let the layers fit the residual F(x)=H(x)−xF(x)=H(x)-x and output y=x+F(x)y=x+F(x). If the best thing to do is nothing, the layers only need to push FF toward zero (Dive into Deep Learning, ResNet). The shortcut adds no parameters when it is the identity, and projection shortcuts were not essential for the degradation problem (He et al., sections 3.2 and 4.1). In their ImageNet table the 34-layer plain network had 28.54 per cent top-1 error and the 34-layer ResNet 25.03, with 18-layer versions at 27.94 and 27.88 (validation, 10-crop).

Diagram: The input xxx goes down two routes at once: through the layers FFF and straight across the shortcut.

gradient: g + J_F^T g

x

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

+

y = x + F(x)

Diagram summary: The input xx goes down two routes at once: through the layers FF and straight across the shortcut. The two results are added to give yy. Going backward, the gradient also takes both routes, so the gradient reaching xx is the incoming gradient gg plus whatever comes back through FF.

The gradient argument (derived here). For y=x+F(x)y=x+F(x) the Jacobian is ∂y/∂x=I+∂F/∂x\partial y/\partial x=I+\partial F/\partial x, so the backward step is gx=gy+JF⊤gyg_x=g_y+J_F^{\top}g_y. The identity term means a copy of gyg_y is always added unchanged. The total can still shrink if the branch term points against it, but it cannot be driven to zero by a small JFJ_F. For a plain layer y=F(x)y=F(x) the backward step is JF⊤gyJ_F^{\top}g_y alone, a product of per-layer factors as in the first lesson. Across LL blocks the product ∏l(I+Jl)\prod_l (I+J_l) expands into a sum that contains a pure identity path through all of them. When a block’s FF is small, the stack starts close to the identity function, an easy place to start.

The script tests this on a stack of width-16 tanh layers with Gaussian weights of variance 1/n1/n, sending a unit-norm gradient back from the output and averaging over 20 seeds. At depth 10 the plain stack returns a gradient of norm 0.202 at the input and the residual stack 3.76. At depth 50 the plain stack returns 0.0183 and the residual stack 22.6. Two caveats. The residual gradient does not vanish, but it can grow, because the branch here is not scaled down; real residual networks pair the shortcut with normalisation and care over initialisation, so this is a demonstration of the identity path and not a recipe. And the He et al. paper explains the benefit as easier optimisation, not as a gradient-norm theorem, so treat “gradients flow through the shortcut” as the standard mechanism and not as the paper’s own proof. A scalar example makes the point exactly: with F′(x)=−0.5F'(x)=-0.5 the layer’s derivative is 1+F′(x)=0.51+F'(x)=0.5, and with F′(x)=0F'(x)=0 it is 1.

When a block changes the number of channels or the resolution, the shortcut cannot be added as is, and a 1 by 1 convolution (with stride 2 to halve the height and width) reshapes it (the book).

Transfer learning and data augmentation

Transfer learning

The book’s recipe for fine-tuning has four steps: pretrain a source model on a large dataset, copy everything except the output layer into a new target model, initialise a new output layer at random, and train the new layer from scratch while the other layers are fine-tuned (Dive into Deep Learning, fine-tuning). The pretrained layers get a small learning rate. The new layer, being random, gets a larger one: 10 times the base rate in the book’s code. The reasoning is that the early layers hold general features such as edges and textures that carry over, and only the task-specific end must be learned.

The book’s example uses ResNet-18 pretrained on ImageNet, replaces its 1,000-way output with 2 outputs for hot dog versus not, and trains on 1,000 images of each class for 5 epochs. The test accuracy was 0.940 when fine-tuned with base rate 5e-5 (the book’s PyTorch run) and 0.944 with 0.01 (its MXNet run), against 0.850 for the same architecture trained from scratch at 5e-4 (PyTorch) and 0.860 at 0.1 (MXNet). So each fine-tuned figure should be compared with the scratch figure from its own framework. These are single runs on one task, but the gap is large and consistent with the idea. The book’s explanation is that the fine-tuned model starts from more effective parameters.

Two options sit on a spectrum. Freeze the pretrained layers and train only the new head: cheap, safe with very little data, and the head is small (for a 512-feature backbone and 2 classes it is 512⋅2+2=1,026512\cdot2+2=1{,}026 parameters, derived here). Fine-tune everything with a small rate: more flexible, needs more data and more care. Freezing first and unfreezing when more data is available is common practice; the book’s freezing variant is left as an exercise. If the backbone has batch norm, keep it in eval mode while frozen so its running statistics do not drift (common practice, following the train and eval behaviour in the previous lesson).

Data augmentation

Augmentation applies random label-preserving changes to training inputs (flips, crops, brightness, contrast, saturation and hue changes) to produce “similar but distinct training examples”, and it is credited with helping models rely less on particular attributes (Dive into Deep Learning, image augmentation). It is applied to training examples only, so predictions are deterministic. This is the same train-versus-eval split as dropout in the previous lesson, and it is another reason validation loss can sit below training loss. The idea is arithmetic: padding a 32 by 32 image by 4 pixels on each side allows 9×9=819\times9=81 different 32 by 32 crops and 162 with a left-right flip (derived here).

The key judgement is whether a change keeps the label. A left-right flip is fine for a cat, since the book says it usually does not change the category, but not for digits or text, which is derived here. The book’s example trains ResNet-18 on CIFAR-10 with random flips; it reports 0.925 train and 0.810 test accuracy in one run and 0.940 and 0.848 in another run on a different framework, and includes no run without augmentation, so it is not evidence of how much augmentation helped. Treat the benefit as something to measure by comparing validation scores with and without it.

Recurrent networks: gradients through time

A recurrent network reuses the same weights at every step: ht=tanh⁡(Whht−1+Wxxt+b)h_t=\tanh(W_h h_{t-1}+W_x x_t+b). The parameter count therefore does not depend on the sequence length (the book: “the same parameters are repeated throughout the unrolled network”, and their gradients are summed across all occurrences). Backpropagation through time is ordinary backpropagation on the unrolled network, and the long sequence is the problem: the input from the first step passes through over 1,000 matrix products on a sequence of that length (Dive into Deep Learning, BPTT).

The derivative of the last state with respect to the first is a product of one Jacobian per step, ∂hT/∂h0=∏t=1Tdiag⁡(1−ht2) Wh\partial h_T/\partial h_0=\prod_{t=1}^{T}\operatorname{diag}(1-h_t^2)\,W_h, where 1−ht21-h_t^2 is the derivative of tanh at step tt (derived here). In the book’s linear case this is a power of the weight matrix and “eigenvalues smaller than 1 vanish and eigenvalues larger than 1 diverge”. Pascanu et al. analyse the same difficulty for recurrent networks and propose clipping the gradient norm for the exploding side (Pascanu et al., abstract).

With one hidden unit the product is ∏tw(1−ht2)\prod_t w(1-h_t^2) and the numbers are easy to read. If the state stays near 0, tanh’s slope is 1 and the product is wTw^T: for w=0.9w=0.9 it is 0.349 at 10 steps, 0.00515 at 50 and 2.66×10−52.66\times10^{-5} at 100, and for w=1.5w=1.5 it is 57.7, 6.38×1086.38\times10^{8} and 4.07×10174.07\times10^{17}. That near-zero case needs zero input, so the state stays at 0. With a constant input of 0.1 the state leaves 0 and, for a large recurrent weight, settles near a fixed point: h≈0.894h\approx0.894 for w=1.5w=1.5 and h≈0.996h\approx0.996 for w=3w=3. There 1−h21-h^2 is 0.201 and 0.008, so the per-step factor w(1−h2)w(1-h^2) is 0.302 and 0.025, far below 1, and the gradient vanishes: 7.55×10−247.55\times10^{-24} and 6.55×10−756.55\times10^{-75} at 50 steps. The saturation is caused by the large recurrent weight pushing the state toward ±1\pm1, not by the input. So the failure is not always an explosion for a large weight: saturation makes tanh shrink the gradient, and whether the product grows or shrinks depends on where the state sits, so the learner cannot assume either. Clipping fixes only the exploding side, because it can scale a large gradient down but cannot scale a vanished one up (derived here). The usual practical limits are shorter sequences and truncated backpropagation through time, which the book notes approximates the true gradient and makes the model favour short-term effects.

LSTM and GRU: gates and an additive path

The LSTM adds a cell state ctc_t that is updated by addition. PyTorch’s equations, with σ\sigma the sigmoid and ⊙\odot elementwise product, are (PyTorch, LSTM):

it=σ(Wiixt+bii+Whiht−1+bhi)input gateft=σ(Wifxt+bif+Whfht−1+bhf)forget gategt=tanh⁡(Wigxt+big+Whght−1+bhg)candidateot=σ(Wioxt+bio+Whoht−1+bho)output gatect=ft⊙ct−1+it⊙gtht=ot⊙tanh⁡(ct)\begin{aligned} i_t&=\sigma(W_{ii}x_t+b_{ii}+W_{hi}h_{t-1}+b_{hi}) &&\text{input gate}\\ f_t&=\sigma(W_{if}x_t+b_{if}+W_{hf}h_{t-1}+b_{hf}) &&\text{forget gate}\\ g_t&=\tanh(W_{ig}x_t+b_{ig}+W_{hg}h_{t-1}+b_{hg}) &&\text{candidate}\\ o_t&=\sigma(W_{io}x_t+b_{io}+W_{ho}h_{t-1}+b_{ho}) &&\text{output gate}\\ c_t&=f_t\odot c_{t-1}+i_t\odot g_t\\ h_t&=o_t\odot\tanh(c_t) \end{aligned}

Each sigmoid gate outputs values in (0,1)(0,1) and acts as a dial; the book describes the input gate as how much of the candidate to add, the forget gate as whether to keep or clear the memory, and the output gate as whether the memory affects the output (Dive into Deep Learning, LSTM). The hidden state hth_t lies in (−1,1)(-1,1) because tanh⁡\tanh is applied before the output gate; the cell state ctc_t has no such bound.

Diagram: The old cell state ct−1c_{t-1}ct−1​ is multiplied by the forget gate and added to the candidate multiplied by the input gate to give...

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 ct−1c_{t-1} is multiplied by the forget gate and added to the candidate multiplied by the input gate to give ctc_t. The new hidden state hth_t is tanh⁡(ct)\tanh(c_t) multiplied by the output gate. The cell state travels along the top with one multiplication and one addition per step, and no matrix multiplication or squashing on that path.

Why this helps. In the cell update, the direct derivative of ctc_t with respect to ct−1c_{t-1} is diag⁡(ft)\operatorname{diag}(f_t). If the forget gates stay near 1, a gradient survives many steps: a product of 0.99 over 100 steps is 0.366, but 0.9 gives 2.66×10−52.66\times10^{-5} and 0.5 gives 7.89×10−317.89\times10^{-31} (script). The book describes the original design as a self-connected edge of fixed weight 1 so the gradient can pass many steps without vanishing or exploding, and says in practice the design alleviates the vanishing-gradient problem. Two points are easy to get wrong. First, the gates are themselves computed from ht−1h_{t-1}, and ht−1h_{t-1} depends on ct−1c_{t-1}, so the full derivative has extra terms and the product of forget gates is only the direct path (derived here). In the script, a one-unit LSTM over 30 steps with the forget bias set to 3 had a finite-difference ∂cT/∂c0\partial c_T/\partial c_0 of 0.1347 (weights scaled by 0.1) or 0.1804 (scale 1), while the direct-path product was 0.2235 and 0.1187: the same order, not equal. With the forget bias at 0 and weight scale 1 both were around 10−1110^{-11}. The bias of 3 was chosen here to show the effect; Jozefowicz et al. report that adding a bias of 1 to the LSTM’s forget gate closes the gap between the LSTM and the GRU (Jozefowicz et al., abstract). Second, the gate values are learned, so “keeps the gradient” describes what the architecture makes possible, not a guarantee.

The GRU uses two gates and no separate cell. PyTorch’s version, with reset gate rtr_t, update gate ztz_t and new candidate ntn_t, is (PyTorch, GRU):

rt=σ(Wirxt+bir+Whrht−1+bhr)zt=σ(Wizxt+biz+Whzht−1+bhz)nt=tanh⁡(Winxt+bin+rt⊙(Whnht−1+bhn))ht=(1−zt)⊙nt+zt⊙ht−1\begin{aligned} r_t&=\sigma(W_{ir}x_t+b_{ir}+W_{hr}h_{t-1}+b_{hr})\\ z_t&=\sigma(W_{iz}x_t+b_{iz}+W_{hz}h_{t-1}+b_{hz})\\ n_t&=\tanh(W_{in}x_t+b_{in}+r_t\odot(W_{hn}h_{t-1}+b_{hn}))\\ h_t&=(1-z_t)\odot n_t+z_t\odot h_{t-1} \end{aligned}

The last line is an interpolation: where ztz_t is near 1 the old state is kept and the input is ignored, and where it is near 0 the state is replaced by the candidate (the book’s description). The convention matters: some papers swap the roles of zz and 1−z1-z, and PyTorch’s page notes that its ntn_t differs from the original paper because it applies the reset gate after the WhnW_{hn} multiplication, “on purpose for efficiency”. The book applies it before. When reading someone else’s equations, check which convention they use.

Parameter counts

The textbook equations have one bias vector per gate; PyTorch has two (bias_ih and bias_hh), whose shapes are (4H)(4H) each for the LSTM and (3H)(3H) for the GRU, with weight_ih_l0 of shape (4H,d)(4H, d) and weight_hh of shape (4H,H)(4H, H) (3 in place of 4 for the GRU; PyTorch, RNN shows the same two biases with shapes (H)(H)). With input size dd and hidden size HH:

LayerTextbook (one bias)PyTorch layout (two biases)d=10, H=20d=10,\ H=20
Vanilla RNNH(d+H+1)H(d+H+1)H(d+H+2)H(d+H+2) (nn.RNN also has bias_ih and bias_hh)620 and 640
LSTM4(dH+H2+H)4(dH+H^2+H)4H(d+H+2)4H(d+H+2)2,480 and 2,560
GRU3(dH+H2+H)3(dH+H^2+H)3H(d+H+2)3H(d+H+2)1,860 and 1,920

The 4 and 3 are the number of gate-sized blocks, and the totals are derived here from the shapes on the documentation pages, not read from a model. So an LSTM has four times the weights of a vanilla RNN of the same size and a GRU three times, and the count does not depend on the sequence length. The book describes the GRU as a streamlined LSTM that often performs comparably and is faster to compute.

RMSNorm and label smoothing

RMSNorm

Layer norm subtracts the mean and divides by the standard deviation. RMSNorm drops the mean subtraction and divides by the root mean square: yi=xiRMS(x)γiy_i=\dfrac{x_i}{\mathrm{RMS}(x)}\gamma_i with RMS(x)=ϵ+1n∑ixi2\mathrm{RMS}(x)=\sqrt{\epsilon+\tfrac1n\sum_i x_i^2} (PyTorch, RMSNorm). Zhang and Sennrich hypothesise that “re-centering invariance in LayerNorm is dispensable”, keep re-scaling invariance, and report that RMSNorm performs comparably and reduces running time by 7% to 64% on different models (Zhang and Sennrich, abstract). PyTorch’s page documents a per-element weight and no bias, and its default ϵ\epsilon, when left unset, is the machine epsilon of the computation type.

The script uses x=(1,2,3,6)x=(1,2,3,6) and ϵ=10−5\epsilon=10^{-5}. Layer norm gives (−1.069,−0.535,0,1.604)(-1.069,-0.535,0,1.604) with mean 0. RMSNorm gives (0.283,0.566,0.849,1.697)(0.283,0.566,0.849,1.697) with mean 0.849: the output is not centred. Multiplying xx by 10 leaves both outputs unchanged (True for both). Adding 5 to every entry leaves layer norm unchanged and turns the RMSNorm output into (0.730,0.852,0.974,1.339)(0.730,0.852,0.974,1.339), so RMSNorm is invariant to scale but not to a shift of the whole vector. The hypothesis is that the network can live without the shift invariance. LLaMA states that it uses RMSNorm, introduced by Zhang and Sennrich, to normalise the input of each transformer sub-layer (Touvron et al., section 2.2); the transformer lesson looks at where the normalisation sits. The saving is a mean computation and a subtraction per vector. The paper’s 7% to 64% range is a running-time measurement across its own models, so do not expect a fixed number.

Label smoothing

With hard labels the target is a one-hot vector, and cross-entropy keeps rewarding a bigger gap between the true logit and the others without limit. Label smoothing replaces the target with a mixture of the one-hot vector and a uniform distribution over the KK classes (Szegedy et al., which uses ε=0.1\varepsilon=0.1 on ImageNet):

qk=(1−ε) 1[k=y]+εKq_k=(1-\varepsilon)\,\mathbb 1[k=y]+\frac{\varepsilon}{K}

PyTorch exposes this as the label_smoothing argument of CrossEntropyLoss, described as a mixture of the ground truth and a uniform distribution (PyTorch, CrossEntropyLoss). The authors’ stated motive is that the model “becomes too confident about its predictions”, and they report a consistent gain of about 0.2 per cent absolute in top-1 and top-5 error on ILSVRC 2012.

Four consequences follow (derived here, checked in the script for K=10K=10, ε=0.1\varepsilon=0.1):

  • The target is (0.91,0.01,…,0.01)(0.91, 0.01, \dots, 0.01). Note the true class gets 1−ε+ε/K1-\varepsilon+\varepsilon/K, not 1−ε1-\varepsilon.
  • The gradient of cross-entropy with respect to the logits is p−qp-q, so it is zero when the prediction equals qq. The best logit gap is finite, ln⁡(0.91/0.01)=4.511\ln(0.91/0.01)=4.511, where hard labels would push it to infinity.
  • The loss has a floor: the entropy of qq, which is 0.5003, not 0. A smoothed training loss of 0.50 is perfect, so loss values cannot be compared across smoothing settings.
  • Past the optimum the loss rises again. At logit gaps of 2, 4.51, 8 and 12 the hard-label loss is 0.7966, 0.0943, 0.0030 and 0.0001, while the smoothed loss is 0.9766, 0.5003, 0.7230 and 1.0801, and the smoothed gradient on the true logit changes sign from −0.4591-0.4591 to 0.00000.0000, 0.08700.0870 and 0.08990.0899.

Code

This standard-library script produced every number in the lesson that is computed here. Figures quoted from sources are not from the script: AlexNet’s 105,705,600 and 34,944 parameters, the ResNet error table, the hot dog accuracies, the 7% to 64% running-time range and the 0.2% label-smoothing gain. It has fixed seeds and runs in well under a second (Python 3.14).

Python

import math
import random
import statistics
import time

T0 = time.time()


def conv_out(n, k, s=1, p=0):
    """Output length along one axis, p padding on EACH side."""
    return (n + 2 * p - k) // s + 1


def conv_params(k_h, k_w, c_in, c_out, bias=True):
    return k_h * k_w * c_in * c_out + (c_out if bias else 0)


print("== 1. Shapes and parameter counts ==")
print("7x7 input, 3x3 kernel, stride 1, pad 0 ->", conv_out(7, 3), "; stride 2 ->", conv_out(7, 3, 2))
print("8x8, 3x3, pad 1, stride 1 ->", conv_out(8, 3, 1, 1), "; stride 2 ->", conv_out(8, 3, 2, 1))
print("10, kernel 3, stride 2, pad 1 ->", conv_out(10, 3, 2, 1), "(9/2 rounds down to 4, plus 1)")
print("227, kernel 11, stride 4, pad 0 ->", conv_out(227, 11, 4, 0))
print("image 8 high x 6 wide, kernel 3 high x 5 wide, pad (1, 2), stride 1 ->", conv_out(8, 3, 1, 1), "high x", conv_out(6, 5, 1, 2), "wide")
print("3x3 conv, 3 -> 64 channels: %d parameters" % conv_params(3, 3, 3, 64))
print("5x5 conv, 16 -> 32 channels: %d parameters" % conv_params(5, 5, 16, 32))
print("1x1 conv, 256 -> 64 channels: %d parameters" % conv_params(1, 1, 256, 64))
n_in, n_out = 32 * 32 * 3, 32 * 32 * 64
print("a dense layer from a 32x32x3 image to a 32x32x64 map: %d weights + %d biases" % (n_in * n_out, n_out))
print("the 3x3 conv giving the same output shape (pad 1): %d parameters, about %.0f times fewer" % (conv_params(3, 3, 3, 64), (n_in * n_out + n_out) / conv_params(3, 3, 3, 64)))
print("transfer learning head: 512 features to 2 classes = %d parameters" % (512 * 2 + 2))
print("pooling parameters: 0; 2x2 stride 2 pooling on 8x8 ->", conv_out(8, 2, 2), "x", conv_out(8, 2, 2), ", channels unchanged")


def conv2d(img, ker):
    kh, kw = len(ker), len(ker[0])
    H, W = len(img), len(img[0])
    return [[sum(ker[a][b] * img[i + a][j + b] for a in range(kh) for b in range(kw)) for j in range(W - kw + 1)] for i in range(H - kh + 1)]


def maxpool1d(v, k=2, s=2):
    return [max(v[i:i + k]) for i in range(0, len(v) - k + 1, s)]


print("\n== 2. Equivariance and pooling ==")
ker = [[1.0, 0.0, -1.0], [2.0, 0.0, -2.0], [1.0, 0.0, -1.0]]
img = [[0.0] * 8 for _ in range(8)]
for r, c in ((2, 2), (2, 3), (3, 2), (3, 3), (4, 3)):
    img[r][c] = 1.0
shifted = [[0.0] * 8 for _ in range(8)]
for r in range(7):
    for c in range(8):
        shifted[r + 1][c] = img[r][c]
a, b = conv2d(img, ker), conv2d(shifted, ker)
same = all(abs(a[i][j] - b[i + 1][j]) < 1e-12 for i in range(5) for j in range(6))
print("shifting the input down 1 row shifts the 6x6 output down 1 row:", same)
print("sample output row:", a[2], "-> shifted:", b[3])
for pos in range(1, 6):
    v = [0.0] * 8
    v[pos] = 1.0
    print("  pixel at %d -> max-pool(2, stride 2) %s" % (pos, maxpool1d(v)))
print("pooling: the pixel moved from 2 to 3 changes nothing, 3 to 4 changes the output; invariance only holds for shifts inside a window")

print("\n== 3. Receptive field ==")
def receptive_field(layers):
    r, j = 1, 1
    for k, s in layers:
        r += (k - 1) * j
        j *= s
    return r
for name, L in (("3 x (3x3, stride 1)", [(3, 1)] * 3), ("one 7x7", [(7, 1)]), ("3 x (3x3, stride 2)", [(3, 2)] * 3),
                ("3x3 conv, then 2x2 pool stride 2", [(3, 1), (2, 2)]), ("2x2 pool stride 2, then 3x3 conv", [(2, 2), (3, 1)])):
    print("  %-34s receptive field %d" % (name, receptive_field(L)))
C = 64
print("weights, C = 64 channels in and out: one 7x7 = %d, three 3x3 = %d" % (49 * C * C, 27 * C * C))


def matvec(W, v):
    return [sum(w * x for w, x in zip(r, v)) for r in W]


def norm(v):
    return math.sqrt(sum(a * a for a in v))


print("\n== 4. Gradient through a deep stack, plain versus residual ==")
print("scalar: y = x + F(x) has dy/dx = 1 + F'(x); with F'(x) = -0.5 that is 0.5, with F' = 0 it is 1")
def grad_ratio(depth, residual, seed, n=16):
    rng = random.Random(seed)
    Ws = [[[rng.gauss(0, 1 / math.sqrt(n)) for _ in range(n)] for _ in range(n)] for _ in range(depth)]
    x = [rng.gauss(0, 1) for _ in range(n)]
    h, acts = x, []
    for W in Ws:
        z = matvec(W, h)
        t = [math.tanh(v) for v in z]
        acts.append((h, t))
        h = [a + b for a, b in zip(h, t)] if residual else t
    g = [1.0 / math.sqrt(n)] * n
    for W, (hin, t) in zip(reversed(Ws), reversed(acts)):
        dz = [gi * (1 - ti * ti) for gi, ti in zip(g, t)]
        WT = [list(col) for col in zip(*W)]
        branch = matvec(WT, dz)
        g = [a + b for a, b in zip(g, branch)] if residual else branch
    return norm(g)
for depth in (10, 50):
    for res in (False, True):
        r = [grad_ratio(depth, res, s) for s in range(20)]
        print("  depth %2d %-8s mean gradient norm at the input, for unit norm at the output, over 20 seeds: %.3g" % (depth, "residual" if res else "plain", statistics.fmean(r)))

print("\n== 5. Recurrent gradients ==")
def rnn_grad(w, T, x=0.1):
    h, d = 0.0, 1.0
    for _ in range(T):
        h = math.tanh(w * h + x)
        d *= w * (1 - h * h)
    return d
for w in (0.9, 1.5, 3.0):
    print("  scalar tanh RNN, w = %.1f, input 0.1: |dh_T/dh_0| at T = 10, 50, 100: %s" % (w, ["%.3g" % abs(rnn_grad(w, T)) for T in (10, 50, 100)]))
for w in (1.5, 3.0):
    h = 0.0
    for _ in range(500):
        h = math.tanh(w * h + 0.1)
    print("  w = %.1f, constant input 0.1: the state settles at h = %.3f, where 1 - h^2 = %.3f and w(1 - h^2) = %.3f" % (w, h, 1 - h * h, w * (1 - h * h)))
for w in (0.9, 1.5):
    print("  with zero input the state stays at 0 and tanh' = 1, so the derivative is w^T: w = %.1f, T = 10, 50, 100: %s" % (w, ["%.3g" % w ** T for T in (10, 50, 100)]))
for f in (0.99, 0.9, 0.5):
    print("  product of %.2f forget gates over T = 10, 50, 100: %s" % (f, ["%.3g" % f ** T for T in (10, 50, 100)]))

def sig(z):
    return 1 / (1 + math.exp(-z))
def lstm_scalar(P, xs, c0, h0=0.0):
    c, h = c0, h0
    fs = []
    for x in xs:
        i = sig(P["xi"] * x + P["hi"] * h + P["bi"])
        f = sig(P["xf"] * x + P["hf"] * h + P["bf"])
        o = sig(P["xo"] * x + P["ho"] * h + P["bo"])
        g = math.tanh(P["xg"] * x + P["hg"] * h + P["bg"])
        c = f * c + i * g
        h = o * math.tanh(c)
        fs.append(f)
    return c, fs
rng = random.Random(4)
T = 30
xs = [rng.gauss(0, 1) for _ in range(T)]
for scale, bf in ((0.1, 3.0), (1.0, 3.0), (1.0, 0.0)):
    P = {k: rng.gauss(0, 1) * scale for k in ("xi", "hi", "xf", "hf", "xo", "ho", "xg", "hg")}
    P.update(bi=0.0, bo=0.0, bg=0.0, bf=bf)
    c0 = 0.5
    cT, fs = lstm_scalar(P, xs, c0)
    eps = 1e-6
    fd = (lstm_scalar(P, xs, c0 + eps)[0] - lstm_scalar(P, xs, c0 - eps)[0]) / (2 * eps)
    prod = 1.0
    for f in fs:
        prod *= f
    print("  scalar LSTM T=30, weight scale %.1f, forget bias %.0f: dc_T/dc_0 (finite difference) %.4g; product of forget gates %.4g" % (scale, bf, fd, prod))

print("\n== 6. Parameter counts, input d = 10, hidden h = 20 ==")
d, h = 10, 20
print("  vanilla RNN, one bias: %d; two biases (nn.RNN keeps bias_ih and bias_hh too): %d" % (h * (d + h + 1), h * (d + h + 2)))
print("  LSTM, one bias per gate (textbook): %d; two biases (PyTorch): %d" % (4 * (d * h + h * h + h), 4 * h * (d + h + 2)))
print("  GRU, two biases (PyTorch): %d; textbook (one bias): %d" % (3 * h * (d + h + 2), 3 * (d * h + h * h + h)))

print("\n== 7. LayerNorm versus RMSNorm ==")
def layer_norm(x, eps=1e-5):
    m = statistics.fmean(x)
    v = statistics.pvariance(x)
    return [(a - m) / math.sqrt(v + eps) for a in x]
def rms_norm(x, eps=1e-5):
    r = math.sqrt(eps + statistics.fmean(a * a for a in x))
    return [a / r for a in x]
x = [1.0, 2.0, 3.0, 6.0]
print("  x =", x)
print("  layer norm:", [round(v, 3) for v in layer_norm(x)], "mean %.3f" % statistics.fmean(layer_norm(x)))
print("  RMS norm  :", [round(v, 3) for v in rms_norm(x)], "mean %.3f" % statistics.fmean(rms_norm(x)))
xs10 = [10 * a for a in x]
print("  both unchanged by x -> 10x:", max(abs(a - b) for a, b in zip(layer_norm(x), layer_norm(xs10))) < 1e-4, max(abs(a - b) for a, b in zip(rms_norm(x), rms_norm(xs10))) < 1e-4)
xp = [a + 5 for a in x]
print("  after adding 5 to every entry: layer norm output unchanged:", max(abs(a - b) for a, b in zip(layer_norm(x), layer_norm(xp))) < 1e-9, "; RMS norm output becomes", [round(v, 3) for v in rms_norm(xp)])

print("\n== 8. Label smoothing ==")
K, eps_ls = 10, 0.1
q = [1 - eps_ls + eps_ls / K] + [eps_ls / K] * (K - 1)
print("  K = 10, epsilon = 0.1 -> target:", [round(v, 3) for v in q[:3]], "... sum", round(sum(q), 6))
H = -sum(v * math.log(v) for v in q)
print("  smallest achievable smoothed cross-entropy (entropy of the target): %.4f; hard-label floor: 0" % H)
print("  logit gap at that optimum: ln(0.91/0.01) = %.3f" % math.log(q[0] / q[1]))
for gap in (2.0, 4.511, 8.0, 12.0):
    pz = [math.exp(gap)] + [1.0] * (K - 1)
    s = sum(pz)
    p = [v / s for v in pz]
    hard = -math.log(p[0])
    smooth = -sum(qi * math.log(pi) for qi, pi in zip(q, p))
    print("  logit gap %5.2f: p_true %.4f  hard loss %.4f  smoothed loss %.4f  gradient on true logit hard %.4f smoothed %.4f" % (gap, p[0], hard, smooth, p[0] - 1, p[0] - q[0]))

print("\n== 9. Augmentation arithmetic ==")
print("  32x32 image padded by 4 each side: %d distinct 32x32 crops; with a left-right flip %d" % ((2 * 4 + 1) ** 2, 2 * (2 * 4 + 1) ** 2))
print("  a 3x3 patch flipped left-right:", [r[::-1] for r in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]])

print("\ntotal %.1f s" % (time.time() - T0))

What to look for: section 1 (shapes and parameter counts), section 2 (the shifted image and where max pooling hides a shift), section 3 (receptive fields), section 4 (gradient norms with and without a shortcut), section 5 (recurrent gradients, the forget-gate product and the finite-difference check), section 6 (parameter counts), section 7 (layer norm against RMSNorm), section 8 (the smoothed loss and its floor), section 9 (augmentation arithmetic). In PyTorch the equivalents are nn.Conv2d, nn.MaxPool2d, nn.LSTM, nn.GRU, nn.RMSNorm and CrossEntropyLoss(label_smoothing=...).

Real-World Application

For an image task with a few thousand labelled examples, start from a pretrained convolutional backbone, replace the head, train the head first and then fine-tune with a small rate while checking validation accuracy (common practice), and add flips and crops that keep the label. Count parameters and receptive fields before you design a new stack: if the receptive field of the last layer is much smaller than the object, no amount of depth at that resolution will see the whole thing. For sequences, a transformer is the default today, but gated recurrent layers still appear in small or streaming models, and the vanishing-gradient argument is what interviewers ask about. Add label smoothing as one hyperparameter when a classifier is overconfident, and remember that its loss values are not comparable with unsmoothed runs.

Interview Perspective

Expect “how many parameters does this conv layer have”, “what is the output shape”, “what is a receptive field”, “why does a skip connection help”, “why do RNNs have vanishing gradients and how does an LSTM fix it”, “LSTM versus GRU”, “how does transfer learning work and what do you freeze”, “what does label smoothing do” and “RMSNorm versus LayerNorm”. A strong answer gives the formula, plugs in numbers, and states the trade-off. A weak answer says “LSTMs remember longer” without naming the additive path and the forget gate.

Provenance: Common industry pattern. These are standard fundamentals for ML roles, not a verified list for any named company.

Practice Questions

  • Basic: A 5 by 5 convolution takes 16 channels in and gives 32 out. How many parameters does it have, with bias, and does that change with the image size?
  • Basic: What is the output size of a 3 by 3 convolution with stride 2 and padding 1 on a 10 by 10 input?
  • Intermediate: Why do three stacked 3 by 3 convolutions have the same receptive field as one 7 by 7, and what is the parameter comparison?
  • Intermediate: Write the Jacobian of y=x+F(x)y=x+F(x) and explain what it says about gradient flow. What would you say if asked whether it removes vanishing gradients?
  • Intermediate: Give the LSTM cell update and explain which term carries the gradient across many steps, and why the forget bias matters.
  • Advanced: Why can a recurrent network with a large recurrent weight still have vanishing gradients? When would clipping help and when would it not?
  • Product-Company (Generated practice): You have 2,000 labelled product photos and a pretrained ResNet. Lay out the training plan: what you freeze, which rates you use, which augmentations you allow and which you reject, and how you decide whether the augmentation helped.
  • Product-Company (Generated practice): Your classifier trained with label smoothing 0.1 has a lower validation accuracy and a higher training loss than the run without it. Is something wrong?

Activity

Run the script, then change the receptive-field stacks in section 3 to a stack you would use (for example, a stride-2 convolution followed by a 2 by 2 pool) and check the answer by hand with the recurrence. Next, change the residual stack in section 4 by multiplying the branch by 0.1 and say what happens to the gradient norm at depth 50. Finally, set the forget bias to 3 and to 0 in section 5 and see what the finite-difference derivative does at T=60T=60.

Homework

Implement the pieces from this lesson in homework/: convolution output size, parameter count, receptive field, a 2-D convolution with stride and padding, a single LSTM step, RMSNorm and label-smoothed cross-entropy. Run the tests until they pass; they use non-square inputs, uneven strides, an asymmetric kernel and distinct gate weights, so a wrong axis, a flipped kernel or a swapped gate fails.

Quick Revision

  • Conv output ⌊(n+2p−k)/s⌋+1\lfloor(n+2p-k)/s\rfloor+1 per axis; parameters khkwcincout+coutk_hk_wc_{\text{in}}c_{\text{out}}+c_{\text{out}}, independent of image size; pooling has none. Receptive field: r←r+(k−1)jr\leftarrow r+(k-1)j, j←jsj\leftarrow js.
  • Weight sharing gives translation equivariance and a huge saving (1,792 against 201 million in the example); pooling gives invariance only within a window.
  • y=x+F(x)y=x+F(x) has Jacobian I+JFI+J_F: an identity path; it eases optimisation (He et al.), it does not guarantee small gradients.
  • Fine-tune: new head at a larger rate, pretrained layers at a small one; augmentation is training-only and must preserve the label.
  • RNN: product of diag⁡(1−h2)Wh\operatorname{diag}(1-h^2)W_h per step; vanishing or exploding; clip for exploding only. LSTM: ct=f⊙ct−1+i⊙gc_t=f\odot c_{t-1}+i\odot g, direct path ff. GRU: ht=(1−z)⊙n+z⊙ht−1h_t=(1-z)\odot n+z\odot h_{t-1}.
  • LSTM has 4 gate blocks, GRU 3; PyTorch has two biases per gate.
  • RMSNorm: no mean subtraction, scale-invariant, not shift-invariant. Label smoothing: q=(1−ε)one-hot+ε/Kq=(1-\varepsilon)\text{one-hot}+\varepsilon/K, finite optimal gap, loss floor equal to the entropy of qq.

Check yourself

  • Walk-through: Without notes, compute the output size and parameter count of a 5 by 5, stride 1, padding 2 convolution from 8 to 16 channels on a 40 by 40 image, and give the receptive field after that layer followed by a 2 by 2 pool at stride 2.
  • Variation: An LSTM trained on long sequences still shows tiny gradients to early steps. List two possible causes related to gates and one check for each.
  • Common misconception: “A skip connection removes vanishing gradients”, “max pooling makes the network translation invariant”, “label smoothing of 0.1 gives the true class a target of 0.9”, and “RMSNorm is layer norm with a different name”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

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

    PyTorch2026Documentation

    Shows the convention differences, such as where the reset gate acts, that trip people up when comparing papers and libraries.

Further reading

Research papers

More for this module: Deep learning and transformers resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Deep learning and transformers.

Check yourself15 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 15 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveCompute the output size, parameter count and receptive field of a stack of convolution and pooling layers with padding and stride, and explain what weight sharing buys compared with a dense layer.

  1. Question 1 of 15A convolution layer has a 3 by 3 kernel, stride 2 and padding 1 on each side. What is its output length along an axis whose input length is 12?

    Choose one answer.

  2. Question 2 of 15A layer takes a 64-channel feature map and applies 128 filters of size 3 high by 5 wide, with bias. How many parameters does it have, and how does the count change if the feature map is 4 times larger in height and width?

    Choose one answer.

  3. Question 3 of 15A model applies a 2 by 2 max pool with stride 2, then a 3 by 3 convolution with stride 1. A second model uses the same two layers in the opposite order. Which statement about the receptive field of the final unit (along one axis) is correct?

    Choose one answer.

  4. Question 4 of 15Which statements about convolution and pooling are true? Select all that apply.

    Choose all that apply.

ObjectiveExplain why a skip connection y = x + F(x) keeps a gradient path through a deep stack, and describe how transfer learning and data augmentation reuse a pretrained model or enlarge the effective training set.

  1. Question 5 of 15A plain 40-layer network has higher training error than a 20-layer one. A teammate adds identity skip connections around pairs of layers and says this fixes it because 'skips remove vanishing gradients'. What is the most accurate response?

    Choose one answer.

  2. Question 6 of 15You fine-tune a pretrained image model on 800 labelled images of your own. Which plan is most consistent with the standard recipe?

    Choose one answer.

  3. Question 7 of 15A team uses random flips and crops on training images and finds their validation loss is below their training loss. Which explanation fits, and what do they check?

    Choose one answer.

ObjectiveExplain vanishing and exploding gradients through time as a product of per-step factors, write the LSTM and GRU updates, say why the additive cell path helps, and count their parameters.

  1. Question 8 of 15A one-unit tanh recurrent network has recurrent weight w = 3 and a constant input of 0.1. A teammate predicts the gradient from step 0 to step 50 explodes. What does the lesson's calculation show?

    Choose one answer.

  2. Question 9 of 15A gradient-norm clipping threshold is added to a plain RNN that suffers from both exploding and vanishing gradients. What does it fix?

    Choose one answer.

  3. Question 10 of 15In an LSTM, which statement correctly explains how gradients survive many time steps?

    Choose one answer.

  4. Question 11 of 15In PyTorch's GRU, h_t = (1 - z_t) * n_t + z_t * h_(t-1). At a time step the update gate z_t is close to 1 for every unit. What happens to the hidden state?

    Choose one answer.

  5. Question 12 of 15A PyTorch nn.LSTM has input size 10 and hidden size 20, one layer, bias on. How many parameters does it have, and why does the count differ from a textbook formula with one bias per gate?

    Choose one answer.

ObjectiveCompare RMSNorm with layer norm, and write the label-smoothed target and loss, including the loss floor and the logit gap it asks for.

  1. Question 13 of 15Which statements about RMSNorm and layer norm are true? Select all that apply.

    Choose all that apply.

  2. Question 14 of 15Cross-entropy with label smoothing 0.1 on a 10-class problem. What is the target for the true class, and what is the lowest loss the model can reach?

    Choose one answer.

  3. Question 15 of 15A model trained with label smoothing 0.1 shows a training loss that stays near 0.5 on a 10-class problem while its accuracy is high. A teammate says the model is underfitting. What is the right reading?

    Choose one answer.