Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

20.3 Linear Attention

A decoder receives three values in the order 2, 8, 20. If the first and third have the same key, can it still retrieve the first value on its own? That depends on what the layer kept when it read the third token. In additive linear attention, you can follow the write, reproduce the readout, and count the bytes in the state.


1. The Core Idea

For input queries QQ, keys KK, values VV and key width dd, dense softmax attention computes a score for each visible token pair. Fused kernels can evaluate the following expression without storing its complete score matrix.

Attention(Q,K,V)=softmax(QKTd)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d}}\right)V

Choose a kernel that scores each pair by the dot product of two feature vectors, ϕ(q)Tϕ(k)\phi(q)^T\phi(k). Its unnormalized numerator can be reassociated as

ϕ(Q)(ϕ(K)TV)\phi(Q)\left(\phi(K)^T V\right)

For a decoder, the limits of the two sums determine which tokens a query can see. At position tt, include only the prefix through tt.

St=∑i=1tϕ(ki)viT,zt=∑i=1tϕ(ki),ytT=ϕ(qt)TStϕ(qt)Tzt.S_t=\sum_{i=1}^t \phi(k_i)v_i^T,\qquad z_t=\sum_{i=1}^t \phi(k_i),\qquad y_t^T=\frac{\phi(q_t)^T S_t}{\phi(q_t)^T z_t}.

qiq_i, kik_i and viv_i are the query, key and value at position ii. A nonnegative feature map ϕ\phi has width mm. Each new token adds an outer product to the m×dvm\times d_v matrix StS_t and its key features to the length-mm vector ztz_t. The denominator is the total kernel weight visible to this query. This equation assumes positive total weight. Implementations need a policy for zero or very small denominators. [1]

2. Why the Idea Is Attractive

For fixed feature and value widths, one more decode step writes mdvm d_v entries and reads a state of the same shape, independent of prefix length. The connection between recurrence and structured matrix products also appears in state space duality. [3] By comparison, a dense attention head retains a key and a value per visible position and can score each key separately. A fixed-size matrix can still take more space at short lengths. The memory calculator shows where that changes.

3. Why Earlier Variants Struggled

Suppose the values 2 and 20 both have key features (1,0)(1,0), and the value 8 has features (0,1)(0,1). The final state holds sums (22,8)(22,8) and counts (2,1)(2,1). A query with features (1,0)(1,0) reads 22/2=1122/2=11. Swapping 2 and 20 leaves this final state unchanged. A reader given only the state cannot recover which one arrived first. Positional features, context-dependent keys and other update rules can change that conclusion.

4. What Modern Work Tries to Improve

An Emerging Hybrid Pattern

Yang et al. tested stacking delta-rule layers with sliding-window or global attention. Their retrieval experiments give a reason to check exact recall separately from average language-model loss. Dense layers can retain individual earlier keys. Recurrent layers carry their own fixed-size state. A serving system for a hybrid model must budget for both. [2]

Additive memory versus the delta rule

A simple gated write decays state and adds new information. The delta rule instead makes a state-dependent correction, subtracting the prediction already stored along the current key. [2]

St=(I−βtktktT)St−1+βtktvtT.S_t=(I-\beta_t k_tk_t^T)S_{t-1}+\beta_t k_tv_t^T.

Here St∈Rdk×dvS_t\in\mathbb R^{d_k\times d_v}, kt∈Rdkk_t\in\mathbb R^{d_k}, vt∈Rdvv_t\in\mathbb R^{d_v}, and βt\beta_t sets write strength. With unit-norm keys, ktktTk_tk_t^T projects onto the key direction. The correction can act along one key direction while preserving state in perpendicular directions. Gated DeltaNet also adds forgetting; check its normalization and gate ordering in the actual implementation. [4]

5. Educational PyTorch Example

Change the last value and predict the first two outputs

The first query reads only the value 2. The next query, with features (1,1)(1,1), gives both visible keys weight 1 and reads (2+8)/2=5(2+8)/2=5. Predict what happens to those outputs when the third value changes from 20 to 100. Run the block on CPU with Python 3.10+ and PyTorch.

Scope of the example. One head processes one unpadded sequence of float32 features. The query and key features are supplied directly. The loop exposes the state after each write. A batched decoder would also need projections, masks, per-request state and a kernel suited to its hardware.

import torch

# Rows already contain the query and key features for one attention head.
queries = torch.tensor([[1., 0.], [1., 1.], [1., 0.]])
keys = torch.tensor([[1., 0.], [0., 1.], [1., 0.]])
values = torch.tensor([[2.], [8.], [20.]])

def scan(queries, keys, values, state=None):
    if state is None:
        memory = values.new_zeros(keys.shape[1], values.shape[1])
        counts = keys.new_zeros(keys.shape[1])
    else:
        memory, counts = state

    outputs = []
    for query, key, value in zip(queries, keys, values, strict=True):
        memory = memory + torch.outer(key, value)
        counts = counts + key
        normalizer = query @ counts
        if normalizer <= 0:
            raise ValueError("query has no overlap with the visible keys")
        outputs.append((query @ memory) / normalizer)
    return torch.stack(outputs), (memory, counts)

stream, _ = scan(queries, keys, values)
weights = (queries @ keys.T).tril()
reference = (weights @ values) / weights.sum(dim=1, keepdim=True)
torch.testing.assert_close(stream, reference)
print(stream.flatten().tolist())

_, prefix_state = scan(queries[:2], keys[:2], values[:2])
suffix, _ = scan(queries[2:], keys[2:], values[2:], prefix_state)
torch.testing.assert_close(suffix, stream[2:])

