Library/Transformers from scratch/Debugging under pressure

Debug a broken miniGPT, then add a KV cache

85 min6 partsAdvancedFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Run a debugging round out loud, with a hypothesis and a check before every change
  • Say what the loss should be at step 0, to two decimals, and what a loss that's too good means
  • Use random tokens and one tiny batch as checks, and say what each of them can't see
  • Check an untrained model for causality, positions, targets, shapes and scales, and against a known-good twin
  • Say which bugs a training curve shows, which only generation shows, and which neither does
  • Add a KV cache to generate, with the position offset, the restart at block_size and the test that proves it

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.

Part 1 of 6about 8 min
The round

The model runs, and the text is still wrong

The file you get runs, its loss goes down, and its text is still wrong. It is short enough to read in five minutes, so nobody is timing how fast you spot a typo. The interviewer watches how you search:

  • Do you say what you expect before you run something?
  • Does each change follow from a fact?
  • Can you prove a fix, or do you only hope it worked?
Predict

Most bugs in a model raise no error. What does the loss usually do with one in?

Pick an answer above to see the rest

Say the symptom, the causes and the check that splits them

The method rests on one habit: from a symptom, name the few causes that fit it.

SymptomCausesThe check
loss 0.02 after 30 steps on random tokens, V = 50attention sees the futurecausality test
the target is in the inputtarget check

Steps 3 and 4 sound like this, out loud. The loss is 0.02 after 30 steps on random tokens, with 50 tokens in the vocabulary. Nothing in random data can be predicted, so the model is reading the answer. It has two ways to do that: attention lets it see the future, or the target is sitting in its input. The causality test tells them apart. If changing tokens 7 onward moves the outputs before position 7, it's attention.

That's the pattern every time: the symptom, its causes, the check that splits them, and what each result means.

Predict

You spot an odd line while reading. What comes before you change it?

Pick an answer above to see the rest
Predict

Which of these is a wrong bug, not just a worse one?

Pick an answer above to see the rest
Predict

You edit three odd-looking lines at once, and the output changes. What do you know?

Pick an answer above to see the rest
Part 1 done
Part 2 of 6about 18 min
Loss checks

A fresh model gives every token the same small chance

With 65 tokens in the vocabulary, a fresh model gives each one a chance of about 1/65:

loss=−ln⁡165=ln⁡65=4.17\text{loss} = -\ln \frac{1}{65} = \ln 65 = 4.17

The cheapest check runs before any training. A fresh model knows nothing, so it gives every token about the same chance, 1/V1/V, where VV is the number of tokens in the vocabulary. Its first loss is then about −ln⁡(1/V)=ln⁡V-\ln(1/V) = \ln V.

Karpathy's recipe makes this a rule: check that the loss starts at the value it should. It takes one forward pass, and it tests the model, the loss and the init together.

The gap above ln V tells you how big the logits are

import math
import torch
import torch.nn.functional as F

torch.manual_seed(0)
V = 65
targets = torch.randint(0, V, (20_000,))
for s in (0.17, 0.58):
    # random logits, spread s
    logits = s * torch.randn(20_000, V)
    loss = F.cross_entropy(logits, targets).item()
    print(f"s {s}: loss {loss:.3f}   ln V + s*s/2 = {math.log(V) + s * s / 2:.3f}")
Predict

Random logits with spread s = 0.17, then 0.58, over 65 tokens. How do the losses compare with ln 65 = 4.17?

Pick one to see what it prints.
Pick an answer above to see the rest

Measure it through the code you were given

Now run that check on the model you were handed. Here data, get_batch and model are the ones in the practice file.

x, y = get_batch(data, model.block_size, 16)
with torch.no_grad():
    logits, loss = model(x, y)
V, s = logits.size(-1), logits.std().item()
print(f"measured {loss.item():.3f}   ln V {math.log(V):.3f}   s {s:.3f}")
print(f"predicted ln V + s^2/2 = {math.log(V) + s * s / 2:.3f}")

On a fresh, healthy GPT with 65 tokens in its vocabulary, and 100,000 random tokens as data, one batch printed this:

measured 4.203   ln V 4.174   s 0.175
predicted ln V + s^2/2 = 4.190

One batch is a little noisy, so the measured loss sits a hundredth above the prediction. Use their get_batch and their model, not a batch you build yourself: a bug anywhere on that path, from their data to their loss, moves this one number.

Three inits give three first losses

