Kernelization: The Licence to Move the Parentheses
Part 3 of 4 on how a transformer remembers. KV cache · Linear attention · → Kernelization · Recurrent memory
The last post moved a pair of parentheses and got a constant-size cache out of it. But it did that by quietly assuming the score is a plain dot product, when in real attention it’s $\exp(q\cdot k)$. This post is about that assumption: what exactly has to be true for the parentheses to move, why the exponential almost qualifies, and what people do about the almost.
The whole thing reduces to one move: get $q$ and $k$ to stand in separate columns, so neither ever needs to know about the other.
上一篇挪了一对括号,换来一个固定大小的缓存。但它是靠悄悄假设分数是个朴素点积做到的,而真实注意力里那是 $\exp(q\cdot k)$。这一篇讲的就是这个假设:括号能挪,到底需要什么条件成立;指数为什么差一点就合格;以及大家拿这个「差一点」怎么办。
整件事收缩成一个动作:让 $q$ 和 $k$ 各自站进自己的一列,从此谁也不必知道对方。
A kernel is an inner product wearing a disguise
One line:
\[\kappa(x,y) \;=\; \phi(x)^{\top}\phi(y)\]That’s it. A kernel is an ordinary inner product in some (possibly much bigger) space, written as a complicated-looking function of the original inputs. The trivial case is $\kappa(x,y)=x^\top y$ with $\phi(x)=x$ — no lift at all. The instructive case is one dimension up:
\[\kappa(x,y)=(1+xy)^2 = 1+2xy+x^2y^2 = \begin{bmatrix}1\\ \sqrt2\,x\\ x^2\end{bmatrix}^{\!\top}\begin{bmatrix}1\\ \sqrt2\,y\\ y^2\end{bmatrix}\]The left side tangles $x$ and $y$ into a quadratic. The right side is a perfectly ordinary dot product of two 3-vectors. They are identically equal. Check it channel by channel:
核,就是套了伪装的内积
一行:
\[\kappa(x,y) \;=\; \phi(x)^{\top}\phi(y)\]就这样。一个核,就是某个(可能大得多的)空间里的普通内积,被写成了原始输入的一个看起来很复杂的函数。平凡的例子是 $\kappa(x,y)=x^\top y$,对应 $\phi(x)=x$,什么都没升。有意思的例子只升了一维:
\[\kappa(x,y)=(1+xy)^2 = 1+2xy+x^2y^2 = \begin{bmatrix}1\\ \sqrt2\,x\\ x^2\end{bmatrix}^{\!\top}\begin{bmatrix}1\\ \sqrt2\,y\\ y^2\end{bmatrix}\]左边把 $x$ 和 $y$ 缠成了一个二次式。右边是两个三维向量规规矩矩的点积。它们恒等。逐个通道核对一遍:
The dashed line in that panel is the whole point. The left column is a function of $x$ alone; the right column is a function of $y$ alone; they touch exactly once, in the final multiply-and-sum. That separation is the licence. It’s what lets you compute $\sum_j \phi(k_j)v_j^{\top}$ before any query exists — and a sum you can compute in advance is a sum you can store in fixed size.
Choosing a kernel is choosing what attention looks like
Write attention as a kernel-weighted average and it is, near enough, Nadaraya–Watson kernel regression:
\[o_i \;=\; \frac{\sum_j \kappa(q_i,k_j)\,v_j}{\sum_j \kappa(q_i,k_j)}\]Numerator and denominator depend on nothing but $\kappa$. So the choice of kernel is the choice of attention’s behaviour — not a detail of it.
那个面板里的虚线才是重点。左边这列只是 $x$ 的函数,右边这列只是 $y$ 的函数,它们全程只碰面一次,在最后那一步相乘求和。这个分离就是那张许可证。 正是它让你能在任何 query 出现之前就把 $\sum_j \phi(k_j)v_j^{\top}$ 算好——而一个能提前算好的和,就是一个能用固定大小存下来的和。
选核,就是在选注意力长什么样
把注意力写成核加权平均,它跟统计里的 Nadaraya–Watson 核回归几乎是同一个东西:
\[o_i \;=\; \frac{\sum_j \kappa(q_i,k_j)\,v_j}{\sum_j \kappa(q_i,k_j)}\]分子分母都只依赖 $\kappa$。所以选哪个核,就是在选注意力的行为——而不是它的某个细节。
Which reframes the exponential in softmax. It isn’t a nonlinearity someone tossed in for flavour. It is a deliberately chosen kernel that happens to satisfy every requirement at once: strictly positive (so weights are weights), sharply peaked (so retrieval is decisive), normalisable (so the denominator never crosses zero) — and, it turns out, a legitimate inner product.
The exponential kernel’s φ really does exist
No trick required; the power series does the work. Substituting $z=q^\top k$:
\[e^{q^\top k}=\sum_{n=0}^{\infty}\frac{(q^\top k)^n}{n!}\]Each term $(q^\top k)^n$ is the inner product $\langle q^{\otimes n},k^{\otimes n}\rangle$ of two $n$-th tensor powers. Concatenate the orders and you have an honest — if infinite — feature map. Here it is written out for $d=2$:
这就把 softmax 里的指数重新定位了。它不是谁为了调味随手加的非线性,而是一个精心挑选的核,恰好同时满足所有要求:恒正(所以权重才是权重)、峰很尖(所以检索是果断的)、可归一化(所以分母不会过零)——而且,事实证明,它还是个合法的内积。
指数核的 φ 真的写得出来
不需要什么技巧,幂级数本身就做完了。代入 $z=q^\top k$:
\[e^{q^\top k}=\sum_{n=0}^{\infty}\frac{(q^\top k)^n}{n!}\]每一项 $(q^\top k)^n$ 都是两个 $n$ 阶张量幂的内积 $\langle q^{\otimes n},k^{\otimes n}\rangle$。把各阶首尾拼起来,你就得到一个货真价实的——尽管是无限维的——特征映射。下面是 $d=2$ 时把它真的写出来:
So the exponential is a valid kernel and $q$ can be factored out — it just needs infinitely many dimensions to do it, and truncating to order $M$ costs $\binom{d+M}{M}$ channels. At $d=64$ that’s 2145 channels by order 2 and tens of millions by order 6, per head. Valid, and unusable.
Random features: sample the infinite inner product
Performer’s answer is to estimate it instead. Draw $\omega\sim\mathcal N(0,I)$ and define
\[f_\omega(x)=\exp\!\Big(\omega^{\top}x-\tfrac{\|x\|^2}{2}\Big)\]Then there’s an exact expectation identity, straight out of the Gaussian moment generating function $\mathbb E[e^{\omega^\top t}]=e^{|t|^2/2}$ with $t=q+k$:
\[\mathbb E_\omega\big[f_\omega(q)\,f_\omega(k)\big] \;=\; e^{q^{\top}k}\]Sample $m$ of them, set $\phi(x)=\tfrac{1}{\sqrt m}[f_{\omega_1}(x),\dots,f_{\omega_m}(x)]$, and the inner product becomes a Monte Carlo estimate of the exact one. $m$ is now a dimension you pick.
所以指数是个合法的核,$q$ 也确实提得出来——只不过它需要无限多维才做得到,而截断到 $M$ 阶要付 $\binom{d+M}{M}$ 个通道。$d=64$ 时,二阶是 2145 个,六阶是几千万个,而且是每个头。合法,但没法用。
随机特征:把那个无限维内积采样出来
Performer 的答案是改成估计它。取 $\omega\sim\mathcal N(0,I)$,定义
\[f_\omega(x)=\exp\!\Big(\omega^{\top}x-\tfrac{\|x\|^2}{2}\Big)\]于是有一个精确的期望恒等式,直接由高斯的矩生成函数 $\mathbb E[e^{\omega^\top t}]=e^{|t|^2/2}$ 取 $t=q+k$ 推出:
\[\mathbb E_\omega\big[f_\omega(q)\,f_\omega(k)\big] \;=\; e^{q^{\top}k}\]采 $m$ 个,令 $\phi(x)=\tfrac{1}{\sqrt m}[f_{\omega_1}(x),\dots,f_{\omega_m}(x)]$,内积就成了对精确值的蒙特卡洛估计。$m$ 现在是你自己挑的维度。
Where it all lands
Three posts, one chain, and every link is load-bearing:
Kernelization issues the licence — if $\kappa$ factors as $\phi(q)^\top\phi(k)$, then $q$ and $k$ are separable. Associativity cashes it in — separate them and the parentheses move, and an $O(N)$ cache collapses into a $d\times d$ state. Fixed capacity sends the bill — $d\times d$ holds $d$ things, so past $d$ tokens the system has no choice but to learn what to throw away. That’s the last post: erase, decay, and the five-year argument about how to forget.
The practical epilogue is a little deflating and worth saying anyway. Almost nobody actually approximates $\exp$. Explicit expansions blow up combinatorially; random features are unbiased but noisy at $O(1/\sqrt m)$, which is one reason Performer-style methods aren’t always stable on long sequences. So the field mostly shrugged and reached for a cheap non-negative map like ELU(x)+1 — which doesn’t even pretend to approximate softmax, and only guarantees the two properties you actually need: non-negative, and normalisable.
That’s not laziness, it’s a budget decision. If you’re going to lose retrieval fidelity either way, lose it cheaply and spend the compute somewhere it buys more — which turned out to be the forgetting rules in the next post.
Separate the variables, and everything else is bookkeeping.
References
- Linear attention via feature maps — Katharopoulos et al., Transformers are RNNs (arXiv:2006.16236)
- Random features for kernels — Rahimi & Recht, Random Features for Large-Scale Kernel Machines (NIPS 2007)
- Applying them to softmax attention — Choromanski et al., Rethinking Attention with Performers (FAVOR+, arXiv:2009.14794)
- A survey of the design space — Tay et al., Efficient Transformers: A Survey (arXiv:2009.06732)
这一切落在哪
三篇,一条链,每一环都是承重的:
核化发出许可证——如果 $\kappa$ 能分解成 $\phi(q)^\top\phi(k)$,$q$ 和 $k$ 就是可分离的。 结合律把它兑现——分离之后括号就能挪,$O(N)$ 的缓存坍缩成一个 $d\times d$ 的状态。 固定容量寄来账单——$d\times d$ 只装得下 $d$ 样东西,所以超过 $d$ 个 token 之后,系统别无选择,只能学会扔掉什么。这就是最后一篇:擦除、衰减,以及那场关于「怎么忘」的五年争论。
还有一个略微扫兴、但值得说的实践尾声。几乎没有人真的去逼近 $\exp$。 显式展开在组合上就炸了;随机特征无偏但含噪,收敛只有 $O(1/\sqrt m)$,这也是 Performer 一类方法在长序列上不总是稳的原因之一。所以这个领域基本上耸了耸肩,改用 ELU(x)+1 这种廉价的非负映射——它压根不装作在逼近 softmax,只保证你真正需要的那两条性质:非负、可归一化。
这不是偷懒,是预算决策。既然横竖都要损失检索保真度,那就损失得便宜点,把算力花到回报更高的地方去——而那个地方,事实证明就是下一篇里的遗忘规则。
把变量分开,剩下的都是记账。
参考
- 用特征映射做线性注意力 — Katharopoulos 等, Transformers are RNNs(arXiv:2006.16236)
- 核的随机特征 — Rahimi & Recht, Random Features for Large-Scale Kernel Machines(NIPS 2007)
- 把它用到 softmax 注意力上 — Choromanski 等, Rethinking Attention with Performers(FAVOR+,arXiv:2009.14794)
- 这个设计空间的综述 — Tay 等, Efficient Transformers: A Survey(arXiv:2009.06732)