Continual Learning: From Attention to Neural Memory

Suppose a document says that a particular animal is called Mira. Several paragraphs later, a question refers to that animal. The model must carry useful information across those paragraphs. Where is it stored, how does the question find it, and what happens if a later sentence corrects the name?

These questions lead to four papers: Linear Transformers (2020), Fast Weight Programmers (2021), TTT Layers (2024), and Titans (2025). Rather than start with their terminology, we will build a small memory, discover its limitations, and introduce each method when it answers the next question.

The discussion concerns learning and remembering while processing a sequence. Whether a system also preserves knowledge permanently across tasks is a separate question, addressed at the end. All numerical vectors below are constructed examples, not measurements of named semantic features in a real LM.

假设一篇文章说,某只动物的名字是 Mira。隔了几段文字,后面的一个问题又提到这只动物。模型需要把有用信息传过中间这些段落。信息存在哪里?问题怎样找到它?如果后文更正了这个名字,记忆又该怎样修改?

这些问题会把我们带到四篇论文:Linear Transformers(2020)Fast Weight Programmers(2021)TTT Layers(2024)Titans(2025)。我们不从论文术语开始,而是先搭一个小记忆,看到它的问题,再引入解决下一个问题的方法。

本文讨论的是处理一条序列时怎样学习与记忆。系统是否还能跨任务永久保留知识,是另一个问题,留到最后讨论。文中的数值向量都是人为构造的教学例子,不是对真实 LM 中某种语义 feature 的测量。

1. What Must Be Carried From One Token to the Next?

1.1 First Separate Tokens, Representations, and Parameters

A language model receives a sequence of tokens: pieces of text represented by integer IDs. A word may occupy more than one token. We write the IDs as $a_1,a_2,\ldots$; the subscript is a position, not a feature coordinate.

An embedding lookup replaces each ID with a vector of numbers. Later layers transform that vector using the visible context. At the particular layer we are studying, call the vector at position $t$ $x_t$. It has $d_{\mathrm{model}}$ entries:

\[x_t=(x_{t,1},\ldots,x_{t,d_{\mathrm{model}}}).\]

One entry is a coordinate, and the number of entries is the dimension or width. Thus $t$ selects a token position, while the second subscript selects a coordinate within that position’s vector. The vector can change between layers even though the token ID does not.

The rules that compute these vectors contain learned numbers: the model’s parameters, collected under the name $\Theta$. During an ordinary inference run, $\Theta$ is fixed, but $x_t$ changes with the input. A changing representation does not imply that training has occurred.

For next-token prediction, the model uses the observed prefix $a_{\le t}=(a_1,\ldots,a_t)$ to produce a distribution over $a_{t+1}$. It must not use the unknown future token to construct that prediction. This restriction is called causality. In a causal network, $x_t$ can contain information from the prefix, not later positions.

Language model 接收一串 tokens:用整数 ID 表示的文本片段。一个词可能对应多个 tokens。我们把这些 IDs 写成 $a_1,a_2,\ldots$;这里的下标表示位置,不是 feature coordinate。

Embedding lookup 把每个 ID 换成一个数值向量,后面的 layers 再根据可见 context 变换它。把我们正在研究的这一层、位置 $t$ 处的向量记为 $x_t$。它包含 $d_{\mathrm{model}}$ 个数:

\[x_t=(x_{t,1},\ldots,x_{t,d_{\mathrm{model}}}).\]

每个数叫一个 coordinate;数的个数叫 dimension 或 width。因此,$t$ 选择 token 位置,第二个下标选择该位置向量中的一个 coordinate。经过不同 layers 时,这个向量可以改变,但 token ID 没有改变。

计算这些向量的规则中包含许多学到的数,叫模型的 parameters,统一记为 $\Theta$。普通 inference 中,$\Theta$ 固定,但 $x_t$ 随输入改变。表示发生变化,不代表进行了训练。

在 next-token prediction 中,模型根据已观察到的 prefix $a_{\le t}=(a_1,\ldots,a_t)$,产生关于 $a_{t+1}$ 的概率分布。它不能先使用未知的未来 token,再预测这个 token。这个限制叫 causality。在 causal network 中,$x_t$ 可以包含前缀的信息,但不能包含后面位置的信息。

1.2 Every Memory Needs a State, a Write, and a Read

Imagine processing the document one piece at a time without repeatedly rereading everything. When the next piece arrives, some information from the past must still be available. Call that carried information the state $s_t$. “State” describes its role; it does not specify whether the data structure is a vector, a list, a matrix, or a small model.

There are two different operations. Writing changes what later steps will have available. Reading uses the current state to produce an output. In abstract notation,

\[s_t=U_\Theta(s_{t-1},x_t),\qquad z_t=R_\Theta(s_t,x_t).\]

$U$ names the update function and $R$ the read function. $s_{t-1}$ means state before the current input; $s_t$ means state after the write. $z_t$ is a feature passed to subsequent layers, not necessarily a token or a probability. The superscript-free $\Theta$ indicates that the same parameterized rules can be reused at every position.

A conventional vector-state RNN is one example: take $s_t=h_t\in\mathbb R^D$. Its learned recurrence converts the old vector and current input into a new vector. A KV cache is another example: the state is a growing list of key–value pairs, and a write appends a pair. Later we will make the state a matrix whose entries are updated by learning.

This gives us three questions to ask of every paper: what is carried, how is it changed, and how is it queried? We will use the same questions even when the carried numbers are called “weights.”

想象模型逐段处理文章,而不是每来一段就重新读完整篇。新内容到来时,过去的一些信息必须仍然可用。把这份传递下来的信息称为 state $s_t$。“State”描述的是作用,不规定数据结构必须是向量、列表、矩阵还是一个小模型。

这里有两个不同操作。写入改变后续步骤能够使用的信息,读取利用当前 state 产生输出。抽象地写成:

\[s_t=U_\Theta(s_{t-1},x_t),\qquad z_t=R_\Theta(s_t,x_t).\]

$U$ 是更新函数,$R$ 是读取函数;$s_{t-1}$ 表示当前输入到来前的 state,$s_t$ 表示写入后的 state。$z_t$ 是交给后续 layers 的 feature,不一定是 token 或概率。这里 $\Theta$ 不带时间下标,表示同一套带参数的规则可以在各个位置复用。

常规 vector-state RNN 就是一个例子:令 $s_t=h_t\in\mathbb R^D$,learned recurrence 把旧向量与当前输入变成新向量。KV cache 是另一个例子:state 是不断增长的 key–value 列表,写入就是追加一对。后面我们还会把 state 变成矩阵,通过学习修改矩阵 entries。

因此,阅读每篇论文时都先问三件事:传递什么、怎样修改、怎样查询? 即使传递的这些数叫“weights”,我们也继续问同样的问题。

2. Attention: Read Content Through a Matching Address

2.1 Why Do We Need Both a Key and a Value?

A database lookup makes the distinction concrete. “Employee 1024” can locate a record, but the desired answer might be the employee’s name or department. The lookup criterion and returned record serve different purposes. A library catalog is similar: its topic tags already have meaning, but are not the book’s contents.

Attention uses a learned, soft version of this organization. At the receiving position $i$, a query $q_i$ expresses a request. Each candidate position $j$ offers a key $k_j$ for matching and a value $v_j$ for transmission. These are not hand-assigned database fields; they are computed from hidden representations.

We use row vectors throughout. A learned matrix transforms an input by mixing its coordinates; this is a linear projection. One attention head computes

\[q_i=x_iW_Q,\qquad k_j=x_jW_K,\qquad v_j=x_jW_V.\]

For example, one key coordinate is $k_{j,b}=\sum_{a=1}^{d_{\mathrm{model}}}x_{j,a}(W_K)_{ab}$. Thus “projecting” does not mean choosing a literal column labeled “animal”; it means learning a weighted combination of available features. The dimensions are

\[W_Q,W_K:\ [d_{\mathrm{model}},d_k],\qquad W_V:\ [d_{\mathrm{model}},d_v].\]

The outputs $q_i,k_j$ have $d_k$ coordinates; $v_j$ has $d_v$. $d_k$ is the matching width, $d_v$ the transmitted-content width. A head is one such set of projections and its associated read operation; multiple heads can learn different matches and contents.

A key therefore can contain semantic information: its meaning is expressed through which queries match it. But it need not be unique, human-interpretable, or a complete encoding of the original vector. Two candidates can match similar requests while carrying different values. “Key = address” is a computational analogy, not a claim that keys are meaningless integers or guaranteed unique identifiers.

数据库查询能说明这个区别。“员工 1024”可以定位一条记录,但我们想拿到的可能是员工姓名或部门。查询条件与返回记录的作用不同。图书馆目录也是如此:主题标签已经包含语义,但标签不等于书的内容。

Attention 使用一种可学习的、软匹配的组织方式。在接收信息的位置 $i$,query $q_i$ 表达检索请求;每个候选位置 $j$ 提供用于匹配的 key $k_j$,以及用于传递的 value $v_j$。它们不是人工填写的数据库字段,而是从 hidden representations 计算出来的。

全文统一采用行向量。一个 learned matrix 把输入的各个 coordinates 混合,产生新向量,这叫 linear projection。一个 attention head 计算:

\[q_i=x_iW_Q,\qquad k_j=x_jW_K,\qquad v_j=x_jW_V.\]

例如,key 的一个 coordinate 是 $k_{j,b}=\sum_{a=1}^{d_{\mathrm{model}}}x_{j,a}(W_K)_{ab}$。所以“投影”不是选择一列标着“动物”的字段,而是学习对已有 features 的加权组合。矩阵维度为:

\[W_Q,W_K:\ [d_{\mathrm{model}},d_k],\qquad W_V:\ [d_{\mathrm{model}},d_v].\]

输出 $q_i,k_j$ 各有 $d_k$ 个 coordinates,$v_j$ 有 $d_v$ 个。$d_k$ 是匹配使用的 width,$d_v$ 是传递内容的 width。一个 head 就是一组这样的 projections 及对应读取操作;多个 heads 可以学习不同的匹配与内容。

因此,key 可以包含语义:哪些 queries 会匹配它,就是这种语义发挥作用的方式。但它不必唯一,不必能被人逐 coordinate 解释,也不必完整保存原向量。两个候选可以匹配相似请求,却传递不同 values。“Key = 地址”是计算上的类比,不是说 key 没有语义,也不保证它像数据库 ID 一样唯一。

2.2 From a Match Score to an Actual Read

How can two vectors match? The simplest score multiplies corresponding coordinates and sums them:

\[q_i k_j^\top=\sum_{b=1}^{d_k}q_{i,b}k_{j,b}.\]

The transpose symbol $\top$ turns the key row into a column, allowing row-times-column multiplication. The result is one number. Q and K must have equal width for this calculation; the value width has no role yet.

Raw scores are not mixing weights: they can be negative and need not sum to one. Softmax exponentiates each score, making it positive, then divides by the sum over the allowed candidates. Write the scaled score as $s_{ij}=q_i k_j^\top/\sqrt{d_k}$. The read is built in two steps:

\[a_{ij}=\frac{\exp(s_{ij})}{\sum_{r\le i}\exp(s_{ir})}, \qquad z_i=\sum_{j\le i}a_{ij}v_j.\]

The denominator runs over positions, not vocabulary entries. Causality limits candidates to $j\le i$. A large $a_{ij}$ means that position $j$ contributes more of its value to receiving position $i$. The coefficients add to one, so this read is a weighted average of values, not usually an exact lookup.

Why divide by $\sqrt{d_k}$? A wider dot product adds more terms. Under a simple model of independent, zero-mean, unit-variance Q/K coordinates, its variance grows as $d_k$ and its typical scale, measured by standard deviation, grows as $\sqrt{d_k}$. The divisor compensates for that width effect. Actual learned coordinates need not satisfy those assumptions; this is not measured unit-variance normalization. Normalizations develops that qualification.

