Grouped-Query Attention Interview Questions: Head Mapping, KV Memory, and Cached Decoding
Quick Overview
An original eight-query/two-KV attention exercise verifies contiguous head mapping against per-head and native GQA references. Cached decoding and an absolute-position chunk mask reproduce full attention; logical KV savings remain separate from unmeasured GPU performance.
For grouped-query attention interview questions, draw the query-to-KV head map before calculating memory savings. GQA retains separate query heads while letting a group of them share key and value heads. Check both the query-to-KV group assignment and the absolute key positions; matching tensor shapes alone proves neither.
This guide uses the original GQA paper and official PyTorch and Transformers documentation for architecture and interface facts. Its numerical checks come from an original CPU float64 experiment with PyTorch 2.14.1. The experiment verifies head mapping and cached-attention equivalence; it measures neither GPU speed nor trained-model quality.
Start with Implement Grouped-Query Attention (GQA). Write eight query heads above two KV heads, assign each query a group, then follow one query through scoring, masking and the value-weighted result. If a cached decoder passes shape checks but changes its output, that trace gives you a specific head assignment to inspect.

Define what is shared and what remains separate
The original GQA paper describes a family between multi-head attention and multi-query attention. Ordinary multi-head attention uses distinct key and value heads alongside its query heads. Multi-query attention shares one KV head across query heads. GQA uses an intermediate number of KV heads.
For the original exercise, query-head count is eight and KV-head count is two. Each KV head serves four contiguous query heads. Query heads zero, one, two and three use KV head zero; heads four through seven use KV head one. The group size is the query-head count divided by the KV-head count.
Sharing keys and values does not make the four query outputs identical. Their query vectors remain different, so they can assign different attention weights to the same keys and produce different weighted combinations of the shared values. Concatenate or otherwise combine those separate query-head outputs according to the model's output projection.
A basic implementation requires the grouping to be well defined. Check divisibility of the query-head count by the KV-head count, matching key/value head counts, compatible head dimensions and the expected head axis. A tensor reshape can succeed while assigning noncontiguous or incorrectly ordered query heads to a group.
Write the projection and cache shapes explicitly
Using batch, heads, sequence and head dimension as the axis order, our query tensor has shape one by eight by six by four. The key and value tensors each have shape one by two by six by four. Attention produces an output for all eight query heads; the shared KV-head count does not shrink the output's query-head axis.
In a model with eight query heads of dimension 128, the query projection produces 1,024 features per token. With two KV heads of that same dimension, each key or value projection produces 256. These are dimensions implied by the declared architecture, not parameter counts for every surrounding projection or normalization layer.
A persistent decoding cache should retain the compact KV representation when the implementation supports it. Explicitly repeating keys and values to eight heads is a useful correctness reference, but materializing and storing that expansion can give back the logical cache savings. Distinguish a temporary expanded view, a physical copy and the persistent cache allocation.
The official PyTorch scaled-dot-product attention interface exposes a GQA option with documented constraints and backend support. Verify the target version and execution backend. Passing a supported CPU reference test does not establish which fused accelerator kernel a production configuration will select.
Calculate the KV payload with its units
For equal key and value dimensions, a simple logical payload calculation multiplies two for K and V, layer count, batch size, retained token count, KV-head count, head dimension and bytes per stored element. This counts cache values under the stated dense-layout assumptions. It does not count model weights, attention workspace, allocator overhead or unused reserved blocks.
Our memory exercise uses 32 layers, batch one, 4,096 retained tokens, head dimension 128 and two bytes per element. With eight KV heads, the payload is 536,870,912 bytes, or 512 MiB. With two KV heads, it is 134,217,728 bytes, or 128 MiB. Dividing 134,217,728 by 536,870,912 gives one quarter for this logical K-plus-V payload.
| Declared architecture | Query heads | KV heads | Logical K-plus-V payload |
|---|---|---|---|
| Multi-head reference | Eight | Eight | 512 MiB |
| Grouped-query example | Eight | Two | 128 MiB |
| Shared assumptions | Batch one, 32 layers | 4,096 tokens, dimension 128 | Two bytes per stored value |
The fourfold ratio applies to this cache term. It does not predict a fourfold reduction in total device memory or latency. A deployment might instead use the released memory for more concurrent requests or a longer context, changing the workload rather than preserving a fixed comparison.
Sliding windows, quantized cache formats, different value dimensions and prefix sharing change the accounting. State which layers retain which token counts before applying a single uniform formula. The official Transformers cache guide describes cache strategies whose allocation and execution trade-offs require that broader context.

