12.6  矩阵状态循环

12.5 节 中的选择性状态空间模型能够逐个词元地决定保留什么以及保留多久,但我们尚未探讨固定大小的状态究竟能存储和检索多少组不同的关联。语言建模的很大一部分依赖联想回忆——将键与值绑定(例如 rate = 0.05,或“Mira 是这艘船的工程师”),并在数百个词元之后键再次出现时检索出对应的值。Transformer 通过把过去所有的键与值保存在不断增长的 KV 缓存中、并将查询与它们逐一比对来解决联想回忆。固定大小的循环状态能否同样存储和检索键值对?其容量又如何随状态规模扩展?

答案是肯定的——只要将状态设为矩阵 \(\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}\),通过累加外积 \(\mathbf{v}_t \mathbf{k}_t^\top\) 更新,并通过矩阵-向量乘法 \(\mathbf{S}_t \mathbf{q}_t\) 查询。我们其实已经见过这种结构的两个实例:未归一化的线性注意力(10.6 节)以及 Mamba 中 \(H \times N\) 的通道-状态矩阵(12.5 节)。下文我们将推导外积矩阵记忆的精确检索误差与容量缩放律,引入输入依赖的标量衰减以遗忘陈旧键值对,建立衰减矩阵循环与因果掩码线性注意力之间的状态空间对偶,实现硬件高效的分块训练算法(chunked_linear_attention),并检验训练好的 GatedLinearAttention 层在多查询联想回忆任务上是否遵循理论容量律。

12.6.1 联想记忆

12.6.1.1 写入与读取键值对

最简单的联想记忆通过对外积求和来存储键值对。以 \(\mathbb{R}^2\) 中的玩具示例来说,将正交单位键 \(\mathbf{k}_1 = (1, 0)^\top\) 与 \(\mathbf{k}_2 = (0, 1)^\top\) 分别绑定到标量值 \(v_1 = 3\) 与 \(v_2 = 5\),存入行向量 \(\mathbf{S} = v_1 \mathbf{k}_1^\top + v_2 \mathbf{k}_2^\top = (3, 5)\)。用任一键右乘都能无误差地取回对应值:\(\mathbf{S}\mathbf{k}_1 = 3\) 且 \(\mathbf{S}\mathbf{k}_2 = 5\)。然而,一旦加入第三对 \(\mathbf{k}_3 = (1, 1)^\top / \sqrt{2}\) 与 \(v_3 = 7\),\(\mathbf{k}_3\) 便会与 \(\mathbf{k}_1\) 和 \(\mathbf{k}_2\) 重叠:\(\mathbf{S}\) 变为 \((3 + 7/\sqrt{2}, 5 + 7/\sqrt{2}) \approx (7.95, 9.95)\),查询 \(\mathbf{k}_1\) 返回 \(7.95\) 而非 \(3\)。两个键维度至多容纳两个互不串扰的正交键。

一般地,给定键向量 \(\mathbf{k}_t \in \mathbb{R}^{d_k}\)、值向量 \(\mathbf{v}_t \in \mathbb{R}^{d_v}\) 和查询向量 \(\mathbf{q}_t \in \mathbb{R}^{d_k}\),状态为矩阵 \(\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}\),每步按如下方式更新与读取:

\[ \mathbf{S}_t = \mathbf{S}_{t-1} + \mathbf{v}_t \mathbf{k}_t^\top, \qquad \mathbf{y}_t = \mathbf{S}_t \mathbf{q}_t. \tag{12.6.1}\]

每次写入都会叠加一个秩一矩阵 \(\mathbf{v}_t \mathbf{k}_t^\top\),将方向 \(\mathbf{k}_t\) 映射到 \(\mathbf{v}_t\),其中 \((\mathbf{q}_t, \mathbf{k}_t, \mathbf{v}_t)\) 是词元表示的可学习线性投影。

12.6.1.2 线性注意力

从 \(\mathbf{S}_0 = \mathbf{0}\) 出发展开 式 12.6.1,可见加性矩阵循环计算的正是未归一化的因果线性注意力(10.6 节,Katharopoulos 等 (2020年)):

\[\mathbf{y}_t = \Big(\sum_{s \le t} \mathbf{v}_s \mathbf{k}_s^\top\Big) \mathbf{q}_t = \sum_{s \le t} (\mathbf{k}_s^\top \mathbf{q}_t)\, \mathbf{v}_s.\]

从右侧求值时,每个输出 \(\mathbf{y}_t\) 以点积相似度 \(\mathbf{k}_s^\top \mathbf{q}_t\) 对所有过去的值 \(\mathbf{v}_s\) 加权;从左侧求值时,外积之和则保存在固定大小的循环状态 \(\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}\) 中向后传递。

12.6.1.3 干扰

在串扰淹没信号之前,\(\mathbf{S} = \sum_{i=1}^n \mathbf{v}_i \mathbf{k}_i^\top\) 究竟能存储多少对键值?用已存单位键 \(\mathbf{k}_j\)(\(\|\mathbf{k}_j\| = 1\))查询时,目标值与其余 \(n - 1\) 对带来的干扰分离如下:

\[ \mathbf{S}\mathbf{k}_j = \mathbf{v}_j + \sum_{i \neq j} (\mathbf{k}_i^\top \mathbf{k}_j)\, \mathbf{v}_i. \tag{12.6.2}\]

精确零误差读出要求键两两正交,而 \(\mathbb{R}^{d_k}\) 中至多存在 \(d_k\) 个正交键。对于随机单位键,我们可以精确计算出期望干扰。

命题。设 \(\mathbf{k}_1, \ldots, \mathbf{k}_n\) 独立且均匀分布在 \(\mathbb{R}^{d_k}\) 的单位球面上,并设 \(\mathbf{v}_1, \ldots, \mathbf{v}_n \in \mathbb{R}^{d_v}\) 为独立于键选取的单位向量。则每个已存键处的期望平方检索误差为:

\[ \mathbb{E}\,\big\|\mathbf{S}\mathbf{k}_j - \mathbf{v}_j\big\|^2 = \frac{n - 1}{d_k}. \tag{12.6.3}\]

证明。展开 \(\sum_{i \neq j} (\mathbf{k}_i^\top \mathbf{k}_j)\mathbf{v}_i\) 的平方范数,由于在给定 \(\mathbf{k}_j\) 的条件下,\(\mathbf{k}_i^\top \mathbf{k}_j\) 与 \(\mathbf{k}_l^\top \mathbf{k}_j\)(\(i \neq l\))相互独立且均值为零,所有交叉项的期望均为零。又因 \(\|\mathbf{v}_i\|^2 = 1\),仅余 \(n - 1\) 个对角项 \(\mathbb{E}[(\mathbf{k}_i^\top \mathbf{k}_j)^2]\)。由 \(\mathbb{R}^{d_k}\) 单位球面的旋转对称性,\(\mathbf{k}_i\) 的每个坐标的期望平方均为 \(1/d_k\),因此 \(\mathbb{E}[(\mathbf{k}_i^\top \mathbf{k}_j)^2] = 1/d_k\)。对这 \(n - 1\) 个干扰项求和即得 \((n - 1)/d_k\)。\(\blacksquare\)

注意检索误差仅取决于负载比 \((n - 1)/d_k\),而与键值对何时写入无关:加性记忆丢失信息是因为拥挤,而非衰老。

