Cheat sheet · Module 3

Cheat sheet: deep learning and transformers

Machine Learning · Cheat sheet · Deep learning and transformers

Open the moduleModule quiz

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 dd inputs, hh hidden units and kk classes, W1W_1 is h×dh\times d, W2W_2 is k×hk\times h, and the parameter count is h(d+1)+k(h+1)h(d+1)+k(h+1) (101,770 for 784, 128 and 10).

  • Without a non-linearity, W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)W_2(W_1x+b_1)+b_2=(W_2W_1)x+(W_2b_1+b_2) is one affine map, so XOR cannot be learned. Two ReLU units, h1=ReLU(a+c)h_1=\mathrm{ReLU}(a+c) and h2=ReLU(a+c−1)h_2=\mathrm{ReLU}(a+c-1) with output h1−2h2h_1-2h_2, give [0,1,1,0][0,1,1,0].
  • Sigmoid: derivative at most 0.25; tanh: at most 1; both flatten far from 0. ReLU: derivative 1 for z>0z>0 and exactly 0 for z<0z<0, so a unit negative on all data is dead. GELU is z Φ(z)z\,\Phi(z) and damps negative inputs without zeroing them.

Backprop for a 2-layer ReLU network with softmax cross-entropy

  • δ2=p−onehot(y)\delta_2=p-\mathrm{onehot}(y), ∂L/∂W2=δ2a1⊤\partial L/\partial W_2=\delta_2a_1^{\top}, δ1=(W2⊤δ2)⊙1[z1>0]\delta_1=(W_2^{\top}\delta_2)\odot\mathbb 1[z_1>0], ∂L/∂W1=δ1x⊤\partial L/\partial W_1=\delta_1x^{\top}, and each bias gradient is its δ\delta. 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, δ2=(0.8808,−0.8808)\delta_2=(0.8808,-0.8808), 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 (L(θ+h)−L(θ−h))/2h(L(\theta+h)-L(\theta-h))/2h has error shrinking as h2h^2 (one-sided: hh). CS231n’s thresholds for relative error: above 10−210^{-2} probably wrong, 10−710^{-7} 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 2.4×10−112.4\times10^{-11}; ReLU mask forgotten 1.00; W2W_2 used instead of W2⊤W_2^{\top} 0.75; sign of p−yp-y flipped 2.00.
  • Cheaper checks: the initial loss should be about ln⁡C\ln C (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 2/(nin+nout)2/(n_{in}+n_{out}); He variance 2/nin2/n_{in} 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 4×10−74\times10^{-7}.

Normalisation and modes (lesson 2): y=γ(x−E[x])/Var[x]+ϵ+βy=\gamma(x-\mathrm{E}[x])/\sqrt{\mathrm{Var}[x]+\epsilon}+\beta.

  • 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 1/B1/\sqrt B), running estimates (momentum 0.1) in eval mode. Layer norm: per example over its features, identical in train and eval.
  • Dropout: zero with probability pp and scale survivors by 1/(1−p)1/(1-p) in training; identity in eval. Forgetting model.eval() leaves dropout on and batch norm on batch statistics. torch.no_grad() is separate from eval(); use both when validating.

