LLM Attention Architecture: Trade-offs from Multi-Head to Multi-Query
This article examines how attention designs affect inference cost in large language models, focusing on KV cache size, memory bandwidth, and quality trade-offs among MHA, GQA, MQA, and low-rank compression. It includes code for estimating KV cache and request cost, discusses scheduling and prefix caching for long-context serving, and offers practical guidance for benchmarking and capacity planning.
1. Architecture Competition Moves into the Details
For some time, the industry generally believed that attention design in mainstream open-source large models had converged, with subsequent improvements focused mainly on training data, post-training methods, and local structural optimizations. Some recent new models have reintroduced earlier attention forms, indicating that there is still room for exploration at the architecture level. To understand this change, it is necessary to first clarify the real cost of attention mechanisms during inference.
2. The Root of the Inference Bottleneck: KV Cache
During autoregressive generation, each time the model generates a new token, it must read the keys (Key) and values (Value) of all previous tokens. These vectors are cached, which is called the KV cache. The size of the KV cache is proportional to the sequence length, number of layers, number of KV heads, and the dimension of a single head. It can be estimated with the following formula:
Bytes per token = 2 × layers × KV heads × head dimension × bytes per element
The 2 in the formula represents the two tensors, K and V. The following script uses hypothetical parameters to estimate memory usage for different structures; these parameters do not correspond to any specific model.
def kv_cache_bytes(seq_len, layers, kv_heads, head_dim, dtype_bytes=2):per_token = 2 * layers * kv_heads * head_dim * dtype_bytesreturn per_token * seq_lenGB = 1024 ** 3for name, heads in [("Multi-Head Attention (MHA)", 64), ("Grouped-Query Attention (GQA)", 8), ("Multi-Query Attention (MQA)", 1)]:size = kv_cache_bytes(seq_len=1_000_000, layers=60, kv_heads=heads, head_dim=128)print(f"{name}: about {size / GB:.1f} GB for 1M tokens")
Under this set of hypothetical parameters, for the same million-token context, the KV cache can differ by dozens of times depending on the number of KV heads. This shows that the attention structure directly determines whether long-context serving can run on a single GPU or a small number of GPUs.
3. Trade-offs of Mainstream Attention Forms
Multi-Head Attention (MHA): Each query head has its own independent K and V. It has the strongest expressive capacity, but also the largest cache footprint.
Multi-Query Attention (MQA): All query heads share the same set of K and V. It has the smallest cache footprint and reads the least data during decoding. The cost is that model expressive capacity may decline, and more attention must be paid to training stability.
Grouped-Query Attention (GQA): Query heads are divided into several groups, and each group shares one set of K and V. It strikes a compromise between cache footprint and model quality and is currently a widely used approach.
Low-rank compression approaches: K and V are projected into a low-dimensional latent space for storage, and then restored during computation, or the projection matrices are absorbed into the computation process. This maintains a balance between memory and expressive capacity, but implementation complexity is higher, and it places greater demands on operator and kernel optimization.
| Method | KV heads | Cache footprint | Expressive capacity | Main trade-off |
|---|---|---|---|---|
| MHA | Same as query heads | Largest | Strongest | Quality first, high memory pressure |
| GQA | A fraction of query heads | Medium | Strong | Compromise between quality and cost |
| MQA | 1 | Smallest | Somewhat reduced | Cost first, quality must be validated |
| Low-rank compression | Compressed latent vectors | Smaller | Close to MHA | Complex implementation, dependent on kernel optimization |
4. Why Falling Back to Shared Key-Value Structures Is Still Worthwhile
The bottleneck in large model inference is often memory bandwidth rather than compute. During the decoding stage, each generated token requires reading the entire KV cache from memory. Shared key-value structures directly reduce the amount of data read per step, so they can increase the number of tokens generated per second and allow the same GPU to handle more concurrent requests.
This judgment rests on two preconditions. First, model quality must meet the requirements. Quality degradation can be compensated for by increasing the number of layers, expanding the hidden dimension, or improving training data, but these methods themselves increase computation. Second, architecture choice is a system-level decision. The same structure can produce very different benefits in high-concurrency short-text scenarios and low-concurrency ultra-long-text scenarios, so it cannot be evaluated based on a single metric alone.
Therefore, when evaluating attention structures, quality metrics, memory footprint, bandwidth pressure, and the target business request distribution should all be considered together.
5. Engineering Challenges of Million-Token Contexts
Long-context serving faces at least three types of problems.
- Computation: Standard attention computation grows quadratically with sequence length, especially during the prefilling stage (the stage that processes the input prompt).
- Memory: The KV cache grows linearly with sequence length. It requires paged management and on-demand allocation of memory blocks to avoid wasting resources by reserving too much space.
- Latency: Long inputs increase first-token latency and affect the responsiveness of other requests. A common approach is chunked prefill, which splits long requests into chunks and schedules them interleaved with requests that are currently decoding.
The following illustrative code shows a simple scheduling idea: in each scheduling cycle, prioritize decode requests, then use the remaining budget to process prefill chunks.
def schedule_step(pending_prefill, running_decodes, budget):batch = []# Decode requests need only one token per step; prioritize them.for req in running_decodes:batch.append(("decode", req, 1))budget -= 1# Split prefill requests into chunks according to budget.for req in pending_prefill:if budget <= 0:breakchunk = min(req.remaining, budget)batch.append(("prefill", req, chunk))budget -= chunkreturn batch
The core idea is to control the total computation per step so that long requests do not block short requests for a long time.
6. Prefix Caching and Cost Estimation
Prefix caching means that when multiple requests share the same prefix (for example, a system prompt, the same document, or conversation history), the server can reuse the already computed KV cache and skip the prefilling computation for the corresponding part. This kind of reuse is common in multi-turn dialogue, retrieval-augmented generation, and fixed-template calls.
The cost of prefix caching is usually divided into three parts: input tokens that miss the cache, input tokens that hit the cache, and output tokens. The cost of a single request can be expressed as:
Single-request cost ≈ missed tokens × miss price + hit tokens × hit price + output tokens × output price
def request_cost(prompt_tokens, hit_tokens, output_tokens, p_miss, p_hit, p_out):miss_tokens = prompt_tokens - hit_tokensreturn miss_tokens * p_miss + hit_tokens * p_hit + output_tokens * p_out
The higher the hit rate, the lower the input cost, so improving the hit rate is key to cost optimization. There are several practical approaches:
- Place fixed content (system instructions, templates, frequently used documents) at the beginning of the prompt, and put variable parts at the end.
- Avoid inserting timestamps, random IDs, or other content that changes every time into the prefix.
- Track the cache hit rate and monitor it together with request volume and cost.
Specific unit prices are subject to the rules published by the service provider; this article does not provide specific values.
7. Practical Recommendations for Developers
Benchmark with your own workload. Public leaderboards reflect general capabilities and may not match your business input lengths and concurrency patterns. During testing, record first-token latency, per-token output latency, throughput, and peak memory usage.
Evaluate tasks separately. Code generation, long-document question answering, and multi-turn dialogue have different sensitivities to attention structure. Quality should be validated separately before choosing an architecture.
Estimate capacity by formula. Use the KV cache formula to calculate the number of concurrent requests a single GPU can support at the target context length, avoiding frequent request eviction after launch due to insufficient memory.
Design stable prompt structures. Fixed prefixes help improve the cache hit rate and directly reduce input cost and first-token latency.
Monitor continuously. Pay attention to cache hits.