Here are three fresh copies of one GPT: 2 layers, 64 wide, 65 tokens in the vocabulary, so ln⁡65=4.17\ln 65 = 4.17. They differ only in their init.

Predict

Tie the head to the token table, and keep PyTorch's default init for the table, spread 1. What's the first loss, against ln 65 = 4.17?

Pick an answer above to see the rest

Read the first loss three ways: healthy, too high or too low

Slide the loss you measured, or pick one of the three inits, and read it:

Read the step-0 loss, V = 65Interactive
below: a leak just above: healthy far above: logits too big
4.19 sits 0.02 above ln 65. That gap means logits with a spread of about √(2 × 0.02) = 0.18. Healthy: move on.
  • Within a few hundredths of ln⁡V+s2/2\ln V + s^2/2. Healthy. Move on.
  • Far above ln⁡V\ln V. The logits are too large, so the model starts confident and wrong. Follow the logit size back through the head and its init. This is usually worse, not wrong: the model still trains. It spends its first steps shrinking the logits, so the curve drops steeply and then runs flat, a shape Karpathy calls a hockey stick.
  • Well below ln⁡V\ln V. Before learning anything, the model already gives the right answers a high chance. A random model can't know them, so something is handing them over. That's a leak, and the next checks find it.
Watch · 9 min

The step-0 check on a real network. The first loss is far above ln 27 = 3.30 because the softmax is confidently wrong, and shrinking the output layer at init fixes the start and lowers the final loss.

Building makemore Part 3: Activations & Gradients, BatchNorm · Andrej Karpathy · Oct 2022YouTube

On random tokens, no honest model gets below ln V

The next check catches a model that sees the answer.

from collections.abc import Callable


def floor_test(model: nn.Module, get_batch: Callable, V: int, steps: int = 300) -> float:
    """Trains on random tokens. Returns the mean of the last 10 losses."""
    # nothing here can be predicted
    data = torch.randint(0, V, (100_000,))
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    losses = []
    for _ in range(steps):
        _, loss = model(*get_batch(data, model.block_size, 16))
        opt.zero_grad(); loss.backward(); opt.step()
        losses.append(loss.item())
    # about ln V, never well below
    return sum(losses[-10:]) / 10

This trains the model on uniformly random tokens, through their batch function, for a few hundred steps. Nothing in random tokens can be predicted. So the best any honest model can do is give every token 1/V1/V, and its loss can't go below ln⁡V\ln V. That lowest possible loss is the data's floor.

Predict

Why train this test on random tokens, not real text?

Pick an answer above to see the rest
Predict

The causality test fails. Do you still run the target check?

Pick an answer above to see the rest
Predict

You close a leak, and the loss jumps from 0.02 to 3.5. What do you do?

Pick an answer above to see the rest

Overfit one batch, to prove the model can learn

A model that can't learn at all is the opposite failure, and it has its own check.

# the only batch it will see
x, y = get_batch(data, model.block_size, 2)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
for step in range(301):
    _, loss = model(x, y)
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 50 == 0:
        print(step, round(loss.item(), 4))

This asks the opposite question. The floor test asks whether the model can cheat. This one asks whether it can learn at all:

CheckIt asksThe answer must be
random tokenscan the model cheat?no
one batchcan the model learn?yes

Take one tiny batch and train on nothing else. Karpathy's recipe suggests as few as two examples, trained until the loss reaches the lowest value it can, here 0. Any working GPT can memorize two sequences.

Predict

The blocks sit in a plain Python list, so the optimizer can't see them. Can the model still memorize two sequences?

Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 8 min
Causality

Change tokens 7 onward, and outputs before 7 must not move

The causal rule can be tested head on.

def causal_test(model: nn.Module, V: int, T: int = 12, cut: int = 7) -> None:
    """Fails if changing tokens cut onward moves any output before cut."""
    idx = torch.randint(0, V, (1, T))
    later = idx.clone()
    # change every token from cut on
    later[0, cut:] = (later[0, cut:] + 1) % V
    with torch.no_grad():
        before = model(idx)[0][:, :cut]
        after = model(later)[0][:, :cut]
    moved = (before - after).abs().max().item()
    assert moved < 1e-5, f"outputs before position {cut} moved by {moved:.3g}"

A causal model's output at position tt may depend on tokens 0 to tt, and on nothing after. This tests exactly that, on a fresh model, with no training. Positions 0 to 6 get the same input in both runs, so their outputs must not move. Positions 7 onward changed, so theirs may.

Predict

Why run the causality test on the whole model, not on the attention module alone?

Pick an answer above to see the rest