Prove the head map with a reference calculation
A transparent reference repeats each KV head four times along the head axis. The resulting order is KV zero four times followed by KV one four times. Repeating the entire two-head sequence four times would produce a different alternating assignment. Both expansions have eight heads, but alternating the groups changes which learned keys and values each query uses.
The excerpt below compares the declared contiguous repetition with the native GQA option. The full fixture also calculates attention independently for each query head using its assigned original KV head, a scaled matrix product, a triangular mask, softmax and a value product.
import torch
from torch.nn.functional import scaled_dot_product_attention as sdpa
torch.manual_seed(20261017)
q = torch.randn(1, 8, 6, 4, dtype=torch.float64)
k = torch.randn(1, 2, 6, 4, dtype=torch.float64)
v = torch.randn(1, 2, 6, 4, dtype=torch.float64)
kr = k.repeat_interleave(4, dim=1)
vr = v.repeat_interleave(4, dim=1)
reference = sdpa(q, kr, vr, is_causal=True, dropout_p=0.)
grouped = sdpa(q, k, v, is_causal=True, enable_gqa=True, dropout_p=0.)
assert reference.shape == (1, 8, 6, 4)
assert torch.allclose(reference, grouped, atol=1e-12, rtol=1e-12)
The separate per-head reference matters because two implementations can share a mistaken expansion rule. For query head h, explicitly select original KV head h divided by four using integer division. Then compare that head's output with the corresponding slice of the full result.
Use independently drawn Q, K and V tensors with seed 20261017, preserving distinct head and position values. An all-zero tensor or identical KV heads can make a wrong mapping appear correct. Our fixture fixes the seed for reproducibility and compares numerical values, not just output dimensions or the absence of an exception.
Treat cached decoding as an integration contract
During one-token decoding at absolute position t, the cache contains keys and values for positions zero through t. Every retained key is therefore at or before the current query. With no padding, excluded positions or sliding-window restriction in this fixture, the single query may attend to every key in that prefix.
The original test takes each query token from the full tensor and supplies the corresponding prefix of keys and values. Calling the attention operation without an additional causal mask reproduces that token's full-sequence causal result. Concatenating all six incremental outputs also matches the original six-token output.
This is a test of already supplied Q, K and V tensors. It does not execute token embeddings, an entire decoder, rotary-position updates or a real cache allocator. A full model must additionally ensure that cached representations, position indices and newly projected states follow its own contract.
The failure example is specific to the documented upper-left causal alignment of this PyTorch interface for a non-square query/key relation. Setting its causal flag for a one-row query and a longer cached prefix restricts the row as though it were the first local query. It does not automatically infer the query's absolute position at the end of that prefix.
In our deterministic fixture, the incorrect call agrees for token zero, where the prefix contains only one key. It disagrees at all five later positions; at token one, the maximum absolute difference is about 3.263014. That number demonstrates the original counterexample, not an expected error magnitude in a trained language model.
Check a multi-token chunk using absolute positions
A chunk makes the position issue visible without a large model. Suppose two queries correspond to absolute positions three and four, while the supplied keys cover positions zero through four. The first query may see keys zero through three; the second may see all five. Write the two allowed-key rows before selecting the mask argument.
The fixture constructs the allowed relation from absolute key positions less than or equal to absolute query positions. Its first row is true, true, true, true, false; its second row is all true. Applying that explicit boolean mask reproduces the corresponding two-token slice of full causal attention.
Boolean-mask meanings are interface-specific. In the SDPA operation used here, true identifies an allowed attention relation. Confirm the contract when moving between interfaces rather than reusing a boolean tensor merely because its shape broadcasts. A suitable shape with inverted meaning can silently remove the intended context.
GQA does not change the required causal relation. The mask must still align query positions with retained key positions while broadcasting across the appropriate query-head dimension. This article uses that integration check to validate the head-sharing implementation; a broader mask taxonomy belongs to a separate debugging exercise.
Separate correctness, memory and performance evidence
The full original fixture passes twenty-five assertions. They compare native GQA with explicit repetition, verify every per-head reference, compare six incremental results, test the two-token absolute-position mask and check the stated byte arithmetic. Dropout is explicitly zero so random masking does not obscure equality.
That evidence supports equivalence for these finite float64 CPU tensors and declared masks. It does not establish a speedup, peak-memory measurement or representational-quality result. The logical half-precision payload calculation uses different assumptions from the float64 correctness run and is labeled separately.
A performance experiment should report device, dtype, backend, batch and sequence sizes, prefill versus decode, warmup and synchronization policy. Measure the relevant allocation term rather than inferring peak device memory from head count. If expansion materializes a copy, include that allocation and its lifetime in the explanation.
A trained architecture also cannot generally reduce its KV-head count by changing a cache reshape alone. Projection weights and learned representations belong to the architecture. The GQA paper discusses conversion and training methods; our head-sharing tensor fixture does not implement a checkpoint conversion or establish the quality of a converted model.
For interview reasoning, finish by naming the next test that could reject your claim. A head-permutation test, a cached/full comparison or a measured allocation can each answer a different question. Keep the evidence attached to that question rather than treating a correct memory formula as proof of a complete inference system.
Practice the related implementation decisions
These verified PracHub titles are practice destinations, not evidence that a company uses this exact numerical fixture.
| Practice question | What to defend |
|---|---|
| Implement Grouped-Query Attention (GQA) | The contiguous query-to-KV mapping and distinct query outputs. |
| Implement Multi-Head Attention with a KV Cache and Cached Grouped-Query Attention | Compact stored KV shape and full-versus-cached equivalence. |
| Transformer Attention: Computing Q, K and V, and How a KV Cache Speeds Up Decoding | Which projections are reused and which work remains per token. |
| Debug a Small PyTorch Transformer with Four Bugs, Then Add a KV Cache | Numerical agreement across incremental positions. |
| Design an LLM Inference Serving System | How logical KV savings affect a measured serving-memory budget. |
Rehearse Implement Grouped-Query Attention (GQA) by deriving the eight-to-two map, predicting the persistent cache shape and checking one cached output. This rehearsal supports only the checked tensor and payload claims, not a GPU speedup, trained-model improvement or interview outcome.
Sources and Further Reading
- Ainslie and colleagues: GQA, Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints — original architecture and training research.
- PyTorch: scaled_dot_product_attention — official GQA, mask and causal-alignment interface.
- Hugging Face Transformers: Cache strategies — official cache-storage and execution trade-offs.
Comments (0)