Now consider “The animal didn’t cross the street because it was tired.” At “it,” a head might retrieve an animate entity. As a deliberately tiny calculation, retain only two candidates and set

\[q=(1,0),\quad k_{\mathrm{animal}}=(1,0),\quad k_{\mathrm{street}}=(0,1).\]

The dot products are 1 and 0. With $d_k=2$, the scaled scores are approximately $(0.707,0)$. Exponentiation gives approximately $(2.028,1)$; dividing by their sum gives $(0.670,0.330)$. Both candidates remain active.

If $v_{\mathrm{animal}}=(2,0)$ and $v_{\mathrm{street}}=(0,3)$, then

\[z=0.670(2,0)+0.330(0,3)\approx(1.340,0.991).\]

Matching decides the coefficients; the values supply the coordinates being mixed. The output would approach the animal value only if the score gap were much larger.

There is also a timing constraint in this example. The causal vector at “animal” cannot already contain the later claim “didn’t cross the street.” At “it,” earlier layers may have gathered that preceding clause, but the future word “tired” is still unavailable. The linguistic story is an analogy, not evidence that real heads encode the named attributes. The full matrix view is in Attention and Language Models.

Could we use K or X directly as the values? (Click to expand)

Yes. Setting $V=K$ is valid when dimensions fit, but ties the features used for matching to those transmitted afterward. Setting $V=X$ transmits the unprojected hidden vectors. Separate $W_V$ lets each head choose its own content projection and width.

For example, a head could match by a subject-related feature while transmitting information about the matched entity. This need not be a literal disentangled representation. The benefit is freedom to optimize the two roles separately, not a theorem that tied values always fail. Some projections can be absorbed into subsequent learned linear maps, depending on the architecture.

两个向量怎样匹配?最简单的分数是把对应 coordinates 相乘,再加起来:

\[q_i k_j^\top=\sum_{b=1}^{d_k}q_{i,b}k_{j,b}.\]

转置符号 $\top$ 把 key 行向量变成列向量,才能进行“行乘列”,得到一个数。Q 与 K 的 width 必须相等才能这样计算;value 的 width 此时还没有参与。

Raw scores 不能直接当作混合比例:它们可能为负,也不必加和为一。Softmax 先对每个 score 取指数,使它为正,再除以允许候选的指数之和。把 scaled score 记为 $s_{ij}=q_i k_j^\top/\sqrt{d_k}$,读取分成两步:

\[a_{ij}=\frac{\exp(s_{ij})}{\sum_{r\le i}\exp(s_{ir})}, \qquad z_i=\sum_{j\le i}a_{ij}v_j.\]

Denominator 遍历的是 positions,不是 vocabulary entries。Causality 把候选限制为 $j\le i$。$a_{ij}$ 越大,位置 $j$ 的 value 向接收位置 $i$ 贡献得越多。由于系数之和为一,这通常是 values 的加权平均,不是精确返回某一条记录。

为什么除以 $\sqrt{d_k}$?较宽的 dot product 累加更多项。在 Q/K coordinates 相互独立、零均值、单位方差的简化模型中,和的 variance 随 $d_k$ 增长,描述典型尺度的 standard deviation 随 $\sqrt{d_k}$ 增长。除法补偿这个 width 效应。真实 learned coordinates 不必满足这些假设,因此这不是根据实际统计量做单位方差归一化。Normalizations 详细讨论了这个限制。

再看 “The animal didn’t cross the street because it was tired.” 在 “it” 位置,一个 head 可能检索有生命的实体。为了算清楚,暂时只保留两个候选,并设置:

\[q=(1,0),\quad k_{\mathrm{animal}}=(1,0),\quad k_{\mathrm{street}}=(0,1).\]

Dot products 分别为 1 和 0。由于 $d_k=2$,scaled scores 约为 $(0.707,0)$;取指数约为 $(2.028,1)$;再除以它们的和,得到 $(0.670,0.330)$。两个候选都仍参与读取。

若 $v_{\mathrm{animal}}=(2,0)$,$v_{\mathrm{street}}=(0,3)$,那么:

\[z=0.670(2,0)+0.330(0,3)\approx(1.340,0.991).\]

匹配负责决定系数,values 提供真正混合的 coordinates。只有 score gap 大得多时,输出才接近单独的 animal value。

这个例子还有时间顺序限制:在 “animal” 位置,causal vector 不可能已经包含后面的“没有过马路”。在 “it” 位置,前面的 layers 可以收集此前子句的信息,但未来的 “tired” 仍不可见。这里的语言学故事是类比,不证明真实 heads 恰好编码了这些命名属性。完整矩阵视角见 Attention and Language Models

能否直接把 K 或 X 当作 Values?(点击展开)

可以。维度合适时,令 $V=K$ 是合法的,但会绑定“匹配时使用的 features”和“匹配后传递的 features”。令 $V=X$ 则传递未投影的 hidden vectors。独立的 $W_V$ 让每个 head 选择自己的 content projection 与 width。

例如,一个 head 可以通过与主语有关的 feature 匹配,再传递被匹配实体的信息。这不要求真实表示恰好逐项解耦。好处是可以分别优化两种作用,不是说 tied values 必然失败。根据 architecture 的安排,某些 projections 也可以被吸收到后续 learned linear maps 中。

2.3 What Does a Growing KV Cache Cost?

For one head, retaining $t$ pairs uses $t(d_k+d_v)$ numbers. To produce the next read in full attention, the query must compare with those keys and combine their values. At fixed widths, the work of that read grows with $t$.

Across $T$ generated positions, the number of candidate comparisons is proportional to $1+2+\cdots+T=T(T+1)/2$. This is the source of quadratic sequence work for full attention. It does not mean every implementation stores a full $T\times T$ attention matrix: memory-efficient kernels can avoid materializing it, while retaining the pairwise computation.

The attraction of explicit storage is equally important: individual retained K/V pairs remain available for later matching. A fixed-size state must instead combine history. Can we summarize the pairs before knowing which query will arrive, and still read useful associations afterward? The next subsection constructs such a summary. The summary is of projected representations, not a guarantee of lossless storage of the original text.

对一个 head,保留 $t$ 对 K/V 需要 $t(d_k+d_v)$ 个数。在 full attention 中,为了产生下一次读取,query 需要与这些 keys 比较,并组合对应 values。Width 固定时,这次读取的工作量随 $t$ 增长。

跨 $T$ 个生成位置,候选比较的数量正比于 $1+2+\cdots+T=T(T+1)/2$。这就是 full attention 的序列工作量呈二次增长的来源。但这不意味着所有实现都存储完整 $T\times T$ attention matrix:节省内存的 kernels 可以不显式生成整张矩阵,仍然执行成对计算。

显式保存也有重要好处:每条被保留的 K/V 仍可供后续匹配。固定大小的 state 则必须合并历史。我们能否在还不知道未来 query 时,就先把 pairs 汇总起来,而且以后仍能读到有用关联?下一节搭建这样的汇总。需要注意,汇总的对象是投影后的 representations,并不是保证无损保存原始文本。

2.4 Linear Transformers: A Summary We Can Update

The obstacle is that softmax’s exponential score depends jointly on the future query and each individual key. The 2020 Linear Transformers paper chooses a different similarity, one that can be separated into features of the query and features of the key. This changes the attention rule; it is not merely deleting a costly line of code. Katharopoulos et al.

We will first use simple positive vectors, then name the general transformation. Suppose two candidate keys are $k_1=(1,1)$ and $k_2=(1,2)$, their values are $v_1=(2,0)$ and $v_2=(0,3)$, and the query is $q=(1,1)$. Use the dot product itself, rather than its exponential, as the nonnegative similarity. The similarities are 2 and 3, so the normalized read should be

\[z=\frac{2(2,0)+3(0,3)}{2+3}=(0.8,1.8).\]

Now compute the same answer without keeping those two pairs separately. Turn each key row into a column and multiply it by its value row:

\[k_1^\top v_1= \begin{bmatrix}2&0\\2&0\end{bmatrix}, \qquad k_2^\top v_2= \begin{bmatrix}0&3\\0&6\end{bmatrix}.\]

This is an outer product, a matrix rather than the scalar produced by a dot product. Entry $(a,b)$ multiplies key coordinate $a$ by value coordinate $b$. Add the two matrices and, separately, add the keys:

\[S_2=\begin{bmatrix}2&3\\2&6\end{bmatrix}, \qquad c_2=(2,3).\]

The matrix stores the numerator information; the vector stores the normalization information. Reading gives $qS_2=(4,9)$ and $qc_2^\top=5$, hence the same $(4,9)/5=(0.8,1.8)$.

Why did that work? Matrix multiplication distributes over addition: $q(k_j^\top v_j)=(qk_j^\top)v_j$. Therefore the query can be applied after summing all the outer products. Adding a third pair requires only adding one more outer product to $S_2$ and one more key to $c_2$.

Real projected Q/K coordinates may be negative. To obtain suitable nonnegative similarities, introduce a feature map $\phi$: a function that transforms each query or key separately into an $r$-coordinate feature vector. Here we choose positive features so nonempty sums have positive denominators. A kernel, in this discussion, is simply the resulting similarity function $\kappa(q,k)=\phi(q)\phi(k)^\top$. These names do not introduce another learning loop.

With $\widetilde q_t=\phi(q_t)$ and $\widetilde k_t=\phi(k_t)$, the same calculation becomes

\[S_t=S_{t-1}+\widetilde k_t^\top v_t,\qquad c_t=c_{t-1}+\widetilde k_t,\] \[\boxed{z_t=\frac{\widetilde q_tS_t}{\widetilde q_tc_t^\top}},\qquad S_0=0,\quad c_0=0.\]

$S_t$ has shape $[r,d_v]$ and $c_t$ has shape $[r]$, independent of sequence length. At fixed widths, a write and read use a fixed amount of work; processing $T$ tokens takes work proportional to $T$ for this mixer. This is what “linear” refers to here, not a claim that the entire network is a linear function.

The rearrangement is exact for the selected feature-map similarity. A fixed finite feature map does not generally reproduce exact exponential softmax on arbitrary inputs. Also, dropping $c_t$ changes normalized averaging into an unnormalized sum. We will deliberately examine that unnormalized memory next, but will not call it the same function. Derivation in §§3.2–3.4

障碍在于,softmax 的指数分数同时依赖未来 query 与每个单独的 key。2020 年 Linear Transformers 论文选择另一种 similarity,让它可以拆成 query 的 features 与 key 的 features。这改变了 attention rule,不是单纯删掉一行昂贵的代码。Katharopoulos 等

先用简单的正值向量算一次,再给一般的变换命名。假设两个候选 keys 为 $k_1=(1,1)$、$k_2=(1,2)$,values 为 $v_1=(2,0)$、$v_2=(0,3)$,query 为 $q=(1,1)$。这次用 dot product 本身,而不是它的指数,作为非负 similarity。两个 similarities 是 2 和 3,因此归一化读取应为:

\[z=\frac{2(2,0)+3(0,3)}{2+3}=(0.8,1.8).\]

现在不分别保留这两组 pairs,试着算出同一个答案。先把每个 key 行向量变成列向量,再乘它的 value 行向量:

\[k_1^\top v_1= \begin{bmatrix}2&0\\2&0\end{bmatrix}, \qquad k_2^\top v_2= \begin{bmatrix}0&3\\0&6\end{bmatrix}.\]

这叫 outer product(外积),产生矩阵,不是 dot product 产生的 scalar。第 $(a,b)$ 项是 key 第 $a$ 个 coordinate 与 value 第 $b$ 个 coordinate 的乘积。把两个矩阵加起来,另外再把 keys 加起来:

\[S_2=\begin{bmatrix}2&3\\2&6\end{bmatrix}, \qquad c_2=(2,3).\]

矩阵保存 numerator 所需的信息,向量保存 normalization 所需的信息。读取时,$qS_2=(4,9)$,$qc_2^\top=5$,于是同样得到 $(4,9)/5=(0.8,1.8)$。

为什么能这样算?因为矩阵乘法对加法可分配: $q(k_j^\top v_j)=(qk_j^\top)v_j$。因此,可以先把所有 outer products 相加,之后再乘 query。第三组 pair 到来时,只需给 $S_2$ 加一个新的 outer product,给 $c_2$ 加一个新的 key。

真实投影后的 Q/K coordinates 可能为负。为了得到合适的非负 similarities,引入 feature map $\phi$:它是分别作用于每个 query 或 key 的函数,输出 $r$ 个 feature coordinates。这里选择正值 features,让非空候选集的 denominator 为正。本讨论中的 kernel 就是由此得到的 similarity function:$\kappa(q,k)=\phi(q)\phi(k)^\top$。这些名字没有引入新的训练循环。

令 $\widetilde q_t=\phi(q_t)$,$\widetilde k_t=\phi(k_t)$,同样的计算就变成:

\[S_t=S_{t-1}+\widetilde k_t^\top v_t,\qquad c_t=c_{t-1}+\widetilde k_t,\] \[\boxed{z_t=\frac{\widetilde q_tS_t}{\widetilde q_tc_t^\top}},\qquad S_0=0,\quad c_0=0.\]

$S_t$ 的 shape 是 $[r,d_v]$,$c_t$ 是 $[r]$,不随序列变长。Widths 固定时,一次写入和读取的工作量固定,因此这个 mixer 处理 $T$ 个 tokens 的工作量正比于 $T$。这里“linear”指的是这个增长关系,不是说整个 network 都是线性函数。

对选定的 feature-map similarity,这个重排是精确的。但固定、有限的 feature map 一般不能在任意输入上精确复现 exponential softmax。另外,删掉 $c_t$ 会把 normalized averaging 改为 unnormalized sum。接下来会有意单独研究这种不归一化的记忆,但不会说它还是同一个函数。推导见 §§3.2–3.4

3. Fast Weight Programmers: How Do We Correct a Memory?

3.1 A Matrix Can Store More Than One Answer

The previous summary matrix is not merely an array we inspect: we multiply it by a query to obtain an output. That suggests treating a matrix as a small function. A function is a rule taking an input to an output. Let our rule be $f(q;W)=qW$, where $W$ has shape $[d_k,d_v]$.

Here we deliberately study a bare, unnormalized memory. There is no feature map or denominator in this example. Suppose $d_k=d_v=2$, and we want two associations:

\[k_1=(1,0)\mapsto v_1=(1,0),\qquad k_2=(0,1)\mapsto v_2=(0,1).\]

Start from a zero matrix $W_0$. The additive writes produce

\[W_1=W_0+k_1^\top v_1= \begin{bmatrix}1&0\\0&0\end{bmatrix},\qquad W_2=W_1+k_2^\top v_2= \begin{bmatrix}1&0\\0&1\end{bmatrix}.\]

A query $(1,0)$ selects the first row, returning $(1,0)$. A query $(0,1)$ selects the second row, returning $(0,1)$. The same matrix supplies two different answers. A query $(0.5,0.5)$ mixes the rows and returns $(0.5,0.5)$; no discrete dictionary lookup is being performed.

Because $W_t$ changes while we process the sequence, its entries are called fast weights. The projections that generate keys and values are called slow weights when they are learned across training sequences and reused within one sequence. Fast versus slow describes the update timescale, not necessarily the learning-rate magnitude or permanent versus temporary storage.

The 2021 Fast Weight Programmers paper makes this connection between linear attention and dynamically written weight matrices explicit. Its next question is more important than the name: what should happen when a key’s association needs correction? Schlag, Irie & Schmidhuber

上一节的汇总矩阵并不是只供我们查看的数组:query 乘上它就能得到输出。因此,可以把矩阵当作一个小函数。函数就是从输入得到输出的一条规则。令这条规则为 $f(q;W)=qW$,其中 $W$ 的 shape 为 $[d_k,d_v]$。

这里有意研究裸的、未归一化的 memory;这个例子没有 feature map,也没有 denominator。假设 $d_k=d_v=2$,我们想保存两组关联:

\[k_1=(1,0)\mapsto v_1=(1,0),\qquad k_2=(0,1)\mapsto v_2=(0,1).\]

从零矩阵 $W_0$ 开始,累加写入得到:

\[W_1=W_0+k_1^\top v_1= \begin{bmatrix}1&0\\0&0\end{bmatrix},\qquad W_2=W_1+k_2^\top v_2= \begin{bmatrix}1&0\\0&1\end{bmatrix}.\]

Query $(1,0)$ 选择第一行,返回 $(1,0)$;query $(0,1)$ 选择第二行,返回 $(0,1)$。同一个矩阵给出了两个不同答案。Query $(0.5,0.5)$ 则混合两行,返回 $(0.5,0.5)$,不是离散字典查询。

由于处理序列时 $W_t$ 不断改变,它的 entries 被称为 fast weights。产生 keys 与 values 的 projections 如果跨训练序列学习、在当前序列中复用,则称为 slow weights。Fast 与 slow 指更新时间尺度,不一定指 learning rate 大小,也不直接规定是否永久保存。

2021 年 Fast Weight Programmers 论文明确建立了 linear attention 与动态写入 weight matrix 的联系。但比命名更重要的是下一个问题:如果某个 key 对应的内容需要更正,该怎么做?Schlag、Irie 与 Schmidhuber

3.2 First Measure What the Memory Predicts Incorrectly

Suppose the first association changes: $(1,0)$ should now return $(0,1)$. Adding the new value to the old matrix would make its first row $(1,1)$, not $(0,1)$. Repeating an unchanged association has a related problem: an unnormalized additive memory keeps increasing its amplitude. The normalized averaging method does not have that amplitude problem, but repeated contradictory values are averaged rather than explicitly replaced.

The remedy is to ask the old memory what it already predicts before writing. For the incoming pair $(k_t,v_t)$, define

\[\widehat v_t=k_tW_{t-1},\qquad e_t=\widehat v_t-v_t.\]

The hat marks a prediction. $e_t$ is the error vector, with one predicted-minus-target difference per value coordinate. In the correction example, $\widehat v_t=(1,0)$, the target is $(0,1)$, and $e_t=(1,-1)$. We want to reduce the first output coordinate and increase the second.

To judge a proposed memory matrix $W$ with one number, square the coordinate errors and add them:

\[\ell_t(W)=\frac12\sum_{b=1}^{d_v}\big[(k_tW)_b-v_{t,b}\big]^2 =\frac12\lVert k_tW-v_t\rVert_2^2.\]

This number is the local loss. Squaring prevents positive and negative errors from cancelling. Summing requires the whole output, not just one coordinate, to match. The notation $\lVert u\rVert_2^2$ means the sum of squares of the entries of $u$. The factor $1/2$ simplifies the derivative without changing which $W$ minimizes the loss.

Here $W$ is the candidate variable being judged; $W_{t-1}$ is its current value. That distinction matters: a formula for the loss describes many possible matrices, while an update chooses a new matrix from the current one.

假设第一条关联变了:$(1,0)$ 现在应该返回 $(0,1)$。如果只是把新 value 加进旧矩阵,第一行会变成 $(1,1)$,不是 $(0,1)$。重复写入没有变化的关联也有问题:未归一化的累加 memory 会不断增大幅度。归一化平均没有这个幅度问题,但相互冲突的 values 会被平均,不会明确替换旧目标。

解决办法是:写入前,先问旧 memory 已经预测了什么。对新来的 $(k_t,v_t)$,定义:

\[\widehat v_t=k_tW_{t-1},\qquad e_t=\widehat v_t-v_t.\]

帽子表示预测值。$e_t$ 是 error vector,每个 coordinate 都是预测减目标。在刚才的更正中,$\widehat v_t=(1,0)$,目标为 $(0,1)$,所以 $e_t=(1,-1)$。我们希望第一个输出 coordinate 减小,第二个增大。

为了用一个数评价某个候选矩阵 $W$,把每个 coordinate 的误差平方后相加:

\[\ell_t(W)=\frac12\sum_{b=1}^{d_v}\big[(k_tW)_b-v_{t,b}\big]^2 =\frac12\lVert k_tW-v_t\rVert_2^2.\]

这个数就是局部 loss。平方让正负误差不能相互抵消,求和则要求整个输出匹配,而不只匹配一个 coordinate。$\lVert u\rVert_2^2$ 表示向量 $u$ 各 entries 的平方和。$1/2$ 用来简化求导,不改变使 loss 最小的 $W$。

这里 $W$ 是被评价的候选变量,$W_{t-1}$ 是它当前的值。这个区别很重要:loss 公式描述许多可能矩阵的好坏,update 才从当前矩阵出发选择一个新矩阵。

3.3 Turn the Error Into a Change of Weights

The error says which output coordinates are wrong. It does not yet say which matrix entries to change. Consider entry $W_{ab}$. Output coordinate $b$ is

\[(k_tW)_b=\sum_{a=1}^{d_k}k_{t,a}W_{ab}.\]

A small change in $W_{ab}$ changes that output in proportion to $k_{t,a}$. If this key coordinate is zero, changing $W_{ab}$ does not affect the current prediction at all. If it is large, the same weight change has a larger effect.

The partial derivative measures how the loss changes when we vary one weight entry while holding the other entries fixed. Differentiating the half-square therefore gives, at the old matrix,

\[\frac{\partial\ell_t}{\partial W_{ab}}=k_{t,a}e_{t,b}.\]

Collect every partial derivative in a matrix of the same shape as $W$. This is the gradient, written $\nabla_W\ell_t$. Our entry formula is exactly an outer product:

\[g_t=\nabla_W\ell_t(W_{t-1})=k_t^\top e_t.\]

The small positive learning rate $\eta_t$ sets how strongly to act on this gradient. Subtracting the gradient moves against the locally increasing direction of the loss:

\[W_t=W_{t-1}-\eta_tg_t =W_{t-1}+\eta_tk_t^\top(v_t-\widehat v_t).\]

This is the delta rule: write a correction based on the difference between the desired and predicted values. If the prediction is already right, the error and this write are zero. This is not “add the whole target again.” The full fast-weight paper has additional feature and normalization choices; the equation here isolates its error-correcting idea. Fast Weight Programmers, §4.2

For the two-row example, $k_t=(1,0)$ and $e_t=(1,-1)$ give

\[g_t=\begin{bmatrix}1&-1\\0&0\end{bmatrix}.\]

With $\eta_t=1$,

\[W_{\mathrm{new}} =\begin{bmatrix}1&0\\0&1\end{bmatrix} -\begin{bmatrix}1&-1\\0&0\end{bmatrix} =\begin{bmatrix}0&1\\0&1\end{bmatrix}.\]

The corrected key $(1,0)$ now reads $(0,1)$. The other key $(0,1)$ still reads $(0,1)$. This particular correction changed only the first row.

Why does subtracting the gradient help, and is the step always safe? (Click to expand)

A derivative is a local slope. In one variable, a positive slope means a small positive change raises the loss, so a small negative change lowers it. The gradient collects those slopes across all weight entries. This is the local argument behind gradient descent, developed in Basics of Optimizers.

It is not a guarantee for arbitrarily large steps. For this linear, single-example squared loss, multiplying the update by the training key gives

\[e_{\mathrm{new}}=(1-\eta_t\lVert k_t\rVert_2^2)e_{\mathrm{old}}.\]