为了在 NumPy 中实证检验 式 12.6.3,matrix_memory 将 \(n\) 对单位键与码本值写入 \(\mathbf{S} = \sum_{i=1}^n \mathbf{v}_i \mathbf{k}_i^\top\)(可选共享方向相关性 \(\rho\)),并返回均方检索误差以及在 256 向量单位码本上的最近邻召回率:

def matrix_memory(d_k, nums, rho=0, num_values=256, trials=20, seed=0):
    """Read error and recall of S = sum_i v_i k_i^T over random unit keys."""
    rng = np.random.default_rng(seed)
    unit = lambda X: X / np.linalg.norm(X, axis=-1, keepdims=True)
    codebook = unit(rng.standard_normal((num_values, d_k)))
    errors, recalls = [], []
    for n in nums:
        error = recall = 0
        for _ in range(trials):
            K = unit(rng.standard_normal((n, d_k)))  # Keys as rows
            shared = unit(rng.standard_normal(d_k))  # A common direction
            K = unit(np.sqrt(1 - rho**2) * K + rho * shared)
            ids = rng.integers(0, num_values, n)
            S = codebook[ids].T @ K  # Sum of v_i k_i^T
            reads = K @ S.T  # Row j is S k_j
            error += ((reads - codebook[ids]) ** 2).sum(1).mean() / trials
            recall += ((reads @ codebook.T).argmax(1) == ids).mean() / trials
        errors.append(error)
        recalls.append(recall)
    return errors, recalls
def matrix_memory(d_k, nums, rho=0, num_values=256, trials=20, seed=0):
    """Read error and recall of S = sum_i v_i k_i^T over random unit keys."""
    rng = np.random.default_rng(seed)
    unit = lambda X: X / np.linalg.norm(X, axis=-1, keepdims=True)
    codebook = unit(rng.standard_normal((num_values, d_k)))
    errors, recalls = [], []
    for n in nums:
        error = recall = 0
        for _ in range(trials):
            K = unit(rng.standard_normal((n, d_k)))  # Keys as rows
            shared = unit(rng.standard_normal(d_k))  # A common direction
            K = unit(np.sqrt(1 - rho**2) * K + rho * shared)
            ids = rng.integers(0, num_values, n)
            S = codebook[ids].T @ K  # Sum of v_i k_i^T
            reads = K @ S.T  # Row j is S k_j
            error += ((reads - codebook[ids]) ** 2).sum(1).mean() / trials
            recall += ((reads @ codebook.T).argmax(1) == ids).mean() / trials
        errors.append(error)
        recalls.append(recall)
    return errors, recalls

我们在负载 \(n \in \{8, 16, \ldots, 512\}\) 上评估独立随机键(\(d_k \in \{32, 64, 128\}, \rho = 0\))与相关键(\(d_k = 64, \rho = 0.5\))下的 matrix_memory,并将平方读取误差与理论直线 \((n - 1)/d_k\) 绘制在同一图中:

nums = [8, 16, 32, 64, 128, 256, 512]
results = {f'dₖ = {d_k}': matrix_memory(d_k, nums) for d_k in (32, 64, 128)}
results['dₖ = 64, ρ = 0.5'] = matrix_memory(64, nums, rho=0.5)
predictions = [[(n - 1) / d_k for n in nums] for d_k in (32, 64, 128)]
d2l.plot(nums, [err for err, _ in results.values()] + predictions,
         'stored pairs n', 'squared read error',
         legend=list(results) + ['$(n-1)/d_k$'], xscale='log', yscale='log',
         fmts=('-o', '-o', '-o', '-s', 'k:', 'k:', 'k:'), figsize=(5, 3.5))
print('recall at n =    ', ' '.join(f'{n:4d}' for n in nums))
for name, (_, recalls) in results.items():
    print(f'{name:17s}', ' '.join(f'{r:4.2f}' for r in recalls))
recall at n =        8   16   32   64  128  256  512
dₖ = 32           1.00 0.99 0.96 0.74 0.39 0.16 0.07
dₖ = 64           1.00 1.00 1.00 1.00 0.96 0.72 0.37
dₖ = 128          1.00 1.00 1.00 1.00 1.00 1.00 0.94
dₖ = 64, ρ = 0.5  1.00 0.99 0.83 0.49 0.21 0.07 0.03

nums = [8, 16, 32, 64, 128, 256, 512]
results = {f'dₖ = {d_k}': matrix_memory(d_k, nums) for d_k in (32, 64, 128)}
results['dₖ = 64, ρ = 0.5'] = matrix_memory(64, nums, rho=0.5)
predictions = [[(n - 1) / d_k for n in nums] for d_k in (32, 64, 128)]
d2l.plot(nums, [err for err, _ in results.values()] + predictions,
         'stored pairs n', 'squared read error',
         legend=list(results) + ['$(n-1)/d_k$'], xscale='log', yscale='log',
         fmts=('-o', '-o', '-o', '-s', 'k:', 'k:', 'k:'), figsize=(5, 3.5))
print('recall at n =    ', ' '.join(f'{n:4d}' for n in nums))
for name, (_, recalls) in results.items():
    print(f'{name:17s}', ' '.join(f'{r:4.2f}' for r in recalls))
recall at n =        8   16   32   64  128  256  512
dₖ = 32           1.00 0.99 0.96 0.74 0.39 0.16 0.07
dₖ = 64           1.00 1.00 1.00 1.00 0.96 0.72 0.37
dₖ = 128          1.00 1.00 1.00 1.00 1.00 1.00 0.94
dₖ = 64, ρ = 0.5  1.00 0.99 0.83 0.49 0.21 0.07 0.03

图像和表格凸显出两条规律:

  1. 召回率随状态总元素数 \(d_k d_v\) 缩放:平方误差曲线完全贴合 \((n - 1)/d_k\)。然而在 \(n = d_k = d_v = 64\) 处,尽管总平方误差已达 \(\approx 1\)(与单位信号 \(\|\mathbf{v}_j\|^2 = 1\) 相当),最近邻召回率仍高达 \(1.00\)(在 \(n = 128\) 时仍为 \(96\%\))。原因在于干扰向量在全部 \(d_v\) 个值维度上各向同性地分散,因此它投影到任意单个候选码本向量上的方差仅为 \(\approx n / (d_k d_v)\)。当 \(d_v = d_k\) 时,将 \(d_k\) 翻倍会使状态元素数 \(d_k d_v\) 增至四倍,固定准确率下可召回的键值对数也随之增至四倍(\(d_k = 32\) 时的 \(n = 32\) 与 \(d_k = 64\) 时的 \(n = 128\) 均达 \(96\%\),\(d_k = 128\) 时 \(n = 512\) 达 \(94\%\);5 将分别改变 \(d_k\) 与 \(d_v\))。

  2. 键相关性导致不可约误差下界:当键以权重 \(\rho\) 共享同一方向时,成对键重叠的平均值为 \(\approx \rho^2\),对零均值的值而言期望平方误差为:

    \[ \mathbb{E}\,\big\|\mathbf{S}\mathbf{k}_j - \mathbf{v}_j\big\|^2 \approx (n - 1)\Big(\rho^4 + \frac{(1 - \rho^2)^2}{d_k}\Big) \]

    (外加来自有限码本样本均值的 \(n\) 二次项;参见 4)。由于 \(\rho^4\) 不会随 \(d_k\) 增大而缩小,相关键(\(\rho = 0.5\))使 \(n = d_k = 64\) 时的召回率从 \(1.00\) 骤降至 \(0.49\)。

