13Debug a broken miniGPT, then add a KV cache
13 Debug a broken miniGPT, then add a KV cache
An April 2026 OpenAI ML engineer screen, as reported: fix a broken miniGPT until it generates correct text, then add a KV cache (1 report). A Research Engineer loop on Blind had an ML debugging round too (1 report); a third report (1 report) comes from a thread about OpenAI and Meta and doesn't say which.
solution.py is a small GPT with its batching and generation code. It runs and its loss goes down,
but it does not generate the text it was trained on. There are five bugs. Find and fix them all, the
way you would on a shared screen: say what you check and why before you change anything.
Then the follow-up: add a KV cache to generate so each new token costs one position, not the
whole context (problem 04 has the attention side).
Read one level at a time and run only its tests until they pass: pytest problems/13_debug_minigpt -k level1.
Earlier levels must keep passing.
Level 1. The attention. It matches F.scaled_dot_product_attention(q, k, v, is_causal=True) with the same
weights, and changing tokens 7 onward doesn't move the model's outputs before position 7. Two bugs.
Level 2. The positions. Six copies of one token give different outputs at positions 1 and 4. One bug.
Level 3. The data and generation. Every target is the token after its input, the last one included, and after
300 training steps on a short text, generate continues a 5-token prompt with 80 tokens of that text. Two bugs.
Level 4. The KV cache. GPT.forward_cached(idx, caches=None) returns the logits and a list with one (k, v)
per block, each (B, n_head, T, head_dim) as in problem 04, for tokens that come after the cached ones: they sit at
position past, the cached length, and a position past block_size raises ValueError. A prefill, a decode step
and a chunk give one full pass's logits. generate runs every step through model.forward_cached (the tests count
what it feeds): the prompt once, cropped to its last block_size tokens, then one token per step. When the cache is
full it starts over from the last block_size tokens, and it gives exactly the tokens of the plain loop.
attn(x) and model(idx, targets) keep working.
Things worth saying out loud: what each symptom tells you (loss too low to be true, a model that can see the future, positions that don't matter), the checks you'd add so each bug can never come back, and which bugs would have shown up in a training curve and which only in generation.