Library

Transformers from scratch

Attention, a GPT, the KV cache, decoding and the gradients underneath, built by hand in NumPy and PyTorch until you can write them under a timer.

Practice questions

51
PyTorch tensors: the attention toolkit
  1. 1.x is (B, T, C) and you need (B, H, T, d) heads. Which line is right?
  2. 2.y is the (B, H, T, d) output of att @ v. What does y.transpose(1, 2).view(B, T, C) do?
  3. 3.allowed = torch.tril(torch.ones(3, 3, dtype=torch.bool)). What does att.masked_fill(allowed, float('-inf')).softmax(dim=-1) give?
  4. 4.qkv is (B, T, 3C) with C = 64. Which call gives q, k and v, each (B, T, C)?
  5. 5.logits is (B, T, V). Which gives a (B, 1) tensor of greedy ids to append to idx?
  6. 6.lin = nn.Linear(512, 1536) and x is (8, 128, 512). What are lin.weight.shape and lin(x).shape?
Scaled dot-product attention
  1. 1.The head size goes from 64 to 256 and you forgot the 1/√d scale. What happens to the attention weights?
  2. 2.scores has shape (B, H, T, T). Which axis does the softmax run over?
  3. 3.You apply the causal mask by multiplying the softmax output by a lower-triangular matrix of ones. What breaks?
  4. 4.Why subtract the row max before exponentiating?
  5. 5.At 8,192 tokens of context, how big is one head's fp16 score matrix for one sequence?
Multi-head causal self-attention
  1. 1.You split heads with q.reshape(B, n_head, T, C // n_head) and skip the transpose. What happens?
  2. 2.Your mask is torch.tril(torch.ones(T, T, dtype=torch.bool), diagonal=-1). What comes out for the first token?
  3. 3.CausalSelfAttention(10, 3) has no divisibility check. When does it fail?
  4. 4.You forgot the causal mask, and the training loss is dropping fast. What's going on?
  5. 5.C is 768. You go from 12 heads to 24. Which cost doubles?
A GPT from scratch
  1. 1.Your GPT has no position embeddings, and you feed it six copies of token 3. How do the logits at positions 1 and 4 compare?
  2. 2.You forget the causal mask and train on uniformly random tokens. What does the training loss do?
  3. 3.You leave out self.lm_head.weight = self.tok_emb.weight in GPT-2 small. What changes?
  4. 4.Your loss uses reduction="sum" and the batch is (2, 12). What does it report at initialization?
  5. 5.block_size is 16, there's no length check, and a batch arrives with 17 tokens. What happens on a CPU?
The KV cache
  1. 1.Why does the cache hold keys and values but never queries?
  2. 2.The cache is (B, H, T_past, d) and the new keys are (B, H, 1, d). Which line grows the cache?
  3. 3.With 3 tokens cached, you feed 2 new tokens at once, so the scores are 2 by 5. Which mask is right?
  4. 4.Whenever a cache comes in, your forward returns that cache instead of the grown one. You prefill a 4-token prompt and then decode 3 tokens. What happens?
  5. 5.Llama 3 8B has 32 layers, 8 key/value heads and a head size of 128. How much KV cache does one 8,192-token sequence need in 16-bit?
Decoding: temperature, top-k, top-p
  1. 1.You write logits * temperature and call it with T = 2. What comes out?
  2. 2.You sort the logits largest first and drop everything below sorted_logits[..., k]. With k = 3 and no ties, how many tokens survive?
  3. 3.Sorted probabilities are 0.5, 0.3, 0.15 and 0.05, and top_p is 0.7. Which tokens form the nucleus?
  4. 4.Your top-p code sorts the logits, masks the sorted tensor and returns it without scattering back. What do you sample?
  5. 5.sample() calls filter_logits() but then draws from (logits / temperature).softmax(-1). With top_k=3, the kept tokens hold 91% of the probability. How often does it draw a token top-k removed?
Backprop by hand
  1. 1.Your gradient check fails, and every analytic gradient is exactly 6 times its finite-difference value. The batch has 6 examples. What's the bug?
  2. 2.dlogits is (N, K) and already divided by N. Which line gives db2?
  3. 3.You write the ReLU backward as dh * (h >= 0), where h = np.maximum(pre, 0). What does it compute?
  4. 4.You forgot the ReLU mask entirely. Which of the practice tests fail?
  5. 5.You skip the max subtraction, and the test pushes the logits up to about 100,000. What comes back?
Matmul forward and backward
  1. 1.y = a @ b with a of shape (8, 16) and b of shape (16, 32). Which line computes the gradient for a?
  2. 2.Your backward ends with return grad_b, grad_a. With a of shape (3, 4) and b of shape (4, 5), PyTorch raises an error. What happens when a and b are both (4, 4)?
  3. 3.You average grad_b over the batch instead of summing it. The practice's batched tests use a batch of 2. What do the tests see?
  4. 4.a is (S, n, k) and b is (k, m). Your backward returns a.transpose(-1, -2) @ grad_out for b and never sums it. What happens in PyTorch?
  5. 5.a is (n, k) and b is (k, m), and both need gradients. The forward costs 2nkm FLOPs. What does the backward cost?
LoRA from scratch
  1. 1.You initialize B with torch.randn(out, r) * 0.01 instead of zeros. What happens?
  2. 2.You wrap nn.Linear(16, 12) with r = 4 and forget to freeze the base. How many parameters report requires_grad=True?
  3. 3.With alpha = 8 and r = 4, merge() runs W += B @ A and forgets the scale. What does the merged layer compute?
  4. 4.After merge(), your forward still adds the LoRA branch. What do you get?
  5. 5.Your layer multiplies the update by 1 instead of alpha / r. Which check catches it?
Debug a broken miniGPT, then add a KV cache
  1. 1.A fresh GPT with a 50,257-token vocabulary reports a step-0 loss of 10.95. What does that tell you?
  2. 2.You train on fresh, uniformly random tokens with V = 100, and the loss is 1.2 by step 300. What's your next move?
  3. 3.The causality test fails on the whole model, but your attention module matches F.scaled_dot_product_attention with is_causal=True to 1e-8. Where do you look next?
  4. 4.Your model trains to a low loss on a short text and writes the text back perfectly. What has that proven?
  5. 5.Your cached generate matches the uncached loop on the first new token and differs from the second one on. What does that tell you?