Estimate KV cache memory with cross-layer KV sharing

Why it matters KV cache size often limits batch size and context length in serving, and cross-layer sharing is one way to shrink it.

Cross-layer KV sharing lets a group of adjacent layers reuse one layer's keys and values, so only one KV cache is stored per group.

Write shared_kv_bytes(n_layers, share, kv_heads, head_dim, tokens, batch, bytes_per_val). Layers are grouped in consecutive groups of size share (the last group may be smaller), and each group stores one K and one V cache. Return a dict: "baseline" is the bytes with no sharing, 2 * n_layers * kv_heads * head_dim * tokens * batch * bytes_per_val; "shared" is the same with n_layers replaced by the number of groups; "saving" is baseline / shared as a float.

Signaturedef shared_kv_bytes(n_layers, share, kv_heads, head_dim, tokens, batch, bytes_per_val)

Example

shared_kv_bytes(32, 2, 8, 128, 4096, 1, 2) is {"baseline": 536870912, "shared": 268435456, "saving": 2.0}.

Understand the idea

Every attention layer normally keeps its own keys and values for all past tokens, so cache memory grows with the number of layers. Cross-layer sharing lets neighbouring layers read the same cache, the way flatmates share one fridge instead of each buying their own.

Example: 32 layers, 8 KV heads of size 128, 4096 tokens, batch 1, 2 bytes per value (bf16). Per layer: 2 * 8 * 128 * 4096 * 2 = 16,777,216 bytes (16 MiB). All 32 layers: 512 MiB. Sharing in pairs leaves 16 caches: 256 MiB, a 2x saving. With 30 layers in groups of 4, you get 8 groups, not 7, because the last two layers still need a cache.

Rule: bytes = 2 * ceil(L / share) * kv_heads * head_dim * tokens * batch * bytes_per_val.

This stacks with grouped-query attention, which already cuts kv_heads. Research models that share KV across layers report large cache savings with a small quality cost.

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

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

  • Sample 1: exampleshared_kv_bytes(32, 2, 8, 128, 4096, 1, 2)
  • Sample 2: uneven groupsshared_kv_bytes(30, 4, 8, 128, 8192, 4, 2)
  • Test 3: no sharingshared_kv_bytes(12, 1, 12, 64, 1024, 8, 2)