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
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
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.
| Idea | What it assumes or fixes | Where it is used |
|---|---|---|
| Convolution | The same local pattern matters at every position | Images, audio, any grid |
| Pooling | Small shifts should not change the answer | After convolutions |
| Skip connection (ResNet) | Very deep stacks are hard to optimise | Almost every deep vision model |
| Transfer learning | Features learned on a big task help a small one | Small labelled datasets |
| RNN, LSTM, GRU | Order matters and sequences vary in length | Older sequence models |
| RMSNorm | Re-centring in layer norm is not needed | Normalisation inside large models |
| Label smoothing | Hard 0 and 1 targets push logits without limit | Classification losses |
| Data augmentation | Some changes to the input keep the label | Training-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 , kernel size , padding zeros on each side and stride :
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 : 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 input channels, each output channel has one kernel of shape (Dive into Deep Learning, channels), so the count does not depend on the image size:
A 3 by 3 convolution from 3 to 64 channels has 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: 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 (starting at 1) and the jump , the distance in input pixels between neighbouring positions of the current layer (starting at 1). Each layer does and then . 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 channels the first has weights and the stack (CS231n). For 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 , let the layers fit the residual and output . If the best thing to do is nothing, the layers only need to push 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).
The gradient argument (derived here). For the Jacobian is , so the backward step is . The identity term means a copy of 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 . For a plain layer the backward step is alone, a product of per-layer factors as in the first lesson. Across blocks the product expands into a sum that contains a pure identity path through all of them. When a block’s 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 , 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 the layer’s derivative is , and with 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 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 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: . 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, , where is the derivative of tanh at step (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 and the numbers are easy to read. If the state stays near 0, tanh’s slope is 1 and the product is : for it is 0.349 at 10 steps, 0.00515 at 50 and at 100, and for it is 57.7, and . 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: for and for . There is 0.201 and 0.008, so the per-step factor is 0.302 and 0.025, far below 1, and the gradient vanishes: and at 50 steps. The saturation is caused by the large recurrent weight pushing the state toward , 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 that is updated by addition. PyTorch’s equations, with the sigmoid and elementwise product, are (PyTorch, LSTM):
Each sigmoid gate outputs values in 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 lies in because is applied before the output gate; the cell state has no such bound.
Why this helps. In the cell update, the direct derivative of with respect to is . 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 and 0.5 gives (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 , and depends on , 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 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 . 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 , update gate and new candidate , is (PyTorch, GRU):
The last line is an interpolation: where 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 and , and PyTorch’s page notes that its differs from the original paper because it applies the reset gate after the 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 each for the LSTM and for the GRU, with weight_ih_l0 of shape and weight_hh of shape (3 in place of 4 for the GRU; PyTorch, RNN shows the same two biases with shapes ). With input size and hidden size :
| Layer | Textbook (one bias) | PyTorch layout (two biases) | |
|---|---|---|---|
| Vanilla RNN | (nn.RNN also has bias_ih and bias_hh) | 620 and 640 | |
| LSTM | 2,480 and 2,560 | ||
| GRU | 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: with (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 , when left unset, is the machine epsilon of the computation type.
The script uses and . Layer norm gives with mean 0. RMSNorm gives with mean 0.849: the output is not centred. Multiplying by 10 leaves both outputs unchanged (True for both). Adding 5 to every entry leaves layer norm unchanged and turns the RMSNorm output into , 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 classes (Szegedy et al., which uses on ImageNet):
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 , ):
- The target is . Note the true class gets , not .
- The gradient of cross-entropy with respect to the logits is , so it is zero when the prediction equals . The best logit gap is finite, , where hard labels would push it to infinity.
- The loss has a floor: the entropy of , 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 to , and .
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).
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 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 .
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 per axis; parameters , independent of image size; pooling has none. Receptive field: , .
- Weight sharing gives translation equivariance and a huge saving (1,792 against 201 million in the example); pooling gives invariance only within a window.
- has Jacobian : 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 per step; vanishing or exploding; clip for exploding only. LSTM: , direct path . GRU: .
- LSTM has 4 gate blocks, GRU 3; PyTorch has two biases per gate.
- RMSNorm: no mean subtraction, scale-invariant, not shift-invariant. Label smoothing: , finite optimal gap, loss floor equal to the entropy of .
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)
Shows the convention differences, such as where the reset gate acts, that trip people up when comparing papers and libraries.
Further reading
The clearest worked parameter and output-size examples, including the AlexNet first layer and the small-filter argument.
Dive into Deep Learning, Long Short-Term Memory (LSTM) (opens in a new tab)
The gate equations with shapes, to compare with the PyTorch layout before you count parameters.
Research papers
Deep Residual Learning for Image Recognition (opens in a new tab)Essential
The degradation experiment and the residual reformulation, in the authors' words. Read the introduction and the plain versus residual comparison table.
Root Mean Square Layer Normalization (opens in a new tab)
The invariance argument behind dropping the mean, and the experiments behind the running-time range.
Rethinking the Inception Architecture for Computer Vision (opens in a new tab)
Where label smoothing was introduced, as a small section inside an architecture paper.
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.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.