26/30
Part 6 of 6 · What interviewers ask nextLearn and do

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.