Why Attention Is Moving to Linear Structures in Large Models
Large language models are increasingly replacing standard full attention with linear attention and hybrid layer designs to manage the prohibitive compute and memory costs of long contexts. This article breaks down the bottlenecks of standard self-attention, explains the math and recursive formulation behind linear attention, introduces gated incremental mechanisms, and compares pure full attention, pure linear attention, and hybrid architectures across computation, KV cache, retrieval ability, and implementation complexity. It also covers practical considerations for training trillion-parameter models, evaluating hybrid models on long-context recall and latency, and understanding this trade-off between capability and cost.
Background: Why Standard Attention Fails Under Long Contexts
Over the past year or two, several publicly released long-context large models have begun adjusting their architecture. Instead of using standard full attention in every layer, they replace most layers with linear attention or other approximation methods, retaining only a small number of full attention layers.
This shift is driven primarily by engineering pressure, which can be grouped into three sets of tensions:
- Parameter scale vs. inference cost: The more parameters a model has, the higher the per-token computation cost. If the context is very long, every decoding step must look back over the entire history, pushing up latency and cost.
- Long context vs. KV cache: Standard attention’s KV cache grows linearly with sequence length. On contexts of hundreds of thousands to millions of tokens, GPU memory is usually the first resource to run out.
- Training throughput vs. sequence length: The compute cost of attention during training scales quadratically with sequence length. As sequences grow longer, the number of tokens processed per unit of time drops sharply.
Hybrid linear attention is designed to alleviate all three tensions simultaneously.
Where Standard Self-Attention Bottlenecks
Standard self-attention can be written as:
Attention(Q, K, V) = softmax(Q·Kᵀ / √d) · V
Here Q, K, and V each have shape n×d, where n is the sequence length and d is the head dimension. The bottleneck sits in the Q·Kᵀ step, which produces an n×n matrix.
- Compute cost: Total complexity is O(n²·d). Doubling the sequence length roughly quadruples compute.
- Peak memory: If the n×n attention matrix is explicitly materialized in the naive way, peak memory is O(n²). Optimized block-wise implementations avoid storing the full matrix, but the compute cost remains unchanged.
- KV cache: During decoding, the model must store the K and V of every historical token at every layer, requiring O(n·d) memory that grows linearly with length.
- Decode dependency: Each newly generated token must read the entire KV cache of past tokens. On long sequences, decode speed becomes limited by memory bandwidth.
When n reaches several hundred thousand, these costs stack up and make it impractical to support very large parameter counts with full attention alone.
The Core Idea Behind Linear Attention
Rearranging the Order of Computation
Linear attention starts with a simple observation: remove the softmax, and you can change the order of matrix multiplication.
Define φ as an element-wise positive mapping, e.g., φ(x) = elu(x) + 1. Linear attention is written as:
Out = φ(Q) · (φ(K)ᵀ · V) / (φ(Q) · (φ(K)ᵀ · 1))
Here 1 is an all-ones vector of length n. The denominator normalizes weights for each position. It serves a similar role to softmax normalization, but it is obtained as a product rather than by exponentiating each row of Q·Kᵀ and summing.
By computing φ(K)ᵀ · V first, we get a d×d matrix, then left-multiply by φ(Q). Total complexity becomes O(n·d²). When d is much smaller than n, this is significantly cheaper than O(n²·d).
Note that this reformulation is not a lossless equivalent of softmax attention. Softmax applies a nonlinear amplification to similarities; the linear form lacks this property, so model expressiveness will differ.
Recurrent View and Fixed-Size State
Linear attention can also be expressed as a recurrent form with a fixed-size state. The pseudocode below is for illustrative purposes only and is not a production-ready implementation:
# Pseudocode: recurrent view of single-head linear attentionS = zeros(d, d) # state matrix, size independent of sequence lengthz = zeros(d) # normalization statefor t in range(seq_len):k_t = phi(K[t])S = S + outer(k_t, V[t]) # write current tokenz = z + k_tout[t] = (phi(Q[t]) @ S) / (phi(Q[t]) · z)
This formulation yields two direct results.
- KV cache becomes fixed-size: During inference, what gets stored is a d×d state and a d-dimensional normalization vector, independent of context length. Full attention layers still have a KV cache that grows with length, so this advantage applies only to linear layers.
- The state can be learned: With gating and decay added, the model can decide how much history to retain.
Gated Incremental Mechanisms
The state update in naive linear attention is an indiscriminate accumulation. As sequences grow longer, old information keeps getting overlaid with new information, interfering with each other, and long-range memory degrades.
The gated incremental mechanism updates the state by a proportion decided by the current input. A common formulation looks like this:
g_t = sigmoid(W_g · x_t + b_g) # gate value, between 0 and 1S_t = g_t * S_{t-1} + (1 - g_t) * outer(k_t, v_t)
The larger g_t is, the more history is preserved; the smaller g_t is, the faster new information overwrites the old state.
This direction is easy to get wrong, so implementations should be double-checked carefully. Also, the initialization of the bias b_g affects early training behavior. If the initial value pushes g_t close to 0, the model will rapidly forget history at the very start of training, making long-range dependencies hard to learn. Many implementations therefore initialize b_g to a large positive value so that g_t stays above 0.9 early on. The exact values should be tuned for the specific model and data.
On long-range retrieval tasks, gated mechanisms typically outperform naive linear attention.
Hybrid Layer Layout: Linear Layers and Full Attention Side by Side
Linear attention has inherent limitations on tasks like “precisely retrieving an early token.” A fixed-size state is a form of lossy compression; it cannot store the full history without loss.
Two engineering approaches are commonly used.
First, attention residual connections. A residual path is added on top of the linear attention output, allowing some raw information to pass directly to later layers and reducing the information loss caused by compression.
Second, hybrid layer layout. A full attention layer is inserted every few linear attention layers, giving the model periodic exact retrieval capability.
# Hybrid layout illustration: 6 linear attention layers + 1 full attention layer, stacked cyclicallyblock = [LinearAttn] * 6 + [FullAttn]
The hybrid ratio directly affects cost. KV cache comes only from full attention layers, so if full attention layers account for a fraction f of all layers, KV cache is roughly f times that of a pure full attention model. For example, with one full attention layer out of eight, KV cache is about one-eighth of a pure full attention model.
Hybrid ratios reported in public sources vary widely, with no unified standard. The ratio depends on the length distribution of training data, how much the target task depends on exact retrieval, and the acceptable memory and latency budget. The choice should be validated on your own workload, not copied from someone else’s ratio.
Comparison of Three Approaches
| Dimension | Pure Full Attention | Pure Linear Attention | Hybrid Linear Attention |
|---|---|---|---|
| Training compute | O(n²·d) | O(n·d²) | Between the two, determined by the full attention layer ratio |
| KV cache | Grows linearly with length | Fixed size | Grows only with the full attention layer ratio |
| Exact long-range retrieval | Strong | Weak | Compensated by full attention layers and residuals |
| Implementation complexity | Low, mature ecosystem | Medium, requires numerical stability handling | High, must maintain both layer types |
| Suitable scenarios | Short context, high recall requirements | Cost-sensitive, lower recall requirements | Long context with recall needs |
Systems Engineering for Trillion-Parameter Models
Once the architecture is settled, training and deployment considerations remain. The following factors have significant impact.
- Sparse expert parallelism: Many very large models use a mixture-of-experts (MoE) structure. Total parameter count is large, but each token activates only a small subset of experts, keeping per-token compute under control.
- Long-context training curriculum: A common approach is to pre-train on shorter sequences first, then gradually extend to longer ones. Numerical stability of linear layer states on long sequences needs dedicated monitoring.
- Native multimodal training: Mixing visual tokens into pre-training lets vision and text share the same representation space, rather than attaching a vision adapter after model training is complete.
- Inference-side optimization: Fixed-size linear states are convenient for prefix reuse and continuous batching. Quantization and speculative decoding can further reduce the cost of long-context serving.
How Developers Should Evaluate and Select
When evaluating hybrid linear attention models, work through the checklist below. Thresholds and metrics should be set by your own team based on business needs.
- Test sets and sequence lengths: Use documents or codebases close to your workload, covering multiple length tiers such as 8K, 32K, and 128K.
- Long-context recall: Use “needle in a haystack” tests to probe retrieval of deeply buried information. Looking at the advertised context window size alone is not enough to judge quality.
- Concurrency and latency: Measure first-token latency and generation throughput at your target concurrency levels, and observe how latency scales as sequence length grows.
- Tool calling and instruction following: Architectural changes can shift how stable instruction following and structured output are, so regression-test them in your real toolchain.
- Total cost metric: Standardize on per-million-token GPU hours or actual billing. Memory savings from fixed-size states translate into cost advantages only under real concurrency.
On the infrastructure side, when choosing a cloud platform, focus on how well the inference service supports long-context throughput, integration with object storage and container platforms, monitoring and alerting capabilities, and billing transparency. These factors typically affect operational costs more than the model’s parameter count alone.
How to Understand This Technical Direction
Linear attention, gated increments, attention residuals, and hybrid layer layouts together form a mainstream path for current long-context models. The core approach: compress historical information into a learnable fixed-size state, then use a small number of full attention layers to retain exact retrieval capability.
This path is a compromise between capability and cost. It is not a lossless replacement for full attention. When selecting a model, you need to be clear about your business priorities among recall precision, latency, and cost.
Understanding this mechanism helps in properly evaluating the real performance of next-generation models. The same ideas can also transfer to your own applications, such as log analysis, time-series modeling, and long user behavior sequence modeling, where a fixed state is useful for handling long histories.
