Module deck

Deep learning and transformers flashcards

Reviewing needs JavaScript. You can read every card in the list below.

Loading your cards...

Back to the module46 cards in this deck

Read all 46 cards as a list

Neural networks and backpropagation: gradients, checks and initialisation

  1. Front
    Why does a neural network need a non-linear activation?
    Back
    An affine function of an affine function is affine: W2(W1 x + b1) + b2 = (W2 W1) x + (W2 b1 + b2). Without an activation, any number of layers is one linear layer, and XOR cannot be solved (a linear rule gets at most 3 of 4 points). Two ReLU units, relu(a+c) and relu(a+c-1) with output h1 - 2 h2, solve it.
  2. Front
    Shapes and parameter count of a 2-layer network (d inputs, h hidden units, k classes)?
    Back
    W1 is h x d, b1 is h, W2 is k x h, b2 is k, so there are h(d+1) + k(h+1) parameters: 101,770 for 784, 128 and 10. A batch X of n rows gives Z1 = X W1^T + b1 of shape n x h. A gradient always has the shape of its parameter.
  3. Front
    Sigmoid and tanh: what is saturation, in numbers?
    Back
    Far from zero both flatten, so their derivatives collapse. Sigmoid derivative: 0.25 at 0, 0.0066 at 5, 4.5e-5 at 10 (never above 0.25). Tanh derivative: 1 at 0, 1.8e-4 at 5, 8.2e-9 at 10. Ten sigmoid layers shrink the derivative part of the gradient by at least 0.25^10, about 1e-6.
  4. Front
    What is a dead ReLU, and how does GELU differ?
    Back
    The ReLU derivative is exactly 0 for negative inputs, so a unit that is negative on all the data gets no gradient and cannot recover. GELU = z times the normal CDF of z is smooth and gives small non-zero values for negative z (-0.159 at z = -1), so gradients still flow.
  5. Front
    Write the backward pass of a 2-layer ReLU network with softmax cross-entropy.
    Back
    delta2 = p - onehot(y); dW2 = delta2 a1^T; db2 = delta2; da1 = W2^T delta2; delta1 = da1 * 1[z1 > 0]; dW1 = delta1 x^T; db1 = delta1. Each gradient has its parameter's shape. Cache z1, a1 and p from the forward pass.
  6. Front
    Why is backprop cheap, and what does it cost in memory?
    Back
    It evaluates the chain rule from the output backwards, reusing the gradient of the layer after and the saved forward values, so one sweep gives every parameter's gradient. The saved activations stay in memory until the backward pass ends and grow with depth and batch size, so training needs more memory than prediction.
  7. Front
    How do you gradient-check a backward pass, and what errors mean what?
    Back
    Nudge one parameter by +h and -h and compare (L(w+h) - L(w-h)) / 2h with the analytic gradient, in double precision on a few examples. Relative error 1e-7 or less is good; above 1e-2 is probably a bug (CS231n; deeper nets accumulate error, so 1e-2 may be fine for 10 layers). In the lesson the correct code gave 2.4e-11 and a missing ReLU mask gave 1.0.
  8. Front
    Two cheap sanity checks before training a network?
    Back
    The initial loss should be about ln C for C balanced classes (2.3026 for 10; 0.693 for 2), and the model must be able to overfit a tiny batch to near zero loss (4 points reached 0.0067 in the lesson). If either fails, look for a bug before tuning anything.
  9. Front
    What causes vanishing and exploding gradients?
    Back
    The gradient through L layers is a product of L per-layer factors (weight scale times activation derivative). Below 1 it shrinks exponentially, above 1 it grows exponentially. In the lesson's 20-layer test the per-layer gradient factor was 0.227 for sigmoid with Xavier weights and 2.10 for ReLU with twice He's variance. Saturation does not guarantee vanishing: tanh with std 1.0 exploded.
  10. Front
    Xavier versus He initialisation, and why not zero?
    Back
    Xavier: variance 2/(n_in + n_out), about 1/n for a square layer, for roughly linear layers. He: variance 2/n_in for ReLU, which zeroes half the pre-activations; with Xavier a ReLU net had its activation rms multiplied by about 0.71 per layer. All-equal weights, zero included, make every unit in a layer identical, so symmetry never breaks.

