1/30
Learn

Debug a broken miniGPT, then add a KV cache

Some ML rounds hand you a broken model instead of a blank file. This one comes up in ML engineer phone screens, and as the ML debugging round of research engineer loops. It reads like this:

Here's a small GPT, with its batching and generation code. It runs, and its loss goes down, but it doesn't generate the text it was trained on. There are five bugs. Find and fix them all. Before you change anything, tell me what you're checking and why.

Once it writes the right text, add a KV cache to generate, so that each new token costs one position, not the whole context.

The practice runs it in four levels: the two attention bugs, the position bug, the two bugs in the data and in generate, then the KV cache, which must give exactly the tokens the plain loop gives.

Here is the file as given, next to a fixed copy. Both trained for 300 steps on one sentence, the quick brown fox jumps over the lazy dog., repeated 30 times. Then each one continued the first five characters, the q:

First lossLoss after 300 stepsContinues the q as
the file as given2.880.002the qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
the fixed file3.390.026the quick brown fox jumps over the lazy dog.

The broken file reaches a lower loss than the fixed one, and still writes the wrong text. It even starts below 3.33, the loss of a fair guess among the sentence's 28 characters. Nothing errors along the way.

So the round tests method more than speed. The lesson builds the checks first, one for each way a model fails quietly: the loss at step 0, a floor on random tokens, causality, positions, targets, a twin for attention and the window in generate. Then it adds the cache. Near the end you walk the whole round on a 45-minute clock, and then you fix the file yourself as the practice problem.