A gradient chart shows the shape of a leak

The causal test says that a leak exists. A chart shows where it is.

def dependency_chart(model: nn.Module, V: int, T: int = 6) -> None:
    """Prints which inputs each output t sends gradient to."""
    seen = {}

    def keep(module: nn.Module, inputs: tuple, out: torch.Tensor) -> None:
        out.retain_grad()
        seen["emb"] = out
    hook = model.tok_emb.register_forward_hook(keep)
    try:
        for t in range(T):
            logits, _ = model(torch.randint(0, V, (1, T)))
            logits[0, t].sum().backward()
            print(t, [int(g.abs().sum() > 0) for g in seen["emb"].grad[0]])
    finally:
        hook.remove()

When the causality test fails, get a picture of the leak. Send a gradient back from one output, and see which inputs receive any of it. Row tt is the output at position tt, the one that predicts token t+1t + 1.

The idea is all that matters here, not the API names. Keep the token embeddings from the latest forward pass, and ask autograd for their gradient. In this code:

  • register_forward_hook(keep) makes PyTorch call keep every time tok_emb runs, so seen holds the latest token embeddings.
  • Autograd fills .grad only on tensors you made with requires_grad=True, like the weights. retain_grad() asks it to fill this computed one's .grad too.
  • logits[0, t].sum().backward() sends a gradient back from output position t alone. The list marks each input position whose embedding got any of it.
Predict

In a healthy model, which input positions does output 3 send gradient to?

Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 20 min
Positions, targets, shapes and twins

One repeated token shows whether order gets in

A model can also ignore position entirely, and still train.

def position_test(model: nn.Module) -> None:
    """Prints how much positions 1 and 4 differ, at the logits and at block 0."""
    seen = {}

    def keep(module: nn.Module, inputs: tuple, out: torch.Tensor) -> None:
        # what block 0 receives
        seen["x"] = inputs[0]
    hook = model.blocks[0].register_forward_hook(keep)
    try:
        with torch.no_grad():
            logits = model(torch.full((1, 6), 3))[0][0]
    finally:
        hook.remove()
    gap = lambda rows: (rows[1] - rows[4]).abs().max().item()
    print("logits, position 1 vs 4:       ", gap(logits))
    print("block 0 input, position 1 vs 4:", gap(seen["x"][0]))

A model that can't tell positions apart still trains. Causal attention leaks some order, and the tokens carry a lot on their own. So use the sharpest input there is: one token, repeated. Every position then sees copies of the same vector, and only the positions can make the outputs differ.

Predict

Zero the position table, and feed one token six times. How different is block 0's input at positions 1 and 4?

Pick an answer above to see the rest

Targets are the inputs shifted by one

Some bugs live outside the model, in the data loading.

def get_batch(
    data: torch.Tensor, block_size: int, batch_size: int, generator: torch.Generator | None = None
) -> tuple[torch.Tensor, torch.Tensor]:
    """The practice's. data: (N,) token ids. Returns x and y, each (batch_size, block_size)."""
    starts = torch.randint(0, len(data) - block_size - 1, (batch_size,), generator=generator)
    x = torch.stack([data[s:s + block_size] for s in starts])
    y = torch.stack([data[s:s + block_size] for s in starts])
    return x, y


# the token after n is n + 1
counting = torch.arange(1_000)
x, y = get_batch(counting, 8, 4, torch.Generator().manual_seed(0))
print(x[0].tolist())
print(y[0].tolist())
print(torch.equal(y, x + 1))
Predict

counting is 0 to 999, so the token after n is n + 1. Read the practice's get_batch above. What does torch.equal(y, x + 1) print?

Pick one to see what it prints.
Pick an answer above to see the rest

Read one real batch as text

Here a token is one character:

inputto be or not t
targeto be or not to

Then decode one real batch back to text, and read each input above its target. Karpathy's recipe says the one place to look at your data is right before it goes into the model. Ten seconds of reading settles what a page of reasoning about slices can't.

In the editor is the practice's get_batch, with targets that copy the inputs. Fix the line that builds y, so that each target is the token after its input, the last one included.

CheckpointFix the batch's targets

This is the practice's get_batch, and its targets are a copy of its inputs. Fix it so y holds the token after each token of x, the last one included.

Every shape and every scale has a reason

When the parts look right but the numbers don't, trace them through the model.