The current error shrinks when $0<\eta_t\lVert k_t\rVert_2^2<2$. It becomes exactly zero when the product equals 1. A unit-length key with $\eta_t=1$ is the example above; the same learning rate can overshoot for a longer key. These conditions concern this one local quadratic loss, not global LM convergence.

Error 告诉我们哪些输出 coordinates 错了,但还没告诉我们该改哪些矩阵 entries。看一个 entry $W_{ab}$,输出第 $b$ 个 coordinate 是:

\[(k_tW)_b=\sum_{a=1}^{d_k}k_{t,a}W_{ab}.\]

小幅修改 $W_{ab}$ 时,输出改变多少,正比于 $k_{t,a}$。如果这个 key coordinate 为零,修改 $W_{ab}$ 根本不会影响当前预测;如果它很大,相同的 weight 修改就会产生更大的输出变化。

Partial derivative(偏导数)测量的是:其他 entries 保持不动,只修改一个 weight entry,loss 会怎样改变。因此,对 half-square 求导,在旧矩阵处得到:

\[\frac{\partial\ell_t}{\partial W_{ab}}=k_{t,a}e_{t,b}.\]

把每个 entry 的偏导数排成与 $W$ 同样形状的矩阵,就是 gradient,记为 $\nabla_W\ell_t$。刚才的 entry 公式恰好是一个 outer product:

\[g_t=\nabla_W\ell_t(W_{t-1})=k_t^\top e_t.\]

取一个较小的正数 learning rate $\eta_t$,决定根据 gradient 改多少。减去 gradient,就是朝局部 loss 增长的反方向移动:

\[W_t=W_{t-1}-\eta_tg_t =W_{t-1}+\eta_tk_t^\top(v_t-\widehat v_t).\]

这就是 delta rule:根据目标与预测的差异写入修正。如果已经预测正确,error 与本次写入就是零,而不是“把整个 target 再加一遍”。完整的 fast-weight 论文还有 feature 与 normalization 等设计;这里的公式单独展示误差修正思想。Fast Weight Programmers,§4.2

回到两行矩阵,$k_t=(1,0)$,$e_t=(1,-1)$,所以:

\[g_t=\begin{bmatrix}1&-1\\0&0\end{bmatrix}.\]

取 $\eta_t=1$:

\[W_{\mathrm{new}} =\begin{bmatrix}1&0\\0&1\end{bmatrix} -\begin{bmatrix}1&-1\\0&0\end{bmatrix} =\begin{bmatrix}0&1\\0&1\end{bmatrix}.\]

更正后的 key $(1,0)$ 现在读出 $(0,1)$;另一个 key $(0,1)$ 仍读出 $(0,1)$。这次特定的修正只改了第一行。

为什么减去 Gradient 有帮助?步子总是安全吗?(点击展开)

Derivative 是局部斜率。一维时,斜率为正,意味着小幅正向移动会增大 loss,因此小幅负向移动会减小 loss。Gradient 收集所有 weight entries 的这些斜率。这是 gradient descent 的局部依据,详见 Basics of Optimizers

但它不保证任意大的 step 都安全。对这里 linear、single-example squared loss 的特例,用 training key 左乘更新式可得:

\[e_{\mathrm{new}}=(1-\eta_t\lVert k_t\rVert_2^2)e_{\mathrm{old}}.\]

当 $0<\eta_t\lVert k_t\rVert_2^2<2$ 时,当前误差缩小;这个乘积为 1 时,当前误差恰好归零。上面的单位长度 key、$\eta_t=1$ 就是特例。同样的 learning rate 遇到更长的 key,则可能越过目标。这些条件只讨论这一项局部 quadratic loss,不是整个 LM 的全局收敛保证。

3.4 Why Can a Correct Write Damage an Older Read?

The two keys above were orthogonal: their dot product is zero. They addressed separate rows. Real learned keys need not be so neatly separated.

Hold an old query $q$ fixed. The new write changes its output by

\[\Delta z=q(W_t-W_{t-1}) =\eta_t(qk_t^\top)(v_t-\widehat v_t).\]

Read the three factors separately. The last vector is the correction desired for the new key. The scalar $qk_t^\top$ measures how much the old query overlaps that key. The learning rate controls the overall strength. A zero overlap protects this old read from this particular delta update. A nonzero overlap allows the correction to spill into it.

For example, take the new key $(0.8,0.6)$. Its dot products with the old probes $(1,0)$ and $(0,1)$ are $0.8$ and $0.6$, so neither probe is protected. This is interference: multiple associations use overlapping directions in the same memory. It occurs even if the projections that created the keys remain frozen.

In the lab, leave $\eta=1$ and select Delta correction. The first two writes build the two rows. The third replaces the first target. The fourth introduces the overlapping key. Compare the probe bars before and after that fourth write. Switching to additive storage shows why correction differs from accumulation. The momentum-and-decay option will be explained in Section 5; it is a small update-rule demonstration, not a full Titans implementation.

Follow the same keys through writing and reading. A successful new association need not preserve every old answer.

前面的两个 keys 是正交的,也就是 dot product 为零,分别对应两行。真实 learned keys 不必分得这么整齐。

固定一个旧 query $q$,本次写入使它的输出改变:

\[\Delta z=q(W_t-W_{t-1}) =\eta_t(qk_t^\top)(v_t-\widehat v_t).\]

分开看这三个因素:最后的向量是新 key 想要的修正;scalar $qk_t^\top$ 衡量旧 query 与这个新 key 有多少重叠;learning rate 控制整体强度。重叠为零时,这次特定的 delta update 不影响该旧读取;重叠不为零时,新修正会波及它。

例如,新 key 为 $(0.8,0.6)$,它与旧 probes $(1,0)$、$(0,1)$ 的 dot products 分别为 $0.8$ 和 $0.6$,所以两个 probes 都没有得到保护。这叫 interference(干扰):多个关联在同一个 memory 中使用重叠方向。即使产生 keys 的 projections 完全冻结,也会发生。

下面实验中先保持 $\eta=1$,选择 Delta correction。前两次写入构造两行,第三次替换第一条目标,第四次引入重叠 key。比较第四次前后的 probe 柱状图,就能看到旧读取受到影响。切换到累加模式,可对比“修正”与“叠加”的区别。Momentum 与 decay 模式在第 5 节解释,它只是小型 update-rule 演示,不是完整 Titans 实现。

用相同 keys 贯穿写入与读取。新关联写入成功,不代表每个旧答案都被保留。

4. TTT Layers: Put a Learning Procedure Inside the Forward Pass

4.1 Have We Replaced the Hidden State, or Renamed It?

Recall the definition from Section 1: a state carries information from earlier inputs to later computation. The matrix $W_t$ does exactly that. It contains the accumulated effect of previous writes, and later queries use it. Therefore $W_t$ is a hidden state whose entries happen to be used as model weights.

The same numbers have two roles at two levels. To the small function $f(q;W)=qW$, they are parameters that define its mapping. To the surrounding sequence model, they are temporary state passed from one position to the next. There is no contradiction.

A conventional RNN might carry a vector $h_t$ and use a fixed readout $G_\Theta(h_t,q)$ to answer a query. Our matrix carries a linear mapping and answers with $qW_t$. Both can return different answers for different queries. The advantage under discussion is an explicit way to organize and update associations, not a capability that vector states are forbidden to have.

For example, flatten a matrix by listing its entries:

\[W=\begin{bmatrix}w_{11}&w_{12}\\w_{21}&w_{22}\end{bmatrix}, \qquad \operatorname{vec}(W)=(w_{11},w_{12},w_{21},w_{22}).\]

This operation, called $\operatorname{vec}$, loses nothing. An update function could reshape that vector, perform the gradient write, and flatten it again. The computation is still a recurrent update. With momentum, its carried update history must be included in the full state too.

Consequently, “vector stores a representation, weights store a function” is a helpful organization metaphor, not an absolute mathematical boundary. A sufficiently expressive recurrence can implement the same update. Choosing the learner explicitly supplies an inductive bias: a preferred family of computations that training does not have to discover from scratch.

Does matrix state automatically have more capacity or higher cost? (Click to expand)

A vector in $\mathbb R^D$ has $D$ entries. A matrix of shape $[d_k,d_v]$ has $d_kd_v$ entries, or $d^2$ in the square case. Those counts describe storage at a chosen precision; they are not counts of guaranteed retrievable facts. A vector could also have $D=d_kd_v$, and recurrent models need not all use vector states.

A bare matrix read and delta write require work proportional to $d_kd_v$. A conventional dense vector recurrence can itself have quadratic cost in its width. A nonlinear memory may require substantially more work. Shape alone does not establish that one family is always faster, larger, or better at remembering. Interference and the structure of the queries matter as well.

回到第 1 节的定义:state 把早先输入的信息传给后续计算。矩阵 $W_t$ 正在做这件事:它包含此前 writes 的累计影响,之后的 queries 使用它。因此,$W_t$ 就是一种 hidden state,只是它的 entries 被当作小模型的 weights 使用。

同一组数在两个层次扮演两个角色。对小函数 $f(q;W)=qW$ 来说,它们是定义映射的 parameters;对外围 sequence model 来说,它们是从一个位置传到下一个位置的临时 state。这并不矛盾。

常规 RNN 可以携带向量 $h_t$,通过固定 readout $G_\Theta(h_t,q)$ 回答 query;我们的矩阵携带一个 linear mapping,通过 $qW_t$ 回答。两者都能对不同 queries 给出不同答案。这里讨论的好处是显式组织和更新关联的方法,不是说 vector state 绝对做不到。

例如,把矩阵的 entries 依次排列,就能展平成向量:

\[W=\begin{bmatrix}w_{11}&w_{12}\\w_{21}&w_{22}\end{bmatrix}, \qquad \operatorname{vec}(W)=(w_{11},w_{12},w_{21},w_{22}).\]

这个操作叫 $\operatorname{vec}$,不丢任何信息。一个 update function 完全可以把向量还原为矩阵,执行 gradient write,再展平。整段计算仍是 recurrent update。若使用 momentum,完整 state 还应包含它携带的 update history。

因此,“向量保存表示,weights 保存函数”是有用的组织类比,不是绝对数学边界。有足够表达能力的 recurrence 可以实现同样的更新。显式选择 learner 提供的是 inductive bias(归纳偏置):优先采用某一类计算,让训练不必从零发现这套计算方法。

Matrix State 是否自动具有更大容量或更高成本?(点击展开)

$\mathbb R^D$ 中的向量有 $D$ 个 entries;shape 为 $[d_k,d_v]$ 的矩阵有 $d_kd_v$ 个,方阵时为 $d^2$。这些是在指定数值精度下的存储数量,不是保证能够检索多少条事实。向量也可以取 $D=d_kd_v$,recurrent models 也不都使用 vector state。

裸矩阵的读取与 delta write 工作量正比于 $d_kd_v$;常规 dense vector recurrence 本身也可能具有关于 width 的二次成本;nonlinear memory 则可能需要更多计算。仅凭 shape 不能断言哪个家族总是更快、更大或更会记忆。Interference 与 queries 的结构同样重要。

4.2 Replace the Linear Mapping With a Small Learner

Our matrix memory can only implement a linear rule: the response to a sum of queries is the sum of their responses. If useful key–value relationships require interactions that a linear map cannot express, we can choose a more flexible function.

Let $f(u;W)$ be a small model taking an input vector $u$ with $d_k$ coordinates and returning $d_v$ coordinates. It could be a matrix multiplication or a multilayer perceptron (MLP): several learned linear transformations separated by nonlinear activation functions. The nonlinearities allow the combined function to do more than a single linear transformation.

