[02-autoregressive-decoding-kv-cache] built a cache that grows one row per generated token. Every real serving deployment needs to know, ahead of time, how much GPU memory that cache will actually consume — this is the calculation every serving-capacity plan starts from. Compute the KV cache memory footprint (in bytes) for a batch of sequences, given model shape parameters and which attention variant (MHA, MQA, or GQA) is in use.
kv_heads = n_heads (MHA) | 1 (MQA) | n_kv_heads (GQA)
bytes_per_token = 2 * n_layers * kv_heads * d_head * bytes_per_element
total_bytes = batch_size * seq_len * bytes_per_token
variant is one of 'mha', 'mqa', 'gqa'; for 'mha' effective kv_heads = n_heads, for 'mqa' it's 1, for 'gqa' it's the given n_kv_heads.n_layers, seq_len, and batch_size.The formula is a pure product of six numbers — no loops or matrices needed, just get the variant-to-kv_heads mapping right. Always include the factor of 2 for storing both K and V, not just one of them.
Click "Run Tests" to test your implementation