Skip to content
Inference Academy

Linear attention, DeltaNet and KDA: how hybrid models keep the cache small

Why the KV cache grows with every token, how linear attention swaps it for a fixed-size state, why that state forgets, how the delta rule, gates and Kimi Delta Attention fix it, how chunking puts it back on tensor cores, and why hybrid models still keep some full attention layers. Every number comes from code you can run.

By

18 min · verified 2026-115 animated diagramsPro
Share

Every token a transformer generates adds a key and a value to the cache of every attention layer. At a million tokens that cache, not the weights, decides how many users fit on a GPU and how fast each step runs. A family of ideas from 2020 to 2026 replaces most of that growing cache with a small fixed-size state. This lesson builds that idea from scratch, shows where it breaks and how each fix works, and ends with what it means for serving.

You need Python 3 and numpy (pip install numpy). The full script is short; each section shows the part it uses.

#The cache that grows

In softmax attention each new token's query is compared with the key of every earlier token, and the output mixes their values (attention from first principles). During decode the engine keeps those keys and values so it does not recompute them (the KV cache). Two consequences:

  • Memory grows linearly with length: one key and one value per token, per layer.
  • Each decode step reads the whole cache from GPU memory, so step time grows with length too (roofline).

Tricks such as GQA and MLA make each token's entry smaller (attention optimisations). They do not change the fact that there is one entry per token. Linear attention does.

#Same answer, two orders

Ignore the scaling for a moment. Attention computes softmax⁡(QK⊤) V\operatorname{softmax}(QK^{\top})\,V. The product QK⊤QK^{\top} is N×NN \times N, so it grows with the sequence. Matrix products are associative: if there were no softmax, (QK⊤)V(QK^{\top})V would equal Q(K⊤V)Q (K^{\top} V), and K⊤VK^{\top} V is only d×dd \times d, whatever NN is.

The softmax is what prevents the reordering, because the exponential ties each query to each key. Linear attention (Katharopoulos et al., 2020) replaces it with a feature map φ\varphi applied to Q and K separately. The map only needs to keep values positive; the original paper used elu⁡(x)+1\operatorname{elu} (x) + 1. Now the output for token tt is:

outt=φ(qt)⋅Stφ(qt)⋅ztSt=St−1+φ(kt) vt⊤(a d×d state)zt=zt−1+φ(kt)(a d-vector, for normalisation)\begin{aligned} \text{out}_t &= \frac{\varphi(q_t) \cdot S_t}{\varphi(q_t) \cdot z_t} \\ S_t &= S_{t-1} + \varphi(k_t)\, v_t^{\top} &&\text{(a } d \times d \text{ state)} \\ z_t &= z_{t-1} + \varphi(k_t) &&\text{(a } d\text{-vector, for normalisation)} \end{aligned}

Check that the masked quadratic form and the token-by-token form give the same numbers:

python
import numpy as np
rng = np.random.default_rng(0)
N, d = 6, 4
Q, K, V = rng.normal(size=(3, N, d))
phi = lambda x: np.where(x > 0, x + 1, np.exp(x))      # elu(x)+1, always positive
q, k = phi(Q), phi(K)

A = np.tril(q @ k.T)                                   # quadratic form with a causal mask
out_quad = (A @ V) / A.sum(1, keepdims=True)

S = np.zeros((d, d)); z = np.zeros(d); out_rec = []    # recurrent form: carry a fixed state
for t in range(N):
    S += np.outer(k[t], V[t]); z += k[t]
    out_rec.append(q[t] @ S / (q[t] @ z))
print(f"max difference {np.abs(out_quad - np.array(out_rec)).max():.1e}; state floats {S.size + z.size}")
text
max difference 4.4e-16; state floats 20

They agree to rounding error. The recurrent form carries 20 numbers here, and it would carry 20 numbers after a million tokens. In a real model dd is a head dimension such as 128, so the state is 128 × 128 per head per layer, and it replaces a cache that grows by one row every token.

A cache that grows versus a state that does not
Animated

Softmax attention: KV cache

The
keyvalue

Rows: 1 · grows every token

Linear attention: fixed state

Numbers: 36 · same size forever

Token 1: “The”

Softmax attention stores this token's key and value as a new row. Linear attention instead adds kᵀv into a fixed 6 × 6 state.

Left: softmax attention keeps every token's key and value. Right: linear attention folds each token into a fixed d × d state (cell colour = value, blue positive, red negative).

#The catch: a fixed state forgets

Think of the state SS as an associative memory: writing kv⊤k v^{\top} stores value vv under key kk, and multiplying by kk again reads it back. That works perfectly when the keys are orthogonal. A d×dd \times d memory has room for only about dd orthogonal keys. After that, new keys overlap old ones and reads come back blended.

Write nn random key-value pairs into a 64 × 64 state, then read each one back and measure how close the read is to the stored value (cosine 1.0 means perfect):

python
def recall(n, d=64, trials=20):
    scores = []
    for _ in range(trials):
        K = rng.normal(size=(n, d)); K /= np.linalg.norm(K, axis=1, keepdims=True)
        V = rng.normal(size=(n, d)); S = np.zeros((d, d))
        for i in range(n):
            S += np.outer(K[i], V[i])                  # additive write
        R = K @ S                                      # read every key back
        scores.append(((R * V).sum(1) / np.linalg.norm(R, axis=1) / np.linalg.norm(V, axis=1)).mean())
    return np.mean(scores)
for n in [16, 64, 256, 1024]: print(n, round(recall(n), 2))
text
16 0.9
64 0.71
256 0.45
1024 0.24

At 16 pairs reads are good. At 1,024 pairs every read is mostly noise. This is why early linear-attention models were cheap but noticeably worse than softmax models: past a few thousand tokens the state is saturated, and nothing in the additive rule ever removes anything.

Pro content

Keep reading with Inference Academy Pro

Unlock the rest of this lesson, including 4 animated diagrams, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.

Still to come in this lesson

  1. The delta rule: overwrite, do not pile on
  2. Gates: forgetting on purpose
  3. Making it fast: chunks put it back on tensor cores
  4. Why hybrids keep some full attention
  5. What it means for serving
  6. What you can now do
  7. Common mistakes
  8. Exercise
  9. Going deeper

You will be able to answer

  • What lets linear attention keep a fixed-size state instead of a growing KV cache?
  • In the lesson's experiment, what happens when you write 1,024 key-value pairs into a 64 × 64 additive state and read them back?
  • What does the delta rule change?
  • What does Kimi Delta Attention add on top of Gated DeltaNet?
  • Why do models such as Kimi Linear, Qwen3-Next and Kimi K3 keep about one full attention layer in four?

Articles that build on this lesson

Preparing for an interview?