Now $W$ means the entire collection of fast parameters, possibly multiple matrices and biases. We still know how to write: ask the model to predict the value from the key, measure the error, and take a gradient step. We still know how to read: run the model on a query.

\[\ell_t(W)=\frac12\lVert f(k_t;W)-v_t\rVert_2^2,\] \[W_t=W_{t-1}-\eta_t\nabla_W\ell_t(W_{t-1}), \qquad z_t=f(q_t;W_t).\]

The subscript on $\nabla_W$ specifies the variables being changed. If $W$ contains multiple tensors, the gradient contains one same-shaped tensor for each, and the update is applied to each tensor. It does not instruct us to update every weight in the surrounding LM.

This is the core viewpoint of TTT Layers: the recurrent state is a learner, and its transition is a self-supervised learning step. The sequence layer’s forward pass—the computation from input to output—now contains a small training operation. That operation still runs on a test sequence, hence “Test-Time Training.” Sun et al., §§2.1–2.3

Why write with $k_t$ but read with $q_t$? Writing asks, “what association should this input teach the memory?” Reading asks, “what information is useful for the current output?” A diary entry and a question about the diary need not have the same form. Separate learned projections let the two roles differ; the read query must nevertheless be learned to work with the mapping trained on keys.

In our token-wise schedule, the current token is written before it is read. This is causal when the resulting feature helps predict the next token: the current input is already known. It would be leakage to use the unknown next token in that write and then claim to predict it. Other architectures can arrange reads and writes differently; timing is part of the algorithm.

矩阵 memory 只能实现 linear rule:两个 queries 相加后的输出,等于分别输出后相加。如果有用的 key–value 关系需要单个 linear map 无法表示的交互,就可以选择更灵活的函数。

令 $f(u;W)$ 是一个小模型,接收有 $d_k$ 个 coordinates 的输入 $u$,返回 $d_v$ 个 coordinates。它可以是矩阵乘法,也可以是 multilayer perceptron(MLP):在多个 learned linear transformations 之间插入 nonlinear activation functions。正是这些 nonlinearities,让整个函数不再等价于一次 linear transformation。

现在 $W$ 表示全部 fast parameters,可能有多个矩阵与 biases。我们仍然知道怎样写:让模型从 key 预测 value,测量误差,再走一步 gradient update。也仍然知道怎样读:把 query 输入这个模型。

\[\ell_t(W)=\frac12\lVert f(k_t;W)-v_t\rVert_2^2,\] \[W_t=W_{t-1}-\eta_t\nabla_W\ell_t(W_{t-1}), \qquad z_t=f(q_t;W_t).\]

$\nabla_W$ 的下标说明改变哪些变量。若 $W$ 包含多个 tensors,gradient 就为每个 tensor 提供一个同 shape 的 tensor,再分别执行更新。它不是让我们修改外围 LM 中的所有 weights。

这就是 TTT Layers 的核心视角:recurrent state 是一个 learner,state transition 是一次 self-supervised learning step。这个 sequence layer 的 forward pass,也就是从输入计算输出的过程,现在包含一次小型训练操作。处理 test sequence 时,这个操作仍然执行,因此叫 “Test-Time Training”。Sun 等,§§2.1–2.3

为什么用 $k_t$ 写,却用 $q_t$ 读?写入问的是“当前输入应该教 memory 哪种关联”,读取问的是“当前输出需要什么信息”。日记条目与关于日记的问题,不必采用同一种形式。独立的 learned projections 允许两种作用不同,但 read query 仍需被训练成能利用以 keys 训练的映射。

在本文逐 token 的安排中,先写入当前 token,再读取。若得到的 feature 用来预测下一个 token,这符合 causality,因为当前输入已经知道。但若把未知的下一个 token 用于写入,再声称预测了它,就是信息泄漏。其他 architectures 可以安排不同的读写顺序;时间顺序是算法的一部分。

4.3 Who Supplies the Correct Keys and Values?

So far, numerical keys and values were supplied by us to make the mechanics visible. A real TTT layer does not receive hand-labeled memory records. It constructs both from the current hidden vector:

\[k_t=x_tW_K,\qquad v_t=x_tW_V,\qquad q_t=x_tW_Q.\]

These are three views of the same input: three transformations emphasizing potentially different information. The training view $k_t$ is the small learner’s input. The label view $v_t$ is the target it tries to predict. The test/read view $q_t$ is used to obtain the output. In this terminology “test view” does not mean it is unavailable during training.

There is no external ground-truth key. The value is a generated continuous target, sometimes loosely called a pseudo-label, not an externally certified answer. Self-supervised means the target is constructed from observed data itself. We can make the key and value now, without waiting for a future token or asking a human to label the document.

But why should the generated target be useful? The local reconstruction loss cannot answer that. For a sufficiently simple model, setting every target to zero and making the learner output zero gives zero reconstruction loss, yet remembers nothing useful. This is a collapsed solution: a trivial representation solves the local objective while discarding the intended information.

We need a second criterion that evaluates the whole LM. Let $\Theta$ collect its slow parameters: the projections, the remaining layers, and, when learned, the initial fast state and step-size rule. After the memory produces $z_t$, the remaining network produces vocabulary logits and a next-token distribution. Denote that probability model by $p_\Theta$. The observed next token $a_{t+1}$ supplies the target for

\[\mathcal L_t=-\log p_\Theta(a_{t+1}\mid a_{\le t};W_t(\Theta)).\]

The probability is evaluated at the actual next-token ID. Taking its negative logarithm penalizes assigning little probability to the observed continuation. For example, probability $0.8$ gives a smaller loss than $0.2$. Summing or averaging these terms gives the LM cross-entropy objective; background on this conditional prediction loss is in Use of Information Theory in Learning Theory, §2.1.

Writing $W_t(\Theta)$ emphasizes that the memory state depends on the slow parameters used to construct its learning process. It is not extra ground truth supplied to the model.

Question Inner reconstruction Outer LM prediction
What is predicted? Value view from key view Next token from observed prefix
What supplies the target? $v_t=x_tW_V$, generated from current input $a_{t+1}$, observed in the training text
What is optimized? Sequence-specific fast state $W$ Slow parameters $\Theta$
What does success mean? Better fit to this local association Better prediction by the complete LM

Both tasks are self-supervised, but at different levels. The next-token “ground truth” is an observed token, not a claim that every statement in the corpus is factually true.

Outer training can favor targets that preserve information useful later—for instance, entity identity when it helps predict a later reference. No human needs to name that feature. However, the outer objective is not a proof that collapse is impossible: other network paths may bypass memory, gradients may be unhelpful, or optimization may stall. It provides a usefulness criterion, not guaranteed success.

前面的数值 keys 与 values 是我们人为给定的,目的是看清机制。真实 TTT layer 不会收到人工标注的 memory records,而是从当前 hidden vector 生成它们:

\[k_t=x_tW_K,\qquad v_t=x_tW_V,\qquad q_t=x_tW_Q.\]

这是同一输入的三个 views:三个可能强调不同信息的变换。Training view $k_t$ 是小 learner 的输入;label view $v_t$ 是它想预测的目标;test/read view $q_t$ 用于获得输出。这里 “test view” 的叫法不表示它在 training 时不可用。

Key 没有外部 ground truth;value 是生成的连续数值 target,有时宽泛地叫 pseudo-label,不是外部认证的正确答案。Self-supervised 指 target 从已观察到的数据本身构造。我们现在就能产生 key 与 value,不必等未来 token,也不必请人给文章标注。

但生成的 target 为什么应该有用?局部 reconstruction loss 回答不了这个问题。对足够简单的模型,把所有 targets 设为零、让 learner 始终输出零,就能得到零 reconstruction loss,却没有记住有用信息。这叫 collapsed solution(坍缩解):用无意义的平凡表示完成局部目标,却丢掉原本想保存的信息。

因此,需要第二个标准来评价完整 LM。用 $\Theta$ 收集它的 slow parameters:projections、其他 layers,以及选择学习时的 fast-state 初始化与 step-size rule。Memory 产生 $z_t$ 后,后续 network 产生 vocabulary logits,再得到 next-token distribution,把这个概率模型记为 $p_\Theta$。训练文本中实际观察到的 next token $a_{t+1}$,为下面这项 loss 提供目标:

\[\mathcal L_t=-\log p_\Theta(a_{t+1}\mid a_{\le t};W_t(\Theta)).\]

这里取的是实际 next-token ID 对应的概率。负对数惩罚“给实际出现的 continuation 很低概率”:例如,概率 $0.8$ 的 loss 小于概率 $0.2$。把各位置相加或平均,就得到 LM 的 cross-entropy objective;这个条件预测损失的基础解释见 Use of Information Theory in Learning Theory,第 2.1 节

写成 $W_t(\Theta)$,是强调 memory state 依赖于构造学习过程的 slow parameters,不是额外给模型输入了一份 ground truth。

问题 Inner reconstruction Outer LM prediction
预测什么? 从 key view 预测 value view 从已见 prefix 预测 next token
谁提供 target? 当前输入生成的 $v_t=x_tW_V$ 训练文本中观察到的 $a_{t+1}$
优化什么? 当前序列的 fast state $W$ Slow parameters $\Theta$
成功意味着什么? 更好拟合这条局部关联 完整 LM 的预测更好

两者都是 self-supervised,只是层次不同。Next-token “ground truth”指观察到的 token,不保证 corpus 中每句话都事实正确。

Outer training 可以偏好保留对后面有用的信息,例如当实体身份帮助预测后文指代时,保留它就可能得到奖励。不必由人先给这个 feature 命名。但 outer objective 不是“不会坍缩”的证明:其他 network paths 可能绕过 memory,gradients 可能不起作用,优化也可能停滞。它提供有用性的评价标准,不保证成功。

4.4 Why Are There Two Loops Rather Than Two Updates Per Token?

There are three different actions that a short diagram can accidentally conflate: compute a loss, compute its gradient, and change parameter values. Producing $\mathcal L_t$ at each token does not mean taking an outer optimizer step at each token.

Use $t$ for positions within a sequence and $n$ for outer optimizer steps. For this teaching schedule, take $T+1$ token IDs. The first $T$ are inputs; the extra token supplies the last next-token target. During outer step $n$, all slow parameters stay at $\Theta_n$ while each independent sequence builds its own trajectory:

\[W_0^{(n)}\longrightarrow W_1^{(n)} \longrightarrow\cdots\longrightarrow W_T^{(n)}.\]

The superscript $(n)$ is a step label, not exponentiation. At each arrow, one inner update modifies $W$. At each position, the model also reads the state and computes a next-token loss contribution. After processing the batch—a collection of sequences used together for one training update—we average those contributions and then change $\Theta$.

For example, a batch of two sequences, each containing four IDs, has three inputs and three targets per sequence. It produces two independent three-step memory trajectories, six next-token loss terms, and one outer optimizer step. It does not run one six-step memory across both examples.

An illustrative SGD outer update is

\[\Theta_{n+1}=\Theta_n-\eta_{\mathrm{outer},n} \left.\nabla_\Theta\mathcal L_{\mathrm{batch}}(\Theta)\right|_{\Theta=\Theta_n}.\]

$\eta_{\mathrm{outer},n}$ is the outer learning rate, distinct from the inner rate $\eta_t$. The vertical bar means evaluate the derivative at the current slow parameters. The next batch starts with the updated $\Theta_{n+1}$, including an updated $W_0$ if it is learned.

“Inner” and “outer” therefore refer to different variables and objectives, and to a dependency: the outer objective evaluates the outcome of the inner learner. Even one inner step could form a nested problem. A long token-wise trajectory just makes that relationship more visible. Gradient accumulation can combine several batches before an outer optimizer step; chunking can alter the inner schedule. Neither variation changes the need to distinguish the two levels.