changed_values = values.clone()
changed_values[2] = 100.
changed, _ = scan(queries, keys, changed_values)
torch.testing.assert_close(changed[:2], stream[:2])
print(changed.flatten().tolist())

The two runs print [2.0, 5.0, 11.0] and [2.0, 5.0, 51.0]. The triangular reference checks every output against a direct all-pairs calculation with the same kernel. Resuming from the saved pair (S2,z2)(S_2,z_2) reproduces the final output. If you replace the sums at each step with one sum over the entire sequence, the first query can already see the third value.

6. Interactive: Memory Complexity Visualizer

For 32 layers, eight KV heads, head width 128 and two bytes per KV element, one token needs 128 KiB of KV. The comparison stack has 32 recurrent heads per layer. With feature and value widths both 128, its FP32 state occupies 64.5 MiB per request. The per-token KV count comes from 2×32×8×128×22\times32\times8\times128\times2 bytes. The recurrent allocation is 32×32×(1282+128)×432\times32\times(128^2+128)\times4 bytes. Try lengths of 128, 516 and 4,096. The KV payload is 16 MiB, 64.5 MiB and 512 MiB respectively. How does switching the recurrent state to BF16 change the crossover?

How many bytes store the context?

Compare two hypothetical 32-layer stacks for one request. Each layer has 32 query or recurrent heads. Both the head width and the feature width are 128. KV uses two bytes per element. Recurrent state includes the normalizer z.

Attention KV cache
16.00 MiB
Recurrent state S + z
64.50 MiB

KV grows by 128 KiB per token. The two payloads cross at 516 tokens with these settings.

The bars share a scale. The larger payload fills the track. Each value counts tensor elements at the stated precision. Weights, activations, workspace and metadata have separate costs.

7. Practical Takeaway

Measure two things on the same prompts. First, can a later query recover an earlier value when keys repeat or the answer changes halfway through the text? Second, how many bytes must the runtime retain per open request at each prefix length? A model can save memory on the longer prefixes and still miss a correction the task requires.

Recent Work: Gating, Delta Updates, and Stateful Serving

As of 2026-10-13. Gated DeltaNet combines selective forgetting with targeted delta-rule updates and studies hybrid attention stacks [4]. Its update can erase information already in memory before a new write, which affects subsequent reads.

An efficient layer still needs an exact state contract. Prefix reuse must restore recurrent state and any attention KV at the same position. Branching speculation must isolate state that cannot be rolled back by merely shortening a token buffer. The recent integration evidence in Chapter 12.1 and Chapter 12.4 explains why architecture-level memory gains require scheduler and recovery validation. Evaluate associative recall, position sensitivity, long-context quality, and cold-versus-restored continuation alongside throughput.

October Deployment Case: Different Layers, Different State

As of 2026-11-25, Ling 3.1 Flash’s public card specifies 63 KDA layers and nine gated-MLA layers, a 7:1 hybrid pattern [5]. That is a concrete disclosed stack, not evidence that every “linear” model uses the same recurrence. Keep recurrent state and attention KV accounting separate; test exact recall, prefix reuse, branching and rollback against the actual runtime. Its hosted 1019 profile is not established as identical to the public weight revision. See Section 17.6 for the source-bound comparison.

Muir: finite-state capacity depends on read and write dynamics

As of 2026-11-25 — emerging research. Muir studies channel-wise gated delta memory. It allocates low-rank gate capacity by sensitivity, adjusts readout across memory timescales, and introduces a boundary-pivoted chunkwise kernel. Its static and dynamic readout variants trade single-lag retention against multi-lag adaptability. Results on TPU-oriented kernels and tested recall tasks do not establish hardware-independent superiority. [6]

A useful evaluation separates isolated-needle retrieval, multiple dependent facts and continuous-text modeling. Compare quality at fixed parameter/compute budgets, numerical conditioning, and actual device throughput; sequence-linear complexity alone does not settle those questions.

Quizzes

Quiz 1: Why does the final query return 11? The first and third keys both match it with weight 1. Their values sum to 22, and their total weight is 2.

Quiz 2: Why does the chunked calculation need the normalizer as well as the value sums? The sums provide the numerator. Without the previous key counts, the denominator misses the earlier matching token and the resumed result is scaled incorrectly.

Quiz 3: Why do 128 tokens use less memory for KV in the calculator’s initial configuration? At 128 KiB per token, the cache holds 16 MiB. The recurrent matrix and normalizer require 64.5 MiB from the first token. The two reach equal size at 516 tokens.

Quiz 4: Can a query distinguish the final states after swapping the values 2 and 20? Both values have the same key features in the exercise. Swapping them preserves their sum and count, so the final additive state is identical. Earlier prefix outputs can still differ.


References

  1. Katharopoulos, A., et al. (2020). Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. arXiv:2006.16236.
  2. Yang, S., et al. (2024). Parallelizing Linear Transformers with the Delta Rule over Sequence Length. arXiv:2406.06484.
  3. Dao, T., & Gu, A. (2024). Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. arXiv:2405.21060.
  4. Yang, S., Kautz, J., & Hatamizadeh, A. (2024). Gated Delta Networks: Improving Mamba2 with Delta Rule. Source.
  5. inclusionAI. Ling-3.1-flash model card, revision 93e96ab91e800998388563295340a4238ff3e962, verified 2026-11-25. Card.
  6. Gangavarapu, T., Tabak, G., & Schaefer, C. J. (2026). Muir: Linear Attention with Sensitivity-Allocated Gating and Matched-Filter Readout. Version pinned; accessed 2026-11-25.