Regularisation

  • Weight decay: L2 adds λ2∥W∥2\tfrac{\lambda}{2}\lVert W\rVert^2, so each weight gradient gains λW\lambda W. 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 v^\sqrt{\hat v}, so decay strength follows about 1/G1/G of each parameter’s gradient scale. AdamW shrinks the weight directly, θ←θ−γλθ\theta\leftarrow\theta-\gamma\lambda\theta, at every gradient scale. The extra step with L2 inside Adam is about γλw/G2+(λw)2\gamma\lambda w/\sqrt{G^2+(\lambda w)^2}: roughly a full learning-rate step when G≈0G\approx0, roughly γλw/G\gamma\lambda w/G when G≫λwG\gg\lambda w. PyTorch AdamW defaults: rate 0.001, betas 0.9 and 0.999, epsilon 10−810^{-8}, weight decay 0.01.
  • Warmup then cosine, with tt counted from the end of warmup and TT the decay length: ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(πt/T))\eta_t=\eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})(1+\cos(\pi t/T)). With 100 warmup steps, 1,000 total and peak 10−310^{-3} the rate is 5×10−45\times10^{-4} 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. (3,4)(3,4) with limit 1 becomes (0.6,0.8)(0.6,0.8); 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 (1000,0)(1000,0) with class 1 give exactly 1000.0.
  • Flat: check the initial loss against ln⁡C\ln C, 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: ⌊(n+2p−k)/s⌋+1\lfloor(n+2p-k)/s\rfloor+1. Parameters: khkwcincout+coutk_hk_wc_{\text{in}}c_{\text{out}}+c_{\text{out}}, 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 r=1r=1, j=1j=1; each layer r←r+(k−1)jr\leftarrow r+(k-1)j, then j←jsj\leftarrow js. Three 3 by 3 layers see 7 by 7 (27C2C^2 weights against 49C2C^2 for one 7 by 7).

Skip connections and transfer

  • y=x+F(x)y=x+F(x) has Jacobian I+JFI+J_F, so the backward step is gx=gy+JF⊤gyg_x=g_y+J_F^{\top}g_y: 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 512⋅2+2=1,026512\cdot2+2=1{,}026 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

  • ∂hT/∂h0=∏tdiag⁡(1−ht2)Wh\partial h_T/\partial h_0=\prod_t\operatorname{diag}(1-h_t^2)W_h. With a near-zero state the factor is ww: 0.9100=2.66×10−50.9^{100}=2.66\times10^{-5}, 1.5100=4.07×10171.5^{100}=4.07\times10^{17}. With constant input 0.1 and w=3w=3 the state saturates near 0.996, the factor falls to 0.025 and the gradient vanishes. Clipping fixes only the exploding side.
  • LSTM: ct=ft⊙ct−1+it⊙gtc_t=f_t\odot c_{t-1}+i_t\odot g_t, ht=ot⊙tanh⁡(ct)h_t=o_t\odot\tanh(c_t). The direct path is diag⁡(ft)\operatorname{diag}(f_t): 0.99 over 100 steps is 0.366, 0.9 gives 2.66×10−52.66\times10^{-5}. The gates also depend on ht−1h_{t-1}, so that product is only the direct path, and learned gates are a possibility, not a guarantee.
  • GRU: ht=(1−zt)⊙nt+zt⊙ht−1h_t=(1-z_t)\odot n_t+z_t\odot h_{t-1}; ztz_t near 1 keeps the old state.
  • Parameters, PyTorch layout with two biases (input size d=10d=10, hidden size H=20H=20): RNN H(d+H+2)H(d+H+2) = 640; LSTM 4H(d+H+2)4H(d+H+2) = 2,560; GRU 3H(d+H+2)3H(d+H+2) = 1,920. The textbook one-bias counts are 620, 2,480 and 1,860. None depends on sequence length.

RMSNorm and label smoothing

  • RMSNorm: xi/ϵ+1n∑xi2⋅γix_i/\sqrt{\epsilon+\tfrac1n\sum x_i^2}\cdot\gamma_i. No mean subtraction: invariant to scaling xx by 10, not to adding 5 to every entry. Layer norm of (1,2,3,6)(1,2,3,6) has mean 0; RMSNorm output has mean 0.849.
  • Label smoothing: qk=(1−ε)1[k=y]+ε/Kq_k=(1-\varepsilon)\mathbb 1[k=y]+\varepsilon/K, so with K=10K=10, ε=0.1\varepsilon=0.1 the true class target is 0.91, not 0.9. The gradient is p−qp-q, the best logit gap is ln⁡(0.91/0.01)=4.511\ln(0.91/0.01)=4.511, and the loss floor is the entropy of qq, 0.5003. Smoothed and unsmoothed losses cannot be compared.