def trace(model: nn.Module, idx: torch.Tensor) -> None:
    """Prints each embedding, LayerNorm and linear output's shape and spread."""

    def show(name: str) -> Callable:
        def hook(module: nn.Module, inputs: tuple, out: torch.Tensor) -> None:
            shape = str(tuple(out.shape))
            print(f"{name:18} {shape:14} std {out.std().item():.3f}")
        return hook
    kinds = (nn.Embedding, nn.LayerNorm, nn.Linear)
    hooks = [m.register_forward_hook(show(n))
             for n, m in model.named_modules() if isinstance(m, kinds)]
    try:
        with torch.no_grad():
            model(idx)
    finally:
        for h in hooks:
            h.remove()

In one pass, this prints the shape and the spread of what every embedding, LayerNorm and linear layer puts out. Here is part of what the healthy V=65V = 65 model prints at init, for idx of shape (2, 12):

tok_emb            (2, 12, 64)    std 0.020
pos_emb            (12, 64)       std 0.021
blocks.0.ln1       (2, 12, 64)    std 0.994
blocks.0.attn.qkv  (2, 12, 192)   std 0.161
blocks.0.attn.proj (2, 12, 64)    std 0.012
blocks.0.mlp.0     (2, 12, 256)   std 0.157
ln_f               (2, 12, 64)    std 0.998
lm_head            (2, 12, 65)    std 0.174
Predict

A linear layer with weights of spread 0.02 reads 64 inputs of spread 1. About what spread comes out?

Pick an answer above to see the rest

A library twin checks a whole part

PyTorch already has a correct attention, and you can test yours against it.

