Grouped query attention (GQA) lets several query heads share a key head and a value head. It preserves multiple query heads while reducing the number of key/value heads stored during autoregressive inference. That makes the KV cache smaller than multi-head attention (MHA) with the same layer count, token count, head dimension, and cache dtype.
For the worked example below—32 layers, 32 query heads, head dimension 128, BF16 cache, and 8,192 cached tokens—MHA with 32 KV heads needs 4 GiB of logical KV cache per request. GQA with 8 KV heads needs 1 GiB. Multi-query attention (MQA) with 1 KV head needs 0.125 GiB. These are cache estimates, not total GPU memory requirements or measured speedups.
Use the ModelFit KV cache calculator to explore the memory inputs after checking your checkpoint's actual architecture.
Grouped query attention vs MHA vs MQA
In an attention layer, queries determine what each token looks for; keys and values represent the information it attends to. During decoding, previously computed keys and values are retained so each new token can attend to earlier tokens without rebuilding those states.
The original GQA paper by Ainslie and colleagues describes an intermediate number of KV heads between MHA and MQA, and studies uptraining existing checkpoints. Its experimental results do not establish a universal speed ratio for every deployment.
The distinction is how many query heads share each key/value head pair:
| Architecture | Query heads in this example | KV heads | Query heads per KV pair | Logical cache relative to MHA |
|---|---|---|---|---|
| Multi-head attention (MHA) | 32 | 32 | 1 | 100% |
| Grouped query attention (GQA) | 32 | 8 | 4 | 25% |
| Multi-query attention (MQA) | 32 | 1 | 32 | 3.125% |
Here, “8 KV heads” means eight key heads and eight value heads; the cache formula includes both. GQA does not mean reducing 32 query heads to 8 query heads. It means keeping 32 query heads while sharing K/V states across groups of four.
The original GQA paper by Ainslie et al. places grouped query attention between MHA and MQA and evaluates a method for uptraining existing multi-head checkpoints. Its quality and speed results apply to the experiments in that paper, rather than promising the same outcome for every checkpoint and serving stack.
The KV cache formula
For ordinary full-attention layers with equal key and value head dimensions, the logical cache payload is:
KV bytes = 2 × layers × cached tokens × KV heads × head dimension × bytes per element
For B independent sequences of equal length, multiply that result by B. For unequal lengths, replace B × cached tokens with the sum of each sequence's retained token count.
| Input | Fixed value | What to check in a deployment |
|---|---|---|
| Layers | 32 | Number of layers retaining KV states |
| Query heads | 32 | Used to understand sharing; not a separate multiplier in this formula |
| KV heads | 32, 8, or 1 | Checkpoint's actual K/V head count |
| Head dimension | 128 | Key and value dimension per head in this example |
| Cached tokens | 8,192 per sequence | Retained prompt plus generated tokens at the point measured |
| Cache dtype | BF16, 2 bytes per element | Actual runtime cache dtype, which may differ from weight dtype |
| Concurrent sequences | 1 or 4 | Independent sequences with no shared cache blocks assumed |
These inputs describe a controlled comparison. The MHA and MQA rows are hypothetical architecture variants; they are not conversions of a particular model. The formula excludes padding, block metadata, reserved capacity, temporary tensors, and runtime workspace. Sliding-window layers, mixed attention architectures, compressed caches, and distributed cache placement need more specific accounting.
Worked memory math: 32, 8, and 1 KV heads
First calculate bytes per cached token across all layers:
MHA: 2 × 32 × 32 × 128 × 2 = 524,288 bytes/token
GQA: 2 × 32 × 8 × 128 × 2 = 131,072 bytes/token
MQA: 2 × 32 × 1 × 128 × 2 = 16,384 bytes/token
The general formula is KV bytes = 2 × layers × KV heads × head dimension × cached tokens × bytes per element × requests. The leading 2 accounts for both keys and values. This assumes ordinary full-attention layers, equal key/value head dimensions, and independently stored requests; it excludes allocator padding, cache metadata, temporary tensors, and replicas.
Then multiply by 8,192 tokens. Divide bytes by 2**30 for GiB, or by 10**9 for decimal GB:
| Architecture | KV heads | Bytes per request at 8,192 tokens | GiB per request | Decimal GB per request | GiB for 4 concurrent requests |
|---|---|---|---|---|---|
| MHA | 32 | 4,294,967,296 | 4 | 4.294967296 | 16 |
| GQA | 8 | 1,073,741,824 | 1 | 1.073741824 | 4 |
| MQA | 1 | 134,217,728 | 0.125 | 0.134217728 | 0.5 |
GQA uses one quarter of the MHA cache in this comparison, a 75% reduction in logical KV payload. MQA uses one thirty-second, a 96.875% reduction. Those percentages apply only to this cache component.
For four independent requests, grouped query attention saves 12 GiB of logical cache against the MHA row: 16 − 4 = 12. Compared with the GQA row, MQA saves another 3.5 GiB: 4 − 0.5 = 3.5.
The four-request calculation assumes all four sequences currently retain 8,192 tokens. Four requests configured with a maximum of 8,192 tokens do not necessarily occupy that much cache right now. Some engines reserve capacity up front; others allocate blocks as sequences grow. Shared prefixes can also change physical allocation. Consult the context window and VRAM guide when turning a token limit into a serving budget.
Copyable Python calculator
This uses only Python's standard library. It computes theoretical cache payload; it does not load a model or measure GPU memory.
layers = 32
query_heads = 32
head_dim = 128
cached_tokens = 8192
bytes_per_element = 2 # BF16 cache, not a weight-quantization setting
for kv_heads in (32, 8, 1):
assert query_heads % kv_heads == 0
per_request = (
2 * layers * cached_tokens * kv_heads
* head_dim * bytes_per_element
)
gib = per_request / (2 ** 30)
gb = per_request / (10 ** 9)
print(
f"KV heads={kv_heads:2d} | "
f"1 request={gib:g} GiB ({gb:.9f} GB) | "
f"4 requests={4 * gib:g} GiB"
)
Expected output:
KV heads=32 | 1 request=4 GiB (4.294967296 GB) | 4 requests=16 GiB
KV heads= 8 | 1 request=1 GiB (1.073741824 GB) | 4 requests=4 GiB
KV heads= 1 | 1 request=0.125 GiB (0.134217728 GB) | 4 requests=0.5 GiB
Map checkpoint fields to the estimate
For a checkpoint using a Llama-style configuration, inspect num_hidden_layers, num_attention_heads, num_key_value_heads, and the attention head dimension. These are separate inputs: the number of query heads is not a substitute for the number of cached KV heads. The Transformers Llama configuration documentation defines these architecture fields.
As an illustrative input mapping, a 32-layer configuration with 32 query heads, 8 KV heads, and head dimension 128 maps to the GQA row. The table is a controlled architecture comparison, not a benchmark or an assertion that the MHA and MQA rows are available versions of a named checkpoint. To investigate a concrete deployment, start from the ModelFit Llama 3.1 8B Instruct page and check the official model repository against your downloaded checkpoint.
The 8,192-token choice is a workload input here, not a claim about any model's maximum context. Likewise, a checkpoint's weight dtype does not prove which KV dtype your inference runtime uses.
When checking another model:
- Inspect its official configuration and attention implementation. Do not infer KV heads from the parameter count or model filename.
- Read a dedicated
head_dimfield if the architecture defines one. Only derive it from hidden size and query heads when the implementation supports that relationship. - Confirm whether all layers use the same attention/cache structure.
- Set the cache dtype independently from the weight quantization choice.
- Estimate retained tokens for each active sequence, then compare logical payload with the serving engine's allocated and reserved memory.
Changing num_key_value_heads in a config file does not convert a pretrained MHA checkpoint into a valid GQA model. Projection weights, head sharing, architecture code, and training all matter. The GQA paper's uptraining procedure is evidence that conversion is a model adaptation task, not a memory-saving config toggle.
Why a smaller KV cache is not the same total VRAM or speed ratio
A practical memory budget includes more than KV states:
Total device memory ≈ resident weights + allocated KV cache
+ activations/workspace + runtime overhead
Reducing the cache from 4 GiB to 1 GiB removes 3 GiB from that component. It does not divide the weights or every temporary allocation by four. As a purely arithmetic illustration, if other allocations stayed fixed at 16 GiB, totals would change from 20 to 17 GiB—a 15% reduction, not 75%. Real architecture variants may also have different K/V projection weight sizes, so measure the actual checkpoint rather than treating the fixed-overhead illustration as a benchmark.
Grouped query attention can reduce K/V memory traffic during decoding, but end-to-end latency depends on kernels, hardware, prompt processing, batch size, sequence length, and the rest of the model. A fourfold cache reduction is not a fourfold throughput claim. Measure prefill latency, decode time per token, throughput, and peak memory separately with the same workload.
Runtime support matters too. PyTorch's scaled dot product attention documentation exposes enable_gqa and documents query/KV head divisibility and equal key/value head counts. It also lists backend restrictions and marks GQA experimental. That operator option is not a universal serving-engine switch or an automatic checkpoint conversion method. Check the documentation for your installed runtime version before relying on a particular kernel.
For general cache allocation and concurrency questions beyond head sharing, continue with KV cache memory explained.
Frequently asked questions
Does GQA reduce the number of query heads?
No. In this worked example, all three architectures have 32 query heads. Grouped query attention uses fewer KV heads and shares each K/V pair among several query heads.
Is MQA a special case of grouped query attention?
Yes, in the generalized grouping view, MQA is the single-KV-head endpoint and MHA is the endpoint with one KV head per query head. “GQA” commonly refers to an intermediate head count, such as 8 KV heads for 32 query heads.
Does 4-bit weight quantization make this BF16 cache four times smaller?
No. Weight quantization and KV cache dtype are separate choices. This table assumes two bytes per cached element throughout. A runtime's supported cache quantization can change that input and introduce metadata or accuracy tradeoffs; a 4-bit weight file alone does not establish the cache format.
Can I fit four times as many requests with GQA?
The logical cache capacity is four times as large for the same cache-only budget when moving from 32 to 8 KV heads under these assumptions. Actual request capacity also depends on weights, runtime allocation, token distributions, workspace, and latency targets. It must be validated on your serving stack.
Should I choose GQA or MQA?
Start with a checkpoint that meets your quality and compatibility needs. Use its actual KV-head count to estimate cache demand, then test memory and performance at your required context and concurrency. Head sharing alone is not a complete model selection criterion.
Plan a deployment with the actual KV-head count
Grouped query attention changes a specific input in your memory plan: the number of retained K/V heads. Keep token count, dtype, layers, head dimension, and concurrency explicit, then calculate the cache component before adding weights and runtime headroom. Try the KV cache calculator with your checkpoint's inputs and verify the resulting budget against a measured workload.