One token cell repeats along each sequence. Only after accumulating the batch loss does the outer optimizer change slow parameters.

一个简图很容易混淆三件事:计算 loss、计算它的 gradient、修改参数值。每个 token 都产生 $\mathcal L_t$,不等于每个 token 都执行一次 outer optimizer step。

用 $t$ 表示序列位置,$n$ 表示 outer optimizer step。这个教学安排使用 $T+1$ 个 token IDs:前 $T$ 个作为 inputs,多出的一个为最后的位置提供 next-token target。在 outer step $n$ 内,所有 slow parameters 固定为 $\Theta_n$,每条独立序列各自构造 trajectory:

\[W_0^{(n)}\longrightarrow W_1^{(n)} \longrightarrow\cdots\longrightarrow W_T^{(n)}.\]

上标 $(n)$ 是 step 编号,不是乘方。每个箭头执行一次 inner update,修改 $W$。同时,每个位置读取 state、计算一项 next-token loss。等处理完 batch——一起用于一次训练更新的一组序列——再平均这些 loss contributions,然后才修改 $\Theta$。

例如,batch 中有两条序列,每条四个 IDs,就各有三个 inputs 与三个 targets。因此得到的是两条独立的三步 memory trajectories、六项 next-token losses,最后一次 outer optimizer step。不是把两个 examples 串成同一条六步 memory。

用 SGD 示意 outer update:

\[\Theta_{n+1}=\Theta_n-\eta_{\mathrm{outer},n} \left.\nabla_\Theta\mathcal L_{\mathrm{batch}}(\Theta)\right|_{\Theta=\Theta_n}.\]

$\eta_{\mathrm{outer},n}$ 是 outer learning rate,与 inner $\eta_t$ 不同。长竖线表示在当前 slow parameters 处计算导数。下一 batch 才使用更新后的 $\Theta_{n+1}$;若 $W_0$ 可学习,它也在这次更新之内。

因此,“inner”和“outer”区分不同变量、不同目标,以及一个依赖关系:outer objective 评价 inner learner 的结果。即使 inner 只有一步,也可以形成嵌套问题;较长的逐 token trajectory 只是让这个关系更明显。Gradient accumulation 可以跨多个 batches 后才执行 outer optimizer step,chunking 也可以改变 inner schedule,但两种变化都不取消这两个层次的区别。

单个 token cell 沿序列反复执行。累计完整 batch loss 后,outer optimizer 才修改 slow parameters。

4.5 How Can a Loss Train the Rule That Produced an Update?

It may sound as if a gradient step is an opaque instruction that blocks further differentiation. In the linear example, it is visibly ordinary arithmetic:

\[W_t=W_{t-1}-\eta_tk_t^\top(k_tW_{t-1}-v_t).\]

Change $v_t$ slightly and the new $W_t$ changes. Change $W_t$ and a subsequent read changes. Change the read and the downstream prediction loss can change. That chain is how the LM objective can train the value projection.

A one-number example makes the dependence explicit. Set the old memory to zero, use $k=q=1$, let the generated target be $v=\beta$, and choose $\eta=1/2$. Here $\beta$ is a scalar standing in for a target produced by slow parameters. The write and read become

\[W_1=0-\tfrac12(0-\beta)=\tfrac12\beta,\qquad z=qW_1=\tfrac12\beta.\]

Increasing $\beta$ by $0.1$ increases the read by $0.05$. Therefore any differentiable downstream loss satisfies

\[\frac{d\mathcal L}{d\beta} =\frac{d\mathcal L}{dz}\,\frac12.\]

The first factor tells us whether changing this output helps the real prediction; the second tells us how changing the generated target changes that output. We did not optimize $\beta$ to make the reconstruction target easy. We evaluated how its effect on the write changes the outer loss.

The same logic applies to $W_K$, $W_Q$, the step-size rule, and the initialization. During the inner partial derivative, $k_t$ and $v_t$ are held fixed while differentiating with respect to $W$. During outer differentiation, the computed update still depends on the projections that produced $k_t$ and $v_t$. Holding a target fixed for one partial derivative does not justify deleting its outer gradient path.

Following the dependence through many writes (Click to expand)

Let $w_t=\operatorname{vec}(W_t)$ flatten the complete fast state. Write an update as $w_t=U_\Theta(w_{t-1},x_t)$ and let $J_t=dw_t/d\Theta$. The entries of $J_t$ record how each state entry changes with each slow parameter. By the chain rule,

\[J_t=A_tJ_{t-1}+B_t.\]

$A_t$ is the derivative of the update with respect to the previous state. It propagates effects that arrived through older writes. $B_t$ collects dependence on $\Theta$ and on the current $x_t$ while the previous state is held fixed. If $W_0$ is learned, $J_0$ contains that initial dependence; if other adaptive states produce $x_t$, include those states in the full recurrence.

Backpropagation through time follows this expanded sequence of state transitions backward. Unrolled optimization describes the fact that some transitions are learning steps. Meta-learning describes the fact that their outcomes train the learning procedure. These are related views of the same computation, not three extra algorithms that must be run.

In code, detaching each state cuts the dependence on earlier writes. That can be an intentional approximation, but is not the full unrolled gradient. For a general inner model differentiated with an automatic-differentiation tool, outer training needs the gradient computation itself to remain differentiable. The analytic linear update in our snippet already expresses it using ordinary tensor operations.

Gradient step 听起来可能像一个阻断后续求导的黑箱指令。但在 linear 例子里,它显然只是普通算术:

\[W_t=W_{t-1}-\eta_tk_t^\top(k_tW_{t-1}-v_t).\]

小幅改变 $v_t$,新的 $W_t$ 就改变;$W_t$ 改变,后续读取就改变;读取改变,下游 prediction loss 就可能改变。LM objective 正是沿这条依赖链训练 value projection。

用单个数的例子把依赖写出来。令旧 memory 为零,$k=q=1$,生成的 target 为 $v=\beta$,取 $\eta=1/2$。这里 $\beta$ 是一个 scalar,用来代替由 slow parameters 产生的 target。写入与读取为:

\[W_1=0-\tfrac12(0-\beta)=\tfrac12\beta,\qquad z=qW_1=\tfrac12\beta.\]

$\beta$ 增加 $0.1$,读取就增加 $0.05$。因此,对于任意可求导的下游 loss:

\[\frac{d\mathcal L}{d\beta} =\frac{d\mathcal L}{dz}\,\frac12.\]

第一个因子说明改变这个输出对真正预测有利还是有害;第二个因子说明改变生成的 target 会怎样改变输出。这里不是为了让 reconstruction target 容易预测而优化 $\beta$,而是评价它改变写入后,对 outer loss 产生的效果。

同样逻辑适用于 $W_K$、$W_Q$、step-size rule 与 initialization。计算 inner partial derivative 时,固定 $k_t,v_t$,只对 $W$ 求导;进行 outer differentiation 时,算出的 update 仍然依赖产生 $k_t,v_t$ 的 projections。在某次偏导里固定 target,不等于可以删除它的 outer gradient path。

怎样跟踪多次写入之间的依赖?(点击展开)

令 $w_t=\operatorname{vec}(W_t)$,把完整 fast state 展平。写成 $w_t=U_\Theta(w_{t-1},x_t)$,并令 $J_t=dw_t/d\Theta$。$J_t$ 的 entries 记录每个 state entry 怎样随每个 slow parameter 改变。根据 chain rule:

\[J_t=A_tJ_{t-1}+B_t.\]

$A_t$ 是 update 对 previous state 的导数,传播从更早 writes 传来的影响;$B_t$ 则收集固定 previous state 时,经由 $\Theta$ 与当前 $x_t$ 产生的依赖。若 $W_0$ 可学习,$J_0$ 包含这个初始依赖;若其他 adaptive states 参与产生 $x_t$,应把它们一起包含在完整 recurrence 中。

Backpropagation through time 沿着展开的 state transitions 反向传播;unrolled optimization 强调其中一些 transitions 是 learning steps;meta-learning 强调这些 steps 的结果用于训练学习方法。它们是同一计算的相关视角,不是还要运行三个额外算法。

代码中每步 detach state 会切断对更早 writes 的依赖。这可以是有意选择的近似,但不是完整 unrolled gradient。一般 inner model 如果用自动求导工具获得 gradient,outer training 就需要保留这次 gradient computation 本身的可求导性。我们的解析 linear update 已经把它写成普通 tensor operations。

4.6 What Stops Updating at Inference, and What Does Not?

After outer training, consider inference with a fixed checkpoint $\Theta^\ast$. We stop the outer optimizer. The Q/K/V projection matrices, surrounding LM, and learned initialization no longer receive persistent optimizer updates.

We do not stop forming new $q_t,k_t,v_t$, because each new input produces new views. We also do not stop the inner learning procedure: start from $W_0$ and run $W_0\to W_1\to\cdots$ as the sequence arrives. The distinction is between fixed projection parameters and changing projected activations.

Why design this separation? It lets a reusable learning procedure adapt a sequence-specific state without directly rewriting the base checkpoint for every document. It localizes the update and can limit adaptation cost. Yet nonlinear inner gradients and outer training through them may still be expensive; a constant-size inference state does not make training free.

The separation has limits. Frozen projections do not eliminate interference inside memory. They do not make every address invariant, because the hidden input $x_t$ can change with context and earlier adaptive layers. Resetting $W$ protects independence between new sequences, but discards their transient memories; carrying it across documents is a separate policy, not automatically lifelong learning or appropriate cross-user sharing.

“No next-token label” also requires precise timing. At the instant we predict an unknown future token, its external label is unavailable. The current-token reconstruction target is available immediately. But an observed prefix already supplies next-token targets for earlier positions, so test-time LM fine-tuning is possible. The lack of an unknown future label does not prove QKV must be frozen; it explains why this particular local target is convenient.

A final implementation detail matters: “frozen slow parameters” does not mean “no derivatives anywhere.” A nonlinear learner may need automatic differentiation to compute its local $W$ gradient at inference. Our linear snippet can explicitly calculate that gradient, so disabling graph recording does not stop its arithmetic write.

Outer training 完成后,考虑固定 checkpoint $\Theta^\ast$ 的 inference。我们停止 outer optimizer:Q/K/V projection matrices、外围 LM 与 learned initialization 不再接受持久的 optimizer updates。

不会停止生成新的 $q_t,k_t,v_t$,因为每个新输入都会产生新 views;也不会停止 inner learning procedure:从 $W_0$ 出发,随着序列到来继续执行 $W_0\to W_1\to\cdots$。必须区分固定的 projection parameters 与变化的 projected activations。

为什么做这种分工?它让可复用的学习方法适应当前序列的 state,而不必为每篇文章直接重写基础 checkpoint,也把更新限制在局部,有机会降低 adaptation 成本。但 nonlinear inner gradients 与穿过它们的 outer training 仍可能昂贵;inference state 大小固定,不等于训练免费。

这个分工也有限制。冻结 projections 不消除 memory 内部的 interference,也不让每个地址保持不变,因为输入 $x_t$ 会随 context 或前面 adaptive layers 改变。重置 $W$ 保持新序列之间的独立性,却会丢掉旧的 transient memories;跨文档延续 state 是另一项策略,不自动等于 lifelong learning,也不自动适合跨用户共享。

“没有 next-token label”还需要精确区分时刻。刚要预测未知未来 token 时,外部 label 不可用,而当前 token 的 reconstruction target 立即可用。但已观察到的 prefix 已经为更早的位置提供 next-token targets,所以可以进行 test-time LM fine-tuning。未知未来 label 的缺失,不证明必须冻结 QKV,只说明这种局部 target 为什么方便。

