KatInterview

Fix a Broken Tiny Transformer and Hand-Derive Matmul Gradients

Machine LearningModel answer
MediumModel answerMachine Learningpytorchtransformerkv-cache

Last 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 torch freely, but you should be able to write attention and a custom autograd.Function yourself.
  • 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 A of shape m x k and B of shape k x n. Be ready to extend to batched and broadcast inputs.

Part A: repair the model and add a KV cache

  1. 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.
  2. 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

  1. Implement the forward pass C = A @ B as a custom op.
  2. Given the upstream gradient dC = dL/dC, derive dA and dB. Show the derivation at the index level, then collapse it to matrix form.
  3. Implement it as a torch.autograd.Function using save_for_backward and validate it with gradcheck.
  4. 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 bmm and 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.