Fix a Broken Tiny Transformer and Hand-Derive Matmul Gradients
Machine LearningModel answerLast updated
Debug a small decoder-only transformer whose generation is wrong, add a KV cache, then derive and implement a custom matmul autograd op and discuss parallel scans.
This is a two-part, hands-on PyTorch exercise. Treat it as a pair-programming session: you run code, read output, and explain tensor shapes and gradients as you go.
Setup
- Python with PyTorch. You can use
torchfreely, but you should be able to write attention and a customautograd.Functionyourself. - The model in Part A is a small decoder-only transformer (a few layers, hidden size in the low hundreds, a small vocabulary). It runs without errors, but text produced by autoregressive generation is wrong. The faults are logical, not syntactic.
- Part B starts with dense 2-D matrices, with
Aof shapem x kandBof shapek x n. Be ready to extend to batched and broadcast inputs.
Part A: repair the model and add a KV cache
- Find and fix the bug(s) so that greedy (argmax) generation yields the expected output. Explain, for each stage, the tensor shapes, the causal mask, the attention computation, how positions are encoded, how the loss targets are shifted, the effect of train vs. eval mode, and how decoding works.
- Implement key-value caching so that each decode step attends over the cached prefix (cost linear in the current length) rather than recomputing the whole sequence (quadratic).
Part B: matmul with a hand-written backward pass
- Implement the forward pass
C = A @ Bas a custom op. - Given the upstream gradient
dC = dL/dC, derivedAanddB. Show the derivation at the index level, then collapse it to matrix form. - Implement it as a
torch.autograd.Functionusingsave_for_backwardand validate it withgradcheck. - Follow-up: explain how a parallel prefix scan (such as Hillis-Steele) could help parallelize the associative accumulation in a tiled matmul, and when it does and does not make sense.
Questions worth asking up front
- Is the model already trained (fix generation only), or must training be fixed too?
- What is the oracle: a target string, a reference implementation, or a loss threshold?
- Are positions learned absolute embeddings or rotary?
- Should the op support
bmmand broadcasting?
Hints
Hint 1
Make the failure deterministic first: eval mode, greedy decoding, fixed seed. Then add shape asserts and check each candidate bug class in turn: scaling, mask applied before softmax, softmax axis, head/time axis mixing, position indices, target shift, dropout in eval.
Hint 2
Cached decode must match uncached decode token for token. At decode, the query has length 1 while keys and values have length T, so the attention matrix is 1 x T and the new token's position index is the cache length, not 0.
Hint 3
Start from C_ij = sum_r A_ir B_rj. Differentiate with respect to A_ir and B_rj, sum over the output indices that touch each entry, and use shape matching (dA like A, dB like B) to confirm the transposes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: debugging the transformer
Workflow. Make the failure reproducible before changing anything: model.eval(), torch.no_grad(), greedy decoding, fixed seed, a short fixed prompt. Then localize by instrumenting rather than guessing: assert shapes at each block boundary, e.g. x: (B, T, D), q/k/v: (B, H, T, Dh), scores: (B, H, T, T).
Bug classes to check, in order of likelihood
- Scaling. Scores must be divided by
sqrt(Dh)(head dim, not model dim). Missing or wrong scaling makes softmax too peaky and degrades output. - Causal mask. The mask must be lower-triangular and applied to the scores before softmax, filling masked positions with
-inf. Multiplying probabilities by the mask after softmax leaves rows unnormalized and still leaks information in training. A leak in training gives a suspiciously low loss and garbage at generation, because the model learned to peek at the future. - Softmax axis. It must run over the key axis (
dim=-1of(B,H,Tq,Tk)). Softmax over the query axis is a classic silent bug. - Head split/merge. Reshape
(B,T,D) -> (B,T,H,Dh) -> transpose(1,2). Reshaping directly to(B,H,T,Dh)without the transpose mixes time and head axes. Merging must undo it exactly, with.contiguous()beforeview. - Positions. Positional embeddings must be indexed by actual position (
arange(T)), and during generation by absolute position, not restarted at 0. - Loss shift. Logits at position
tpredict tokent+1:loss = CE(logits[:, :-1], tokens[:, 1:]). Without the shift the model learns identity copying. - Train vs. eval. Dropout must be off in eval; check
self.traininggating on attention and residual dropout. - Decoding. Take logits at the last position only,
argmax(-1), append, and crop to the context window.
State which one you found, and show the smallest test that proves the fix (e.g. perturbing a future token must not change earlier logits).
KV cache design
- Prefill: run the full prompt once, save per-layer
k, vof shape(B,H,T,Dh). - Decode step: feed only the newest token with position index
T_cache. Computeq,k,vfor that token, concatenatek,vonto the cache along the time axis (dim=2), and attend withq: (B,H,1,Dh)againstK: (B,H,T+1,Dh). The score matrix is1 x (T+1), so no causal mask is needed (the single query may see all cached keys). Cost per step is O(T) per layer instead of O(T^2). - Thread the cache through every layer (a list of
(k, v)per layer).
def attn(self, x, cache=None):
B, T, D = x.shape
q, k, v = self.qkv(x).split(D, dim=-1)
q, k, v = [t.view(B, T, H, Dh).transpose(1, 2) for t in (q, k, v)]
if cache is not None:
k = torch.cat([cache[0], k], dim=2)
v = torch.cat([cache[1], v], dim=2)
new_cache = (k, v)
s = q @ k.transpose(-1, -2) / Dh**0.5
if cache is None: # prefill: causal mask
mask = torch.tril(torch.ones(T, T, device=x.device)).bool()
s = s.masked_fill(~mask, float('-inf'))
y = s.softmax(-1) @ v
return self.proj(y.transpose(1, 2).reshape(B, T, D)), new_cache
If decoding more than one token at once with a cache, the mask must be offset (tril(diagonal=T_cache)) and non-square.
Invariant: cached and uncached generation must give identical tokens (and logits within float tolerance). Test this on several prompts.
Cost. Cache memory is 2 * layers * B * H * T * Dh * bytes, linear in context. Reducers: multi-query or grouped-query attention (fewer KV heads), fp16/int8 cache quantization, paged cache allocation, and sliding windows.
Part B: matmul backward
Index derivation. With C_ij = sum_r A_ir B_rj:
dL/dA_ir = sum_{j} dL/dC_ij * dC_ij/dA_ir = sum_j dC_ij B_rj = (dC B^T)_irdL/dB_rj = sum_{i} dC_ij A_ir = (A^T dC)_rj
So dA = dC @ B^T and dB = A^T @ dC. Shape check: (m,n)(n,k) = (m,k) matches A, and (k,m)(m,n) = (k,n) matches B.
class MatMul(torch.autograd.Function):
@staticmethod
def forward(ctx, A, B):
ctx.save_for_backward(A, B)
return A @ B
@staticmethod
def backward(ctx, dC):
A, B = ctx.saved_tensors
return dC @ B.transpose(-1, -2), A.transpose(-1, -2) @ dC
Validate with torch.autograd.gradcheck(MatMul.apply, (A, B)) using small float64 tensors with requires_grad=True.
Batched and broadcast. For bmm the same formulas work per batch with transposes on the last two dims. If an operand was broadcast (e.g. B shared across the batch, shape (k,n) against (b,m,k)), the gradient for that operand must be summed over the broadcast axes so its shape matches the input. A common mistake is returning a gradient with the broadcast shape.
Follow-up: Hillis-Steele scan
A tiled matmul accumulates partial products along k, which is an associative operation (addition). Hillis-Steele computes all inclusive prefixes in log2(n) steps, where at step d each element adds the one at offset 2^d (offsets 1, 2, 4, ...). It does O(n log n) work with O(log n) depth.
- When it helps: if you genuinely need every prefix (e.g. running partial sums, or linear-attention/state-space style recurrences where each position's prefix is an output), or when depth matters and you have abundant parallel lanes.
- When it does not: for matmul you need only the final sum per output, so a tree reduction does O(n) work with O(log n) depth, which is work-efficient. Tuned GEMM kernels use register/shared-memory tiling with in-thread accumulation, which beats a scan. A work-efficient scan (Blelloch) is preferred over Hillis-Steele when prefixes are needed and work matters.
Common mistakes
- Applying the mask after softmax, or softmax on the wrong axis.
- Resetting position indices to 0 during cached decode.
- Forgetting to sum gradients over broadcast dimensions.
- Claiming correctness without a parity test or
gradcheck.