Cheat sheet · Module 3
Cheat sheet: deep learning and transformers
Machine Learning · Cheat sheet · Deep learning and transformers
The pattern: a network is a function, a loss and an optimizer, and everything here is about keeping signals and gradients at a usable scale through many layers. Gradients are products of per-layer factors, so below 1 they vanish and above 1 they explode. Backprop gives the product, initialisation sets the factor, normalisation and clipping hold it, skip connections and gates add a path with no weight matrix or squashing (identity for skips, a forget-gate factor for LSTMs).
Shapes and parameters (lesson 1): for inputs, hidden units and classes, is , is , and the parameter count is (101,770 for 784, 128 and 10).
- Without a non-linearity, is one affine map, so XOR cannot be learned. Two ReLU units, and with output , give .
- Sigmoid: derivative at most 0.25; tanh: at most 1; both flatten far from 0. ReLU: derivative 1 for and exactly 0 for , so a unit negative on all data is dead. GELU is and damps negative inputs without zeroing them.
Backprop for a 2-layer ReLU network with softmax cross-entropy
- , , , , and each bias gradient is its . Weight gradient = error at the layer’s output times its input; the error goes back through the transposed weights and the activation’s derivative.
- Backward costs about twice forward (two matrix products per layer against one), and the saved activations make training need more memory than prediction.
- Worked example: loss 2.1269, , and the inactive hidden unit gets zero gradient on both its input and output weights. One step at rate 0.1 takes the loss to 0.6089.
Checking a backward pass
- Central difference has error shrinking as (one-sided: ). CS231n’s thresholds for relative error: above probably wrong, or below good; deeper nets accumulate error. Use double precision and few data points, since a ReLU kink makes the two sides legitimately disagree.
- In the lesson’s example: correct code ; ReLU mask forgotten 1.00; used instead of 0.75; sign of flipped 2.00.
- Cheaper checks: the initial loss should be about (2.3026 for 10 classes), and the model must overfit a tiny batch to near zero loss.
Initialisation: all-equal weights never break symmetry. Xavier variance ; He variance because ReLU zeroes about half the pre-activations.
- 20 layers of width 64, gradient factor per layer: tanh std 0.01 gives 0.078 (vanishes), tanh Xavier 0.898, tanh std 1.0 gives 1.955 (explodes even though activations saturate), sigmoid Xavier 0.227, ReLU Xavier 0.744, ReLU He 1.052, ReLU with twice He 2.103.
- A factor of two in variance separates stable (He) from decaying (Xavier, about 0.71 per layer in activation rms) for ReLU. Ten sigmoid layers shrink the gradient to about .
Normalisation and modes (lesson 2): .
- Batch norm: statistics per feature over the batch, so one example’s output depends on the others, noisy in small batches (spread of the batch mean 0.701, 0.358, 0.178, 0.089 at batch sizes 2, 8, 32, 128, matching ), running estimates (momentum 0.1) in eval mode. Layer norm: per example over its features, identical in train and eval.
- Dropout: zero with probability and scale survivors by in training; identity in eval. Forgetting
model.eval()leaves dropout on and batch norm on batch statistics.torch.no_grad()is separate fromeval(); use both when validating.
Regularisation
- Weight decay: L2 adds , so each weight gradient gains . Early stopping: restore the best validation epoch, then report on a separate test set because choosing the epoch used up the validation set.
- Two-moons experiment (30 training points, 8 seeds): weight decay 0.01 cut the mean final test loss from 0.616 to 0.417 and was better on 7 of 8 seeds; dropout 0.3 only to 0.595 (3 of 8, within noise); accuracy stayed 0.822 to 0.828. Early stopping reached 0.380, and the best epochs ranged from 2 to 188.
AdamW, schedule, clipping
- Adam with L2 divides the penalty by , so decay strength follows about of each parameter’s gradient scale. AdamW shrinks the weight directly, , at every gradient scale. The extra step with L2 inside Adam is about : roughly a full learning-rate step when , roughly when . PyTorch AdamW defaults: rate 0.001, betas 0.9 and 0.999, epsilon , weight decay 0.01.
- Warmup then cosine, with counted from the end of warmup and the decay length: . With 100 warmup steps, 1,000 total and peak the rate is at step 49 and at step 550; at step 325 it is still 85% of the peak.
- Clip by global norm: if the norm exceeds the limit, multiply every gradient by limit over norm. with limit 1 becomes ; direction kept, length capped; a norm of 0.5 is untouched.
Debugging NaN or flat loss
- NaN: find the first non-finite step. At step 0 suspect data, labels and loss code (
log(0), softmax overflow). If the loss rose first, the rate is too high (lower it, warm up, clip). A sudden NaN points to a bad batch, division by zero or exploding activations. Compute the loss as logsumexp minus the true logit; logits with class 1 give exactly 1000.0. - Flat: check the initial loss against , then whether four examples can be overfit, then the learning rate (is the schedule already near zero?), then the initial weight scale.
- Healthy-looking but poor: softmax before
CrossEntropyLoss(it expects raw logits), evaluating in training mode, scalers fitted on rows that include validation, unshuffled data, changed batch size with the same rate.
Convolutions and pooling (lesson 3)
- Output length per axis: . Parameters: , independent of image size (3 by 3, 3 to 64 channels: 1,792; 5 by 5, 16 to 32: 12,832; 1 by 1, 256 to 64: 16,448). A dense layer with the same output shape as the first would need 201,326,592 weights.
- Weight sharing gives translation equivariance. Pooling has no parameters, works per channel, and is invariant only to shifts inside a window.
- Receptive field: start , ; each layer , then . Three 3 by 3 layers see 7 by 7 (27 weights against 49 for one 7 by 7).
Skip connections and transfer
- has Jacobian , so the backward step is : an identity path always exists. It eases optimisation (He et al.: 34-layer plain 28.54 top-1 error, 34-layer ResNet 25.03); it does not guarantee well-scaled gradients: they can still shrink or grow.
- Fine-tune: copy the pretrained layers, add a new random output layer with a larger rate (10 times in the book’s code), keep the pretrained layers at a small rate. Freezing a 512-feature backbone with 2 classes trains weights. Keep frozen batch norm in eval mode.
- Augmentation applies to training inputs only and must preserve the label (a left-right flip is fine for a cat, not for digits or text); measure its benefit on validation.
Recurrent networks, LSTM, GRU
- . With a near-zero state the factor is : , . With constant input 0.1 and the state saturates near 0.996, the factor falls to 0.025 and the gradient vanishes. Clipping fixes only the exploding side.
- LSTM: , . The direct path is : 0.99 over 100 steps is 0.366, 0.9 gives . The gates also depend on , so that product is only the direct path, and learned gates are a possibility, not a guarantee.
- GRU: ; near 1 keeps the old state.
- Parameters, PyTorch layout with two biases (input size , hidden size ): RNN = 640; LSTM = 2,560; GRU = 1,920. The textbook one-bias counts are 620, 2,480 and 1,860. None depends on sequence length.
RMSNorm and label smoothing
- RMSNorm: . No mean subtraction: invariant to scaling by 10, not to adding 5 to every entry. Layer norm of has mean 0; RMSNorm output has mean 0.849.
- Label smoothing: , so with , the true class target is 0.91, not 0.9. The gradient is , the best logit gap is , and the loss floor is the entropy of , 0.5003. Smoothed and unsmoothed losses cannot be compared.
Attention and the transformer (lesson 4)
- with of , of , of : scores , output . Unit-variance components give variance ; dividing by restores 1 and keeps softmax out of saturation (at the largest unscaled weight was 0.9981, scaled 0.2970).
- Causal mask: set future scores to before the softmax so rows still sum to 1; zeroing weights afterwards does not. Unmasked attention is permutation-equivariant, so add positions (sinusoidal or rotary). Heads add no weights beyond ( per layer). Attention costs : doubling the context quadruples the score entries.
- Pre-norm: keeps a clean residual path. Layer weights , about for , so a stack is about (two of every three weights in the MLP). GELU is , SiLU is .
- Training: teacher forcing gives next-token targets per pass of tokens; uniform guessing over 50 tokens costs nats. Generation is autoregressive.
KV cache and sampling
- The cache stores keys and values of past tokens: 5,050 projections become 100 for . Memory bytes per sequence: 2.0 GiB for 32 layers, 32 key-value heads, width 128, 4,096 tokens, 16-bit numbers; 8 key-value heads give 0.5 GiB.
- Temperature divides the logits (); low sharpens, high flattens. Top-k keeps tokens; top-p keeps the smallest set reaching and adapts to confidence; both renormalise. Apply temperature, then the filter, then draw.
LoRA, preference tuning, hallucination, RAG
- LoRA: with random and zero at the start, so the model begins identical to the base. It trains weights (rank 8 on 4096 by 4096: 65,536, 0.3906%) and merges into , so inference cost is unchanged. Trade-off: a rank- update cannot express every change.
- SFT shows demonstration answers; RLHF trains a reward model on ranked answers (loss : 0.6931 at margin 0) then uses reinforcement learning; DPO replaces the reward-model fitting and RL loop with a classification-style loss on pairs.
- Next-token training has no truth signal, so fluent false statements are probable. Missing or changing facts: retrieval (RAG), which can cite sources. Behaviour or style: fine-tuning, often LoRA. Both: both. Measure on held-out examples of the real task.
Choosing a remedy
| Symptom | First check | Likely fix |
|---|---|---|
| Gradient shrinks by a constant factor per layer | Print activation and gradient scale per layer | He for ReLU, Xavier for tanh, a scale-aware choice; not all-equal weights |
| Loss NaN at step 0 | Data, labels, log(0), softmax overflow | Logsumexp loss, clean the batch |
| Loss rises, then NaN | Learning rate | Lower it, warm up, clip by global norm |
| Loss flat from the start | Initial loss against , overfit four examples | Fix labels or loss, learning rate, initial scale |
| Training falls, validation rises | Training and validation curves | Weight decay, dropout, more data, early stopping |
| The same request gives different scores when serving | Is the model still in training mode? | model.eval() (and no_grad) |
| Deep plain network trains worse than a shallower one | Training error, not just validation | Skip connections |
| Small labelled image set | Pretrained backbone available? | Freeze or fine-tune with a small rate, label-preserving augmentation |
| Out-of-date or private facts | Do answers need citations? | Retrieval, not fine-tuning |
| Output varies between identical requests | Sampling settings | Lower temperature or a filter; log the settings |
| Long-context serving runs out of memory | KV-cache size | Smaller batch, shorter context, quantised or offloaded cache; choose a model with fewer key-value heads (grouped-query attention) |
Quick answers
- Why is attention scaled by and not ? The dot product has variance , so its standard deviation is .
- Why does a skip connection help? The Jacobian is , so the gradient always has an identity path; it eases optimisation but does not guarantee well-scaled gradients: they can still shrink or grow.
- Why does an LSTM keep gradients longer than an RNN? The cell path is additive with derivative , so forget gates near 1 let it survive; the gates are learned, so it is not guaranteed.
- Adam with L2 or AdamW? AdamW: its decay does not depend on the gradient scale.
- Does batch norm behave the same at train and eval? No: batch statistics in training, running estimates in eval. Layer norm is the same in both.
- Is a gradient-check relative error of 3e-3 on a 20-layer network a bug? Below the rule of thumb, and errors accumulate with depth, so not by itself; rerun in double precision with few points, since a ReLU kink can cause legitimate disagreement.
- Does temperature 0 make a model truthful? No: it approaches greedy decoding, and the training loss has no truth signal.
Traps
“Zero initialisation is fine, the gradients will differ” · “ReLU never has vanishing gradients” · all-equal weights · skipping model.eval() · evaluating with dropout on · softmax before CrossEntropyLoss · L2 penalty equals weight decay in Adam · “a skip connection removes vanishing gradients” · max pooling gives full translation invariance · label smoothing 0.1 means a 0.9 target · comparing smoothed and unsmoothed losses · clipping fixes vanishing gradients · “RMSNorm is layer norm renamed” · zeroing attention weights after the softmax · “multi-head attention has times the parameters” · “a KV cache removes attention’s quadratic cost” · fine-tuning to add facts that change · LoRA changes the architecture at inference.