Training deep networks: normalisation, regularisation, AdamW and debugging

  1. Front
    Batch norm versus layer norm?
    Back
    Batch norm takes mean and variance per feature across the batch, so one example's output depends on its batch, the statistics are noisy for small batches (spread about 1/sqrt(B)), and eval mode uses running estimates. Layer norm takes them per example across features and is the same in train and eval, which suits sequences and small batches.
  2. Front
    What changes between training and evaluation mode?
    Back
    Dropout is on in training and the identity in eval. Batch norm uses batch statistics in training and running estimates in eval. Call model.eval() for validation and serving; torch.no_grad() only turns off gradient tracking and is a separate switch. Forgetting eval() leaves noise and batch dependence in your results.
  3. Front
    How does dropout work in modern libraries?
    Back
    Training: zero each activation with probability p and multiply survivors by 1/(1-p), so the expected activation is unchanged. Inference: identity. The original paper scaled weights at test time instead; the two agree in expectation. In the lesson's tiny two-moons test, dropout 0.3 helped on only 3 of 8 seeds, so treat the rate as a setting to tune.
  4. Front
    L2 penalty versus weight decay?
    Back
    The L2 form adds lambda x W to the gradient. Under plain SGD it is equivalent to weight decay once the decay is scaled by the learning rate. Under Adam it is not, because the penalty gets divided by the gradient scale; that is why AdamW decouples the decay. Usually applied to weights, not biases.
  5. Front
    AdamW versus Adam with L2, in numbers?
    Back
    Adam with L2 divides the penalty by sqrt(v-hat), so its strength follows about 1/G for loss gradient scale G: with decay 0.01 and learning rate 0.001, the extra shrinkage per step was 1e-3 for G = 0, 7.07e-4 for 0.01, 1e-5 for 1 (equal to AdamW) and 1e-7 for 100. AdamW applies w <- w - lr x decay x w before the moment updates: 1e-5 at every G (a stylised setup with w fixed at 1).
  6. Front
    What does early stopping do, and what must you watch when reporting results?
    Back
    It keeps the weights from the epoch with the lowest validation loss. The best epoch ranged from 2 to 188 over 8 seeds, so it must be found on held-out data. The chosen validation loss is optimistic, so report the final number on a separate test set.
  7. Front
    What did the two-moons experiment show (30 points, 8 seeds)?
    Back
    No regularisation: train loss 0.123, test loss 0.616, accuracy 0.826. Weight decay 0.01: test loss 0.417 (better on 7 of 8 seeds), accuracy 0.828. Dropout 0.3: 0.595 (better on 3 of 8, within noise), accuracy 0.822. Early stopping beat the last epoch on 8 of 8 seeds (test loss 0.380). Weight decay improved the loss, not the accuracy, and dropout changed little, in this one tiny problem.
  8. Front
    What do warmup and cosine decay do?
    Back
    Warmup ramps the rate from near 0 to the peak over the first steps (used for large-minibatch SGD and the original transformer: 4,000 steps). Cosine decay then follows eta_min + 0.5 (peak - eta_min)(1 + cos(pi t/T)); a quarter of the way down it is still at 85% of the peak. Why warmup helps Adam is still studied.
  9. Front
    How does clipping by global norm work?
    Back
    Compute one norm over all parameter gradients as if concatenated; if it exceeds max_norm, multiply every gradient by max_norm/norm. The direction is kept and the length capped; gradients below the limit are untouched. (3, 4) has norm 5 and becomes (0.6, 0.8) at limit 1. It guards against rare spikes.
  10. Front
    Loss is NaN: what is your checklist?
    Back
    Find the first non-finite step. NaN at step 0: inspect data and labels for NaN or inf, then the loss code (softmax overflow, log of 0; use logsumexp). After a rise: learning rate too high (lower it, warm up, clip). Sudden: a bad batch, zero variance in a norm layer, exploding activations. Then overfit 4 examples and run a gradient check.
  11. Front
    Loss is flat from the start: what do you check, in order?
    Back
    The initial loss against ln C; whether the model can overfit four examples (if not, a bug in data, loss or backward pass); the learning rate, including a schedule that already decayed to zero; the initial weight scale (tiny init or dead units). The classic slip is a softmax before a loss that expects logits.
  12. Front
    Softmax before CrossEntropyLoss: what goes wrong?
    Back
    PyTorch's CrossEntropyLoss expects unnormalised logits. Feeding it softmax outputs applies softmax twice; with 3 classes the true-class probability can never exceed e/(e+2), about 0.58 (derived), so learning is weak while the code still runs.

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

  1. Front
    Output size and parameter count of a convolution layer?
    Back
    Per axis: floor((n + 2p - k) / s) + 1, with p zeros on each side; height and width are separate. Parameters: k_h x k_w x c_in x c_out + c_out, independent of the image size. A 3x3 conv from 3 to 64 channels has 1,792; a dense layer to the same 32x32x64 output would need 201,326,592 weights.
  2. Front
    How do you compute a receptive field for a stack of layers?
    Back
    Start with r = 1 and jump j = 1. For each (kernel k, stride s): r = r + (k - 1) * j, then j = j * s. Three 3x3 stride-1 layers: 7. Three 3x3 stride-2 layers: 15. Pool (2, stride 2) then a 3x3 conv: 6; the other order: 4. Derived here; it matches CS231n's 7x7 for three 3x3 layers.
  3. Front
    What does weight sharing give a convolution, and what does pooling add?
    Back
    Sharing one kernel across positions gives far fewer parameters and translation equivariance: shift the input and the output shifts. Pooling has no parameters and works per channel; it gives invariance only to shifts inside its window (a pixel moving from position 3 to 4 changed the 2x2 stride-2 pooled output in the lesson's script).
  4. Front
    Why does y = x + F(x) help deep networks train, and what does it not do?
    Back
    He et al. report degradation (deeper plain nets have higher training error, not from overfitting) and fix it by fitting the residual F(x) = H(x) - x; doing nothing means F near 0. The Jacobian is I + J_F, so a gradient has an identity path (derived here). It does not cap the gradient: an unscaled residual stack returned a gradient norm of 22.6 at depth 50, against 0.0183 plain.
  5. Front
    What is the fine-tuning recipe, and what must augmentation respect?
    Back
    Pretrain on a source task, copy everything except the output layer, randomly initialise a new output layer, train it from scratch at a larger rate (10x in the book) and fine-tune the rest at a small rate. Freeze the backbone with very little data (common practice). Augmentation is training-only and must keep the label: a left-right flip is fine for a cat, wrong for digits or text.
  6. Front
    Why do RNN gradients vanish or explode, and what does clipping fix?
    Back
    dh_T/dh_0 is a product over steps of diag(1 - h^2) W_h. With zero input the state stays near 0 and the factor is w: w = 0.9 gives 0.00515 at 50 steps, w = 1.5 gives 6.38e8. With constant input 0.1 the large weight saturates the state (h = 0.894 for w = 1.5, 0.996 for w = 3), the factor w(1 - h^2) is 0.302 or 0.025, and the gradient vanished (7.55e-24 and 6.55e-75 at 50 steps). Clipping caps large gradients but cannot raise vanished ones.
  7. Front
    Write the LSTM update and say why it helps gradients.
    Back
    i, f, o = sigmoid(...), g = tanh(...); c_t = f * c_(t-1) + i * g; h_t = o * tanh(c_t). The direct derivative of c_t with respect to c_(t-1) is diag(f), with no matrix multiplication or squashing, so gates near 1 keep the gradient (0.99^100 = 0.366, 0.5^100 = 7.89e-31). The full derivative has extra terms through the gates, so this is the direct path.
  8. Front
    Write the GRU update. Parameter counts for d = 10, H = 20?
    Back
    r, z = sigmoid(...); n = tanh(W_in x + b_in + r * (W_hn h + b_hn)); h_t = (1 - z) * n + z * h_(t-1) in PyTorch's convention; z near 1 keeps the old state. PyTorch has two biases per gate: LSTM 4H(d + H + 2) = 2,560 and GRU 3H(d + H + 2) = 1,920, against 2,480 and 1,860 with one bias. The counts do not depend on sequence length.
  9. Front
    RMSNorm versus layer norm?
    Back
    RMSNorm divides by sqrt(eps + mean(x^2)) and does not subtract the mean. Both ignore a global rescale; only layer norm ignores adding a constant (x + 5 left layer norm unchanged and changed RMSNorm). The paper says re-centring is dispensable and reports 7% to 64% less running time on its models.
  10. Front
    Label-smoothed target, loss floor and optimal logit gap?
    Back
    q_k = (1 - eps) * [k = y] + eps / K: for K = 10 and eps = 0.1 that is 0.91 and 0.01. The gradient on the logits is p - q, so the best gap is ln(0.91 / 0.01) = 4.511, and the loss floor is the entropy of q, 0.5003, not 0. Loss values are not comparable across smoothing settings. The paper used eps = 0.1 and reported about 0.2 points of error.

Transformers, large language models, sampling and fine-tuning

  1. Front
    What does attention compute, and what are the shapes?
    Back
    softmax(Q K^T / sqrt(d_k)) V. Q is n_q x d_k, K is n_k x d_k, V is n_k x d_v; scores n_q x n_k, output n_q x d_v. Self-attention takes Q, K, V from the same X. With n = 10, d_model = 256, h = 4 each head has 10 x 64 queries and a 10 x 10 score matrix.
  2. Front
    Why divide by sqrt(d_k)?
    Back
    With independent components of mean 0 and variance 1, q.k has variance d_k. Dividing by sqrt(d_k) restores variance 1 so softmax is not saturated. In the script, unscaled scores at d_k = 256 gave a largest weight of 0.9981 and a Jacobian norm of 0.00366; scaled gave 0.2970 and 0.37223 (one draw).
  3. Front
    How is the causal mask applied, and what goes wrong if it is applied late?
    Back
    Set scores for keys later than the query to minus infinity before the softmax, so those weights are exactly 0 and rows still sum to 1. Zeroing weights after the softmax leaves the future scores in the denominator (information leaks) and rows no longer sum to 1.
  4. Front
    What is the cost of attention in sequence length?
    Back
    The score matrix is n x n: O(n^2 d) time and O(n^2) memory if stored. Going from 1,000 to 2,000 tokens takes the entries per head from 1,000,000 to 4,000,000, four times as many. Recurrent layers need O(n) sequential steps; attention needs O(1).
  5. Front
    Why does attention need positions, and how are they added?
    Back
    Unmasked attention treats its input as a set: shuffling the rows shuffles the outputs the same way (a causal mask leaks some position implicitly, per Haviv et al.). Add a position encoding to the embeddings: sinusoidal PE(p,2i) = sin(p / 10000^(2i/d)), PE(p,2i+1) = cos(same angle), a learned table (nearly identical results in the original paper), or rotary embeddings that rotate queries and keys by position.
  6. Front
    What is byte pair encoding and what is an embedding lookup?
    Back
    BPE starts from characters and repeatedly merges the most frequent adjacent pair into a new token, so rare words become pieces. An embedding lookup selects a row of a V x d_model matrix, equal to a one-hot vector times the matrix. Vocabulary 50,000 and width 768 give 38,400,000 parameters (illustrative).
  7. Front
    Describe the pre-norm block and why it is preferred.
    Back
    h = x + Attention(Norm(x)), then out = h + MLP(Norm(h)). The residual path is never normalised, and Xiong et al. report well-behaved gradients at initialisation and training without warm-up with comparable results; post-norm, LayerNorm(x + Sublayer(x)), has large gradients near the output at the start.
  8. Front
    Estimate the parameters of a transformer stack.
    Back
    Per layer 4d^2 (attention) + 2 d d_ff (MLP) = 12d^2 when d_ff = 4d; about 12 L d^2 for L layers, ignoring biases, norms and embeddings. d = 1024, L = 24: 301,989,888. d = 4096, L = 32: 6,442,450,944. Two thirds of a layer is the MLP.
  9. Front
    GELU versus SiLU?
    Back
    GELU = x Phi(x) with the normal CDF; SiLU = x sigmoid(x). Both are smooth, slightly negative for negative inputs and close to x for large positive ones. At x = -1: GELU -0.1587, SiLU -0.2689; at x = 3: 2.9960 and 2.8577. Which is better is empirical.
  10. Front
    How is a decoder-only model trained, and how does it generate?
    Back
    Teacher forcing: feed the true sequence once, the causal mask hides the future, position t predicts token t+1, so n tokens give n-1 targets; loss is mean cross-entropy (a uniform guess over 50 tokens: ln 50 = 3.9120). Generation is autoregressive: sample a token, append, repeat.
  11. Front
    What does the KV cache save and cost?
    Back
    Earlier keys and values do not change, so store them instead of recomputing: 5,050 projections for 100 tokens without a cache against 100 with. Memory: 2 x L x H_kv x d_head x T x bytes per sequence; 32 layers, 32 heads, width 128, 4,096 tokens, 2 bytes: 2.0 GiB; with 8 KV heads: 0.5 GiB.
  12. Front
    Temperature, top-k and top-p?
    Back
    Temperature divides logits: lower is sharper. Logits [2,1,0.5,0,-1] at T=1 give top probability 0.5630; at T=0.5, 0.8292. Top-k keeps k tokens (k=2: 0.7311, 0.2689). Top-p keeps the smallest set reaching p, so it shrinks when the model is confident. Both renormalise.
  13. Front
    What does LoRA train, and what does merging do?
    Back
    W' = W + (alpha/r) B A with A r x d_in and B d_out x r, W frozen, B starting at 0. Trained weights r(d_in + d_out): a 4096 x 4096 matrix has 16,777,216 weights, rank 8 trains 65,536 (0.3906%). Merging gives one matrix again, so no extra inference cost.
  14. Front
    How do SFT, RLHF and DPO differ, and when use RAG or fine-tuning?
    Back
    SFT trains on example answers; RLHF uses ranked answers to train a reward model, then optimises the model against it; DPO uses a classification-style loss on preference pairs without a separate reward model or RL loop. Missing or changing facts and citations: retrieval. Behaviour and style: fine-tuning. Hallucination follows from a likelihood objective with no truth signal.