12.6.2 衰减

12.6.2.1 遗忘旧键值对

若没有衰减,曾经写入的每一对键值都会以全权重留在 \(\mathbf{S}_t\) 中,干扰便随序列长度无界增长。在每次写入前用标量衰减 \(a_t \in (0, 1)\) 乘以状态,即可让较早的键值对逐渐淡出:

\[ \mathbf{S}_t = a_t\, \mathbf{S}_{t-1} + \mathbf{v}_t \mathbf{k}_t^\top, \qquad a_t \in (0, 1). \tag{12.6.4}\]

在常数衰减 \(a\) 下,\(\ell\) 步前写入的键值对携带权重 \(a^\ell\)。权重之和为 \(1/(1 - a)\)(相当于 \(1/(1 - a)\) 对的有效窗口),而进入干扰方差的权重平方和为 \(1/(1 - a^2)\),从而无论总序列多长,稳态期望干扰均以 \(1 / ((1 - a^2) d_k)\) 为上界(6)。根据输入词元计算 \(a_t\),可让每个头在一段跨度内保持状态并在主题或从句边界处清空它。(相关变体包括 RetNet (Sun 等 2023年) 中的逐头固定衰减、Mamba-2 (Dao 和 Gu 2024年) 中的逐头输入依赖标量衰减,以及门控线性注意力 (Yang 等 2024年) 中的逐键坐标向量衰减 \(\mathbf{S}_{t-1}\textrm{diag}(\boldsymbol{\alpha}_t)\);此处我们为每个头使用单个输入依赖标量衰减。)

12.6.2.2 将选择性状态空间模型视为矩阵记忆

将 Mamba 选择性 SSM(12.5 节,略去跳跃连接 \(D_c x_{t,c}\))的 \(H\) 个通道状态 \(\mathbf{h}_t^{(c)} \in \mathbb{R}^N\) 按行堆叠为矩阵 \(\mathbf{S}_t \in \mathbb{R}^{H \times N}\),可见 Mamba 本身就是一种衰减矩阵状态循环:

\[ \begin{aligned} \mathbf{S}_t &= \mathbf{E}_t \odot \mathbf{S}_{t-1} + (\boldsymbol{\Delta}_t \odot \mathbf{x}_t)\, \mathbf{B}_t^\top, \\ \mathbf{y}_t &= \mathbf{S}_t \mathbf{C}_t, \qquad \mathbf{E}_t = \exp(\textrm{diag}(\boldsymbol{\Delta}_t)\, \boldsymbol{\Lambda}). \end{aligned} \]

与 式 12.6.4 逐项对照,值向量为 \(\mathbf{v}_t = \boldsymbol{\Delta}_t \odot \mathbf{x}_t \in \mathbb{R}^H\),键向量为 \(\mathbf{k}_t = \mathbf{B}_t \in \mathbb{R}^N\),查询向量为 \(\mathbf{q}_t = \mathbf{C}_t \in \mathbb{R}^N\)。唯一区别在于 Mamba 的衰减矩阵 \(\mathbf{E}_t \in \mathbb{R}^{H \times N}\) 在通道与状态两个维度上都变化;将 \(\mathbf{E}_t\) 限制为每个头单个标量 \(a_t\) 即得 Mamba-2 (Dao 和 Gu 2024年)(1),并开启下文的矩阵乘法对偶形式。

12.6.3 对偶形式

12.6.3.1 带衰减的展开

从 \(\mathbf{S}_0 = \mathbf{0}\) 出发展开 式 12.6.4,可知第 \(s\) 步写入的键值对到达第 \(t \ge s\) 步时会被累积衰减乘积 \(L_{ts} = a_{s+1} a_{s+2} \cdots a_t\) 衰减:

\[\mathbf{y}_t = \sum_{s \le t} L_{ts}\, (\mathbf{k}_s^\top \mathbf{q}_t)\, \mathbf{v}_s, \qquad L_{ts} = a_{s+1} a_{s+2} \cdots a_t. \tag{12.6.5}\]

将 \(\mathbf{q}_t, \mathbf{k}_t, \mathbf{v}_t, \mathbf{y}_t\) 按行堆叠为 \(\mathbf{Q}, \mathbf{K}, \mathbf{V}, \mathbf{Y}\),并在 \(s > t\) 时令 \(L_{ts} = 0\),即得对偶形式:

\[\mathbf{Y} = (\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top)\, \mathbf{V}. \tag{12.6.6}\]

式 12.6.6 正是带有可学习、输入依赖衰减掩码 \(\mathbf{L}\) 的因果线性注意力——Dao 和 Gu (2024年) 将这一对应关系称为状态空间对偶(SSD)。以逐步循环求值 式 12.6.6 需要 \(O(T d_v d_k)\) 计算量与 \(O(d_v d_k)\) 显存;通过完整的 \(T \times T\) 矩阵 \(\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top\) 求值则可运行并行矩阵乘法,耗费 \(O(T^2(d_k + d_v))\) 计算量与 \(O(T^2)\) 显存。下面我们显式写出这两种形式,先从顺序逐步循环 linear_attention_recurrent 开始:

def linear_attention_recurrent(Q, K, V, a):
    """y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, step by step."""
    S, outputs = Q.new_zeros(V.shape[-1], K.shape[-1]), []
    for q, k, v, a_t in zip(Q, K, V, a):
        S = a_t * S + torch.outer(v, k)
        outputs.append(S @ q)
    return torch.stack(outputs)
def linear_attention_recurrent(Q, K, V, a):
    """y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, step by step."""
    def step(S, inputs):
        q, k, v, a_t = inputs
        S = a_t * S + jnp.outer(v, k)
        return S, S @ q
    S0 = jnp.zeros((V.shape[-1], K.shape[-1]))
    return jax.lax.scan(step, S0, (Q, K, V, a))[1]

接着,decay_mask(log_a) 通过前缀和构造下三角衰减矩阵 \(L_{ts} = \exp(\sum_{r=s+1}^t \log a_r)\),使 linear_attention_dual 能够一次性在所有位置上计算 \(\mathbf{Y} = (\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top)\mathbf{V}\):

def decay_mask(log_a):
    """L[t, s] = a_{s+1} * ... * a_t for s <= t, and 0 for s > t."""
    cum = log_a.cumsum(-1)
    log_L = cum[..., :, None] - cum[..., None, :]  # Sum of log a over (s, t]
    causal = torch.ones(log_L.shape[-2:], dtype=torch.bool,
                        device=log_a.device).tril()
    return torch.exp(log_L.masked_fill(~causal, -torch.inf))

def linear_attention_dual(Q, K, V, a):
    """The same outputs as Y = (L * Q K^T) V, all positions at once."""
    return (decay_mask(torch.log(a)) * (Q @ K.T)) @ V
def decay_mask(log_a):
    """L[t, s] = a_{s+1} * ... * a_t for s <= t, and 0 for s > t."""
    cum = log_a.cumsum(-1)
    log_L = cum[..., :, None] - cum[..., None, :]  # Sum of log a over (s, t]
    causal = jnp.tril(jnp.ones(log_L.shape[-2:], dtype=bool))
    return jnp.exp(jnp.where(causal, log_L, -jnp.inf))

def linear_attention_dual(Q, K, V, a):
    """The same outputs as Y = (L * Q K^T) V, all positions at once."""
    return (decay_mask(jnp.log(a)) * (Q @ K.T)) @ V

