Inference: Attention Optimizations
By Ludovico Bessi, Senior ML Engineer at Google ยท Updated
Making attention cheaper at serving time: fewer KV heads, smarter memory, sparse patterns, and reuse.
Why Attention Is the Inference Bottleneck at Long Context
At short contexts, decode time is dominated by reading the weights. As context grows, each decode step must also read the entire KV cache, and attention's share of time and memory rises until it dominates. Optimizations fall into four groups:
- Store less per token โ MQA, GQA, MLA.
- Manage memory better โ PagedAttention.
- Attend to fewer tokens โ local, sliding-window, sparse and hybrid attention (Longformer, Block Transformer, Infini-attention).
- Reuse and distribute work โ RadixAttention for shared prefixes, Ring Attention for very long sequences.
Multi-Query and Grouped-Query Attention
In standard multi-head attention (MHA), each of h query heads has its own key and value head. Multi-query attention (MQA; Shazeer, 2019) uses a single shared key and value head for all query heads. The KV cache shrinks by a factor of h โ 32ร or 64ร โ and decode gets much faster because far fewer bytes are read per step.
MQA can cost some quality and training stability. Grouped-query attention (GQA; Ainslie et al., 2023) is the middle ground: query heads are split into g groups, each sharing one KV head. With 8 KV heads and 64 query heads, the cache shrinks 8ร, with quality close to MHA. GQA is now the default in Llama 2 70B, Llama 3, Mistral and most open models. The GQA paper also showed an existing MHA checkpoint can be "uptrained" to GQA using about 5% of the original pre-training compute.
Multi-Head Latent Attention
DeepSeek-V2 introduced multi-head latent attention (MLA): instead of caching full keys and values, cache a single compressed latent vector per token per layer, and project it back up to per-head keys and values at attention time. The projection can be folded into the query and output matrices, so decode works directly on the compressed cache. DeepSeek reported that DeepSeek-V2 needs a 93.3% smaller KV cache than its earlier dense DeepSeek 67B model, while performing better.
PagedAttention
PagedAttention stores the KV cache in fixed-size blocks indexed by a per-request block table, eliminating most fragmentation and enabling sharing between sequences. It does not change the math of attention โ it changes how attention finds its keys and values. The full treatment is in KV Cache Basics.
Sparse and Local Attention
If each token attended only to a fixed number of nearby tokens, the KV cache would stop growing and attention cost would become constant per token.
Sliding-window (local) attention
Each token attends only to the previous w tokens. Information still flows further than w because each layer extends the reach: after L layers, a token can be influenced by tokens up to about L ร w positions back. Mistral 7B used a 4,096-token window. A sliding-window layer needs only a rolling buffer of w entries in its KV cache.
Longformer attention
Longformer (Beltagy et al., 2020) combines:
- Sliding-window attention for local context,
- Dilated windows (attending to every k-th token) in some heads to widen the receptive field cheaply,
- Global attention on a few task-specific tokens (such as a classification token or question tokens) that attend to and are attended by everything.
Cost grows linearly with sequence length rather than quadratically. Longformer was designed for encoder tasks on long documents, but its local + global pattern is the template for many later designs.
Hybrid attention: local + global layers
Pure local attention loses precise long-range retrieval. Hybrid models interleave local layers with a few full (global) attention layers. Gemma 2 alternates sliding-window and global layers; Gemma 3 uses several local layers per global layer. Only the global layers need a full-length KV cache, so total cache size drops several-fold while long-range ability is mostly preserved. Character.AI described a similar design (mostly local layers, cross-layer KV sharing, MQA) as key to its serving costs.
Block Transformer
The Block Transformer (Ho et al., 2024) splits attention hierarchically to speed up decoding:
- A block decoder in the lower layers treats groups of tokens (blocks) as single units and models global context between blocks with coarse attention.
- A token decoder in the upper layers attends only within the current block to generate individual tokens, conditioned on the block-level context.
Because global attention runs over far fewer units and local attention over short blocks, KV cache reads per step drop sharply. The authors reported 10โ20ร higher inference throughput than vanilla transformers with equivalent perplexity and zero-shot task performance.
Infini-attention
Infini-attention (Munkhdalai et al., 2024) adds a compressive memory inside each attention layer. The input is processed in segments. Within a segment, the model uses normal (local) attention. When a segment ends, its keys and values are folded into a fixed-size associative memory using a linear-attention update rule, and later segments retrieve from that memory. A learned gate mixes local attention and memory retrieval.
The memory has constant size, so the model can in principle process unbounded input with bounded memory. The trade-off is that compressed memory is lossy: exact recall of distant details is weaker than with full attention.
RadixAttention: Reusing Shared Prefixes
Many requests share their beginnings: system prompts, few-shot examples, documents in a RAG pipeline, earlier turns of a conversation, or branches of an agent's reasoning. RadixAttention, introduced with the SGLang serving system (Zheng et al., 2023), keeps the KV cache of finished requests in a radix tree keyed by token sequences.
- When a request arrives, the engine finds the longest cached prefix in the tree and reuses those KV entries, prefilling only the new suffix.
- Tree nodes are evicted with an LRU policy when memory is needed, starting from leaves.
- The scheduler can order requests to maximize cache hits (cache-aware scheduling).
For workloads with heavy prefix sharing โ multi-turn chat, agents, few-shot prompting, structured generation with many calls โ this can cut prefill work dramatically. vLLM's hash-based automatic prefix caching achieves a similar effect with paged blocks.
Ring Attention for Very Long Contexts
When a single sequence is too long for one GPU's memory or prefill is too slow, Ring Attention splits the sequence across GPUs arranged in a ring. Each GPU computes attention for its block of queries while passing key/value blocks around the ring, overlapping communication with computation and combining partial results with an online softmax. It is mainly a training and long-prompt prefill technique; see Distributed Training.
Choosing Among Them
| Technique | Decided at | Saves | Cost |
|---|---|---|---|
| MQA / GQA / MLA | Training | KV cache size and bandwidth | Small quality risk (MQA most) |
| PagedAttention | Serving | Fragmentation waste | Slight kernel overhead |
| Sliding window / hybrid | Training | KV cache at long context | Weaker exact long-range recall |
| Longformer-style sparse | Training | Quadratic cost | Pattern must suit the task |
| Block Transformer | Training | KV reads per step | New architecture, less tooling |
| Infini-attention | Training | Unbounded context in fixed memory | Lossy long-range memory |
| RadixAttention / prefix caching | Serving | Repeated prefill | Memory for cached prefixes |
| Ring Attention | Serving / training | Per-GPU memory, long prefill time | Inter-GPU communication |
If you serve existing models, the levers you control are PagedAttention, prefix caching and parallelism. If you choose which model to serve, prefer GQA or MLA models and consider hybrid local/global designs for long-context workloads.
Key Takeaways
- MQA, GQA and MLA cut the KV cache by sharing or compressing keys and values; GQA is the industry default.
- PagedAttention solves memory management, not attention math.
- Local, sparse and hybrid attention cap the KV cache at long context at some cost to long-range recall.
- Block Transformer and Infini-attention restructure attention hierarchically or with compressive memory.
- RadixAttention and prefix caching skip prefill for shared prefixes; Ring Attention spreads one long sequence across GPUs.