最后,“冻结 slow parameters”不等于“任何地方都不求导”。Nonlinear learner 在 inference 时可能仍需自动求导,计算局部 $W$ gradient。我们的 linear snippet 可以显式算出这个 gradient,所以关闭 graph recording 不会阻止算术写入。

4.7 What Does Published TTT Add to the Teaching Example?

We now have enough vocabulary to read the implementation choices without treating them as unexplained names. TTT-Linear and TTT-MLP differ in the inner model. The practical learner also uses a residual path and LayerNorm: roughly, it adds a normalized learned transformation to its input. The bare $qW$ example does not include those operations, so it is not the complete published TTT-Linear.

The initialization $W_0$ can be learned in the outer loop. Every independent sequence begins with the same learned starting point but then develops different fast weights. The inner rate can also depend on the current input through a learned rule. For example, a sigmoid converts a scalar score into a number between zero and one, which can multiply a positive base rate. The rule’s parameters are slow; its token-specific rate is not. The normalization and residual concepts are developed in Normalizations. TTT implementation choices, §2.7

A remaining practical obstacle is sequential dependence. If every gradient uses the immediately preceding updated state, computing token 2’s gradient must wait for token 1’s update. GPUs favor doing many similar operations together. Mini-batch TTT groups tokens into chunks and evaluates gradients at a shared chunk-start state, then accumulates the appropriate prefix of writes. It is a different schedule from fully online gradient descent.

A two-token example: why chunking changes the update schedule (Click to expand)

Take scalar memory $w_0=0$, scalar keys both 1, targets $v_1=1,v_2=3$, and rate $\eta=0.5$. The local gradient is $w-v$.

Fully online updates give $g_1=-1$, $w_1=0.5$, then $g_2=0.5-3=-2.5$ and $w_2=1.75$. In a shared-start two-token chunk, both gradients use $w_0$: $g_1=-1,g_2=-3$. Accumulating them gives $w_2=0-0.5(-1-3)=2$. The two procedures are not identical.

For causality, the first token’s read must use only its prefix of updates, giving $w_1=0.5$, not the chunk-final $w_2=2$. Computing gradients together does not authorize future writes to affect earlier predictions.

The paper’s dual form is an algebraic organization of the chosen chunked computation using matrix operations, avoiding explicitly constructing every intermediate parameter matrix. It accelerates that schedule; it does not magically make all possible update schedules equivalent. Mini-batch TTT and dual form, §§2.4–2.5

现在我们已经有足够的概念基础,可以读懂实现选择,而不是只记一串名字。TTT-LinearTTT-MLP 的区别在 inner model。实际 learner 还使用 residual path 与 LayerNorm:大致是把一个归一化后的 learned transformation 加回输入。裸的 $qW$ 例子没有这些操作,因此不是论文 TTT-Linear 的完整形式。

Initialization $W_0$ 可以在 outer loop 中学习。每条独立序列从同一个 learned starting point 出发,之后形成各自的 fast weights。Inner rate 也可以通过 learned rule 依赖当前输入。例如,sigmoid 把 scalar score 变成零到一之间的数,再乘一个正的 base rate。规则的参数是 slow,逐 token 算出来的 rate 则不是。Normalization 与 residual 的基础见 NormalizationsTTT 的实现选择,§2.7

实际还有顺序依赖的障碍。如果每个 gradient 都使用刚刚更新后的 state,计算第 2 个 token 的 gradient 就必须等第 1 次更新结束。但 GPU 更适合同时执行许多相似操作。Mini-batch TTT 把 tokens 分成 chunks,在共享的 chunk-start state 处计算 gradients,再累计相应 prefix 的 writes。它与完全 online gradient descent 的顺序不同。

两个 Tokens 的例子:为什么 Chunking 改变了更新顺序?(点击展开)

令 scalar memory $w_0=0$,两个 scalar keys 都为 1,targets 分别为 $v_1=1,v_2=3$,rate $\eta=0.5$。局部 gradient 为 $w-v$。

完全 online 时,先得到 $g_1=-1$、$w_1=0.5$;再得到 $g_2=0.5-3=-2.5$,于是 $w_2=1.75$。在共享起点的两-token chunk 中,两个 gradients 都用 $w_0$ 计算,得到 $g_1=-1,g_2=-3$;累加后 $w_2=0-0.5(-1-3)=2$。两种过程不相同。

为了满足 causality,第一个 token 的读取只能使用它自己的 update prefix,即 $w_1=0.5$,不能读取 chunk-final 的 $w_2=2$。一起计算 gradients,不代表未来 writes 可以影响较早预测。

论文的 dual form 是把选定的 chunked computation 重新组织为矩阵运算,避免显式构造每个中间参数矩阵。它加速这套 schedule,不会让所有不同的 update schedules 自动等价。Mini-batch TTT 与 dual form,§§2.4–2.5

4.8 Read the Complete Training and Inference Code

The first tab implements our bare linear memory for one sequence of hidden vectors. Follow the prediction, error, gradient, write, and read in that order. The second adds momentum and decay, discussed next.

The “Outer training” tab constructs a minimal embedding–memory–vocabulary-head model and shows the batch, sequence, and token loops explicitly. The matrix $W$ is reset separately for each sequence. The target $v$ appears inside the memory write; the observed next token appears inside cross-entropy. There is one outer optimizer step after the batch’s losses have been averaged.

The “Inference” tab reuses the same linear learner on an observed prefix but does not update slow parameters. It returns next-token logits and the final fast state. This helper replays the prefix from its starting state; efficient streaming would carry the state forward explicitly. None of these small examples includes a published paper’s full backbone or optimized chunked kernels.

Every marked expression has a nearby hover/focus annotation explaining its role and shape. Click to keep the annotation open; press Escape to close it.

Different targets, different updated variables, and different step counts—all in one explicitly nested computation.

第一个 tab 实现单条 hidden-vector sequence 的裸 linear memory。按预测、error、gradient、写入、读取的顺序看。第二个 tab 加入下一节讨论的 momentum 与 decay。

“Outer training” tab 构造最小的 embedding–memory–vocabulary-head 模型,明确写出 batch、sequence 与 token 循环。每条序列分别重置矩阵 $W$。Target $v$ 出现在 memory write 里,真实 next token 出现在 cross-entropy 里。平均 batch 的 losses 后,才执行一次 outer optimizer step。

“Inference” tab 在已观察到的 prefix 上复用同一个 linear learner,但不更新 slow parameters,返回 next-token logits 与最终 fast state。这个辅助函数每次从起点重放 prefix;高效 streaming 则应显式向后传递 state。这些小例子都不包含论文完整的 backbone 或优化过的 chunked kernels。

每个标记表达式都有贴在旁边的 hover/focus 注记,解释作用与 shape;点击可以固定注记,Escape 关闭。

不同 targets、不同更新变量、不同 step 数量,都在同一段明确的嵌套计算中。

5. Titans: How Long Should a Write Keep Affecting Memory?

5.1 From the Current Error to a History of Updates

A plain gradient write reacts to the current pair. After computing $g_t$, it adds only $-\eta_tg_t$ to memory. This raises another question: should a recent trend in the writes continue to influence the next update, instead of being discarded immediately?

Introduce a second fast state $U_t$, with the same shape or parameter structure as $W_t$. It stores the update, not the key, value, or memory prediction. Combine a fraction of the previous update with the new gradient contribution:

\[U_t=\mu_tU_{t-1}-\eta_tg_t,\qquad U_0=0.\]

$\mu_t$ is the retention factor for the previous update; $\eta_t$ scales the current gradient. This is a momentum-style rule. With $\mu_t=0$, only the new gradient contributes. With $\mu_t=0.9$ and a zero current gradient, $0.9U_{t-1}$ still remains. Thus influence can continue across nearby sequence positions.

Repeated expansion shows what is carried. For constant $\mu$ and $\eta$, $U_t=-\eta(g_t+\mu g_{t-1}+\mu^2g_{t-2}+\cdots)$ when starting from zero. Older gradients have undergone more decay; gradients pointing against each other can cancel. With input-dependent coefficients the weights become products of the intervening retention factors. This is a weighted history of update evidence, not a second exact store of old token records.

Titans uses an associative-memory objective together with this kind of gradient-history mechanism. The paper calls its gradient signal surprise. In our notation the differentiated variable is the memory’s parameters. Titans, §3.1

Why can prediction error be a useful writing signal? A memory that already predicts a target well needs little correction. A mismatch can call for change. But large gradient does not mean “semantically important fact”: it also depends on input scale and the function’s sensitivity. Noise can produce a large gradient; a large loss in a flat region can produce a small one. This is a model-dependent signal, not a relevance oracle.

Nor is it automatically Shannon surprisal, $-\log p(a_t\mid a_{<t})$. That quantity comes from a token probability; this gradient comes from a memory reconstruction objective. The shared word does not make them the same measurement. Basics of Optimizers discusses momentum as optimization; here its running index is the incoming sequence.

普通 gradient write 只对当前 pair 作出反应:算出 $g_t$ 后,给 memory 加上 $-\eta_tg_t$。这带来另一个问题:最近几次写入的趋势,是否也应该继续影响下一次更新,而不是立即被丢掉?

引入第二个 fast state $U_t$,与 $W_t$ 具有相同的 shape 或参数结构。它存的是 update,不是 key、value 或 memory prediction。把一部分旧 update 与新的 gradient contribution 合在一起:

\[U_t=\mu_tU_{t-1}-\eta_tg_t,\qquad U_0=0.\]

$\mu_t$ 控制保留多少旧 update,$\eta_t$ 缩放当前 gradient。这是一种 momentum-style rule。$\mu_t=0$ 时,只考虑当前 gradient;若 $\mu_t=0.9$ 且当前 gradient 为零,仍剩下 $0.9U_{t-1}$,于是影响可以在邻近的序列位置之间延续。

反复展开就能看到保留了什么。若 $\mu,\eta$ 固定,从零开始时 $U_t=-\eta(g_t+\mu g_{t-1}+\mu^2g_{t-2}+\cdots)$。越旧的 gradients 经历了越多次衰减,方向相反的 gradients 也可能抵消。系数依赖输入时,weights 会变成沿途 retention factors 的乘积。这是 update evidence 的加权历史,不是另外保存一份精确的旧 token records。

Titans 把 associative-memory objective 与这类 gradient-history 机制结合起来。论文把 gradient signal 称为 surprise。在本文记号中,被求导的变量是 memory parameters。Titans,§3.1

为什么 prediction error 可以成为写入信号?如果 memory 已经能很好预测 target,就不需要太多修正;不匹配则可能需要改变。但大 gradient 不等于“语义重要事实”:它还依赖输入尺度与函数敏感性。噪声可能产生大 gradient,平坦区域中的大 loss 也可能只产生小 gradient。因此,这是依赖模型的信号,不是判断内容重要性的神谕。

它也不自动等于 Shannon surprisal $-\log p(a_t\mid a_{<t})$。后者来自 token probability,这里的 gradient 来自 memory reconstruction objective。使用同一个词,不代表测量同一种量。Basics of Optimizers 从优化角度讨论 momentum;这里不断推进的索引则是输入 sequence。

5.2 Keeping Update Momentum and Keeping Old Memory Are Different

Momentum says how much of the previous update to retain. It does not directly specify how much of the existing memory to retain. To control the latter, introduce a forgetting coefficient $\alpha_t$ between zero and one:

\[W_t=(1-\alpha_t)W_{t-1}+U_t.\]

Before adding the new update, this multiplies the old parameter values by a retention factor $1-\alpha_t$. With $\alpha_t=0$, no explicit parameter decay is applied. With $\alpha_t=0.1$, old values retain 90% of their magnitude before the update. With $\alpha_t=1$, the old $W$ contribution disappears, but $U_t$ may still be nonzero.

Together the teaching recurrence is