12.6.3.2 分块计算

两种纯粹形式都不适合 GPU 训练:词元级循环需要执行 \(T\) 个微小顺序步骤,而完整对偶形式要为每个头物化 \(T \times T\) 矩阵。分块将序列划分为 \(T / m\) 个长度为 \(m\) 的块,兼得两者之长(图 12.6.1)。由于任意跨块衰减 \(L_{ts}\) 都可分解为(键到所在块末的衰减)\(\times\)(中间整块衰减)\(\times\)(查询自所在块首的衰减),\(\mathbf{L}\) 的每个非对角块秩为 \(1\)——而 \(\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top\) 的每个非对角块秩至多为 \(d_k\),可由跨块边界传递的 \(d_v \times d_k\) 状态矩阵完全概括(2)。

图 12.6.1: 随机衰减下 式 12.6.6 的掩码 \(\mathbf{L}\) 分块示意图。对角块(蓝框)是并行计算的小型掩码注意力乘积。对角线以下的每个块(橙框)在 \(\mathbf{L}\) 中秩为一、在 \(\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top\) 中秩至多为 \(d_k\),由块间传递的状态(箭头)完全刻画;随衰减累乘,阴影逐渐变淡。

将每个块内的位置从 \(1\) 编号至 \(m\),chunked_linear_attention 分三步批量执行:

  1. 块内计算(对角块):在每个长度为 \(m\) 的块内,利用其 \(m \times m\) 衰减掩码并行求值对偶形式 式 12.6.6。

  2. 块间传递(块边界状态):设 \(\gamma^{(c)} = a_1 \cdots a_m\) 为第 \(c\) 块的总衰减。第 \(c\) 块末尾的状态满足块级线性循环

    \[\mathbf{S}^{(c)} = \gamma^{(c)}\, \mathbf{S}^{(c-1)} + \sum_{t=1}^{m} L_{mt}\, \mathbf{v}_t \mathbf{k}_t^\top, \tag{12.6.7}\]

    可由 d2l.linear_scan 在 \(\lceil \log_2(T/m) \rceil\) 轮内跨全部 \(T / m\) 个块求得。

  3. 历史状态读出(非对角块):向第 \(c\) 块的每个位置 \(t\) 加上 \((a_1 \cdots a_t)\,\mathbf{S}^{(c-1)}\mathbf{q}_t\)。

此时几乎全部浮点运算都转化为稠密矩阵乘法,峰值工作显存也从 \(O(T^2)\) 降至 \(O(Tm + (T/m) d_v d_k)\)。

