Long Context in LLMs: How Attention Compression Works
This article explains why long context has become core infrastructure for next-generation LLMs, driven by test-time scaling and long-horizon agent workflows. It breaks down the quadratic cost of standard attention, compares sparse, linear, and compression-based approaches, and focuses on sequence-dimension compression that merges historical states into fewer, denser representations. It also covers layered compression, hybrid strategies, the value chain of efficient long context, practical engineering recommendations, and how to evaluate long-context capability beyond benchmark scores.
1. Why Long Context Is Becoming Core Infrastructure
Over the past year, open-source LLMs have improved quickly, and the gaps on general benchmarks have narrowed. As a result, leaderboard scores alone are no longer enough to judge a model’s real engineering value. Competition has shifted from “parameter count and training data volume” to “effective compute at inference time,” often called test-time scaling.
Test-time scaling means a model generates a long chain of thought before answering, repeatedly checking, backtracking, and verifying itself. A longer chain of thought means a longer sequence, and the compute and memory cost of standard attention grows quadratically with sequence length. This creates a clear bottleneck: the benefit of “thinking longer” is quickly consumed by the cost of a longer context.
At the same time, agent workflows built for long-horizon tasks naturally demand very long contexts: multi-turn tool-call histories, cross-document synthesis, repository-level code understanding, and long-running task state all push context into the tens or hundreds of thousands of tokens, sometimes millions. If long-context efficiency is insufficient, agents cannot run reliably, and the business value never materializes.
Long context is therefore no longer an optional feature but core infrastructure for the next generation of LLMs. Whoever breaks through on long context first can advance reasoning, long-horizon task capability, and online post-training faster.
2. The Root of the Complexity: Why Attention Is the Bottleneck
The core operation of standard self-attention computes relevance between every token and all historical tokens, giving O(n²) time complexity, while key-value states that grow linearly with length must also be cached in memory. Doubling the length makes the compute four times larger, which directly limits the context size that can be supported.
Existing mitigation approaches fall into three broad categories:
- Sparsification: compute attention only between a subset of tokens, reducing the number of entries actually involved in computation;
- Linearization or approximation: replace softmax attention with structures such as kernel functions or state spaces to achieve linear complexity;
- Compression: merge historical states to reduce the number of representations that participate in attention.
The first two often lose precision on long-text recall and exact retrieval tasks. The third is closer to the goal of “preserving a global view while lowering per-unit cost.”
3. A Paradigm Shift: From “Thinner” to “Shorter”
A notable direction is redefining the dimension along which compression happens. The traditional approach makes things thinner along the feature dimension, for example by reducing channels or cutting heads. A more aggressive route makes things shorter along the sequence dimension, merging lengthy historical states into fewer, higher-density representations, then letting the current token interact with those compressed representations.
This idea can be abstracted as the following illustrative logic (structure only, not a specific implementation):
# Pseudocode: attention with sequence-dimension compressiondef compressed_attention(q, k, v, block_size):# 1. Split historical keys/values into blocks and merge within each blockk_c, v_c = merge_by_block(k, v, block_size)# 2. The current query only computes relevance with compressed representationsscores = softmax(q @ k_c.T / scale)# 3. Weighted aggregation over compressed valuesreturn scores @ v_c
The engineering implication is that the “denominator” of attention changes from the original sequence length to the number of compressed blocks, so the cost drops significantly in long-sequence scenarios while cross-segment global information is preserved, avoiding the field-of-view loss of sliding-window approaches. Furthermore, different compression granularities can be used at different layers: finer granularity in shallow layers and coarser granularity in deeper layers, forming a hierarchical compression structure that balances cost and precision.
It is important to stress that compression is not lossless. Merging within a block loses information, so implementations typically combine gated selection, local-window compensation, and a hybrid strategy of “uncompressed neighbors plus compressed distant context” to ensure both near-range precision and long-range globality.
4. The Value Chain of Long-Context Capability
The benefits of efficient long context are chained together:
- Reasoning: longer chains of thought become affordable, enabling multi-step verification and self-correction;
- Agents: the state and tool outputs of long-horizon tasks can be fully retained, reducing repeated calls caused by information loss;
- Training: online post-training and long-horizon task sampling become easier to run, creating a positive loop between data and capability;
- Cost: the per-unit context cost drops, making long-document and multi-document analysis applications operationally viable.
5. Engineering Recommendations
- Layer the context: manage system prompts, long-term memory, the current task, and tool results in separate layers, and summarize/compress long-term memory before it enters the context;
- Combine retrieval and compression: use retrieval to narrow the candidate set first, then compression to preserve a global overview, balancing recall and cost;
- Set budgets and eviction policies: define a token budget for the context, and evict by time decay and importance scoring when the limit is exceeded;
- Evaluate in segments: do not look only at overall accuracy; separately evaluate long-text recall, cross-segment reasoning, and long-horizon task completion;
- Monitor resource curves: use monitoring, alerting, and logging services to track how memory usage, first-token latency, and throughput change with length, and locate the real bottleneck.
If cloud resources are used to carry such workloads, a combination of general capabilities can help: elastic scaling on a container platform, object storage for long-document corpora, message queues to decouple agent tasks, and monitoring, alerting, and logging services for full-chain observability, avoiding long-term idle resources provisioned for a single peak.
6. Evaluation and Selection: Look Beyond the Leaderboard
Benchmark scores reflect only one facet of capability. Evaluating long-context capability should focus on three types of metrics: first, effective context length, meaning how far out the model can still recall and reason stably; second, the cost curve under long sequences, including the growth slope of memory and latency with length; third, long-horizon task completion rate, examining whether an agent still stays aligned with its goal after dozens of turns.
The conclusion is clear: attention compression, especially compression and restructuring along the sequence dimension, is becoming the key dividing line for long-context capability. For developers, understanding the trade-off logic of compression and building a layered context and observable cost system delivers more long-term value than chasing a single leaderboard position.
