← all writing

Linear Attention: Move the Parentheses

Part 2 of 4 on how a transformer remembers. KV cache · → Linear attention · Kernelization · Recurrent memory

Last post ended with a cache that is correct, necessary, and unboundedly large. This post is about the one algebra step that makes it finite — and it really is one step. Not a new architecture, not an approximation scheme. You move a pair of parentheses.

《transformer 怎么记东西》四篇之二。 KV 缓存 · → 线性注意力 · 核化 · 递归记忆

上一篇结束在一个正确、必需、而且无上界增长的缓存上。这一篇讲把它变成有限的那一步代数——而且真的只有一步。不是新架构,也不是什么近似方案。你只是把一对括号挪了个位置。

One step

Delete the softmax. Just for a moment — we’ll come back to what that costs. The output of a query is then three matrices multiplied together:

\[o \;=\; q\,K^{\top}V, \qquad q\in\mathbb{R}^{1\times d},\ \ K,V\in\mathbb{R}^{N\times d}\]

Matrix multiplication is associative, so you can evaluate that left-to-right or right-to-left and get the same answer. The answers are identical. The machines are not.

Left-to-right, $qK^{\top}$ is a $1\times N$ row of scores — one per token. That object grows every time you speak, and it’s exactly what the KV cache exists to feed. Right-to-left, $K^{\top}V$ is $d\times d$. It does not depend on $q$ at all, it can be built once and reused, and its size has nothing to do with $N$.

就一步

把 softmax 删掉。先删一会儿——这一刀的代价我们后面再算。这样一个 query 的输出就是三个矩阵连乘:

\[o \;=\; q\,K^{\top}V, \qquad q\in\mathbb{R}^{1\times d},\ \ K,V\in\mathbb{R}^{N\times d}\]

矩阵乘法满足结合律,所以你从左往右算、从右往左算,结果一样。答案完全相同,机器完全不同。

从左往右,$qK^{\top}$ 是一行 $1\times N$ 的分数——每个 token 一个。这个东西你每多说一句就长一点,而它正是 KV 缓存要去喂的对象。从右往左,$K^{\top}V$ 是 $d\times d$。它根本不含 $q$,可以只算一次然后反复使用,而且它的大小和 $N$ 毫无关系

The reason this works is worth stating plainly, because it’s the hinge the whole field turns on. Path A’s $i$-th term is $(q\cdot k_i)\,v_i$. That scalar $(q \cdot k_i)$ is linear in $q$, so $q$ factors out of the sum:

\[\sum_i (q\cdot k_i)\,v_i \;=\; q\Big(\underbrace{\textstyle\sum_i k_i^{\top}v_i}_{S,\ d\times d}\Big)\]

Everything inside the bracket is free of $q$. It can be precomputed, stored, and reused — and it’s one fixed-size matrix no matter how many terms went into the sum. That is the constant-size cache.

Why softmax can’t play

Softmax attention’s score isn’t $q \cdot k_i$, it’s $\exp(q\cdot k_i)$. The exponential welds $q$ and $k$ together: there’s no way to write $\exp(q\cdot k)$ as something-with-only-q times something-with-only-k in finite dimensions. So $q$ won’t come out of the sum, no term can be evaluated before the query arrives, and every $k_i, v_i$ has to be kept.

That’s the trade in one sentence. Softmax buys you a sharp, content-addressable lookup and pays for it with an O(N) cache. Dropping it buys you an O(1) cache and pays for it with a weaker lookup. How much weaker, and whether you can get some of it back, is the next post.

Writing

Split $S=\sum_i k_i^{\top}v_i$ into steps and the famous recurrence falls out:

\[S_t \;=\; S_{t-1} + k_t^{\top}v_t\]

Every token contributes one outer product — a full $d\times d$ matrix — and they all land on the same board. Here is the same history stored both ways, side by side.

这一步为什么成立,值得说明白,因为整个领域都绕着这个铰链转。路径 A 的第 $i$ 项是 $(q\cdot k_i)\,v_i$。那个标量 $(q \cdot k_i)$ 对 $q$ 是线性的,所以 $q$ 能从求和号里提出来:

\[\sum_i (q\cdot k_i)\,v_i \;=\; q\Big(\underbrace{\textstyle\sum_i k_i^{\top}v_i}_{S,\ d\times d}\Big)\]

括号里的东西完全不含 $q$。它可以提前算好、存起来、反复用——而且不管求和号里塞了多少项,它都是一个固定大小的矩阵。这就是那个恒定大小的缓存。

为什么 softmax 玩不了这一招

Softmax 注意力的分数不是 $q \cdot k_i$,而是 $\exp(q\cdot k_i)$。指数把 $q$ 和 $k$ 焊死在一起:在有限维里,你没法把 $\exp(q\cdot k)$ 写成只含 q 的东西只含 k 的东西。于是 $q$ 提不出来,任何一项都得等 query 到了才能算,每个 $k_i, v_i$ 也就一个都不能丢。

这笔交易一句话说完。Softmax 给你一个又尖又能按内容寻址的查表,代价是 O(N) 的缓存。把它扔掉,你换来 O(1) 的缓存,代价是查表变弱。 弱多少、能不能补回来一些,是下一篇的事。

写入

把 $S=\sum_i k_i^{\top}v_i$ 拆到每一步,那个著名的递推就出来了:

\[S_t \;=\; S_{t-1} + k_t^{\top}v_t\]

每个 token 贡献一个外积——一整个 $d\times d$ 的矩阵——而它们全部落在同一块板子上。下面是同一段历史用两种方式存着,并排放。

Reading, and what leaks in

Write two pairs and query with the first key:

\[k_1 S \;=\; k_1\big(k_1^{\top}v_1 + k_2^{\top}v_2\big) \;=\; \underbrace{\|k_1\|^2\,v_1}_{\text{what you wanted}} \;+\; \underbrace{(k_1\cdot k_2)\,v_2}_{\text{what leaked in}}\]

Two things to take from this. First, normalise the keys and $|k_1|^2 = 1$, so the first term is exactly right — that’s the entire justification for the F.normalize(k) you’ll find in every implementation. Second, the leak is exactly the inner product of the two keys. Orthogonal keys, no leak.

读取,以及漏进来的东西

写两对,然后用第一个 key 去查:

\[k_1 S \;=\; k_1\big(k_1^{\top}v_1 + k_2^{\top}v_2\big) \;=\; \underbrace{\|k_1\|^2\,v_1}_{\text{你想要的}} \;+\; \underbrace{(k_1\cdot k_2)\,v_2}_{\text{漏进来的}}\]

两件事要带走。第一,把 key 归一化,$|k_1|^2 = 1$,第一项就精确对了——这就是你在每份实现里都能看到的 F.normalize(k) 的全部理由。第二,漏进来的那一项恰好等于两个 key 的内积。key 正交,就不漏。

And now the fact you can’t negotiate with: in $d$ dimensions there are at most $d$ mutually orthogonal directions. Once you’ve written more than $d$ tokens, some new key must have a nonzero inner product with something already stored. Interference stops being a matter of luck or tuning and becomes arithmetic. That’s the wall the last post in this series is entirely about.

The bill

Per head, softmax stores $2Nd$ numbers; linear stores $d^2$. They break even at $N = d/2$ — 64 tokens for a head dimension of 128. Past that the flat line stays flat forever.

接下来是那个没得商量的事实:$d$ 维空间里最多只有 $d$ 个互相正交的方向。 一旦你写进去的 token 超过 $d$ 个,就必然有某个新 key 和已经存着的东西有非零内积。干扰不再是运气或调参的问题,而是算术。这堵墙,正是本系列最后一篇的全部内容。

账单

就单个头而言,softmax 要存 $2Nd$ 个数,线性只要存 $d^2$ 个。两者在 $N = d/2$ 打平——头维度 128 时就是 64 个 token。过了这个点,那条平线就一直平下去。

  Softmax attention Linear attention
cache size $2Nd$, grows with $N$ $d^2$, constant
per-token decode cost $\approx 4Nd$, grows $\approx 4d^2$, constant
memory traffic per token the whole KV cache one $d\times d$ state
the history itself lossless, every token addressable lossy, tokens interfere past capacity
training parallel by construction needs a chunkwise rewrite to parallelise

Read the last two rows together and you have the reason nobody ships a pure linear stack. The left column and the right column are complements, not competitors — which is why current hybrids interleave them, a few recurrent layers for every full-attention layer, cheap constant-cost memory for the near past and periodic exact retrieval for everything else.

What we broke

Everything above rests on one assumption we made in the first paragraph and never paid for: that the score is $q\cdot k$ rather than $\exp(q\cdot k)$. That assumption is what let $q$ leave the sum. It is also a real loss of expressiveness — a plain dot product is a much blunter retriever than a sharpened exponential one.

So the honest question is: how much of softmax can you recover while keeping $q$ and $k$ separable? That’s a question about kernels, and it’s the next post.


Same three matrices. Different order. Different machine.

References

  • Linear attention — Katharopoulos et al., Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention (arXiv:2006.16236)
  • The fast-weight reading of the same recurrence — Schlag, Irie, Schmidhuber, Linear Transformers Are Secretly Fast Weight Programmers (arXiv:2102.11174)
  • Making it fast in practice (chunkwise parallel form) — Yang et al., Gated Linear Attention Transformers with Hardware-Efficient Training (arXiv:2312.06635)
  • A hybrid that ships — Moonshot AI, Kimi Linear (arXiv:2510.26692)
  Softmax 注意力 线性注意力
缓存大小 $2Nd$,随 $N$ 增长 $d^2$,恒定
每 token 解码代价 约 $4Nd$,随 $N$ 增长 约 $4d^2$,恒定
每 token 内存流量 整个 KV 缓存 一个 $d\times d$ 状态
历史本身 无损,每个 token 可独立寻址 有损,超出容量后互相干扰
训练 天然并行 需要改写成分块形式才能并行

把最后两行连起来读,就是没人上纯线性栈的理由。左右两列是互补的,不是竞争的——所以现在的混合架构把它们交错着放,每若干层递归层配一层全注意力:便宜的恒定成本记忆管近处,周期性的精确检索管其余。

我们弄坏了什么

上面所有东西都压在一个我们在第一段就做出、却一直没付账的假设上:分数是 $q\cdot k$ 而不是 $\exp(q\cdot k)$。正是这个假设让 $q$ 得以离开求和号。而它也是实打实的表达力损失——一个朴素的点积,比一个被指数放大过的检索器要钝得多。

所以诚实的问题是:在保持 $q$ 和 $k$ 可分离的前提下,你能把 softmax 找回来多少?这是个关于的问题,也就是下一篇。


同样三个矩阵,不同的顺序,不同的机器。

参考

  • 线性注意力 — Katharopoulos 等, Transformers are RNNs: Fast Autoregressive Transformers with Linear AttentionarXiv:2006.16236
  • 同一个递推的「快速权重」读法 — Schlag, Irie, Schmidhuber, Linear Transformers Are Secretly Fast Weight ProgrammersarXiv:2102.11174
  • 怎么在实践中跑得快(分块并行形式) — Yang 等, Gated Linear Attention Transformers with Hardware-Efficient TrainingarXiv:2312.06635
  • 一个真的上线了的混合架构 — Moonshot AI, Kimi LineararXiv:2510.26692