KatInterview

Build Causal Attention, a KV Cache, and Grouped-Query Attention

Machine LearningModel answer
HardModel answerMachine Learningtransformersattentiondeep-learning

Last updated

Implement causal multi-head attention from scratch, add a KV cache for step-by-step decoding, then extend it to grouped-query attention where query heads share KV heads.

You are building the attention layer of a decoder-only transformer in three stages, each one extending the last. Use NumPy or PyTorch directly — no built-in attention functions or transformer libraries.

The layer is part of an autoregressive model: every token can only attend to itself and the tokens before it. The primary input is a batch of hidden states x with shape (batch, seq_len, d_model). The layer owns its own projection weights for queries, keys, values, and output.

Before coding, think through these questions out loud:

  • Which tensor library will you use, and are einsum and broadcasting fair game?
  • Are projection weights owned by the layer, or do queries/keys/values arrive already projected?
  • Can you assume all sequences in a batch have the same length, or do you need a padding mask?
  • Is the KV cache preallocated to a fixed maximum length, or does it grow by appending?
  • Is positional encoding (e.g., rotary embeddings) applied inside this layer or upstream?

Part 1 — Causal multi-head self-attention

Implement the full forward pass with n_heads heads, each of size head_dim = d_model // n_heads:

  1. Project x into queries, keys, and values.
  2. Split each into n_heads heads and arrange the axes consistently.
  3. Compute scaled dot-product attention: scale by 1 / sqrt(head_dim), apply a causal mask, run a numerically stable softmax.
  4. Reassemble the heads and apply the output projection.

Your answer should address:

  • How you split and merge heads without scrambling the axis order.
  • Where the causal mask comes from and what values it uses.
  • Time and memory complexity as functions of sequence length T and model width d_model.

Part 2 — KV cache for token-by-token decoding

Without a cache, generating each new token requires recomputing keys and values for every earlier token — work that grows linearly with the sequence. Fix that by storing past keys and values.

The first forward call (prefill) processes the whole prompt at once. Every subsequent call (decode step) receives only the single new token and must attend to all prior tokens through the cache.

Extend your Part 1 implementation to:

  1. Maintain a cache that holds the keys and values for all previously processed tokens.
  2. On each call, append the new keys and values, then attend from current queries over the full cached sequence.
  3. Build the attention mask correctly when the number of queries (1 during decoding) differs from the number of cached keys.

Your answer should address:

  • How the cache is laid out and updated.
  • How much computation the cache saves per decode step (versus the uncached baseline).
  • How much memory the cache consumes as a function of sequence length, batch size, and model dimensions.
  • A correctness check: show that decoding token-by-token with the cache matches a single uncached forward pass over the full sequence.

Part 3 — Grouped-query attention with the cache

Standard multi-head attention gives every query head its own key and value head. Grouped-query attention (GQA) reduces that cost: the n_heads query heads are divided into n_kv_heads groups, and every query head in a group shares one key/value head. n_kv_heads evenly divides n_heads.

Extend your implementation to support GQA while keeping the KV cache from Part 2.

Your answer should address:

  • How you route each query head to the right key/value head without a mixing bug.
  • What the cache stores under GQA and how its memory footprint compares to full multi-head attention.
  • How the same code degenerates to standard multi-head attention (when n_kv_heads == n_heads) and to multi-query attention (when n_kv_heads == 1).

Hints

Hint 1

For the head split, reshape x to (batch, seq_len, n_heads, head_dim) then transpose so heads are a leading axis — and keep that convention all the way through to the merge step so you never need to rearrange mid-computation.

Hint 2

For the KV cache, storing a (batch, max_len, n_kv_heads, head_dim) tensor and tracking a single integer cursor is simpler and faster than appending lists; on the decode step you slice [0:cursor] for keys and values, and your query-side mask is just a row vector of length cursor rather than a full square.

Hint 3

For GQA, compute a group index as head_idx // (n_heads // n_kv_heads); you can either index with that vector or use repeat_interleave to expand KV heads up to n_heads before the dot product — the second form reuses your Part 1 attention kernel unchanged.