Build Causal Attention, a KV Cache, and Grouped-Query Attention
Machine LearningModel answerLast 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
einsumand 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:
- Project
xinto queries, keys, and values. - Split each into
n_headsheads and arrange the axes consistently. - Compute scaled dot-product attention: scale by
1 / sqrt(head_dim), apply a causal mask, run a numerically stable softmax. - 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
Tand model widthd_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:
- Maintain a cache that holds the keys and values for all previously processed tokens.
- On each call, append the new keys and values, then attend from current queries over the full cached sequence.
- 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 (whenn_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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The three parts share one class; each part only adds to what came before, so there is no rewrite. The key disciplines are consistent axis order, a correct causal mask at every call shape, and a clean group-indexing scheme for GQA.
Part 1 — Multi-head attention
Projections and head split. Project x with three weight matrices to get Q, K, V of shape (batch, seq_len, d_model). Reshape each to (batch, seq_len, n_heads, head_dim) and transpose to (batch, n_heads, seq_len, head_dim). Keeping heads in axis 1 means every subsequent operation is a batched matrix multiply over the last two axes.
Scaled dot-product attention. Compute scores = Q @ K.T / sqrt(head_dim), giving shape (batch, n_heads, seq_len, seq_len). Apply a causal mask by filling positions where col > row with -inf before the softmax; after softmax those become zero weight. Use a numerically stable softmax (subtract the row-max first, or rely on torch.softmax).
Complexity. The dominant cost is the QK^T multiply: O(T^2 · d_model) time, O(T^2 · n_heads) memory for the attention matrix. Both grow quadratically with sequence length.
import torch
import torch.nn as nn
import math
class GroupedQueryAttention(nn.Module):
def __init__(self, d_model, n_heads, n_kv_heads, max_len=2048):
super().__init__()
assert n_heads % n_kv_heads == 0
self.n_heads = n_heads
self.n_kv_heads = n_kv_heads
self.head_dim = d_model // n_heads
self.groups = n_heads // n_kv_heads
self.max_len = max_len
self.Wq = nn.Linear(d_model, n_heads * self.head_dim, bias=False)
self.Wk = nn.Linear(d_model, n_kv_heads * self.head_dim, bias=False)
self.Wv = nn.Linear(d_model, n_kv_heads * self.head_dim, bias=False)
self.Wo = nn.Linear(n_heads * self.head_dim, d_model, bias=False)
# KV cache: preallocated, grown by a cursor
self.register_buffer('cache_k',
torch.zeros(1, max_len, n_kv_heads, self.head_dim))
self.register_buffer('cache_v',
torch.zeros(1, max_len, n_kv_heads, self.head_dim))
self.cursor = 0 # how many positions are filled
def _split_heads(self, x, n_h):
# x: (B, T, n_h * head_dim) -> (B, n_h, T, head_dim)
B, T, _ = x.shape
return x.view(B, T, n_h, self.head_dim).transpose(1, 2)
def _sdp_attention(self, q, k, v, mask):
# q: (B, n_q_heads, Tq, D) k/v: (B, n_kv, Tk, D)
scale = math.sqrt(self.head_dim)
scores = torch.matmul(q, k.transpose(-2, -1)) / scale # (B, n_q, Tq, Tk)
scores = scores.masked_fill(mask, float('-inf'))
weights = torch.softmax(scores, dim=-1)
return torch.matmul(weights, v) # (B, n_q, Tq, D)
Part 2 — KV cache
Layout. Preallocate cache_k and cache_v of shape (batch, max_len, n_kv_heads, head_dim) and track an integer cursor. On every call, write the new K/V slice at [cursor : cursor + T_new], then read back [0 : cursor + T_new] as the full key/value context. This avoids repeated allocation from list concatenation.
Mask shape. During prefill T_q == T_k and the mask is a standard lower-triangular square. During decode T_q == 1 and T_k == cursor + 1; the mask is a (1, T_k) row of all False (the single query attends everywhere), so the -inf fill never fires.
Compute savings. Without a cache, generating token t costs O(t · d_model) for the KV projections alone, so the total over a sequence of length L beyond the prompt is O(L^2 · d_model). With the cache, those projections are paid once during prefill; each decode step costs O(L · d_model) for the attention dot-product — a factor of L saving per step.
Memory cost. The cache holds 2 · batch · max_len · n_kv_heads · head_dim floats. At float16 that is 2 · 1 · 2048 · 8 · 64 · 2 bytes ≈ 4 MB per layer for one sequence — substantial when stacked across many layers.
Correctness check. Run a full uncached forward over a 5-token sequence, then reset the cursor and run prefill on tokens 1–4 followed by one decode step on token 5. The outputs for token 5 must match to within floating-point tolerance.
def forward(self, x, use_cache=False):
B, T, _ = x.shape
q = self._split_heads(self.Wq(x), self.n_heads) # (B, n_heads, T, D)
k = self._split_heads(self.Wk(x), self.n_kv_heads) # (B, n_kv, T, D)
v = self._split_heads(self.Wv(x), self.n_kv_heads)
if use_cache:
# write new slice into cache
self.cache_k[:B, self.cursor:self.cursor+T] = k.transpose(1, 2)
self.cache_v[:B, self.cursor:self.cursor+T] = v.transpose(1, 2)
T_total = self.cursor + T
# read back full context
k = self.cache_k[:B, :T_total].transpose(1, 2) # (B, n_kv, T_total, D)
v = self.cache_v[:B, :T_total].transpose(1, 2)
self.cursor = T_total
# causal mask: shape (T_q, T_k)
q_idx = torch.arange(self.cursor - T, self.cursor, device=x.device).unsqueeze(1)
k_idx = torch.arange(self.cursor, device=x.device).unsqueeze(0)
mask = k_idx > q_idx # True where attention must be blocked
else:
row = torch.arange(T, device=x.device).unsqueeze(1)
col = torch.arange(T, device=x.device).unsqueeze(0)
mask = col > row
# Part 3: expand KV heads to match query heads
k = k.repeat_interleave(self.groups, dim=1) # (B, n_heads, T_k, D)
v = v.repeat_interleave(self.groups, dim=1)
out = self._sdp_attention(q, k, v, mask) # (B, n_heads, T, D)
out = out.transpose(1, 2).contiguous().view(B, T, -1)
return self.Wo(out)
Part 3 — Grouped-query attention
Head routing. Each query head h maps to KV head h // groups. repeat_interleave(groups, dim=1) on the K and V tensors expands them from n_kv_heads to n_heads in the right order, so head h in the expanded tensor is indeed the correct KV head. An alternative is to index with a precomputed vector [0,0,...,1,1,...,n_kv-1,n_kv-1,...]; both are correct, repeat_interleave is more readable.
Cache size under GQA. The cache stores only n_kv_heads heads, not n_heads. For a model with n_heads=32, n_kv_heads=8, the KV cache is 4× smaller than standard multi-head attention — the primary motivation for GQA in production LLMs.
Special cases. Setting n_kv_heads = n_heads makes groups = 1; repeat_interleave is a no-op and the code is identical to standard multi-head attention. Setting n_kv_heads = 1 makes groups = n_heads; every query head shares the single KV head — that is multi-query attention (MQA).
Common mistakes
- Transposing at the wrong point. Forgetting to call
.contiguous()before.view()after a transpose causes a runtime error or silent shape bug. - Wrong mask during decode. Using a square causal mask when
T_q=1, T_k>1either blocks all attention or wastes compute filling a row that will never matter. - Cache shape mismatch. Allocating the cache for
n_headsinstead ofn_kv_headsdefeats GQA's memory benefit and breaks the head-expansion step. - Not resetting the cursor between sequences. The cursor must be zeroed at the start of each new sequence; stale cache entries cause silent correctness failures that are hard to catch without the uncached comparison test.
- Softmax over
-infcolumns. If every key in a row is masked (impossible with a correct causal mask, but possible with a buggy padding mask), the softmax output isNaN. Adding an epsilon or checking for all-masked rows prevents this.