Compare KV cache size for multi-head, grouped-query and latent attention

The KV cache, not the weights, often decides how many users a GPU can serve. Grouped-query attention shrinks it by sharing key/value heads. Latent-attention designs in the style of DeepSeek-V2's MLA go further: per token and layer they cache one compressed latent vector plus a small shared rotary key, and rebuild per-head keys and values from the latent.

Write kv_cache_bytes(layers, heads, kv_heads, head_dim, latent_dim, rope_dim, tokens, bytes_per_val). Return a dict of ints:
- "mha": 2 * layers * heads * head_dim * tokens * bytes_per_val (keys and values for every head)
- "gqa": 2 * layers * kv_heads * head_dim * tokens * bytes_per_val
- "latent": layers * (latent_dim + rope_dim) * tokens * bytes_per_val (one latent and one rotary key, no factor of 2)

Signaturedef kv_cache_bytes(layers, heads, kv_heads, head_dim, latent_dim, rope_dim, tokens, bytes_per_val)

Example

kv_cache_bytes(1, 4, 2, 8, 6, 2, 10, 2) gives mha 1280, gqa 640, latent 160.

Understand the idea

During generation, every past token's keys and values are kept in memory for every layer. This KV cache often limits how many users a GPU can serve. Standard multi-head attention stores a key and a value per head. Grouped-query attention lets several query heads share one key/value head, shrinking the cache. Latent attention stores just one compressed vector plus a small rotary key per token and layer, and rebuilds keys and values from it. Worked example: 32 layers, 32 heads, 8 kv_heads, head_dim 128, 1000 tokens, 2 bytes per value, latent_dim 512, rope_dim 64. MHA = 2 * 32 * 32 * 128 * 1000 * 2 = 524,288,000 bytes. GQA = 2 * 32 * 8 * 128 * 1000 * 2 = 131,072,000. Latent = 32 * (512 + 64) * 1000 * 2 = 36,864,000. Rules: mha = 2 * L * heads * head_dim * T * B; gqa = same with kv_heads; latent = L * (latent_dim + rope_dim) * T * B, with no factor of 2 because one vector serves both keys and values. Used for GPU capacity planning; LLaMA 3 uses GQA and DeepSeek-V2 uses latent attention.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplekv_cache_bytes(1, 4, 2, 8, 6, 2, 10, 2)
  • Sample 2: large model, 32k tokenskv_cache_bytes(60, 128, 8, 128, 512, 64, 32768, 2)
  • Test 3: fp8 cachekv_cache_bytes(32, 32, 8, 128, 512, 64, 4096, 1)