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.
Tensor fluency
Attention
Building a GPT
Gradients and fine-tuning
Debugging under pressure
Practice questions
51PyTorch tensors: the attention toolkit
- 1.
xis(B, T, C)and you need(B, H, T, d)heads. Which line is right? - 2.
yis the(B, H, T, d)output ofatt @ v. What doesy.transpose(1, 2).view(B, T, C)do? - 3.
allowed = torch.tril(torch.ones(3, 3, dtype=torch.bool)). What doesatt.masked_fill(allowed, float('-inf')).softmax(dim=-1)give? - 4.
qkvis(B, T, 3C)with C = 64. Which call gives q, k and v, each(B, T, C)? - 5.
logitsis(B, T, V). Which gives a(B, 1)tensor of greedy ids to append toidx? - 6.
lin = nn.Linear(512, 1536)andxis(8, 128, 512). What arelin.weight.shapeandlin(x).shape?
Scaled dot-product attention
- 1.The head size goes from 64 to 256 and you forgot the 1/√d scale. What happens to the attention weights?
- 2.
scoreshas shape(B, H, T, T). Which axis does the softmax run over? - 3.You apply the causal mask by multiplying the softmax output by a lower-triangular matrix of ones. What breaks?
- 4.Why subtract the row max before exponentiating?
- 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.You split heads with
q.reshape(B, n_head, T, C // n_head)and skip the transpose. What happens? - 2.Your mask is
torch.tril(torch.ones(T, T, dtype=torch.bool), diagonal=-1). What comes out for the first token? - 3.
CausalSelfAttention(10, 3)has no divisibility check. When does it fail? - 4.You forgot the causal mask, and the training loss is dropping fast. What's going on?
- 5.C is 768. You go from 12 heads to 24. Which cost doubles?
A GPT from scratch
- 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.You forget the causal mask and train on uniformly random tokens. What does the training loss do?
- 3.You leave out
self.lm_head.weight = self.tok_emb.weightin GPT-2 small. What changes? - 4.Your loss uses
reduction="sum"and the batch is (2, 12). What does it report at initialization? - 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.Why does the cache hold keys and values but never queries?
- 2.The cache is
(B, H, T_past, d)and the new keys are(B, H, 1, d). Which line grows the cache? - 3.With 3 tokens cached, you feed 2 new tokens at once, so the scores are 2 by 5. Which mask is right?
- 4.Whenever a cache comes in, your
forwardreturns that cache instead of the grown one. You prefill a 4-token prompt and then decode 3 tokens. What happens? - 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.You write
logits * temperatureand call it with T = 2. What comes out? - 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.Sorted probabilities are 0.5, 0.3, 0.15 and 0.05, and
top_pis 0.7. Which tokens form the nucleus? - 4.Your top-p code sorts the logits, masks the sorted tensor and returns it without scattering back. What do you sample?
- 5.
sample()callsfilter_logits()but then draws from(logits / temperature).softmax(-1). Withtop_k=3, the kept tokens hold 91% of the probability. How often does it draw a token top-k removed?
Backprop by hand
- 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.
dlogitsis(N, K)and already divided by N. Which line givesdb2? - 3.You write the ReLU backward as
dh * (h >= 0), whereh = np.maximum(pre, 0). What does it compute? - 4.You forgot the ReLU mask entirely. Which of the practice tests fail?
- 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.
y = a @ bwithaof shape(8, 16)andbof shape(16, 32). Which line computes the gradient fora? - 2.Your backward ends with
return grad_b, grad_a. Withaof shape(3, 4)andbof shape(4, 5), PyTorch raises an error. What happens whenaandbare both(4, 4)? - 3.You average
grad_bover the batch instead of summing it. The practice's batched tests use a batch of 2. What do the tests see? - 4.
ais(S, n, k)andbis(k, m). Your backward returnsa.transpose(-1, -2) @ grad_outforband never sums it. What happens in PyTorch? - 5.
ais(n, k)andbis(k, m), and both need gradients. The forward costs 2nkm FLOPs. What does the backward cost?
LoRA from scratch
- 1.You initialize
Bwithtorch.randn(out, r) * 0.01instead of zeros. What happens? - 2.You wrap
nn.Linear(16, 12)with r = 4 and forget to freeze the base. How many parameters reportrequires_grad=True? - 3.With alpha = 8 and r = 4, merge() runs
W += B @ Aand forgets the scale. What does the merged layer compute? - 4.After merge(), your forward still adds the LoRA branch. What do you get?
- 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.A fresh GPT with a 50,257-token vocabulary reports a step-0 loss of 10.95. What does that tell you?
- 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.The causality test fails on the whole model, but your attention module matches
F.scaled_dot_product_attentionwithis_causal=Trueto 1e-8. Where do you look next? - 4.Your model trains to a low loss on a short text and writes the text back perfectly. What has that proven?
- 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?