Long-Context Attention Compression: Thinning vs. Shortening the Cache
Longer context lets large models handle multi-step tasks, tool use, and multi-document analysis, but standard self-attention and the KV cache make cost grow much faster than sequence length. This article explains the two cost sources, two compression directions—narrower token representations and fewer attention entries—and the design, training, evaluation, and risk controls needed to keep quality and inference cost in balance.
1. Why long context has become infrastructure
Large-model applications are moving from single-turn Q&A to multi-step tasks. During inference, a model may generate long intermediate steps. An agent repeatedly reads tool results, conversation history, and task state. Cross-document analysis requires the model to understand several sources at once. All of these workloads depend on a longer usable context. Context length is therefore more than a specification number: it determines which tasks the model can complete and whether the cost of a single task is acceptable.
Cost rises faster than context length. Standard self-attention scales with the square of sequence length. If a sequence grows from 4,000 tokens to 128,000 tokens, the quadratic attention term alone grows by about 1,000 times (a 32× increase in length becomes 1,024× after squaring). Cost grows far faster than the context window itself.
2. Two sources of attention cost
Before choosing a compression method, separate where the cost comes from.
1. Compute. Attention scores each query token against every key, forming an n × n matrix. During training and prefill, this compute grows with the square of n.
2. Memory and memory bandwidth. During generation, the model caches the keys and values of historical tokens at every layer—the KV cache. Cache size grows linearly with sequence length and multiplies with the number of concurrent requests. Each new token requires reading the full historical KV from memory, so bandwidth often becomes the bottleneck before raw compute does.
The dominant factor differs by stage. Training is more sensitive to compute; inference is more sensitive to KV-cache memory use and read speed. A compression design should start by deciding which cost it is meant to reduce.
3. Two compression directions: thinner and shorter
Treat the attention cache as a matrix: rows are tokens, columns are the feature dimensions of each token. Compression can run along either axis.
Thinner: reduce the width of each token’s representation. Common methods include shared key-value heads, low-rank factorization of projection matrices, and low-bit quantization of the cache. These changes are relatively straightforward and require smaller changes to an existing architecture. Each token still keeps its own entry, so the compression ratio has a clear upper bound.
Shorter: reduce the number of entries that participate in attention. Merge the key-value representations of several neighboring tokens into one block-level summary, or select only the relevant blocks at query time. Sequence length shrinks directly, so compute and memory fall together. The risk is losing important detail during the merge.
The two directions are not mutually exclusive. A common engineering combination is to keep full representations for nearby content, use coarse block summaries for distant content, and quantize the cache as a whole.
4. Design points for compressing along the sequence
Sequence-dimension compression has to solve four concrete problems.
4.1 Block splitting and summary generation. Split the sequence into fixed-length blocks. Each block produces one summary vector through a learnable pooling function, such as a weighted sum. The compression ratio m means that every m tokens are merged into one entry. A larger m lowers cost and increases information loss. In practice, several values of m usually need to be tested to find the quality–cost balance.
4.2 Fine local detail with coarse global context. Keep full keys and values for the most recent tokens so local grammar, reference, and formatting stay precise. Use block summaries for earlier history. This split matches the locality of language: most dependencies fall within a nearby range.
4.3 Sparse selection. At query time, score the current query against each block summary and let only the top-k blocks join exact attention. Compute then largely decouples from sequence length. A wrong selection can drop critical information, so the selection mechanism itself needs to be trained.
4.4 Causality constraints. When generating token t, summaries may use only information at or before t. A block that is not yet full must be handled separately. Otherwise future information leaks in, and training and inference diverge.
The following pseudocode omits masks, multiple heads, and positional encoding. It only shows the data flow:
function compress_kv(keys, values, block_size):blocks = split_into_blocks(keys, values, block_size)summaries = []for block in blocks:k_sum = learned_pool(block.keys)v_sum = learned_pool(block.values)summaries.append((k_sum, v_sum))return summariesfunction attend(query, recent_kv, block_summaries, top_k):scores = [dot(query, s.key) for s in block_summaries]selected = top_k_indices(scores, top_k)context_kv = gather(block_summaries, selected) + recent_kvreturn softmax_attention(query, context_kv)
The important part is the two steps: compress history into summaries, then select summaries for the query. In a real system, both steps have to be aligned with training.
5. Training and inference must stay consistent
If the compression module is added only at inference time, the model has not learned how to read summary vectors, and quality usually drops sharply. The compression structure therefore needs to be present from early training so the model adapts to the compressed representation.
Positional information also needs an explicit definition. A block summary covers a range of token positions, and its positional encoding must be defined. If that definition is vague, relative distances become disordered, and the model may be unable to tell the order of information.
Long-context training is usually staged. Stabilize training on shorter sequences first, then extend length gradually while mixing in long documents, multi-file code, and retrieval-style data. Training from scratch on extremely long sequences is expensive, and convergence is often unstable.
6. Evaluation: do not rely on the average score alone
A long-context design should be judged on both efficiency and quality.
Efficiency metrics include time to first token, per-token generation latency, peak memory, single-GPU concurrency, and cost normalized per thousand tokens.
Quality metrics should be split by task type:
- Key-fact retrieval: insert target information at different positions in a long text and measure hit rate as a function of position.
- Cross-passage reasoning: require the model to combine facts scattered across the text and answer questions that need multi-hop reasoning.
- Long-document summary consistency: check whether facts in the summary match the source, especially numbers, names, and times.
- Cross-file code understanding: test whether the model can locate the relationship between a definition and its call sites.
Use a fixed test set, compare results before and after compression, and break results down by context length and information position. An average score hides degradation in the middle of the context. For latency, report percentiles such as P95 and P99, not only the mean.
7. Risks and limits
Exact-copy tasks carry the highest risk. Numbers, code identifiers, and legal clauses must be accurate word for word. A summary representation can introduce small deviations that are also hard to catch in manual review.
Errors accumulate across multi-turn generation. A summary error in an earlier step affects later reasoning. Error amplification in long task chains is more visible than in single-turn Q&A.
Mitigations include:
- Keep the original text for critical spans and retrieve it back into the context.
- Check citations for key fields in the output, and require the model to mark where the information came from.
- Add rule checks or human review for high-risk fields such as amounts, dates, and identifiers.
8. Putting it into practice
- Identify the task type first. Retrieval, summarization, and reasoning tolerate compression differently. Classify tasks before choosing compression strength.
- Establish a baseline. Run the evaluation set on a smaller uncompressed version and record quality and cost references. Compare every later change with that baseline.
- Route by length. Send short requests down the standard path and switch long requests to the compressed path once they cross a threshold. Set the threshold from evaluation results, not from intuition.
- Build an observation loop. Continuously record the context-length distribution, latency percentiles, and sampled quality results. On a cloud platform such as Baidu AI Cloud, object storage can hold evaluation datasets and version records, a logging service can retain inference details, and monitoring alerts can track latency and error rate, forming a reproducible evaluation loop.
9. Summary
The core of long-context attention compression is a tradeoff among what to keep, what to merge, and when to read exactly. Thinning and shortening can be combined, but each step adds a new source of error. Whether a design is usable depends on task quality, inference cost, and stability on long task chains together. A single leaderboard score is not enough to make the decision.
