Long-Context LLMs: Hybrid Attention and KV Cache Optimization
Long-context inference is constrained by attention computation, KV cache capacity, and memory bandwidth. This article explains how sliding-window and sparse attention, latent KV compression, and index sharing reduce those costs. It also covers complementary approaches—including fine-grained experts, hashed memory, and speculative decoding—and provides a practical cache-sizing example and evaluation guidelines.
1. Where Long-Context Inference Costs Come From
Long-context inference has two main sources of overhead.
The first is attention computation. With standard global attention, each token attends to all preceding tokens, so total attention computation grows quadratically with sequence length.
The second is the key-value cache, or KV cache. During autoregressive generation, the model retains historical keys and values at each attention layer. Cache size grows linearly with context length and the number of layers.
At hundreds of thousands or even millions of tokens, GPU memory capacity and memory bandwidth often become bottlenecks before compute capacity does. The central optimization question is therefore not simply “How can attention run faster?” but “How can each layer store and read only the information it needs?”
2. Combining Different Attention Layers
2.1 Sliding-Window and Sparse Global Attention
A common approach divides attention layers into two types:
- Sliding-window attention (SWA): Each token attends only to the most recent W tokens. The cache retains a fixed-size window, so per-token attention computation and cache storage at each layer do not grow with total context length.
- Sparse global attention: Each token can potentially access the full history, but an indexer first selects the k most relevant tokens. Attention is computed only over those selected tokens. The selected attention computation depends primarily on k rather than total sequence length, although indexing still requires computation and storage.
Interleaving these layers gives them different responsibilities. Local layers handle nearby syntax, variable definitions, and paragraph continuity. A smaller number of sparse layers retrieve information from much farther back in the context.
This preserves access to long-range dependencies without making every layer pay the full cost of global attention.
2.2 A Code Repository Example
Consider a code repository containing approximately 200,000 tokens. The model must analyze a function defined roughly 80,000 tokens before its current position.
Sliding-window layers can inspect the code around the function call and interpret its immediate context, but they cannot directly access the distant definition. A sparse layer’s indexer can search the history for that definition and include it in the attention computation.
With this division of labor, the model does not need to retain the entire history at every layer, yet it can still reason across files.
2.3 Principles for Arranging Layers
There is no universally optimal layer schedule. Important considerations include:
- The number of sparse layers: Fewer sparse layers reduce cache requirements but also provide fewer opportunities to retrieve distant information.
- Sparse-layer placement: Keeping sparse layers near the beginning of the network or at other important positions can help establish global representations early.
- Local-window size: The window should cover most short-range dependencies, such as function bodies, paragraphs, or a conversation turn.
The following configuration illustrates one possible arrangement. It does not represent the parameters of a specific model.
layer_plan = (["sparse", "sparse"]+ ["swa", "swa", "swa", "sparse"] * 10)# 42 layers total: 12 sparse layers and 30 sliding-window layers
3. Compressing the KV Cache with Latent Representations
Even when most layers use sliding windows, sparse layers may still retain cached information for every historical token. Reducing cache size per token is therefore another major optimization direction.
One approach is Multi-head Latent Attention (MLA). Instead of caching full multi-head keys and values, it stores a lower-dimensional latent representation from which the required information can be projected when needed.
Caching compressed vectors reduces memory usage. The trade-off is additional projection computation, while an excessively small latent dimension can reduce representational capacity. The compression dimension must therefore balance memory savings against model quality.
Both sliding-window and sparse layers can use latent compression. Combining compressed representations with a hybrid layer schedule can substantially reduce the overall cache footprint.
4. Compressing and Sharing the Attention Index
Sparse attention also needs an index. Historical tokens require index representations so that the indexer can estimate their relevance to the current query. At long context lengths, this index cache can itself consume substantial GPU memory.
One option is group-level selection. Adjacent tokens are divided into groups, and each group receives a summary representation. The indexer first selects relevant groups, then examines tokens within those groups.
Larger groups reduce index storage but make selection coarser, potentially causing important tokens to be missed. Group size should be tested against the intended workload.
Another option is to share index results or an index pool across multiple layers. Neighboring layers often have similar attention patterns, so reuse can reduce repeated computation and storage.
However, sharing should not be assumed to be lossless. Its effect on model quality must be measured.
5. Fine-Grained Experts and Lower-Dimensional Computation
Mixture-of-experts (MoE) models use routing to activate only a subset of experts for each token. This allows a large total parameter count while controlling the amount of computation performed per token.
One direction is to use more, smaller experts and activate more of them for each token.
The intuitive benefit is a larger space of possible expert combinations. With a similar number of active parameters, the model can combine more distinct expert subsets, potentially supporting finer functional specialization.
Another approach performs expert computation in a lower-dimensional space. The hidden representation is first projected to a smaller dimension, processed by the expert feed-forward networks, and then projected back to its original dimension.
This reduces each expert’s parameter count and computation, but introduces several costs:
- Projection layers add their own parameters and computation.
- More experts can increase routing overhead and cross-device communication.
- Uneven routing can overload some experts, requiring load-balancing losses or capacity limits.
6. Hashed External Memory
Language contains many frequent, relatively fixed local patterns, including common phrases, proper names, and recurring code syntax. Repeatedly recognizing these patterns through multiple neural-network layers can be expensive.
A hashed n-gram memory table offers an alternative. The model hashes a sequence of recent tokens and retrieves a corresponding vector from a lookup table. That vector becomes an additional input to the computation.
Lookup operations are approximately constant-time and can offload some local pattern recognition.
Most of the additional parameters reside in the table, with relatively little extra computation. However, the approach has clear limitations:
- Hash collisions: Different patterns may map to the same entry. Table size and hash-function design must control collision rates.
- Memory access costs: Lookups depend on the memory hierarchy and available bandwidth.
- Limited scope: The table can supplement local pattern recognition, but it cannot replace deeper reasoning.
7. Lightweight Speculative Decoding
Speculative decoding uses a smaller draft model or lightweight drafting component to propose several candidate tokens. The main model then verifies those candidates in parallel. Accepted tokens reduce the number of sequential decoding steps required from the main model.
Possible drafting designs include:
- A separate small model: This introduces additional deployment and maintenance costs.
- A lightweight prediction head that shares parameters or cache with the main model: This can reduce drafting overhead.
- Reuse of the main model’s KV cache and attention indices: This avoids repeatedly encoding the same context.
Reusing the main model’s state can substantially reduce additional drafting work. However, draft quality depends on whether the shared information is sufficient for accurate predictions.
The acceptance rate is a major determinant of the final speedup and must be measured on the target workload.
8. Estimating GPU Memory Requirements
A useful starting point for evaluating a long-context design is to calculate its KV cache size.
def kv_cache_bytes(seq_len, num_layers, dim_per_token, bytes_per_elem=2):"""Estimate stored historical KV tensors only; exclude indices, weights, and runtime overhead."""return seq_len * num_layers * dim_per_token * bytes_per_elem
Here, dim_per_token represents the total number of cached elements per token per layer, whether the cache contains full keys and values or a compressed representation.
Consider the following hypothetical configuration:
- Context length: 1,048,576 tokens, or 2^20
- Precision: BF16, using 2 bytes per element
- Sparse layers: 12 layers, each caching 512 elements per token under an assumed latent-compression scheme
- Sliding-window layers: 30 layers, each with a 512-token window and 512 cached elements per token
These parameters are illustrative rather than specifications for a particular model.
Sparse-Layer Cache
The sparse layers retain the full history:
1,048,576 × 12 × 512 × 2 bytes = 12 GiB
Sliding-Window Cache
The sliding-window layers retain only the most recent 512 tokens:
512 × 30 × 512 × 2 bytes = 15 MiB
The combined cache is therefore approximately 12 GiB, with the sliding-window portion contributing relatively little.
Comparison with a Full-History KV Cache
Now consider 42 layers that all retain full-history KV caches, with 2,048 cached elements per token per layer. This corresponds to eight KV heads with a head dimension of 128, counting both keys and values.
1,048,576 × 42 × 2,048 × 2 bytes = 168 GiB
The hybrid compressed configuration reduces the estimated attention-history cache by roughly an order of magnitude.
This calculation covers only cached attention history. Actual deployment memory must also include:
- Indexer caches
- Model weights
- Activations
- Concurrent requests and batching
- Framework and runtime overhead
9. Engineering Trade-Offs and Evaluation
Long-context architectures must balance several competing objectives.
Model Quality
Local and sparse attention can discard distant details. Evaluation should include long-range retrieval, code understanding, and multi-document question answering.
Throughput and Latency
Smaller caches can support greater concurrency, but indexing, routing, and projection introduce additional computation. End-to-end latency must be measured rather than inferred from cache savings alone.
GPU Memory
The benefits of cache compression increase with context length. At shorter context lengths, the savings may be much less significant.
Implementation Complexity
Multiple attention types, shared indices, and speculative decoding all increase implementation and debugging complexity.
For consistent comparisons, use a fixed evaluation set and record:
- Task-quality metrics
- Time to first token
- Output tokens per second
- Peak GPU memory usage
Repeat these measurements at different context lengths. A single metric rarely captures the full trade-off.
10. Conclusion
Long-context optimization rests on three central ideas: let most layers process local information, use sparse selection for global access, and compress or share caches and indices wherever practical.
Expert networks, hashed external memory, and speculative decoding provide complementary ways to reduce computational pressure.
Each technique introduces trade-offs. The right combination depends on the target workload, available hardware, and required model quality—not on cache size or attention speed alone.