Attention and the transformer (lesson 4)

  • softmax(QK⊤/dk)V\mathrm{softmax}(QK^{\top}/\sqrt{d_k})V with QQ of nq×dkn_q\times d_k, KK of nk×dkn_k\times d_k, VV of nk×dvn_k\times d_v: scores nq×nkn_q\times n_k, output nq×dvn_q\times d_v. Unit-variance components give q⋅kq\cdot k variance dkd_k; dividing by dk\sqrt{d_k} restores 1 and keeps softmax out of saturation (at dk=256d_k=256 the largest unscaled weight was 0.9981, scaled 0.2970).
  • Causal mask: set future scores to −∞-\infty 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 WQ,WK,WV,WOW_Q,W_K,W_V,W_O (4d24d^2 per layer). Attention costs O(n2d)O(n^2d): doubling the context quadruples the score entries.
  • Pre-norm: x+Sublayer(Norm(x))x+\mathrm{Sublayer}(\mathrm{Norm}(x)) keeps a clean residual path. Layer weights 4d2+2d dff4d^2+2d\,d_{\text{ff}}, about 12d212d^2 for dff=4dd_{\text{ff}}=4d, so a stack is about 12Ld212Ld^2 (two of every three weights in the MLP). GELU is xΦ(x)x\Phi(x), SiLU is xσ(x)x\sigma(x).
  • Training: teacher forcing gives n−1n-1 next-token targets per pass of nn tokens; uniform guessing over 50 tokens costs ln⁡50=3.9120\ln 50=3.9120 nats. Generation is autoregressive.

KV cache and sampling

  • The cache stores keys and values of past tokens: 5,050 projections become 100 for n=100n=100. Memory 2⋅L⋅Hkv⋅dhead⋅T⋅b2\cdot L\cdot H_{kv}\cdot d_{\text{head}}\cdot T\cdot b 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 (pi∝ezi/Tp_i\propto e^{z_i/T}); low sharpens, high flattens. Top-k keeps kk tokens; top-p keeps the smallest set reaching pp and adapts to confidence; both renormalise. Apply temperature, then the filter, then draw.

LoRA, preference tuning, hallucination, RAG

  • LoRA: W′x=Wx+αrB(Ax)W'x=Wx+\tfrac{\alpha}{r}B(Ax) with AA random and BB zero at the start, so the model begins identical to the base. It trains r(din+dout)r(d_{\text{in}}+d_{\text{out}}) weights (rank 8 on 4096 by 4096: 65,536, 0.3906%) and merges into WW, so inference cost is unchanged. Trade-off: a rank-rr update cannot express every change.
  • SFT shows demonstration answers; RLHF trains a reward model on ranked answers (loss −ln⁡σ(r(x,yw)−r(x,yl))-\ln\sigma(r(x,y_w)-r(x,y_l)): 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

SymptomFirst checkLikely fix
Gradient shrinks by a constant factor per layerPrint activation and gradient scale per layerHe for ReLU, Xavier for tanh, a scale-aware choice; not all-equal weights
Loss NaN at step 0Data, labels, log(0), softmax overflowLogsumexp loss, clean the batch
Loss rises, then NaNLearning rateLower it, warm up, clip by global norm
Loss flat from the startInitial loss against ln⁡C\ln C, overfit four examplesFix labels or loss, learning rate, initial scale
Training falls, validation risesTraining and validation curvesWeight decay, dropout, more data, early stopping
The same request gives different scores when servingIs the model still in training mode?model.eval() (and no_grad)
Deep plain network trains worse than a shallower oneTraining error, not just validationSkip connections
Small labelled image setPretrained backbone available?Freeze or fine-tune with a small rate, label-preserving augmentation
Out-of-date or private factsDo answers need citations?Retrieval, not fine-tuning
Output varies between identical requestsSampling settingsLower temperature or a filter; log the settings
Long-context serving runs out of memoryKV-cache sizeSmaller 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 dk\sqrt{d_k} and not dkd_k? The dot product has variance dkd_k, so its standard deviation is dk\sqrt{d_k}.
  • Why does a skip connection help? The Jacobian is I+JFI+J_F, 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 diag⁡(ft)\operatorname{diag}(f_t), 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 10−210^{-2} 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 hh times the parameters” · “a KV cache removes attention’s quadratic cost” · fine-tuning to add facts that change · LoRA changes the architecture at inference.