Compare KV cache bytes across attention variants
Calculate MHA, GQA, MQA and latent-attention cache sizes from the same dimensions and see why fewer KV heads does not always mean less state.
The KV cache is often the largest per-request memory cost at long context. Its size depends on the number of layers, the sequence length, the number of KV heads, the head dimension and the dtype. Multi-head attention stores a key and a value for every head. Grouped-query attention stores them for fewer KV heads and repeats them at attention time. Multi-query attention stores one KV head. Multi-latent attention stores a latent vector per token and projects it back.
This example computes all four for the same small dimensions: two layers, eight positions, four query heads, two KV heads, head dimension two, and two bytes per element. MHA needs 512 bytes, GQA 256, MQA 128. The latent variant also reports 512, because its latent dimension equals the model dimension here. That equality is a property of these inputs, not a general claim about MLA.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch21/attention_variants.py --jsonPython 3.11 or later with PyTorch. CPU-only, seeded, no model download, network, GPU or credentials. It finishes in about a second.
Implementation
kv_cache_bytes multiplies keys and values by layers, positions, KV heads, head
dimension and dtype width. The three attention modules produce outputs of the same
shape, so the cache calculation is the variable under test. The latent figure
uses the latent dimension directly.
def kv_cache_bytes(num_layers: int, seq_len: int, num_kv_heads: int, head_dim: int, dtype_bytes: int = 2) -> int:
# keys + values
return 2 * num_layers * seq_len * num_kv_heads * head_dim * dtype_bytes
def run(dim: int = 8, num_heads: int = 4, num_kv_heads: int = 2, latent_dim: int = 8, seq_len: int = 8, layers: int = 2) -> dict:
x = torch.randn(1, seq_len, dim)
mha = MHA(dim, num_heads)
gqa = GQA(dim, num_heads, num_kv_heads)
mla = MLA(dim, num_heads, latent_dim)
with torch.no_grad():
y_mha = mha(x)
y_gqa = gqa(x)
y_mla = mla(x)
return {
"mha_kv_bytes": kv_cache_bytes(layers, seq_len, num_heads, dim // num_heads),
"gqa_kv_bytes": kv_cache_bytes(layers, seq_len, num_kv_heads, dim // num_heads),
"mqa_kv_bytes": kv_cache_bytes(layers, seq_len, 1, dim // num_heads),
"mla_latent_bytes": 2 * layers * seq_len * latent_dim * 2,
"mha_output_shape": list(y_mha.shape),
"gqa_output_shape": list(y_gqa.shape),
"mla_output_shape": list(y_mla.shape),
}Expected outcome
Observed with the command above (exit 0):
{
"mha_kv_bytes": 512,
"gqa_kv_bytes": 256,
"mqa_kv_bytes": 128,
"mla_latent_bytes": 512,
"mha_output_shape": [
1,
8,
8
],
"gqa_output_shape": [
1,
8,
8
],
"mla_output_shape": [
1,
8,
8
]
}The arithmetic for MHA is 2 * 2 layers * 8 positions * 4 heads * 2 dim * 2 bytes = 512. Halving the KV heads halves the cache to 256; one KV head gives
128. The latent figure is 2 * 2 * 8 * 8 * 2 = 512; with latent_dim=8 it is
not smaller than MHA. All three modules return the same output shape, which is
necessary but not sufficient to show they compute the same function.
Mechanism and limitations
Documented: GQA rejects a head count that is not divisible by the KV-head
count, repeats KV heads to match query heads, and applies the causal mask. MLA
projects to a latent vector and back to keys and values. run seeds the input,
runs all three modules and reports cache bytes plus output shapes. The tests check
the KV-byte identity, GQA divisibility, output shapes, the MHA/GQA/MQA ordering
and JSON serialisation.
Observed: the command exited 0 with the four cache sizes and three shapes
above. The targeted tests.test_ch21_attention is part of the canonical suite;
no independent test count is claimed here.
Not shown: model quality, attention parity between variants, trained weights, latent absorption, the actual DeepSeek MLA layout, or GPU cache layout. The modules are randomly initialised sketches; equal output shape does not mean equal output. The latent formula is a simplified accounting, not a measurement of a production MLA cache.
Challenge this result
Set latent_dim=4 and recompute the latent bytes by hand before running. Then set
num_kv_heads=1 and compare GQA with MQA. Explain why GQA with one KV head is MQA,
and why MLA’s saving depends on the latent dimension rather than on the number of
query heads. Finally, state one quality experiment that would be needed before
choosing a variant for a model, beyond cache bytes.
Source and verification
Canonical source:
examples/ch21/attention_variants.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch21_attention.py
.
Chapter: Multi-Head and Multi-Latent Attention
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it uses randomly initialised modules.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.