def twin(attn: nn.Module, x: torch.Tensor) -> torch.Tensor:
    """x: (B, T, C). Returns attn's output, rebuilt on F.scaled_dot_product_attention."""
    B, T, C = x.shape
    H = attn.n_head
    q, k, v = attn.qkv(x).split(C, dim=2)
    q, k, v = (t.view(B, T, H, C // H).transpose(1, 2) for t in (q, k, v))
    y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    return attn.proj(y.transpose(1, 2).reshape(B, T, C))

attn = model.blocks[0].attn
x = torch.randn(2, 9, attn.proj.in_features)
with torch.no_grad():
    print("max diff:", (attn(x) - twin(attn, x)).abs().max().item())

Some parts have a library version you can trust: F.scaled_dot_product_attention for attention, F.layer_norm, F.cross_entropy. A twin is your part rebuilt around that library call. Write it from what you know, not by copying the lines under test. Then give both the same weights and the same input, and print the largest difference between them.

Predict

Your attention and its twin differ by about 1e-2 on the same weights and input. What does that mean?

Pick an answer above to see the rest
Predict

You set the twin's is_causal=False, and now it matches yours exactly. What does your module do?

Pick an answer above to see the rest

Swap the twin into every block

The twin also narrows down a failing model.

for block in model.blocks:
    block.attn.forward = lambda x, a=block.attn: twin(a, x)

When a whole-model test fails, swap the twin in for every block and run the test again:

The failing test, rerun with the twin in every blockMeans
passes nowthe bug is inside your attention
still failsthe bug is somewhere else

With the mask removed, the causality test fails, and it passes again once the twin is in.

Assigning to block.attn.forward replaces that one module's forward, so block.attn(x) now runs the twin.

Predict

Leave out the default a=block.attn in the lambda. Which block's attention would every lambda call?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 18 min
Generation, and the whole round

Every new token must match a fresh pass on its window

Generation has bugs of its own, separate from training.

def check_generate(model: nn.Module, generate: Callable, prompt: torch.Tensor, n: int) -> None:
    """Fails if a new token isn't the pick from its last block_size tokens."""
    out = generate(model, prompt, n)
    with torch.no_grad():
        for t in range(prompt.size(1), out.size(1)):
            window = out[:, max(0, t - model.block_size):t]
            want = model(window)[0][:, -1].argmax(dim=-1)
            assert torch.equal(out[:, t], want), f"token {t} is off"

generate has its own contract: every new token is the model's pick given the most recent block_size tokens. This check reruns the model on exactly that window, for each new token:

Each new token comes from the 4 tokens before itInteractive
block_size = 4. The dashed cell is the token being picked.
t4 comes from the last 4 tokens, t0 t1 t2 t3: idx[:, -block_size:].

Run it past block_size, on a trained model

Run it past block_size: a window bug can't show before the window fills. Turn on crop from the front in the figure above: from t5 on, the wrong crop reads the same first window every step.

Predict

Greedy decoding always picks the top-scoring token. On an untrained model, does a wrong crop show in the text?

Pick an answer above to see the rest

One end-to-end test runs every part

Then the end-to-end test. Train on a short text until the model memorizes it. Generate from its first few tokens to well past block_size, and compare with the text.

That one test runs the batch function, the model, the loss, the optimizer and generate together. It takes seconds, so one is enough.

In the editor is the practice's generate, which crops the wrong end of the window. Fix it, so that every new token is the model's pick given the most recent model.block_size tokens.

CheckpointCrop the window from the right end

This is the practice's generate. Fix its window so every new token is the model's pick given the most recent model.block_size tokens. The tests use a model with a 4-token window whose pick depends on every token in it.

Each symptom points at a few causes

Each symptom narrows the search to a few causes, and one check usually splits them.

Predict

Good loss, wrong text. Where do you look?

Pick an answer above to see the rest

Every check becomes a test

A fix that isn't tested can come back.

Predict

You write a test for a bug you just found. Where do you run it first?

Pick an answer above to see the rest
Predict

The text repeats one token, so you switch from argmax to sampling, and the repetition goes away. Is the bug fixed?

Pick an answer above to see the rest

A worked example: the round in 45 minutes

The round, minute by minute

Here is the whole round on the practice file, with what to do and say at each step, and how long each one takes:

StepWhat you do and sayMinutes
1Read the whole file out loud: each part, every shape, every constant and its reason. Note what looks off, and change nothing.5
2Run it as given: a training run, then a generation past block_size. Write down every symptom.3
3The step-0 loss through their own get_batch, against ln⁡V\ln V. Say what the gap means.4
4The checks that need no training: causality, positions, targets, shapes and the twin. For each failure, say the hypothesis, change one line and rerun them all.13
5The random-token floor and one overfit batch. Then the end-to-end test and the generation check, past block_size.7
6Say which check caught each bug, and where each one would have shown.3
7The KV cache: one forward path, positions from the cache, a restart when the window fills, and the two comparisons.10

Close by saying where each bug would have shown

Predict

A bug in how generate crops its window. Would a training curve have shown it?

Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 13 min
What interviewers ask next

What interviewers ask next: a KV cache in generate

The attention side is built, so the model and the loop are left

Once the text is right, the follow-up is a KV cache. The KV cache lesson built the attention side. Each layer appends this step's keys and values to its cache, offsets the mask by the cached length and returns the grown (k, v). Each block hands its cache back next to its output.

What's left is the model and the loop around it. Two things decide whether those are right: the position each new token gets, and what the loop does when the cache runs out of room.

Two words from that lesson come up again. The prefill is the first pass over the whole prompt, which fills the cache. A decode step runs one new token on top of the cache.

Send training and generation through one forward path

# one layer's (k, v), each (B, H, T, d)
Cache = tuple[torch.Tensor, torch.Tensor]


class CausalSelfAttention(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # plain callers still get a tensor
        return self.forward_cached(x)[0]

    def forward_cached(
        self, x: torch.Tensor, cache: Cache | None = None
    ) -> tuple[torch.Tensor, Cache]:
        # the cached attention, as before
        ...


class Block(nn.Module):
    def forward(
        self, x: torch.Tensor, cache: Cache | None = None
    ) -> tuple[torch.Tensor, Cache]:
        a, cache = self.attn.forward_cached(self.ln1(x), cache)
        x = x + a
        return x + self.mlp(self.ln2(x)), cache


class GPT(nn.Module):
    def forward_cached(
        self, idx: torch.Tensor, caches: list[Cache] | None = None
    ) -> tuple[torch.Tensor, list[Cache]]:
        """idx: (B, T), after the cached tokens. Returns (B, T, V) and the caches."""
        B, T = idx.shape
        # cached length
        past = 0 if caches is None else caches[0][0].size(2)
        if past + T > self.block_size:
            raise ValueError(f"position {past + T - 1} is past block_size")
        pos = torch.arange(past, past + T, device=idx.device)
        x = self.tok_emb(idx) + self.pos_emb(pos)
        caches = caches or [None] * len(self.blocks)
        new = []
        for block, cache in zip(self.blocks, caches):
            x, cache = block(x, cache)
            new.append(cache)
        return self.lm_head(self.ln_f(x)), new

The KV cache lesson's loop calls the model's parts directly. In a debugging round, send training and generation through one method instead, so a fix lands in both:

CallerGoes through
training: model(idx, targets)forward_cached, then the blocks
generation: generateforward_cached, then the blocks

The __init__ methods don't change. attn(x) still returns a tensor, and model(idx, targets) still returns the logits and the loss, so every test you've written keeps running. Only Block returns something new, and only forward_cached calls it.

GPT.forward is left out above, because it's yours to write. In the editor is ToyGPT, a stand-in with two tables. Its forward_cached(idx, past) returns the logits for tokens that come after past cached ones, and the new past. Write forward(idx, targets=None), the training path: get the logits from forward_cached at position 0, and return (logits, None) without targets or (logits, loss) with them.

New tokens sit at position past, not at 0

Six tokens are cached at positions 0 to 5, and one new token arrives:

Positionspos_emb row for the new token
righttorch.arange(past, past + T)6
wrongtorch.arange(T)0

The new tokens sit at positions past onward, so they need pos_emb rows past onward. Embed them at torch.arange(T), and every decode step lands at position 0.

The first new token still comes out right, because it comes from the prefill, which starts at 0 with an empty cache. Every one after it is computed at the wrong position.

Predict

Where should forward_cached read past, the cached length, from?

Pick an answer above to see the rest
Predict

The window is full, and the loop crops a off the front to make room for e. Can you keep the cached keys and values of b, c and d?

Pick an answer above to see the rest
Predict

A 4-token window and a 2-token prompt. The cache is full after step 3. What does step 4 feed the model?

Pick an answer above to see the rest

Prove that the cache changes the cost and nothing else

The KV cache is the last part of the round, and it needs its own proof.

with torch.no_grad():
    # idx is (B, 12)
    full, _ = model(idx)
    # prefill
    a, caches = model.forward_cached(idx[:, :7])
    # one decode step
    b, caches = model.forward_cached(idx[:, 7:8], caches)
    # a chunk on top
    c, caches = model.forward_cached(idx[:, 8:], caches)
assert torch.allclose(full, torch.cat([a, b, c], dim=1), atol=1e-4)

cached = generate(model, prompt, 80)
assert torch.equal(cached, generate_uncached(model, prompt, 80))

The contract is that caching changes the cost and nothing else. So test the model and the loop separately, and keep the old loop as generate_uncached.

TestRunMust match
the modelone full pass on 12 tokens, against a prefill of 7, a decode step of 1 and a chunk of 4the same logits
the loopthe old loop and the cached loop, 80 new tokens eachthe same tokens

The first compares a prefill, a decode step and a chunk with one full pass, through the whole model. The atol, the absolute tolerance, has room because float noise grows with the logits: on a trained model the two differed by up to 8e-6.

The second runs both loops from one prompt on a trained model, far enough past block_size that the restart fires many times. On a model trained to memorize a short text, with a 32-token window and 80 new tokens, the cached loop matched the uncached one on every token. With the position offset left out, it went wrong at position 16. It didn't recover until the window filled and the restart re-embedded everything from position 0. Compare every token, not the last few.

Predict

You check a cached step against F.scaled_dot_product_attention(..., is_causal=True): one new query on 6 cached keys. What does is_causal=True let the query see?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.A fresh GPT with a 50,257-token vocabulary reports a step-0 loss of 10.95. What does that tell you?

  2. 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. 3.The causality test fails on the whole model, but your attention module matches F.scaled_dot_product_attention with is_causal=True to 1e-8. Where do you look next?

  4. 4.Your model trains to a low loss on a short text and writes the text back perfectly. What has that proven?

  5. 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?

Where this shows up

The reports behind this lesson, each with its source.

Same April 2026 MLE report, ML debug round: fix a broken miniGPT in PyTorch until it generates correct text, then implement a KV cache.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-24Source

Research Engineer loop per a Blind commenter (Oct 2025): a deep dive, regular coding and ML debugging.

Candidate report·Blind (commenter on a candidate's post)·2025-10-08Source

Same Blind commenter (Oct 2025): the recruiter's e-mail said to study the transformer model ahead of the ML debugging round.

Candidate report·Blind (commenter on a candidate's post)·2025-10-08Source

A candidate in a thread about OpenAI and Meta GenAI ML coding rounds (Jan 2025) found ML coding with debugging a PyTorch model hard; the company is not named in the comment.

Candidate report·Blind (candidate comment)·2025-01-31Source

Practice

Sources (1)
  1. A Recipe for Training Neural Networks · Andrej Karpathy's blog · Apr 25, 2019
    “Verify that your loss starts at the correct loss value. E.g. if you initialize your final layer correctly you should measure -log(1/n_classes) on a softmax at initialization.”