\(g_t=\nabla_W\ell_t(W_{t-1}),\) \(U_t=\mu_tU_{t-1}-\eta_tg_t,\qquad W_t=(1-\alpha_t)W_{t-1}+U_t.\)

The gradient is evaluated at the old memory, before the decay shown here. Our $\mu_t$ names the momentum coefficient and $\eta_t$ the gradient step size; these correspond to different symbols in the Titans paper. The distinction avoids confusing a paper-specific letter with a universal meaning. Titans, Eqs. 12–14

Use a scalar example to separate their effects. Suppose old memory is $W_{t-1}=2$, the previous update is $U_{t-1}=0.2$, and the new gradient is $g_t=-0.4$. Take $\mu_t=0.5$, $\eta_t=0.1$, and $\alpha_t=0.1$. Then $U_t=0.5(0.2)-0.1(-0.4)=0.14$, and $W_t=0.9(2)+0.14=1.94$. The gradient and momentum contribution is positive, yet the final memory value decreases because decay is stronger. The three coefficients do different jobs.

Why permit forgetting at all? A finite memory may receive corrected, obsolete, or unrelated information. Always preserving all accumulated influence can make new associations hard to represent. A learned gate can regulate retention as context changes. “Gate” here means a computed multiplier, often constrained to a range such as $[0,1]$; it is not a literal database delete operation.

Consequently, multiplying weights by a scalar does not selectively erase exactly one named fact, and $\alpha_t=0$ does not guarantee no forgetting: new writes can still interfere. Input-dependent gates can learn useful behavior, but the equations do not prove semantic selectivity or perfect long-term recall.

Momentum 决定保留多少旧 update,不直接决定保留多少已有 memory。为了控制后者,引入零到一之间的 forgetting coefficient $\alpha_t$:

\[W_t=(1-\alpha_t)W_{t-1}+U_t.\]

加上新 update 之前,先把旧参数乘上 retention factor $1-\alpha_t$。$\alpha_t=0$ 时,没有显式 parameter decay;$\alpha_t=0.1$ 时,旧数值先保留 90% 幅度再加 update;$\alpha_t=1$ 时,旧 $W$ 的贡献消失,但 $U_t$ 仍可能非零。

把整个教学递推连起来:

\(g_t=\nabla_W\ell_t(W_{t-1}),\) \(U_t=\mu_tU_{t-1}-\eta_tg_t,\qquad W_t=(1-\alpha_t)W_{t-1}+U_t.\)

这里 gradient 在 decay 前的旧 memory 处计算。本文用 $\mu_t$ 表示 momentum coefficient、$\eta_t$ 表示 gradient step size,它们与 Titans 原文所用的字母不同。重要的是作用,不是把某篇论文的字母当作普遍定义。Titans,Eqs. 12–14

用 scalar 例子分开看效果。假设旧 memory 为 $W_{t-1}=2$,旧 update 为 $U_{t-1}=0.2$,新 gradient 为 $g_t=-0.4$;取 $\mu_t=0.5$、$\eta_t=0.1$、$\alpha_t=0.1$。那么 $U_t=0.5(0.2)-0.1(-0.4)=0.14$, $W_t=0.9(2)+0.14=1.94$。 Gradient 与 momentum 提供了正向 update,但最终 memory 数值反而下降,因为 decay 更强。三个系数做的是不同事情。

为什么允许遗忘?有限 memory 可能收到被更正、已过时或不相关的信息。如果一直保留所有累计影响,就可能难以表示新关联。Learned gate 可以随着 context 变化调节 retention。这里的 “gate”是计算出来的 multiplier,通常被限制在 $[0,1]$ 等范围,不是数据库中真实存在的删除操作。

因此,把 weights 乘 scalar 不会精确删除某一条命名事实,$\alpha_t=0$ 也不保证不遗忘,因为新 writes 仍可能产生 interference。Input-dependent gates 可以学到有用行为,但这些公式不证明能够精准选择语义,也不证明完美长期回忆。

5.3 How Does This Memory Fit Into a Language Model?

A writing rule is not a complete architecture. After defining the adaptive memory, we must decide what feeds it and how its output is combined with other information. Titans distinguishes three roles:

  • Recent-context attention: explicitly match against representations in the currently retained local window. A local window bounds how many recent positions are considered.
  • Adaptive neural memory: store older associations in a parameterized function that continues to receive writes. It can use a deeper MLP rather than only a bare linear matrix.
  • Persistent learned memory: input-independent learned entries shared across sequences. These are trained slow parameters, not a continuously updated record of the current user’s conversations.

“Long-term” in the second role is relative to the local attention window: its state can carry effects from earlier segments. It does not itself promise persistence across independent runs. A deeper function expands the family of key–value mappings, but not to unlimited, error-free capacity.

To combine the components, the paper studies Memory as a Context (MAC), Memory as a Gate (MAG), and Memory as a Layer (MAL). These answer a wiring question: present retrieved memory as additional context for attention, combine memory and attention through gating, or compose them as layers. They are architecture choices, not three names for the same recurrence. Titans, §§3.3–4

Walk through MAC at the level of one segment, a consecutive block of tokens. First, the current segment supplies queries to the memory left by previous segments. The retrieved vectors represent relevant historical information. Next, attention receives those vectors, the persistent entries, and the current segment. The attention-produced representations are then used in the adaptive memory update and in constructing the output.

That order differs from the simple “write this token, then read it” cell in Section 4. The old memory first helps interpret the current segment; the resulting computation then helps determine what to write. Exact masks and state versions still matter: an earlier output cannot be allowed to consult a chunk-final state containing future-token writes. A segment-level diagram does not waive token-level causality.

The design balances two forms of access: explicit recent records and compressed historical associations. How well that balance works depends on the learned representations, available state and update costs. The formulas alone do not settle it.

写入规则不是完整 architecture。定义 adaptive memory 后,还需要决定给它什么输入,以及怎样把它的输出与其他信息组合。Titans 区分三种作用:

  • Recent-context attention:显式匹配当前保留的 local window 中的 representations。Local window 限制一次考虑多少个近期位置。
  • Adaptive neural memory:把较早的关联存入持续接受 writes 的参数化函数。它可以使用更深的 MLP,而不只是一张裸 linear matrix。
  • Persistent learned memory:与当前输入无关、跨序列共享的 learned entries。它们属于训练得到的 slow parameters,不是不断更新的用户对话记录。

第二种作用中的 “long-term”是相对于 local attention window:state 能携带更早 segments 的影响,不自动承诺跨独立运行持久保存。更深的函数扩大了可表示的 key–value mappings,但没有变成无限、无误差的容量。

组合这些 components 时,论文研究 Memory as a Context(MAC)Memory as a Gate(MAG)Memory as a Layer(MAL)。它们回答的是连接方式问题:把检索出的 memory 作为 attention 的额外 context、通过 gating 组合 memory 与 attention,或把两者按 layers 组合。它们是 architecture choices,不是同一个 recurrence 的三个名字。Titans,§§3.3–4

以一个 segment,也就是一块连续 tokens,为单位走一遍 MAC。首先,当前 segment 向此前 segments 留下的 memory 提供 queries,取得相关历史信息的 vectors。然后,attention 接收这些 vectors、persistent entries 和当前 segment。Attention 产生的 representations 再被用于 adaptive memory update 与输出构造。

这个顺序不同于第 4 节简化的“先写当前 token,再读”cell:旧 memory 先帮助理解当前 segment,处理结果再帮助决定写什么。具体 masks 与 state 版本仍很重要,不能让较早输出查询到包含未来 token writes 的 chunk-final state。Segment-level 示意图并没有取消 token-level causality。

这个设计平衡两种访问方式:显式保留的近期 records,以及压缩后的历史 associations。平衡效果取决于学到的表示、state 大小和 update costs,不是只看公式就能确定。

5.4 What Has Improved—and What Has Not Been Guaranteed?

Return to the original question: where does the document’s information go? Full attention can retain individual K/V entries; a recurrent summary combines them into fixed-size state; a delta learner corrects a stored mapping; TTT makes that mapping a trainable model; Titans additionally studies how update history, forgetting and attention cooperate.

Paper Problem reached in our derivation Main mechanism
Linear Transformers, 2020 Avoid scanning a growing list with a suitable similarity Recurrent numerator matrix and normalization vector
Fast Weight Programmers, 2021 Correct an existing association instead of only adding Error-based write into fast weights
TTT Layers, 2024 Choose a richer state and learn what its local task should be Inner learner, learned views, outer LM objective
Titans, 2025 Manage continuing writes and combine history with local context Momentum, decay, neural-memory/attention integration

These are conceptual connections, not a proof that each later method uniformly dominates the earlier ones. They also describe different meanings of “learning”:

In ordinary in-context learning, outputs change with the input context without gradient updates to the model parameters. Its KV cache can still change. In test-time memory learning, selected fast weights also change during the sequence. In continual pre-training, optimization continues on new data and changes persistent model parameters. Continuing pre-training is not the same mechanism as the per-sequence fast-weight updates studied here; sharing the word “continual” does not establish that connection.

To establish lifelong retention, we would additionally need to state what persists across tasks, what old capabilities must be retained, and how they are measured after new learning. Transfer asks whether learning one task helps another. A replay method revisits stored or regenerated old examples; a fair comparison must account for that storage and computation. Those are further design and evaluation questions, not consequences of a local reconstruction loss decreasing.

The core insight is therefore precise: a model’s weights can serve as its sequence state, and a learning algorithm can serve as its state-update rule. The outer loop learns a reusable way to create addresses, targets and queries; the inner loop executes that procedure on the current sequence. This explains the different QKV update roles without assuming all continual-learning methods freeze the same parameters—or that a temporary memory has become permanent knowledge.

回到开头:文章的信息去了哪里?Full attention 可以保留单独的 K/V entries;recurrent summary 把它们合并进固定大小的 state;delta learner 修正已有映射;TTT 把这个映射组织成可训练的小模型;Titans 进一步研究 update history、forgetting 与 attention 怎样配合。

论文 推导中遇到的问题 主要机制
Linear Transformers,2020 能否用合适的 similarity 避免扫描增长的列表? 递推保存 numerator matrix 与 normalization vector
Fast Weight Programmers,2021 能否修正已有关联,而不只相加? 根据 error 写入 fast weights
TTT Layers,2024 能否选择更丰富的 state,并学习其局部任务? Inner learner、learned views、outer LM objective
Titans,2025 怎样管理持续写入,并结合历史与局部 context? Momentum、decay、neural memory 与 attention 的组合

这些是概念上的联系,不证明后来的方法在所有条件下都优于之前的方法。它们也涉及不同含义的“学习”:

普通 in-context learning 随输入 context 改变输出,不要求对模型参数做 gradient update,但 KV cache 仍可改变。Test-time memory learning 还会在序列内部修改选定的 fast weights。Continual pre-training 则继续在新数据上优化、修改持久模型参数。继续预训练与本文逐序列更新 fast weights 不是同一种机制,不能因为名字中都有“continual”就把它们当作直接关联。

若要证明具有 lifelong retention,还必须说明哪些信息跨任务保留、哪些旧能力不能丢,以及新学习后怎样测量它们。Transfer 问的是学习一个任务是否帮助另一个任务;replay 则重新访问保存或再生成的旧 examples,公平比较时要把它的存储与计算也计入。这些都是额外的设计与评价问题,不是局部 reconstruction loss 下降就能推出的结论。

因此,核心认识应当准确地表述为:小模型的 weights 可以充当序列 state,学习算法可以充当 state-update rule。 Outer loop 学习可复用的地址、目标与 query 构造方法;inner loop 在当前序列上执行它。这解释了 QKV 不同的更新角色,但不假设所有 continual-learning 方法都冻结同样的参数,也不把临时记忆误认为永久知识。