def chunked_linear_attention(Q, K, V, log_a, chunk_size):
    """y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, computed in chunks.

    Q, K: (batch_size, T, d_k); V: (batch_size, T, d_v); log_a: (batch_size, T)
    """
    B, T, m = Q.shape[0], Q.shape[1], chunk_size
    Q, K, V = (X.reshape(B, T // m, m, -1) for X in (Q, K, V))
    log_a = log_a.reshape(B, T // m, m)
    # 1. Within chunks: the dual form, one m x m mask per chunk
    Y = (decay_mask(log_a) * (Q @ K.mT)) @ V
    # 2. Across chunks: S^(c) = gamma^(c) S^(c-1) + sum_t L_mt v_t k_t^T
    cum = log_a.cumsum(-1).unsqueeze(-1)  # Log decay from the chunk's start
    writes = V.mT @ (K * torch.exp(cum[:, :, -1:] - cum))
    S = d2l.linear_scan(torch.exp(cum[:, :, -1:]), writes)  # At chunk ends
    S = torch.cat([torch.zeros_like(S[:, :1]), S[:, :-1]], 1)  # At the starts
    # 3. Every step reads the state at its chunk's start, decayed to it
    return (Y + (Q * torch.exp(cum)) @ S.mT).reshape(B, T, -1)
def chunked_linear_attention(Q, K, V, log_a, chunk_size):
    """y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, computed in chunks.

    Q, K: (batch_size, T, d_k); V: (batch_size, T, d_v); log_a: (batch_size, T)
    """
    B, T, m = Q.shape[0], Q.shape[1], chunk_size
    Q, K, V = (X.reshape(B, T // m, m, -1) for X in (Q, K, V))
    log_a = log_a.reshape(B, T // m, m)
    # 1. Within chunks: the dual form, one m x m mask per chunk
    Y = (decay_mask(log_a) * (Q @ K.mT)) @ V
    # 2. Across chunks: S^(c) = gamma^(c) S^(c-1) + sum_t L_mt v_t k_t^T
    cum = log_a.cumsum(-1)[..., None]  # Log decay from the chunk's start
    writes = V.mT @ (K * jnp.exp(cum[:, :, -1:] - cum))
    S = d2l.linear_scan(jnp.exp(cum[:, :, -1:]), writes)  # At chunk ends
    S = jnp.concatenate([jnp.zeros_like(S[:, :1]), S[:, :-1]], 1)  # Starts
    # 3. Every step reads the state at its chunk's start, decayed to it
    return (Y + (Q * jnp.exp(cum)) @ S.mT).reshape(B, T, -1)

我们来验证在长度为 \(T = 512\) 的序列上,顺序循环、完整对偶形式以及块大小 \(m \in \{16, 64, 256\}\) 的分块算法在 float32 精度下完全一致。

gen = torch.Generator().manual_seed(0)  # Local: later training stays unseeded
T, d_k, d_v = 512, 64, 64
Q, K, V = (torch.randn(T, d, generator=gen) for d in (d_k, d_k, d_v))
a = 0.8 + 0.19 * torch.rand(T, generator=gen)  # Decays in (0.8, 0.99)
Y = linear_attention_recurrent(Q, K, V, a)
forms = {'dual form': linear_attention_dual(Q, K, V, a)}
for m in (16, 64, 256):
    forms[f'chunks of {m}'] = chunked_linear_attention(
        Q[None], K[None], V[None], torch.log(a)[None], m)[0]
for name, Y_form in forms.items():
    print(f'{name:13s} relative deviation from the recurrence: '
          f'{(Y_form - Y).abs().max() / Y.abs().max():.1e}')
dual form     relative deviation from the recurrence: 1.5e-06
chunks of 16  relative deviation from the recurrence: 2.2e-07
chunks of 64  relative deviation from the recurrence: 2.5e-07
chunks of 256 relative deviation from the recurrence: 8.8e-07
T, d_k, d_v = 512, 64, 64
key_q, key_k, key_v, key_a = jax.random.split(jax.random.key(0), 4)
Q, K = jax.random.normal(key_q, (T, d_k)), jax.random.normal(key_k, (T, d_k))
V = jax.random.normal(key_v, (T, d_v))
a = 0.8 + 0.19 * jax.random.uniform(key_a, (T,))  # Decays in (0.8, 0.99)
with jax.default_matmul_precision('highest'):  # Full float32, not TF32
    Y = linear_attention_recurrent(Q, K, V, a)
    forms = {'dual form': linear_attention_dual(Q, K, V, a)}
    for m in (16, 64, 256):
        forms[f'chunks of {m}'] = chunked_linear_attention(
            Q[None], K[None], V[None], jnp.log(a)[None], m)[0]
for name, Y_form in forms.items():
    print(f'{name:13s} relative deviation from the recurrence: '
          f'{jnp.abs(Y_form - Y).max() / jnp.abs(Y).max():.1e}')
dual form     relative deviation from the recurrence: 2.4e-06
chunks of 16  relative deviation from the recurrence: 3.1e-07
chunks of 64  relative deviation from the recurrence: 3.9e-07
chunks of 256 relative deviation from the recurrence: 9.4e-07

所有形式的相对误差均吻合至 \(\sim 10^{-6}\)(3 分析了最优块大小 \(m\))。

12.6.4 门控线性注意力层

12.6.4.1 网络层设计

GatedLinearAttention 将多头分块线性注意力封装为序列混合器。对于每个头 \(h\),它计算输入依赖的标量衰减 \(a_{t,h} = \sigma(\mathbf{w}_h^\top \mathbf{x}_t + b_h)\),并通过 init_decays 初始化偏置,使初始时间尺度 \(\tau_h\)(\(a_{t,h} \approx e^{-1/\tau_h}\))在各头间对数均匀覆盖 \([4, 256]\) 步。

class GatedLinearAttention(nn.Module):
    """Multi-head linear attention with one input-dependent decay per head."""
    def __init__(self, num_hiddens, num_heads, chunk_size=16, conv_width=4,
                 timescales=(4, 256)):
        super().__init__()
        d = num_hiddens
        self.num_heads, self.chunk_size = num_heads, chunk_size
        self.W_qkv = nn.Linear(d, 3 * d, bias=False)
        self.conv = nn.Conv1d(3 * d, 3 * d, conv_width, groups=3 * d,
                              padding=conv_width - 1)  # One filter per channel
        self.W_a = nn.Linear(d, num_heads)  # Decay gate, one per head
        self.W_g = nn.Linear(d, d)  # Output gate
        self.W_o = nn.Linear(d, d, bias=False)
        d2l.init_lecun(self)
        self.init_decays(*timescales)  # Memories of 4 to 256 steps by default

    def init_decays(self, tau_min, tau_max):
        """Start the decays at exp(-1/tau), tau log-uniform in range."""
        b = self.W_a.bias
        tau = torch.logspace(math.log10(tau_min), math.log10(tau_max), len(b))
        with torch.no_grad():  # log sigmoid(b) = -1 / tau
            b.copy_(-torch.log(torch.expm1(1 / tau)))
class GatedLinearAttention(nnx.Module):
    """Multi-head linear attention with one input-dependent decay per head."""
    def __init__(self, num_hiddens, num_heads, chunk_size=16, conv_width=4,
                 timescales=(4, 256), *, rngs):
        d = num_hiddens
        self.num_heads, self.chunk_size = num_heads, chunk_size
        self.W_qkv = nnx.Linear(d, 3 * d, use_bias=False, rngs=rngs)
        self.conv = nnx.Conv(3 * d, 3 * d, (conv_width,),  # Causal, one
                             feature_group_count=3 * d,  # filter per channel
                             padding=((conv_width - 1, 0),), rngs=rngs)
        self.W_a = nnx.Linear(d, num_heads, rngs=rngs)  # Decay, per head
        self.W_g = nnx.Linear(d, d, rngs=rngs)  # Output gate
        self.W_o = nnx.Linear(d, d, use_bias=False, rngs=rngs)
        self.init_decays(*timescales)  # Memories of 4 to 256 steps by default

    def init_decays(self, tau_min, tau_max):
        """Start the decays at exp(-1/tau), tau log-uniform in range."""
        b = self.W_a.bias
        tau = jnp.logspace(math.log10(tau_min), math.log10(tau_max), len(b))
        b[...] = -jnp.log(jnp.expm1(1 / tau))  # log sigmoid(b) = -1 / tau

我们将记忆更新封装在独立的 memory 方法中,以便 12.7 节 继承 GatedLinearAttention 并替换为 Delta 法则而无需重复实现模块其余部分。heads_to_batch 与 batch_to_heads 负责将头轴折叠进批次轴或展开还原。

def heads_to_batch(Z, num_heads):
    """(batch_size, T, num_heads * e) -> (batch_size * num_heads, T, e)."""
    B, T, _ = Z.shape
    return Z.reshape(B, T, num_heads, -1).transpose(1, 2).flatten(0, 1)

def batch_to_heads(Y, batch_size):
    """(batch_size * num_heads, T, e) -> (batch_size, T, num_heads * e)."""
    _, T, e = Y.shape
    return Y.reshape(batch_size, -1, T, e).transpose(1, 2).flatten(2)

@d2l.add_to_class(GatedLinearAttention)
def decays(self, X):
    """Log decays, (batch_size * num_heads, T)."""
    return heads_to_batch(F.logsigmoid(self.W_a(X)), self.num_heads)[..., 0]

@d2l.add_to_class(GatedLinearAttention)
def memory(self, X, Q, K, V, log_a):
    """Outputs of the decayed matrix memory of every head. X is unused here;
    the delta rule of the next section reads its write strengths from it."""
    return chunked_linear_attention(Q, K, V, log_a, self.chunk_size)
def heads_to_batch(Z, num_heads):
    """(batch_size, T, num_heads * e) -> (batch_size * num_heads, T, e)."""
    B, T, _ = Z.shape
    return Z.reshape(B, T, num_heads, -1).swapaxes(1, 2).reshape(
        B * num_heads, T, -1)

def batch_to_heads(Y, batch_size):
    """(batch_size * num_heads, T, e) -> (batch_size, T, num_heads * e)."""
    _, T, e = Y.shape
    return Y.reshape(batch_size, -1, T, e).swapaxes(1, 2).reshape(
        batch_size, T, -1)

@d2l.add_to_class(GatedLinearAttention)
def decays(self, X):
    """Log decays, (batch_size * num_heads, T)."""
    return heads_to_batch(jax.nn.log_sigmoid(self.W_a(X)),
                          self.num_heads)[..., 0]

@d2l.add_to_class(GatedLinearAttention)
def memory(self, X, Q, K, V, log_a):
    """Outputs of the decayed matrix memory of every head. X is unused here;
    the delta rule of the next section reads its write strengths from it."""
    return chunked_linear_attention(Q, K, V, log_a, self.chunk_size)

在前向传播中(图 12.6.2):

  1. 宽度为 4 的深度因果卷积与 SiLU 将相邻词元混合进 \((\mathbf{Q}, \mathbf{K}, \mathbf{V})\),使位置 \(t\) 的值词元能在单层内直接与位置 \(t - 1\) 的键词元绑定(12.8 节 将对该卷积做消融)。
  2. 对查询与键执行 \(\ell_2\) 归一化使其成为单位向量(与 式 12.6.3 的设定一致)。
  3. 对每个头的读出做 RMS 规范化,经 \(\textrm{SiLU}(\mathbf{W}_g \mathbf{x}_t)\) 门控后投影回宽度 \(d\) (Yang 等 2024年)。
图 12.6.2: 门控线性注意力层。一次投影与短因果卷积产生所有头的查询、键与值,第二次投影给出每个头的衰减 \(a_t\)。矩阵记忆以分块方式计算,其读出逐头进行 RMS 规范化,与由输入算出的门相乘后投影回宽度 \(d\)。
@d2l.add_to_class(GatedLinearAttention)
def forward(self, X):  # X: (batch_size, num_steps, num_hiddens)
    B, T = X.shape[:2]
    QKV = self.conv(self.W_qkv(X).mT)[..., :T].mT  # Causal: drop the tail
    Q, K, V = (heads_to_batch(Z, self.num_heads)
               for Z in F.silu(QKV).chunk(3, -1))
    Q, K = F.normalize(Q, dim=-1), F.normalize(K, dim=-1)  # Unit length
    Y = self.memory(X, Q, K, V, self.decays(X))  # (B * num_heads, T, d / h)
    Y = F.rms_norm(Y, Y.shape[-1:], eps=1e-6)  # Unit RMS per head
    return self.W_o(batch_to_heads(Y, B) * F.silu(self.W_g(X)))
@d2l.add_to_class(GatedLinearAttention)
def __call__(self, X):  # X: (batch_size, num_steps, num_hiddens)
    QKV = jax.nn.silu(self.conv(self.W_qkv(X)))
    Q, K, V = (heads_to_batch(Z, self.num_heads)
               for Z in jnp.split(QKV, 3, -1))
    Q, K = (Z / jnp.maximum(jnp.linalg.norm(Z, axis=-1, keepdims=True), 1e-12)
            for Z in (Q, K))  # Unit length
    Y = self.memory(X, Q, K, V, self.decays(X))  # (B * num_heads, T, d / h)
    Y = Y / jnp.sqrt((Y ** 2).mean(-1, keepdims=True) + 1e-6)  # Unit RMS
    return self.W_o(batch_to_heads(Y, X.shape[0]) * jax.nn.silu(self.W_g(X)))

12.6.4.2 联想回忆

训练好的神经网络是否按照随机键推导出的 \(O(d_k d_v)\) 容量律来填充其矩阵状态?我们使用合成的多查询联想回忆基准 (Arora 等 2024年) 对此进行检验。每条序列先呈现 \(n\) 个键值对(一个互异键词元后接一个取自 4 个类别的值词元),再接可选填充词元,最后以随机顺序再次给出全部 \(n\) 个键作为查询。(选项 num_rebound 与 gap 会用新值覆盖部分键,将在 12.7 节 中使用。)

def associative_recall(rng, batch_size, num_pairs, num_keys=512,
                       num_values=4, num_steps=256, num_rebound=0, gap=None):
    """Key-value pairs, filler, then every key again as a query. The first
    num_rebound keys are written twice, the second time with a new value,
    at any later write or, given gap, gap writes after the first one.
    Returns the tokens (values, then keys, then the filler), the latest
    value of each query's key, and a mask of the queries for rebound keys."""
    n, r = num_pairs, num_rebound
    keys = np.argsort(rng.random((batch_size, num_keys)), 1)[:, :n]
    values = rng.integers(0, num_values, (batch_size, n + r))
    values[:, n:] = (values[:, :r] + rng.integers(  # A new value
        1, num_values, (batch_size, r))) % num_values
    if gap is None:  # Random write order, each second write after the first
        slots = np.argsort(rng.random((batch_size, n + r)), 1)
        slots[:, :r], slots[:, n:] = (np.minimum(slots[:, :r], slots[:, n:]),
                                      np.maximum(slots[:, :r], slots[:, n:]))
    else:  # First writes in random order, second ones gap first writes later
        first = np.argsort(rng.random((batch_size, n)), 1)
        times = np.concatenate([first, first[:, :r] + gap - 0.5], 1)
        slots = np.argsort(np.argsort(times, 1), 1)
    X = np.full((batch_size, num_steps), num_values + num_keys)  # Filler
    rows = np.arange(batch_size)[:, None]
    X[rows, 2 * slots] = num_values + np.concatenate([keys, keys[:, :r]], 1)
    X[rows, 2 * slots + 1] = values
    order = np.argsort(rng.random((batch_size, n)), 1)  # Queries
    X[:, -n:] = num_values + np.take_along_axis(keys, order, 1)
    latest = np.concatenate([values[:, n:], values[:, r:n]], 1)
    return X, np.take_along_axis(latest, order, 1), order < r
def associative_recall(rng, batch_size, num_pairs, num_keys=512,
                       num_values=4, num_steps=256, num_rebound=0, gap=None):
    """Key-value pairs, filler, then every key again as a query. The first
    num_rebound keys are written twice, the second time with a new value,
    at any later write or, given gap, gap writes after the first one.
    Returns the tokens (values, then keys, then the filler), the latest
    value of each query's key, and a mask of the queries for rebound keys."""
    n, r = num_pairs, num_rebound
    keys = np.argsort(rng.random((batch_size, num_keys)), 1)[:, :n]
    values = rng.integers(0, num_values, (batch_size, n + r))
    values[:, n:] = (values[:, :r] + rng.integers(  # A new value
        1, num_values, (batch_size, r))) % num_values
    if gap is None:  # Random write order, each second write after the first
        slots = np.argsort(rng.random((batch_size, n + r)), 1)
        slots[:, :r], slots[:, n:] = (np.minimum(slots[:, :r], slots[:, n:]),
                                      np.maximum(slots[:, :r], slots[:, n:]))
    else:  # First writes in random order, second ones gap first writes later
        first = np.argsort(rng.random((batch_size, n)), 1)
        times = np.concatenate([first, first[:, :r] + gap - 0.5], 1)
        slots = np.argsort(np.argsort(times, 1), 1)
    X = np.full((batch_size, num_steps), num_values + num_keys)  # Filler
    rows = np.arange(batch_size)[:, None]
    X[rows, 2 * slots] = num_values + np.concatenate([keys, keys[:, :r]], 1)
    X[rows, 2 * slots + 1] = values
    order = np.argsort(rng.random((batch_size, n)), 1)  # Queries
    X[:, -n:] = num_values + np.take_along_axis(keys, order, 1)
    latest = np.concatenate([values[:, n:], values[:, r:n]], 1)
    return X, np.take_along_axis(latest, order, 1), order < r

我们先查看一条包含 4 对键值与 1 个重绑定键的短序列(词元 0..3 为值,4..515 为键,516 为填充):

X, Y, rebound = associative_recall(np.random.default_rng(0), 1, 4,
                                   num_steps=16, num_rebound=1)
print('tokens: ', X[0])
print('answers:', Y[0], ' written twice:', rebound[0])
tokens:  [273   3  15   3 200   2 407   0 273   0 516 516 200 407 273  15]
answers: [2 0 0 3]  written twice: [False False  True False]
X, Y, rebound = associative_recall(np.random.default_rng(0), 1, 4,
                                   num_steps=16, num_rebound=1)
print('tokens: ', X[0])
print('answers:', Y[0], ' written twice:', rebound[0])
tokens:  [273   3  15   3 200   2 407   0 273   0 516 516 200 407 273  15]
answers: [2 0 0 3]  written twice: [False False  True False]

我们保存训练框架 train_recall:它使用 AdamW(带余弦预热,峰值学习率 \(0.01\))训练 2,000 步,循环遍历键值对负载 \(n \in \{4, 8, 16, 32, 64\}\),并在 1,024 条新序列上评估每个负载下的召回率。

def train_recall(model, pairs=(4, 8, 16, 32, 64), num_updates=2000,
                 **task):
    """Train on associative recall (task: options of associative_recall)
    with a cycling number of pairs, 256 sequences per update, AdamW at peak
    rate 0.01; return the accuracy per number of pairs."""
    rng = np.random.default_rng()
    length = lambda n: 32 * math.ceil(
        (3 * n + 2 * task.get('num_rebound', 0)) / 32)
    data = lambda n, size: associative_recall(
        rng, size, n, num_steps=length(n), **task)[:2]
    model.to(d2l.try_gpu())
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2,
                                  weight_decay=0.01)
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda t: (
        d2l.cosine_warmup(t, num_updates, num_updates // 10)))
    d2l.train_queries(model, lambda step: data(pairs[step % len(pairs)],
                      256), num_updates, optimizer, scheduler)
    return {n: float(d2l.query_accuracy(model, *data(n, 1024)))
            for n in pairs}
def train_recall(model, pairs=(4, 8, 16, 32, 64), num_updates=2000,
                 **task):
    """Train on associative recall (task: options of associative_recall)
    with a cycling number of pairs, 256 sequences per update, AdamW at peak
    rate 0.01; return the accuracy per number of pairs."""
    rng = np.random.default_rng()
    length = lambda n: 32 * math.ceil(
        (3 * n + 2 * task.get('num_rebound', 0)) / 32)
    data = lambda n, size: associative_recall(
        rng, size, n, num_steps=length(n), **task)[:2]
    schedule = lambda t: 1e-2 * d2l.cosine_warmup(t, num_updates,
                                                  num_updates // 10)
    optimizer = nnx.Optimizer(model, optax.chain(
        optax.clip_by_global_norm(1.0),
        optax.adamw(schedule, weight_decay=0.01)), wrt=nnx.Param)
    d2l.train_queries(model, lambda step: data(pairs[step % len(pairs)],
                      256), num_updates, optimizer)
    return {n: float(d2l.query_accuracy(model, *data(n, 1024)))
            for n in pairs}

为了在不改变模型宽度或参数量的前提下调节矩阵状态容量,我们在 memory_model(num_heads) 中固定宽度为 \(d = 32\) 的两块 SeqLM,将其划分为 \(h \in \{8, 4, 2\}\) 个维度为 \(e = d / h \in \{4, 8, 16\}\) 的头:

def memory_model(num_heads, num_hiddens=32, vocab_size=4 + 128 + 1):
    """Two blocks of gated linear attention; tokens: values, keys, filler."""
    return d2l.SeqLM(vocab_size, num_hiddens, [GatedLinearAttention(
        num_hiddens, num_heads, timescales=(256, 2048)) for _ in range(2)])
def memory_model(num_heads, num_hiddens=32, vocab_size=4 + 128 + 1):
    """Two blocks of gated linear attention; tokens: values, keys, filler."""
    rngs = nnx.Rngs(d2l.get_key())  # A new initialization each call
    return d2l.SeqLM(vocab_size, num_hiddens, [GatedLinearAttention(
        num_hiddens, num_heads, timescales=(256, 2048), rngs=rngs)
        for _ in range(2)], rngs=rngs)

由于每个头维护一个 \(e \times e\) 状态矩阵,每层状态总元素数按 \(h \cdot e^2 = d \cdot e \in \{128, 256, 512\}\) 缩放,而总参数量几乎完全相同(约 \(37{,}000\))。我们使用 train_recall 对每种头配置各训练两次:

recall = {}
for num_heads in (8, 4, 2):
    d_h = 32 // num_heads
    name = f'{num_heads} heads of {d_h}, {num_heads * d_h ** 2} entries'
    models = [memory_model(num_heads) for _ in range(2)]
    recall[name] = [train_recall(model, num_keys=128) for model in models]
    print(f'{name:26s} {d2l.num_params(models[0]):,} parameters')
8 heads of 4, 128 entries  37,461 parameters
4 heads of 8, 256 entries  37,197 parameters
2 heads of 16, 512 entries 37,065 parameters
recall = {}
for num_heads in (8, 4, 2):
    d_h = 32 // num_heads
    name = f'{num_heads} heads of {d_h}, {num_heads * d_h ** 2} entries'
    models = [memory_model(num_heads) for _ in range(2)]
    recall[name] = [train_recall(model, num_keys=128) for model in models]
    print(f'{name:26s} {d2l.num_params(models[0]):,} parameters')
8 heads of 4, 128 entries  37,461 parameters
4 heads of 8, 256 entries  37,197 parameters
2 heads of 16, 512 entries 37,065 parameters

绘制并列表展示平均召回准确率随键值对数量 \(n \in \{4, 8, 16, 32, 64\}\) 的变化,即可看出检索容量如何随状态总元素数扩展:

pairs = list(recall[name][0])
d2l.plot(pairs, [[np.mean([run[n] for run in runs]) for n in pairs]
                 for runs in recall.values()], 'pairs in the sequence',
         'recall, mean of two runs', legend=list(recall), xscale='log',
         ylim=(0.2, 1.02), fmts=('-o', '-s', '-^'), figsize=(4.5, 3))
d2l.plt.xticks(pairs, pairs)  # Ticks at the numbers of pairs
print(f'{"pairs":26s}', ''.join(f'{n:>11d}' for n in pairs))
for name, runs in recall.items():
    print(f'{name:26s}', ''.join(f'{runs[0][n]:6.2f}/{runs[1][n]:.2f}'
                                 for n in pairs))
pairs                                4          8         16         32         64
8 heads of 4, 128 entries    0.99/0.99  0.95/0.95  0.84/0.84  0.67/0.66  0.53/0.51
4 heads of 8, 256 entries    1.00/1.00  0.99/0.99  0.95/0.96  0.87/0.88  0.72/0.73
2 heads of 16, 512 entries   1.00/1.00  1.00/1.00  1.00/0.99  1.00/0.96  0.99/0.91

pairs = list(recall[name][0])
d2l.plot(pairs, [[np.mean([run[n] for run in runs]) for n in pairs]
                 for runs in recall.values()], 'pairs in the sequence',
         'recall, mean of two runs', legend=list(recall), xscale='log',
         ylim=(0.2, 1.02), fmts=('-o', '-s', '-^'), figsize=(4.5, 3))
d2l.plt.xticks(pairs, pairs)  # Ticks at the numbers of pairs
print(f'{"pairs":26s}', ''.join(f'{n:>11d}' for n in pairs))
for name, runs in recall.items():
    print(f'{name:26s}', ''.join(f'{runs[0][n]:6.2f}/{runs[1][n]:.2f}'
                                 for n in pairs))
pairs                                4          8         16         32         64
8 heads of 4, 128 entries    0.98/0.99  0.95/0.96  0.84/0.85  0.68/0.68  0.52/0.54
4 heads of 8, 256 entries    1.00/1.00  1.00/0.99  0.97/0.98  0.87/0.92  0.72/0.80
2 heads of 16, 512 entries   0.99/1.00  0.98/1.00  0.94/1.00  0.85/1.00  0.67/0.99

三种配置在 4 对键值上均能完美解决(\(\ge 98\%\));随着负载增加,召回率直接随状态元素数缩放:将状态容量从 128 个元素(\(8 \times 4^2\))翻倍至 256 个元素(\(4 \times 8^2\)),在固定准确率下可召回的键值对数大致翻倍(64 对处从 \(\sim 0.50\) 升至 \(\sim 0.75\)),而 512 个元素(\(2 \times 16^2\))在所有 \(\ge 16\) 的负载上均优于 128 个元素。

所有加性矩阵记忆仍存在一个结构缺陷:写入 \(\mathbf{v}_t \mathbf{k}_t^\top\) 只是简单地叠加到 \(\mathbf{k}_t\) 下已存的值上。如果某个键第二次被绑定到新值,查询该键将返回新旧值的叠加。教会记忆覆盖键的旧值正是 12.7 节 的主题。

12.6.5 小结

矩阵值状态 \(\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}\) 通过外积写入 \(\mathbf{v}_t \mathbf{k}_t^\top\) 存储键值对,并通过线性查询 \(\mathbf{S}_t \mathbf{q}_t\) 检索。展开后,该循环正是因果线性注意力——而 Mamba 的选择性 SSM 则是键为 \(\mathbf{B}_t\)、查询为 \(\mathbf{C}_t\) 的一个特例。在随机单位键下,成对串扰在 \(n\) 次写入后产生 \((n - 1)/d_k\) 的期望平方检索误差,而最近邻召回容量随状态总元素数 \(d_k d_v\) 缩放。为每个头加入输入依赖的标量衰减 \(a_t \in (0, 1)\) 可使旧键值对淡出,并导出与因果掩码线性注意力 \(\mathbf{Y} = (\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top)\mathbf{V}\) 之间的状态空间对偶。以分块方式求值该对偶形式,在 \(O(T)\) 显存下结合了块内并行矩阵乘法与块间扫描。在固定参数量的多查询联想回忆任务上,将 GatedLinearAttention 层的状态元素数翻倍大致使可召回键值对数翻倍,但纯加性写入仍无法覆盖先前已绑定的键。

12.6.6 练习

  1. 将 Mamba 视为矩阵记忆。 在 \(\mathbf{S}_t = \mathbf{E}_t \odot \mathbf{S}_{t-1} + (\boldsymbol{\Delta}_t \odot \mathbf{x}_t)\, \mathbf{B}_t^\top\)(其中 \(\mathbf{E}_t = \exp(\textrm{diag}(\boldsymbol{\Delta}_t)\, \boldsymbol{\Lambda})\))这一形式中,衰减的对数是将速率矩阵第 \(c\) 行乘以步长 \(\Delta_{t,c}\) 所得。
    1. 对 \(\boldsymbol{\Delta}_t\) 和速率 \(\boldsymbol{\Lambda}\) 施加哪些条件,可使 \(\mathbf{E}_t\) 成为全一矩阵的标量倍,从而使更新具有 式 12.6.4 的形式?Mamba-2 施加了其中哪些条件,又保留了哪些输入依赖项?
    2. 针对本节中的每种衰减形式(RetNet、Mamba-2、门控线性注意力、Mamba),统计每个词元决定单个 \(d_v \times d_k\) 头的衰减所需的输入依赖数值个数。
  2. 秩一分块。 设 \(p_t = a_1 a_2 \cdots a_t\) 为 式 12.6.6 中衰减的连乘积。
    1. 用 \(p_t\) 表示 \(L_{ts}\),并证明 \(\mathbf{L}\) 中凡是所有行索引均不小于列索引的子矩阵,其秩均为一。
    2. 推导出 \(\mathbf{L} \odot \mathbf{Q}\mathbf{K}^\top\) 中将某一块耦合到更早块的每个子块秩至多为 \(d_k\)。指出 chunked_linear_attention 在何处分别施加该子块的查询侧衰减与键侧衰减。
    3. 若采用逐键坐标衰减 \(\mathbf{S}_t = \mathbf{S}_{t-1} \textrm{diag}(\boldsymbol{\alpha}_t) + \mathbf{v}_t \mathbf{k}_t^\top\),则不存在单个掩码 \(\mathbf{L}\) 乘以 \(\mathbf{Q}\mathbf{K}^\top\)。写出查询 \(t\) 与键 \(s\) 的衰减分数,并证明耦合两块的子块秩仍至多为 \(d_k\)。
  3. 运算量统计。 将一次乘加计为两次浮点运算,设 \(d_k = d_v = d\),仅保留主导项。
    1. 统计长度为 \(T\)、块大小为 \(m\) 时循环形式、对偶形式与分块形式的运算量,并将分块运算量拆分为算法的三个部分。
    2. 证明当 \(m \le d\) 时,分块形式的运算量至多为循环形式的一个小常数倍;计算在 \(T = 4096\)、\(d = 64\)、\(m = 256\) 时分块与对偶运算量之比。
    3. 将某种调度的运行时间建模为其运算量除以吞吐量 \(P\),再加上每个顺序步骤的固定开销 \(\tau\):循环形式有 \(T\) 步,分块形式有 \(T/m\) 步。求最小化分块时间的块大小,并在 \(T = 4096\)、\(d = 64\)、\(P = 10^{13}\) 次运算/秒、\(\tau = 5\,\mu\textrm{s}\) 下求值。该模型预测分块形式比循环形式快多少倍?
  4. 相关键。 ● matrix_memory 中 \(\rho > 0\) 的键由 \(\sqrt{1-\rho^2}\, \mathbf{g}_i + \rho\, \mathbf{c}\) 归一化得到,其中 \(\mathbf{g}_i\) 为独立随机单位向量,\(\mathbf{c}\) 为共享单位向量。正文公式将两不同键的重叠建模为 \(\rho^2 + \epsilon_{ij}\)(\(\epsilon_{ij}\) 独立,均值为零、方差为 \((1-\rho^2)^2/d_k\)),并假设值的均值为零。
    1. matrix_memory 的值取自 256 个随机向量组成的码本,其均值 \(\bar{\mathbf{v}}\) 并不严格为零。证明这会给期望平方误差增加一项正比于 \((n-1)(n-2)\, \|\bar{\mathbf{v}}\|^2\) 的项,并将你的完整预测与实测误差比较。
    2. 将码本中心化(减去均值后再将每个条目重新归一化),验证曲线的上翘现象消失。
    3. 在 \(d_k = 64\) 与 \(d_k = 256\) 下测量 \(\rho \in \{0, 0.25, 0.5, 0.75\}\) 的误差与召回率。对哪些 \(\rho\) 增大键宽仍有帮助?误差在何处趋近 \((n-1) \rho^4\)?
  5. [code] 不同宽度的键与值。 ● 为 matrix_memory 增加独立的值宽度参数 d_v,使码本包含 \(\mathbb{R}^{d_v}\) 中的 256 个随机单位向量。
    1. 保持 \(n/(d_k d_v) = 1/32\),测量 \((d_k, d_v) = (64, 64)\)、\((256, 16)\) 与 \((16, 256)\) 的召回率。召回率是否仅取决于乘积 \(d_k d_v\)?
    2. 证明期望平方读取误差不依赖于 \(d_v\),因此无法解释你测得的现象。
    3. 每个码本条目大约存储在 \(n/256\) 个键下。证明它们与读取键的重叠沿该条目贡献了约 \(n/(256\, d_k)\) 的方差分量,并用它解释乘积律在哪些形状下失效。
  6. [code] 作为滑动窗口的衰减。 ● 为 matrix_memory 加入常数衰减 \(a\),使在末尾前 \(\ell\) 步写入的键值对以权重 \(a^\ell\) 进入最终记忆。
    1. 在 \(d_k = 64\) 且 \(n = 256\) 下,针对 \(a \in \{1, 0.99, 0.95, 0.9\}\) 分别测量最早四分之一与最新四分之一键值对的召回率。衰减给最新键值对带来了什么收益,又给最旧键值对造成了什么代价?
    2. 仿照命题的证明,证明任意键处的期望平方干扰至多为 \(1 / ((1-a^2)\, d_k)\)。证明无论 \(a < 1\) 取何值,平方信号 \(a^{2\ell}\) 超过该上界的键值对数目至多约为 \(d_k / e\)。

讨论