KatInterview

Fix Bugs in a Transformer and Build a KV Cache from Scratch

Machine LearningModel answer
HardModel answerMachine Learningtransformersattentionkv-cache

Last updated

Systematically locate and repair common implementation errors in a decoder-only Transformer, then add per-layer key-value caching to make autoregressive generation efficient.

Setup

You are working with a decoder-only Transformer language model: token and position embeddings feed into a stack of blocks, each containing masked multi-head self-attention followed by a position-wise feed-forward network, with residual connections and layer normalization throughout. A final linear projection maps the last hidden state to vocabulary logits. Inside the attention module, tensors carry shape (batch, heads, sequence, head_dim).

Someone has seeded the implementation with four or five deliberate mistakes. The code may or may not raise an exception — some bugs produce silently wrong numbers.


Part 1 — Find and Fix the Bugs

You are not handed a list of where the bugs are. Walk through how you would hunt them down efficiently without one.

Your answer should cover:

  • A systematic inspection strategy for the attention computation (projections, head reshaping, the scaling factor, the causal mask, softmax, and the output projection), the per-block wiring, and the next-token prediction loss.
  • Small, targeted tests that would surface a bug even when all tensor shapes are correct and no exception is raised.
  • For each category of likely bug: what it looks like, how you detect it, and how you fix it.
  • How you confirm that all fixes work correctly together.

Part 2 — Implement KV Caching from Scratch

Once the model is correct, restructure generation so it runs in two phases:

  1. Prefill — run the full prompt through every layer once.
  2. Decode — generate one new token at a time; each attention layer reads from a stored cache of all previous keys and values rather than recomputing them.

Write the cache yourself; do not rely on any library's built-in generation helper.

Your answer should cover:

  • The data structure that holds per-layer keys and values, including tensor shapes.
  • What changes inside the attention forward pass when the query sequence length is 1 but the key/value sequence length grows with each step.
  • How position offsets and the causal mask need to be adjusted during the decode phase.
  • A verification strategy that confirms cached and uncached generation produce identical logits (within floating-point tolerance).
  • Time and memory complexity of generation with and without the cache, and the practical trade-offs that come with caching.

Constraints

  • Write in the same tensor library the existing code uses.
  • Cached generation must match full recomputation numerically, not just approximately in terms of generated text.
  • Treat batch sizes greater than 1 and prompts of varying lengths as cases your answer should address, even if you only code the single-sequence path.

Hints

Hint 1

Start debugging by checking the attention scaling factor and the causal mask independently. A wrong scale silently changes every attention score; a mask that uses the wrong sign or the wrong diagonal offset causes the model to attend to future tokens without any shape error.

Hint 2

When implementing the cache, track a current position offset (an integer equal to the number of tokens already processed). Pass it into the attention layer so rotary or absolute position embeddings are applied at the right indices, and so the causal mask covers the right span.

Hint 3

To verify correctness, run greedy decoding for ~20 steps with and without the cache on a fixed random prompt and compare the logits at each step with torch.allclose. Also check that the cached keys and values at the end of generation equal what a full forward pass on the complete sequence would have produced.