Fix Bugs in a Transformer and Build a KV Cache from Scratch
Machine LearningModel answerLast 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:
- Prefill — run the full prompt through every layer once.
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Systematic Bug Hunting
Inspection Strategy
Rather than reading every line hoping a bug jumps out, work through the forward pass in the order data flows and write a small test at each stage before moving on.
Attention projections and head reshaping. After the Q, K, V linear projections, the code splits the embedding dimension into heads. Two bugs appear here constantly: reshaping to (batch, seq, heads, head_dim) and then forgetting to transpose to (batch, heads, seq, head_dim), or transposing the wrong two axes. Test by checking that q.shape == (B, H, S, D) and that the values are not just a reshape artifact — run with B=1, H=2, S=3, D=4 and verify the head slices actually differ.
The scaling factor. Attention scores should be divided by sqrt(head_dim), not sqrt(embed_dim) and not head_dim alone. A wrong scale pushes softmax toward uniform or peaky distributions. Detect it by printing the pre-softmax scores with a known Q and K: with head_dim=64 the scale should be 1/8. A common bug is using model.d_model instead of model.head_dim.
The causal mask. The mask must zero out (or set to -inf) positions where j > i, i.e., the upper triangle excluding the diagonal. Two recurring mistakes: using torch.triu with diagonal=0 instead of diagonal=1 (which masks the current position too), and adding the mask with the wrong sign so future tokens get higher scores rather than lower. Test by running a two-token sequence and checking that the attention weight for position 0 attending to position 1 is exactly zero.
Residual connections and layer norm placement. Pre-norm (LayerNorm before the sublayer) and post-norm (after) behave differently but both are valid. The bug is usually an inconsistency — norm applied in one block but not another, or the residual addition accidentally omitted. Check by confirming output = x + sublayer(norm(x)) (pre-norm) is uniform across all blocks.
The loss function. For next-token prediction the target at position i is the token at position i+1, so the logits and targets must be shifted by one. A common mistake is loss(logits, targets) where logits has shape (B, S, V) and targets has shape (B, S) without the shift, causing the model to predict the current token from itself. Also check that the loss function receives logits, not probabilities — passing softmax output into CrossEntropyLoss applies softmax twice.
Verification tests
- Overfit a single batch of two sequences for ~200 steps; a correct model reaches near-zero loss. If it plateaus above ~1.0, a bug is likely in the loss or masking.
- Run the model twice on the same input with
dropout=0andtorch.manual_seedfixed; outputs must be bitwise identical. - Set all weights to identity-like values and verify the output matches a hand-computed expectation.
Part 2 — KV Cache Implementation
Cache Data Structure
class KVCache:
def __init__(self, num_layers, max_seq_len, num_heads, head_dim, device):
# Pre-allocate to avoid repeated concatenation
shape = (1, num_heads, max_seq_len, head_dim)
self.k = [torch.zeros(shape, device=device) for _ in range(num_layers)]
self.v = [torch.zeros(shape, device=device) for _ in range(num_layers)]
self.length = 0 # tokens stored so far
def update(self, layer_idx, new_k, new_v):
# new_k, new_v: (1, H, T, D) where T=1 during decode
t = new_k.shape[2]
self.k[layer_idx][:, :, self.length:self.length + t] = new_k
self.v[layer_idx][:, :, self.length:self.length + t] = new_v
def get(self, layer_idx):
return (self.k[layer_idx][:, :, :self.length],
self.v[layer_idx][:, :, :self.length])
Pre-allocating to max_seq_len avoids the O(n) concatenation cost that accumulates to O(n²) memory operations over a full generation run.
Changes to the Attention Forward Pass
The layer needs two new parameters: layer_idx and an optional cache.
def forward(self, x, position_offset=0, cache=None, layer_idx=None):
B, S, E = x.shape
q = self.W_q(x).view(B, S, self.H, self.D).transpose(1, 2)
k = self.W_k(x).view(B, S, self.H, self.D).transpose(1, 2)
v = self.W_v(x).view(B, S, self.H, self.D).transpose(1, 2)
if cache is not None:
cache.update(layer_idx, k, v)
cache.length += S # only increment once per forward pass
k, v = cache.get(layer_idx) # full history
scale = self.D ** -0.5
scores = torch.matmul(q, k.transpose(-2, -1)) * scale
# S_q x S_kv causal mask
S_kv = k.shape[2]
mask = torch.ones(S, S_kv, device=x.device).tril(
diagonal=S_kv - S # offset so each query can see all past tokens
)
scores = scores.masked_fill(mask == 0, float('-inf'))
attn = torch.softmax(scores, dim=-1)
out = torch.matmul(attn, v)
return self.W_o(out.transpose(1, 2).reshape(B, S, E))
The diagonal offset S_kv - S is the key detail: during decode, S=1 and S_kv grows each step, so the single query must attend to all S_kv previous positions without any masking.
Position Handling
For absolute learned embeddings, pass position_offset into the embedding lookup:
positions = torch.arange(S, device=x.device) + position_offset
x = token_emb(tokens) + pos_emb(positions)
For rotary embeddings (RoPE), apply the rotation using frequencies at indices [position_offset : position_offset + S] rather than always starting at 0.
Generation Loop
def generate(model, prompt_ids, max_new_tokens, max_seq_len):
cache = KVCache(model.num_layers, max_seq_len,
model.num_heads, model.head_dim, prompt_ids.device)
model.eval()
with torch.no_grad():
# Prefill
logits = model(prompt_ids, position_offset=0, cache=cache)
next_token = logits[:, -1:].argmax(-1)
generated = [next_token]
offset = prompt_ids.shape[1]
# Decode
for _ in range(max_new_tokens - 1):
logits = model(next_token, position_offset=offset, cache=cache)
next_token = logits[:, -1:].argmax(-1)
generated.append(next_token)
offset += 1
return torch.cat(generated, dim=1)
Verification
# Logit-level check, not just text-level
with torch.no_grad():
full_seq = torch.cat([prompt_ids, generated_ids], dim=1)
logits_full = model_no_cache(full_seq) # no cache
# Cached logits were collected during generation; compare step by step
assert torch.allclose(logits_cached, logits_full[:, prompt_len-1:-1], atol=1e-5)
Also verify that cache.k[i][:, :, :total_len] equals the K matrix from a single full-sequence forward pass through layer i.
Complexity
| Time per token | Memory | |
|---|---|---|
| No cache | O(n²·d) — recomputes all attention | O(n·d) activations |
| With cache | O(n·d) — one query against n keys | O(n·L·H·D) for stored KV |
For a 7B-parameter model with 32 layers, 32 heads, head_dim 128, and a 4k context, the KV cache holds roughly 4096 × 32 × 2 × 32 × 128 × 2 bytes ≈ 2 GB in fp16 — a real constraint at long contexts. Common mitigations include grouped-query attention (GQA), which reduces the number of KV heads, and sliding-window attention, which caps cache growth.
Common Mistakes to Avoid
- Incrementing
cache.lengthinside the K/V update helper — it gets called once per layer but the offset should advance once per generation step. - Forgetting to set
model.eval(), leaving dropout active and making cached and uncached runs diverge. - Applying position embeddings before caching K and V but after retrieving them, causing positions to be applied twice to cached tokens.