10.7  注意力电路

如 10.1 节 所指出,注意力热力图只是关于层在计算什么的假设,而非证明。热力图展示的是头看向何处,但这只占其计算的一半;头真正写入输出的内容取决于其值投影与输出投影。一个锐利关注某词元的头,可能复制该词元的身份、提取单个子空间特征,也可能仅贡献一个微不足道的向量。

为了理解训练好的注意力头究竟在计算什么,我们在纯注意力语言模型 TinyCharLM(10.4 节)上采用 Elhage 等 (2021年) 的机制电路表述。每个头分解为作用于残差流上的两个秩至多为 \(d_h\) 的双线性/线性算子:决定关注哪些位置的 QK 电路,以及决定被关注向量如何改变输出对数几率的 OV 电路。借助这一分解,我们证明为何单层模型只能表达二元语法与跳三元语法(含单词元复制),却无法完成上下文模式补全(\([\mathrm{A}][\mathrm{B}] \ldots [\mathrm{A}] \to [\mathrm{B}]\)),而两层模型则可将前词元头与匹配复制头组合为归纳头 (Olsson 等 2022年)。最后,我们通过权重检查与因果头消融检验这一电路假设。

import copy

10.7.1 电路与残差流

10.7.1.1 QK 电路与 OV 电路

在 TinyCharLM(10.4.5.1 节)中,词元嵌入 \(\mathbf{e}_{x_i} \in \mathbb{R}^d\)(\(d = 128\))依次经过 \(N\) 个残差块——每块包含 \(H = 4\) 个宽度 \(d_h = d/H = 32\) 的因果注意力头,不含多层感知机、规范化或偏置项——最后经绑定反嵌入投影 \(\mathbf{E} \in \mathbb{R}^{|\mathcal{V}| \times d}\) 输出对数几率。

将词元向量写成列向量 \(\mathbf{h}_j \in \mathbb{R}^d\),每个头通过 \(\mathbf{W}_v \in \mathbb{R}^{d_h \times d}\) 投影 \(\mathbf{h}_j\) 并形成加权和 \(\sum_{j \le i} \alpha_{ij} \mathbf{W}_v \mathbf{h}_j\)。将块的输出矩阵切分为 \(H\) 个列切片 \(\mathbf{W}_o \in \mathbb{R}^{d \times d_h}\)(每头一个),即可把拼接再投影的步骤改写为各头独立贡献之和:

\[ \mathbf{W}_o \sum_{j \leq i} \alpha_{ij}\, \mathbf{W}_v \mathbf{h}_j = \sum_{j \leq i} \alpha_{ij}\, \mathbf{W}_o \mathbf{W}_v\, \mathbf{h}_j. \]

类似地,查询位置 \(i\) 与键位置 \(j\) 之间的 softmax 前得分为 \((\mathbf{W}_q \mathbf{h}_i)^\top (\mathbf{W}_k \mathbf{h}_j) / \sqrt{d_h}\),其中 \(\mathbf{W}_q, \mathbf{W}_k \in \mathbb{R}^{d_h \times d}\)。因此,每个头完全由两个秩至多为 \(d_h\) 的 \(d \times d\) 矩阵刻画 (Elhage 等 2021年):

\[ s_{ij} = \frac{\mathbf{h}_i^\top \mathbf{W}_{\mathrm{QK}}\, \mathbf{h}_j}{\sqrt{d_h}}, \qquad \mathbf{W}_{\mathrm{QK}} = \mathbf{W}_q^\top \mathbf{W}_k, \qquad \mathbf{W}_{\mathrm{OV}} = \mathbf{W}_o \mathbf{W}_v. \tag{10.7.1}\]

  • QK 电路 \(\mathbf{W}_{\mathrm{QK}}\)(在 RoPE 下为 \(\mathbf{W}_q^\top \mathbf{R}_{j-i} \mathbf{W}_k\),10.4.3 节)决定头关注何处。
  • OV 电路 \(\mathbf{W}_{\mathrm{OV}}\) 决定当某个源位置被关注时,头向目标位置写入何种向量。

研究乘积 \(\mathbf{W}_{\mathrm{QK}}\) 与 \(\mathbf{W}_{\mathrm{OV}}\) 而非单个因子,既消除了规范自由度(对任意可逆矩阵 \(\mathbf{G} \in \mathbb{R}^{d_h \times d_h}\),\(\mathbf{W}_o \mathbf{G}^{-1}\) 与 \(\mathbf{G}\mathbf{W}_v\) 给出完全相同的 \(\mathbf{W}_{\mathrm{OV}}\)),又显式揭示了秩 \(d_h\) 的子空间瓶颈。

10.7.1.2 跨层的残差表征

令 \(\mathbf{h}_i^{(0)} = \mathbf{e}_{x_i}\),第 \(\ell \in \{1, \ldots, N\}\) 块以加法更新位置 \(i\) 的表征:

\[ \mathbf{h}_i^{(\ell)} = \mathbf{h}_i^{(\ell-1)} + \sum_{m=1}^{H} \sum_{j \leq i} \alpha_{ij}^{\ell m}\, \mathbf{W}_{\mathrm{OV}}^{\ell m}\, \mathbf{h}_j^{(\ell-1)}, \tag{10.7.2}\]

随后绑定输出头生成对数几率 \(\mathbf{z}_i = \mathbf{E}\, \mathbf{h}_i^{(N)}\)。序列 \(\mathbf{h}_i^{(0)}, \ldots, \mathbf{h}_i^{(N)}\) 即位置 \(i\) 的残差流(图 10.7.1):一条每个头都以加法读写的共享通信通道。

图 10.7.1: 残差流。每个位置从其嵌入一直携带一个向量到输出对数几率。QK 电路决定注意力权重 \(\alpha_{3j}\),OV 电路决定每个被关注向量对目标流的贡献。

10.7.1.3 二元语法、跳三元语法与单层的局限

按深度展开 式 10.7.2 可以看清 \(N\) 层注意力能够表达哪些函数:

  • 零块(\(N = 0\)):\(\mathbf{z}_i = \mathbf{E}\,\mathbf{e}_{x_i}\),仅通过对称半正定格拉姆矩阵 \(\mathbf{E}\mathbf{E}^\top\) 建模受限的词元二元语法对数几率(1)。

  • 一块(\(N = 1\)):

    \[ \mathbf{z}_i = \mathbf{E}\,\mathbf{e}_{x_i} + \sum_{m=1}^{H} \sum_{j \leq i} \alpha_{ij}^{m}\; \mathbf{E}\,\mathbf{W}_{\mathrm{OV}}^{m}\,\mathbf{e}_{x_j}. \tag{10.7.3}\]

    每个头项实现一条形如 \(x_j \ldots x_i \to x_{\textrm{next}}\) 的跳三元语法规则(例如从“in”关注更早的“keep”并提升“mind”,或通过提升 \(x_j\) 本身实现复制)。

  • 两块(\(N = 2\))与归纳头:设上下文包含 \([\mathrm{A}][\mathrm{B}] \ldots [\mathrm{A}]\),模型须通过上下文查找预测 \([\mathrm{B}]\)。单块模型无法凭内容匹配做到这一点:要从位置 \(j\) 复制 \([\mathrm{B}]\),头必须关注位置 \(j\),但在 式 10.7.3 中,位置 \(j\) 的键仅依赖 \(\mathbf{e}_{x_j} = \mathbf{e}_{[\mathrm{B}]}\),对其前驱 \(x_{j-1} = [\mathrm{A}]\) 一无所知。

    两块通过 K-组合 解决此问题(图 10.7.2,2):在第 1 块中,前词元头关注偏移 \(-1\) 并将 \(x_{j-1} = [\mathrm{A}]\) 写入位置 \(j\) 的残差流 \(\mathbf{h}_j^{(1)}\);在第 2 块中,归纳头用其查询 \([\mathrm{A}]\) 匹配 \(\mathbf{h}_j^{(1)}\) 中的该键特征,再用其 OV 电路把 \(x_j = [\mathrm{B}]\) 复制进预测对数几率。

图 10.7.2: 归纳电路横跨两层。第 1 层的前词元头将每个词元的前驱写入其残差流,使 B 位置的键得以宣告“紧随 A”。第 2 层归纳头的 QK 电路将当前 A 与该宣告匹配,其 OV 电路则把 B 复制进预测结果。

10.7.2 复制与归纳

10.7.2.1 重复序列任务

为了检验梯度下降能否发现这一两层电路,我们在重复随机词元合成序列上训练:每条序列从大小 \(64\) 的词表中均匀抽取长度 \(L \in [L_{\min}, L_{\max}]\) 的随机模式,并将其平铺至长度 \(64\)。因每个模式均全新抽取,第一份副本(\(t < L\))不可预测(随机猜测交叉熵 \(\log 64 \approx 4.16\) 奈特)。位置 \(t = L\) 处模式重启的词元同样不可预测:上下文中尚无任何重复,模型无从得知 \(L\)。因此我们将 \(t \le L\) 的目标统算作第一份副本;后续副本(\(t > L\))则可通过上下文查找从前文预测。

def repeated_batch(batch_size, num_steps, vocab, Lmin, Lmax, device=None):
    """Random patterns of length Lmin..Lmax, tiled to num_steps tokens."""
    L = torch.randint(Lmin, Lmax + 1, (batch_size,), device=device)
    s = torch.randint(0, vocab, (batch_size, num_steps), device=device)
    pos = torch.arange(num_steps, device=device)
    return torch.gather(s, 1, pos[None, :] % L[:, None]), L

x, L = repeated_batch(batch_size=2, num_steps=16, vocab=10, Lmin=5, Lmax=8)
print(f'pattern lengths: {L.tolist()}')
print(x)
pattern lengths: [5, 6]
tensor([[3, 6, 6, 6, 2, 3, 6, 6, 6, 2, 3, 6, 6, 6, 2, 3],
        [9, 2, 9, 6, 3, 7, 9, 2, 9, 6, 3, 7, 9, 2, 9, 6]])
def repeated_batch(key, batch_size, num_steps, vocab, Lmin, Lmax):
    """Random patterns of length Lmin..Lmax, tiled to num_steps tokens."""
    key_L, key_s = jax.random.split(key)
    L = jax.random.randint(key_L, (batch_size,), Lmin, Lmax + 1)
    s = jax.random.randint(key_s, (batch_size, num_steps), 0, vocab)
    pos = jnp.arange(num_steps)
    return jnp.take_along_axis(s, pos[None, :] % L[:, None], axis=1), L

x, L = repeated_batch(d2l.get_key(), batch_size=2, num_steps=16,
                      vocab=10, Lmin=5, Lmax=8)
print(f'pattern lengths: {L.tolist()}')
print(x)
pattern lengths: [6, 5]
[[6 8 1 6 3 6 6 8 1 6 3 6 6 8 1 6]
 [7 0 0 4 8 7 0 0 4 8 7 0 0 4 8 7]]

eval_copy 测量第一份副本(\(t \le L\))的交叉熵、后续副本(\(t > L\))的交叉熵,以及后续副本的 top-1 准确率:

@torch.inference_mode()
def eval_copy(model, x, L):
    """First-copy loss, later-copy loss, and later-copy accuracy."""
    logits, Y = model(x[:, :-1]), x[:, 1:]
    ce = F.cross_entropy(logits.transpose(1, 2), Y, reduction='none')
    later = torch.arange(1, Y.shape[1] + 1, device=Y.device) > L[:, None]
    acc = (logits.argmax(-1) == Y)[later].float().mean()
    return torch.stack((ce[~later].mean(), ce[later].mean(), acc)).tolist()

class RepeatedTokens(d2l.DataModule):
    """An endless stream of fresh repeated-token minibatches."""
    def __init__(self, Lmin, Lmax, batch_size=128, num_steps=64, vocab=64):
        super().__init__()
        self.save_hyperparameters()

    def train_dataloader(self):
        while True:
            x, _ = repeated_batch(self.batch_size, self.num_steps,
                                  self.vocab, self.Lmin, self.Lmax)
            yield x[:, :-1], x[:, 1:]

def train_repeat(model, num_steps, Lmin, Lmax, eval_every=50):
    """Train with Adam; return (first, later) copy losses per round."""
    data, device = RepeatedTokens(Lmin, Lmax), d2l.try_gpu()
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    history = []
    for _ in range(num_steps // eval_every):
        d2l.train_steps(model, data, optimizer, eval_every)
        x, L = repeated_batch(256, 64, 64, Lmin, Lmax, device)
        history.append(eval_copy(model, x, L)[:2])
    return history

def drop_step(hist, eval_every=50):
    """First step at which the later-copy loss is below 1 nat, or None."""
    return next((eval_every * (k + 1) for k, (_, rep) in enumerate(hist)
                 if rep < 1), None)
def eval_copy(model, x, L):
    """First-copy loss, later-copy loss, and later-copy accuracy."""
    logits, Y = model(x[:, :-1]), x[:, 1:]
    ce = optax.softmax_cross_entropy_with_integer_labels(logits, Y)
    later = jnp.arange(1, Y.shape[1] + 1)[None, :] > L[:, None]
    acc = ((logits.argmax(-1) == Y) * later).sum() / later.sum()
    first = (ce * ~later).sum() / (~later).sum()
    rep = (ce * later).sum() / later.sum()
    return [float(v) for v in jax.device_get((first, rep, acc))]

class RepeatedTokens(d2l.DataModule):
    """An endless stream of fresh repeated-token minibatches."""
    def __init__(self, Lmin, Lmax, batch_size=128, num_steps=64, vocab=64):
        super().__init__()
        self.save_hyperparameters()

    def train_dataloader(self):
        while True:
            x, _ = repeated_batch(d2l.get_key(), self.batch_size,
                                  self.num_steps, self.vocab, self.Lmin,
                                  self.Lmax)
            yield x[:, :-1], x[:, 1:]

def train_repeat(model, num_steps, Lmin, Lmax, eval_every=50):
    """Train with Adam; return (first, later) copy losses per round."""
    data = RepeatedTokens(Lmin, Lmax)
    optimizer = nnx.Optimizer(model, optax.adam(1e-3), wrt=nnx.Param)
    history = []
    for _ in range(num_steps // eval_every):
        d2l.train_steps(model, data, optimizer, eval_every)
        x, L = repeated_batch(d2l.get_key(), 256, 64, 64, Lmin, Lmax)
        history.append(eval_copy(model, x, L)[:2])
    return history

def drop_step(hist, eval_every=50):
    """First step at which the later-copy loss is below 1 nat, or None."""
    return next((eval_every * (k + 1) for k, (_, rep) in enumerate(hist)
                 if rep < 1), None)

10.7.2.2 固定偏移捷径

在测试变周期之前,假设模式周期固定为 \(L = 32\)。一个单块模型(num_blks=1, bias=True)轻而易举便在第二份副本上达到 \(100\%\) 准确率:

model_shortcut = d2l.TinyCharLM(vocab_size=64, num_blks=1, pos='rope',
                                bias=True)
train_repeat(model_shortcut, 800, Lmin=32, Lmax=32)
first, rep, acc = eval_copy(model_shortcut, *repeated_batch(
    256, 64, 64, 32, 32, d2l.try_gpu()))
print(f'first copy {first:.2f} nats, second copy {rep:.2f} nats, '
      f'second-copy accuracy {acc:.2f}')
first copy 4.38 nats, second copy 0.14 nats, second-copy accuracy 1.00
model_shortcut = d2l.TinyCharLM(vocab_size=64, num_blks=1, pos='rope',
                                bias=True, rngs=nnx.Rngs(d2l.get_key()))
train_repeat(model_shortcut, 800, Lmin=32, Lmax=32)
first, rep, acc = eval_copy(model_shortcut, *repeated_batch(
    d2l.get_key(), 256, 64, 64, 32, 32))
print(f'first copy {first:.2f} nats, second copy {rep:.2f} nats, '
      f'second-copy accuracy {acc:.2f}')
first copy 4.27 nats, second copy 0.08 nats, second-copy accuracy 1.00

既然电路分析指出基于内容的归纳需要两层,单层如何复制出后继词元?当 \(L = 32\) 恒定时,位置 \(i + 1\) 的目标词元总等于固定偏移 \(j = i - 31\) 处的词元。单个带常偏置查询与键的 RoPE 头根本无需匹配内容,纯粹按相对偏移 \(-31\) 关注即可(3)。在周期 \(L = 24\)(目标位于偏移 \(-23\))的模式上评估 model_shortcut 立刻揭穿了这一捷径:注意力依然锁死在偏移 \(-31\),准确率骤降至随机水平(\(1/64 \approx 0.02\)):

x, L = repeated_batch(256, 64, 64, 24, 24, d2l.try_gpu())
first, rep, acc = eval_copy(model_shortcut, x, L)
with torch.inference_mode():
    m = model_shortcut.attention_weights(x[:, :-1])[0]
print(f'patterns of length 24: second-copy accuracy {acc:.2f}')
for offset in (31, 23):
    mass = m.diagonal(-offset, dim1=2, dim2=3).mean((0, 2))
    print(f'mass at offset {offset}, per head: '
          + ' '.join(f'{v:.2f}' for v in mass.tolist()))
patterns of length 24: second-copy accuracy 0.02
mass at offset 31, per head: 1.00 0.96 1.00 1.00
mass at offset 23, per head: 0.00 0.00 0.00 0.00
x, L = repeated_batch(d2l.get_key(), 256, 64, 64, 24, 24)
first, rep, acc = eval_copy(model_shortcut, x, L)
m = model_shortcut.attention_weights(x[:, :-1])[0]
print(f'patterns of length 24: second-copy accuracy {acc:.2f}')
for offset in (31, 23):
    mass = jnp.diagonal(m, -offset, axis1=2, axis2=3).mean((0, 2))
    print(f'mass at offset {offset}, per head: '
          + ' '.join(f'{v:.2f}' for v in mass.tolist()))
patterns of length 24: second-copy accuracy 0.02
mass at offset 31, per head: 0.92 1.00 0.94 1.00
mass at offset 23, per head: 0.00 0.00 0.00 0.00

10.7.2.3 两块归纳电路

从 \(L \in \{16, \ldots, 32\}\) 均匀采样模式周期彻底堵死了任何固定偏移捷径。我们训练三个独立的两块模型与一个单块对照模型(全部 bias=False),共 \(5{,}000\) 步:

runs = []  # (blocks, model, history): three two-block runs, one control
for num_blks in (2, 2, 2, 1):
    model = d2l.TinyCharLM(vocab_size=64, num_blks=num_blks, pos='rope')
    runs.append((num_blks, model, train_repeat(model, 5000, 16, 32)))
models_two = [model for _, model, _ in runs[:3]]
_, model_two, hist_two = runs[0]   # Run 1: maps and curves shown for it
_, model_one, hist_one = runs[3]
x, L = repeated_batch(256, 64, 64, 16, 32, d2l.try_gpu())
print('blocks  first copy  later copies  accuracy  below 1 nat at step')
for num_blks, model, hist in runs:
    first, rep, acc = eval_copy(model, x, L)
    print(f'{num_blks:6d}{first:12.2f}{rep:14.2f}{acc:10.2f}'
          f'{drop_step(hist) or "never":>21}')
blocks  first copy  later copies  accuracy  below 1 nat at step
     2        4.44          0.30      0.94                 2150
     2        4.31          0.16      0.96                 1550
     2        4.31          0.19      0.95                 2650
     1        4.26          3.55      0.11                never
runs = []  # (blocks, model, history): three two-block runs, one control
for num_blks in (2, 2, 2, 1):
    model = d2l.TinyCharLM(vocab_size=64, num_blks=num_blks, pos='rope',
                           rngs=nnx.Rngs(d2l.get_key()))
    runs.append((num_blks, model, train_repeat(model, 5000, 16, 32)))
models_two = [model for _, model, _ in runs[:3]]
_, model_two, hist_two = runs[0]   # Run 1: maps and curves shown for it
_, model_one, hist_one = runs[3]
x, L = repeated_batch(d2l.get_key(), 256, 64, 64, 16, 32)
print('blocks  first copy  later copies  accuracy  below 1 nat at step')
for num_blks, model, hist in runs:
    first, rep, acc = eval_copy(model, x, L)
    print(f'{num_blks:6d}{first:12.2f}{rep:14.2f}{acc:10.2f}'
          f'{drop_step(hist) or "never":>21}')
blocks  first copy  later copies  accuracy  below 1 nat at step
     2        4.45          0.32      0.94                 2550
     2        4.43          0.42      0.91                 2300
     2        4.43          0.30      0.94                 2400
     1        4.28          3.60      0.11                never

全部三次两块运行都取得了超过 \(90\%\) 的后续副本准确率(损失约 \(0.2\)–\(0.4\) 奈特),而单块模型停滞在 \(3\) 奈特以上(\(\sim 10\%\) 准确率,仅能提升上下文中出现过的词元集合)。每次运行的第一份副本损失最终都略高于随机值 \(\log 64\):四个模型都学会了偏好前文出现过的词元,而在第一周期内这种自信反而弄巧成拙——当某词元在第一周期内碰巧重复时,两块模型会预测它先前出现时的后继。此外,训练曲线在一段初始平台后呈现陡峭的相变:

steps = list(range(50, 5001, 50))
d2l.plot(steps, [[h[1] for h in hist_two], [h[1] for h in hist_one],
                 [h[0] for h in hist_two], [math.log(64)] * len(steps)],
         'step', 'loss (nats)',
         legend=['later copies, 2 blocks', 'later copies, 1 block',
                 'first copy, 2 blocks', 'log 64'], figsize=(5, 3))

steps = list(range(50, 5001, 50))
d2l.plot(steps, [[h[1] for h in hist_two], [h[1] for h in hist_one],
                 [h[0] for h in hist_two], [math.log(64)] * len(steps)],
         'step', 'loss (nats)',
         legend=['later copies, 2 blocks', 'later copies, 1 block',
                 'first copy, 2 blocks', 'log 64'], figsize=(5, 3))

10.7.3 电路的证据

为了验证 model_two 是否真正实现了 图 10.7.2 中的两步归纳电路,我们依次检查:(1) 注意力图、(2) OV 复制矩阵与 (3) 头消融。

10.7.3.1 学得头的注意力模式

在周期 \(L = 24\) 的测试序列上,我们的电路预测:第 1 块至少有一个头应回看前一位置(\(j = i - 1\)),而第 2 块的头应在 \(i \ge 24\) 后关注归纳目标 \(j = i + 1 - L = i - 23\):

x, L = repeated_batch(1, 64, 64, 24, 24, d2l.try_gpu())
with torch.inference_mode():
    maps = torch.stack(model_two.attention_weights(x[:, :-1]))
d2l.show_heatmaps(maps[:, 0], xlabel='key position',
                  ylabel='query position',
                  titles=[f'head {h}' for h in range(4)],
                  figsize=(9, 4.5), cmap='Blues')

x, L = repeated_batch(d2l.get_key(), 1, 64, 64, 24, 24)
maps = jnp.stack(model_two.attention_weights(x[:, :-1]))
d2l.show_heatmaps(maps[:, 0], xlabel='key position',
                  ylabel='query position',
                  titles=[f'head {h}' for h in range(4)],
                  figsize=(9, 4.5), cmap='Blues')

为了跨变周期 \(L \in \{16, \ldots, 32\}\) 及全部三次运行量化这两种角色,head_scores 计算每个头落在前一词元(\(j = i - 1\))以及归纳目标(\(i \ge L\) 时的 \(j = i + 1 - L\))上的平均注意力权重:

@torch.inference_mode()
def head_scores(model, x, L):
    """Mean attention on the previous token and on the induction target:
    shape (blocks, 2, heads)."""
    maps = torch.stack(model.attention_weights(x[:, :-1]))
    i = torch.arange(maps.shape[-1], device=x.device)
    tgt = i + 1 - L[:, None]               # Induction target of query i
    is_tgt = i == tgt[..., None]           # (batch, query, key)
    valid = tgt >= 1                       # Query token occurred before
    prev = maps.diagonal(-1, dim1=3, dim2=4).mean((1, 3))
    ind = (maps * is_tgt[:, None]).sum(-1)  # (blocks, batch, heads, query)
    ind = (ind * valid[:, None]).sum((1, 3)) / valid.sum()
    return torch.stack((prev, ind), 1)

x, L = repeated_batch(256, 64, 64, 16, 32, d2l.try_gpu())
all_scores = [head_scores(model, x, L) for model in models_two]
scores = all_scores[0]  # Run 1, whose maps are shown above
for r, run_scores in enumerate(all_scores):
    for b, rows in enumerate(run_scores.tolist()):
        for name, row in zip(('previous', 'induction'), rows):
            print(f'run {r + 1}, block {b + 1}, {name:<9}: '
                  + ' '.join(f'{v:.2f}' for v in row))
run 1, block 1, previous : 0.34 0.46 0.00 0.50
run 1, block 1, induction: 0.00 0.01 0.00 0.00
run 1, block 2, previous : 0.09 0.12 0.07 0.14
run 1, block 2, induction: 0.40 0.38 0.41 0.58
run 2, block 1, previous : 0.02 0.03 0.99 0.00
run 2, block 1, induction: 0.00 0.01 0.00 0.00
run 2, block 2, previous : 0.07 0.06 0.08 0.06
run 2, block 2, induction: 0.45 0.58 0.23 0.61
run 3, block 1, previous : 0.19 0.01 0.39 0.46
run 3, block 1, induction: 0.00 0.00 0.00 0.00
run 3, block 2, previous : 0.08 0.07 0.06 0.07
run 3, block 2, induction: 0.20 0.20 0.47 0.24
def head_scores(model, x, L):
    """Mean attention on the previous token and on the induction target:
    shape (blocks, 2, heads)."""
    maps = jnp.stack(model.attention_weights(x[:, :-1]))
    i = jnp.arange(maps.shape[-1])
    tgt = i + 1 - L[:, None]               # Induction target of query i
    is_tgt = i == tgt[..., None]           # (batch, query, key)
    valid = tgt >= 1                       # Query token occurred before
    prev = jnp.diagonal(maps, -1, axis1=3, axis2=4).mean((1, 3))
    ind = (maps * is_tgt[:, None]).sum(-1)  # (blocks, batch, heads, query)
    ind = (ind * valid[:, None]).sum((1, 3)) / valid.sum()
    return jnp.stack((prev, ind), 1)

x, L = repeated_batch(d2l.get_key(), 256, 64, 64, 16, 32)
all_scores = [head_scores(model, x, L) for model in models_two]
scores = all_scores[0]  # Run 1, whose maps are shown above
for r, run_scores in enumerate(all_scores):
    for b, rows in enumerate(run_scores.tolist()):
        for name, row in zip(('previous', 'induction'), rows):
            print(f'run {r + 1}, block {b + 1}, {name:<9}: '
                  + ' '.join(f'{v:.2f}' for v in row))
run 1, block 1, previous : 0.00 0.46 0.33 0.50
run 1, block 1, induction: 0.00 0.01 0.01 0.00
run 1, block 2, previous : 0.09 0.08 0.06 0.09
run 1, block 2, induction: 0.64 0.39 0.38 0.35
run 2, block 1, previous : 0.04 0.39 0.02 0.49
run 2, block 1, induction: 0.01 0.00 0.01 0.01
run 2, block 2, previous : 0.06 0.06 0.06 0.05
run 2, block 2, induction: 0.52 0.31 0.32 0.35
run 3, block 1, previous : 0.06 0.42 0.02 0.50
run 3, block 1, induction: 0.02 0.01 0.00 0.01
run 3, block 2, previous : 0.05 0.05 0.09 0.06
run 3, block 2, induction: 0.60 0.34 0.38 0.33

在每次运行中,第 1 块都有一到三个头专职为前词元头,而第 2 块的头将注意力集中到归纳目标 \(j = i + 1 - L\) 上。

10.7.3.2 复制矩阵

关注位置 \(j\) 唯有在第 2 块的 OV 电路提升词元 \(x_j\) 的对数几率时,才能预测出 \(x_j\)。记

\[ C_{ab} = \mathbf{e}_b^\top \mathbf{W}_{\mathrm{OV}}\, \bar{\mathbf{h}}_a \tag{10.7.4}\]

为块内各头之和的 OV 电路读取词元 \(a\) 所在位置的平均残差流向量 \(\bar{\mathbf{h}}_a\)(或原始嵌入 \(\mathbf{e}_a\))时,赋予词元 \(b\) 的对数几率增量。执行复制的 OV 电路几乎在全部 \(64\) 行上都将行最大值落在对角线(\(b = a\))处(对比随机猜测的 \(1/64 \approx 0.02\)):

def circuits(model, blk):
    """W_QK and W_OV of every head of block blk, each (heads, D, D)."""
    # nn.Linear stores its weight as (output, input), the orientation of the
    # column-vector equations, so no transpose is needed
    W_qkv = model.blks[blk]['qkv'].weight           # (3D, D): W_q; W_k; W_v
    W_o = model.blks[blk]['proj'].weight            # (D, D): heads in columns
    H, D = model.num_heads, W_o.shape[0]
    W_q, W_k, W_v = W_qkv.reshape(3, H, D // H, D)  # Each (H, d_h, D)
    W_QK = W_q.mT @ W_k
    W_OV = W_o.reshape(D, H, D // H).transpose(0, 1) @ W_v
    return W_QK, W_OV

@torch.inference_mode()
def copy_matrix(model, blk, X=None):
    """C[a, b] = e_b^T W_OV h_a: W_OV summed over the heads of blk, h_a the
    mean stream vector entering blk at the positions of token a in X, or the
    embedding e_a if X is None."""
    E = h = model.token_emb.weight
    if X is not None:
        S = model.stream(X, blk)[0]            # The stream entering blk
        h = torch.zeros_like(E).index_add_(0, X.flatten(), S.flatten(0, 1))
        h = h / torch.bincount(X.flatten(), minlength=len(E))[:, None]
    W_OV = circuits(model, blk)[1].sum(0)
    return h @ W_OV.T @ E.T

def diagonal_share(C):
    """Fraction of the rows of C whose largest entry is on the diagonal."""
    rows = torch.arange(len(C), device=C.device)
    return float((C.argmax(-1) == rows).float().mean())
def circuits(model, blk):
    """W_QK and W_OV of every head of block blk, each (heads, D, D)."""
    # nnx.Linear stores its kernel as (input, output), the transpose of the
    # column-vector equations, so both kernels are transposed first
    W_qkv = model.blks[blk]['qkv'].kernel[...].T    # (3D, D): W_q; W_k; W_v
    W_o = model.blks[blk]['proj'].kernel[...].T     # (D, D): heads in columns
    H, D = model.num_heads, W_o.shape[0]
    W_q, W_k, W_v = W_qkv.reshape(3, H, D // H, D)  # Each (H, d_h, D)
    W_QK = W_q.mT @ W_k
    W_OV = W_o.reshape(D, H, D // H).swapaxes(0, 1) @ W_v
    return W_QK, W_OV

def copy_matrix(model, blk, X=None):
    """C[a, b] = e_b^T W_OV h_a: W_OV summed over the heads of blk, h_a the
    mean stream vector entering blk at the positions of token a in X, or the
    embedding e_a if X is None."""
    E = h = model.token_emb.embedding[...]
    if X is not None:
        S = model.stream(X, blk)[0]            # The stream entering blk
        h = jnp.zeros_like(E).at[X.flatten()].add(S.reshape(-1, E.shape[1]))
        h = h / jnp.bincount(X.flatten(), length=len(E))[:, None]
    W_OV = circuits(model, blk)[1].sum(0)
    return h @ W_OV.T @ E.T

def diagonal_share(C):
    """Fraction of the rows of C whose largest entry is on the diagonal."""
    return float((C.argmax(-1) == jnp.arange(len(C))).mean())

在全部三次两块训练运行(分别作用在平均第 1 块残差流 \(\bar{\mathbf{h}}_a\) 与原始词元嵌入 \(\mathbf{e}_a\) 上)以及单块对照模型上评估 diagonal_share(copy_matrix(...)),可见 OV 电路形成了近乎对角的复制矩阵:

x, L = repeated_batch(256, 64, 64, 16, 32, d2l.try_gpu())
print('rows whose largest entry is the diagonal (chance 1/64)')
print(f'{"":<32}   run 1   run 2   run 3')
for name, X in (('2 blocks, block 2, mean stream', x),
                ('2 blocks, block 2, embeddings', None)):
    shares = [diagonal_share(copy_matrix(m, 1, X)) for m in models_two]
    print(f'{name:<32}' + ''.join(f'{v:8.2f}' for v in shares))
print(f'{"1 block, mean stream":<32}'
      f'{diagonal_share(copy_matrix(model_one, 0, x)):8.2f}')
d2l.show_heatmaps(copy_matrix(model_two, 1, x)[None, None].cpu(),
                  xlabel='logit boosted', ylabel='token attended to',
                  figsize=(3.6, 3.6), cmap='Blues')
rows whose largest entry is the diagonal (chance 1/64)
                                   run 1   run 2   run 3
2 blocks, block 2, mean stream      1.00    1.00    0.91
2 blocks, block 2, embeddings       0.61    0.97    0.70
1 block, mean stream                1.00

x, L = repeated_batch(d2l.get_key(), 256, 64, 64, 16, 32)
print('rows whose largest entry is the diagonal (chance 1/64)')
print(f'{"":<32}   run 1   run 2   run 3')
for name, X in (('2 blocks, block 2, mean stream', x),
                ('2 blocks, block 2, embeddings', None)):
    shares = [diagonal_share(copy_matrix(m, 1, X)) for m in models_two]
    print(f'{name:<32}' + ''.join(f'{v:8.2f}' for v in shares))
print(f'{"1 block, mean stream":<32}'
      f'{diagonal_share(copy_matrix(model_one, 0, x)):8.2f}')
d2l.show_heatmaps(copy_matrix(model_two, 1, x)[None, None],
                  xlabel='logit boosted', ylabel='token attended to',
                  figsize=(3.6, 3.6), cmap='Blues')
rows whose largest entry is the diagonal (chance 1/64)
                                   run 1   run 2   run 3
2 blocks, block 2, mean stream      1.00    1.00    1.00
2 blocks, block 2, embeddings       0.81    0.81    0.27
1 block, mean stream                0.98

留意两处颇具启发性的细节:(1) 单块对照模型同样学出了对角 OV 复制矩阵,说明没有 QK 的 K-组合,单靠 OV 复制无法检索上下文后继(见 6);(2) 第 2 块从第 1 块残差流 \(\bar{\mathbf{h}}_a\) 复制远比单从原始嵌入 \(\mathbf{e}_a\) 复制可靠——后者在不同运行间的对角占比波动很大。

10.7.3.3 头消融

为了检验因果必要性,ablate 将块内所选头的输出投影切片 \(\mathbf{W}_o^m\) 置零。我们对比移除第 1 块的前词元头(得分 \(> 0.2\))、移除第 1 块的其余头,以及由强到弱累加移除第 2 块的归纳头:

def ablate(model, blk, heads):
    """Copy of model with the given heads of block blk removed."""
    model = copy.deepcopy(model)
    W_o = model.blks[blk]['proj'].weight   # (D, D): heads side by side
    with torch.no_grad():
        W_o.view(W_o.shape[0], model.num_heads, -1)[:, heads] = 0
    return model
def ablate(model, blk, heads):
    """Copy of model with the given heads of block blk removed."""
    model = nnx.clone(model)
    W_o = model.blks[blk]['proj'].kernel   # (D, D): heads stacked in rows
    W = W_o[...].reshape(model.num_heads, -1, W_o.shape[1])
    W_o[...] = W.at[jnp.array(heads, dtype=int)].set(0).reshape(W_o.shape)
    return model

在全部三个训练好的两块模型上执行 ablate,量化移除第 1 块前词元头与移除第 2 块最强归纳头分别使后续副本交叉熵和复制准确率退化多少:

x, L = repeated_batch(256, 64, 64, 16, 32, d2l.try_gpu())
H, table = model_two.num_heads, {}  # Variant: (loss, accuracy) per run
for r, (model, s) in enumerate(zip(models_two, all_scores)):
    prev = [h for h in range(H) if s[0, 0, h] > 0.2]  # Previous-token heads
    rest = [h for h in range(H) if h not in prev]
    order = s[1, 1].argsort(descending=True).tolist()  # Strongest first
    print(f'run {r + 1}: block 1 previous-token heads {prev}, others {rest}')
    variants = {'none': model,
                'block 1, previous-token heads': ablate(model, 0, prev),
                'block 1, all other heads': ablate(model, 0, rest)}
    for k in range(1, H + 1):
        variants[f'block 2, top {k} induction'] = ablate(model, 1, order[:k])
    for name, variant in variants.items():
        table.setdefault(name, []).append(eval_copy(variant, x, L)[1:])
table['one-block model'] = [eval_copy(model_one, x, L)[1:]]
print(f'{"heads removed":<31}later-copy loss / accuracy: run 1, 2, 3')
for name, cols in table.items():
    print(f'{name:<31}'
          + ''.join(f'{rep:7.2f} /{acc:5.2f}' for rep, acc in cols))
run 1: block 1 previous-token heads [0, 1, 3], others [2]
run 2: block 1 previous-token heads [2], others [0, 1, 3]
run 3: block 1 previous-token heads [2, 3], others [0, 1]
heads removed                  later-copy loss / accuracy: run 1, 2, 3
none                              0.31 / 0.94   0.15 / 0.96   0.17 / 0.96
block 1, previous-token heads     4.64 / 0.07   3.71 / 0.09   3.80 / 0.17
block 1, all other heads          5.66 / 0.02   3.96 / 0.10   3.85 / 0.13
block 2, top 1 induction          0.63 / 0.92   0.56 / 0.91   1.65 / 0.70
block 2, top 2 induction          1.66 / 0.68   4.49 / 0.28   3.14 / 0.45
block 2, top 3 induction          3.38 / 0.24   5.68 / 0.06   3.88 / 0.23
block 2, top 4 induction          4.25 / 0.02   4.19 / 0.01   4.18 / 0.02
one-block model                   3.56 / 0.11
x, L = repeated_batch(d2l.get_key(), 256, 64, 64, 16, 32)
H, table = model_two.num_heads, {}  # Variant: (loss, accuracy) per run
for r, (model, s) in enumerate(zip(models_two, all_scores)):
    prev = [h for h in range(H) if s[0, 0, h] > 0.2]  # Previous-token heads
    rest = [h for h in range(H) if h not in prev]
    order = jnp.argsort(-s[1, 1]).tolist()  # Strongest first
    print(f'run {r + 1}: block 1 previous-token heads {prev}, others {rest}')
    variants = {'none': model,
                'block 1, previous-token heads': ablate(model, 0, prev),
                'block 1, all other heads': ablate(model, 0, rest)}
    for k in range(1, H + 1):
        variants[f'block 2, top {k} induction'] = ablate(model, 1, order[:k])
    for name, variant in variants.items():
        table.setdefault(name, []).append(eval_copy(variant, x, L)[1:])
table['one-block model'] = [eval_copy(model_one, x, L)[1:]]
print(f'{"heads removed":<31}later-copy loss / accuracy: run 1, 2, 3')
for name, cols in table.items():
    print(f'{name:<31}'
          + ''.join(f'{rep:7.2f} /{acc:5.2f}' for rep, acc in cols))
run 1: block 1 previous-token heads [1, 2, 3], others [0]
run 2: block 1 previous-token heads [1, 3], others [0, 2]
run 3: block 1 previous-token heads [1, 3], others [0, 2]
heads removed                  later-copy loss / accuracy: run 1, 2, 3
none                              0.32 / 0.93   0.42 / 0.90   0.32 / 0.94
block 1, previous-token heads     4.31 / 0.05   4.55 / 0.05   4.29 / 0.04
block 1, all other heads          4.98 / 0.02   5.02 / 0.06   5.23 / 0.03
block 2, top 1 induction          0.76 / 0.91   0.70 / 0.88   0.58 / 0.91
block 2, top 2 induction          1.76 / 0.69   1.78 / 0.68   1.46 / 0.73
block 2, top 3 induction          3.34 / 0.25   2.73 / 0.44   3.16 / 0.32
block 2, top 4 induction          4.24 / 0.01   4.31 / 0.02   4.28 / 0.02
one-block model                   3.59 / 0.11

消融第 1 块的前词元头使后续副本准确率骤降至不足 \(0.2\)(退回单块模型水平),证实其必要性。有趣的是,消融第 1 块的其余头同样会破坏检索:由于 copy_matrix 依赖第 1 块变换后的残差流(且在无规范化网络中置零消融会偏移流范数;关于均值消融见 5),第 2 块同样依赖这些头。在第 2 块中,四个头冗余分担归纳任务,必须同时消融多个头准确率才会跌回随机水平。

10.7.4 上下文学习

10.7.4.1 泛化至未见模式

由于存在 \(64^{16} \approx 8 \times 10^{28}\) 种可能模式,每条测试序列都是全新的,且整个训练分布上任意词元对均等概率出现。归纳电路仅凭上下文窗口中的单次接触,便在运行中即时将每个词元绑定到其后继——这正是上下文学习的一个极简实例:

x, L = repeated_batch(512, 64, 64, 24, 24, d2l.try_gpu())
with torch.inference_mode():
    acc = (model_two(x[:, :-1]).argmax(-1) == x[:, 1:]).float().mean(0)
d2l.plot([torch.arange(1, 64), [24, 24]], [acc.cpu(), [0, 1]],
         'target position', 'accuracy', fmts=('-', 'k:'))

x, L = repeated_batch(d2l.get_key(), 512, 64, 64, 24, 24)
acc = (model_two(x[:, :-1]).argmax(-1) == x[:, 1:]).mean(0)
d2l.plot([jnp.arange(1, 64), [24, 24]], [acc, [0, 1]],
         'target position', 'accuracy', fmts=('-', 'k:'))

准确率在第一份副本(以及内容匹配尚未见到重复词元的重启边界 \(t = 24\))处为 \(1/64\),到位置 \(25\) 跃升至约 \(0.8\),数个位置后突破 \(0.9\)。

重启后的剩余误差从何而来?当某词元在 \(L\) 词元模式中带着不同后继出现 \(K > 1\) 次时,仅凭当前词元匹配存在歧义:在 \(K\) 次出现中均匀挑选的成功率为 \(1/K\)。对 \(L = 24\) 与 \(p = 1/64\),某词元在模式内重复的概率为 \(1 - (63/64)^{23} \approx 0.30\),均匀单词元匹配预测的总体准确率为

\[ \mathbb{E}\left[\frac{1}{K}\right] = \frac{1 - (1 - p)^L}{L p} \approx 0.84, \qquad p = \frac{1}{64}, \]

而仅在重复词元上为 \(\approx 0.47\)。将测试位置按 \(K = 1\)(唯一)与 \(K > 1\)(重复)拆分可见,三次运行在唯一词元上均达到 \(0.97\) 以上,在重复词元上约达 \(0.7\)–\(0.9\),远超 \(0.47\) 的单词元基线。一个合理但此处未检验的解释是:模型同时匹配了更长的 \(n\) 元上下文并偏好特定 RoPE 偏移(2):

period, num_steps = 24, 64
x, _ = repeated_batch(512, num_steps, 64, period, period, d2l.try_gpu())
pattern = x[:, :period]
K = (pattern[:, :, None] == pattern[:, None, :]).sum(-1)  # Count in pattern
K = K[:, torch.arange(period, num_steps - 1) % period]  # Current token
parts = (K == 1, K > 1, K > 0)           # Unique, repeated, all
rows = {'share of targets': [p.float().mean() for p in parts],
        'single-token match': [(1 / K[p]).mean() for p in parts]}
for r, model in enumerate(models_two):
    with torch.inference_mode():
        hit = (model(x[:, :-1]).argmax(-1) == x[:, 1:])[:, period:]
    rows[f'run {r + 1} accuracy'] = [hit[p].float().mean() for p in parts]
print(f'{"current token":<18}   unique repeated      all')
for name, row in rows.items():
    print(f'{name:<18}' + ''.join(f'{v:9.2f}' for v in row))
current token        unique repeated      all
share of targets       0.69     0.31     1.00
single-token match     1.00     0.47     0.84
run 1 accuracy         0.99     0.80     0.93
run 2 accuracy         1.00     0.87     0.96
run 3 accuracy         1.00     0.85     0.95
period, num_steps = 24, 64
x, _ = repeated_batch(d2l.get_key(), 512, num_steps, 64, period, period)
pattern = x[:, :period]
K = (pattern[:, :, None] == pattern[:, None, :]).sum(-1)  # Count in pattern
K = K[:, jnp.arange(period, num_steps - 1) % period]  # Current token
parts = (K == 1, K > 1, K > 0)           # Unique, repeated, all
rows = {'share of targets': [p.mean() for p in parts],
        'single-token match': [(1 / K[p]).mean() for p in parts]}
for r, model in enumerate(models_two):
    hit = (model(x[:, :-1]).argmax(-1) == x[:, 1:])[:, period:]
    rows[f'run {r + 1} accuracy'] = [hit[p].mean() for p in parts]
print(f'{"current token":<18}   unique repeated      all')
for name, row in rows.items():
    print(f'{name:<18}' + ''.join(f'{v:9.2f}' for v in row))
current token        unique repeated      all
share of targets       0.70     0.30     1.00
single-token match     1.00     0.48     0.84
run 1 accuracy         0.99     0.81     0.93
run 2 accuracy         0.97     0.75     0.91
run 3 accuracy         0.99     0.81     0.94

10.7.4.2 更大模型中的归纳头

Olsson 等 (2022年) 表明,各种规模的语言模型在训练中都会经历一次陡峭相变以形成归纳头,且恰与通用上下文学习能力的涌现同步(8)。除复制与模糊模式补全外,注意力层还能在回归任务上实现上下文梯度下降步(7,(Oswald 等 2023年)),不过预训练语言模型是否真以此方式执行上下文学习仍有争论 (Shen 等 2024年)。

前文分析依托于无规范化且无多层感知机的模型,而真实的 Transformer 块(第 11 章)两者兼备。它们改变分析手法,却不改变核心思想。层规范化会按流自身范数重缩放残差流,因此从流到对数几率的映射唯有在固定该尺度后才呈线性;电路分析会将该尺度冻结在观测值上,其余处理照旧。多层感知机则增添了不经注意力模式的通路,某头的输出在被后续头读取前可能被多层感知机改写。最后,训练好的语言模型中的归纳头执行模糊匹配:它们能对仅相似而非完全相同的词元补全 \([\mathrm{A}^*][\mathrm{B}^*] \ldots [\mathrm{A}] \to [\mathrm{B}]\)。

10.7.5 作为解释的注意力权重

我们的探究表明,单凭注意力热力图不足以构成机制解释:

  • 重要头可能拥有平淡无奇的热力图:第 1 块的非前词元头在热力图中看似无所事事,消融它们却会破坏第 2 块的检索。
  • 锐利的热力图可能几乎毫无作用:在预训练语言模型中,空闲头常把大部分权重放在首个词元(注意力汇)上,而其 OV 向量的范数近乎为零 (Xiao 等 2024年; Gu 等 2025年)。

表 10.7.1 汇总了用于验证归纳电路的多层级证据体系。

表 10.7.1: 按层级划分的归纳头解释证据。
本节检验 证据层级 支持结论 遗留局限
后续副本损失 行为层 两块可解重复词元任务,单块不能 未定位具体组件
变更周期 输入干预 固定周期模型利用位置而非内容 同步改变了任务与输入
头得分 激活层 各头按预测偏移分配注意力 忽略了值变换
复制矩阵 权重与均值激活 第 2 块 OV 电路复制词元 不具备检索能力的模型中同样存在
头消融 组件干预 后续副本预测需要整个第 1 块(不仅前词元头)与第 2 块归纳头 置零会使残差流偏离训练分布

10.7.6 小结

每个注意力头通过两个秩至多为 \(d_h\) 的矩阵作用于残差流:决定关注位置的 QK 电路 \(\mathbf{W}_q^\top \mathbf{W}_k\),以及决定向目标位置写入何种向量的 OV 电路 \(\mathbf{W}_o \mathbf{W}_v\)。单层注意力可表达二元语法与跳三元语法(含单词元复制),而补全全新上下文模式 \([\mathrm{A}][\mathrm{B}] \ldots [\mathrm{A}] \to [\mathrm{B}]\) 至少需要两层,以便前词元头与匹配复制归纳头通过残差流组合。在变周期重复随机模式上训练时,两块模型经历陡峭相变并达到超过 \(90\%\) 的上下文准确率,而固定周期则会让单块模型钻脆弱的位置捷径。因此,在实践中确立一个头究竟计算了什么,必须综合注意力模式探针、OV 权重检查与因果头消融。

10.7.7 练习

  1. 绑定二元语法。在零块模型中,词元 \(a\) 之后出现词元 \(b\) 的对数几率为 \(\mathbf{e}_b^\top \mathbf{e}_a\),因此仅嵌入几何结构就决定了模型偏好的后继。当 \(\mathbf{e}_b^\top \mathbf{e}_a\) 为该行最大对数几率时称 \(b\) 为 \(a\) 的首选后继(假设无并列)。
    1. 证明若所有嵌入范数相等,每个词元的首选后继都是它自己。
    2. 去掉等范数假设。证明 \(b \neq a\) 成为 \(a\) 的首选后继仅当 \(\|\mathbf{e}_b\| > \|\mathbf{e}_a\|\),由此推出首选后继无法形成长度 \(k \geq 2\) 的环 \(a_1 \to a_2 \to \cdots \to a_k \to a_1\)。
    3. 设语料中字符 t 最常见的后继是 h,h 是 e,e 是空格,空格是 t。证明无论训练多久,没有任何零块模型能同时将这四者复现为首选后继。
    4. 在单块模型中,首位置的每个头只关注该位置自身。将此处的对数几率写为 \(\mathbf{E}\mathbf{M} \mathbf{e}_{x_0}\)(其中矩阵 \(\mathbf{M}\) 由 OV 电路构成),并解释为何前几问的两项约束均不再适用于 \(\mathbf{E}\mathbf{M}\mathbf{E}^\top\)。
  2. 穿过两块的路径。固定一个含 \(N\) 块、每块 \(H\) 头的模型在长度为 \(T\) 的序列上的注意力模式,记 \(\mathbf{A}^{\ell m}\) 为元素为 \(\alpha_{ij}^{\ell m}\) 的 \(T \times T\) 矩阵。
    1. 将 \(N = 2\) 时的 式 10.7.2 对数几率展开为路径项之和。证明穿过第 1 块头 \(m\) 与第 2 块头 \(m'\) 的路径等价于单个模式为 \(\mathbf{A}^{2m'}\mathbf{A}^{1m}\)、OV 电路为 \(\mathbf{W}_{\mathrm{OV}}^{2m'}\mathbf{W}_{\mathrm{OV}}^{1m}\) 的头,并给出该电路秩的上界。
    2. 统计 \(N\) 块的路径项数,并计算 model_two 的路径项数。
    3. 在训练好的模型中,第 2 块的注意力模式并不固定:它通过第 2 块的 QK 电路依赖 \(\mathbf{h}^{(1)}\)。将 \(\mathbf{h}_i^{(1)}\) 与 \(\mathbf{h}_j^{(1)}\) 代入 式 10.7.1 的得分中,按查询侧、键侧或两侧同时包含第 1 块头输出将各项分类。这些项分别称为 Q-组合 与 K-组合,第一问中的路径则称为 V-组合 (Elhage 等 2021年)。图 10.7.2 中的归纳电路依赖哪一种项?
    4. 证明当第 1 块包含关注偏移 \(-1\) 与 \(-2\) 的头时,两块模型能够匹配双词元前缀 \((x_{i-1}, x_i)\),并指明承担该匹配两半的各自组合项。
  3. [code] 无偏置时的捷径。10.7.2.2 节 中的固定偏移模型带有投影偏置。
    1. 设某头旋转前的查询与键在每个位置均为相同的常向量 \(\mathbf{q}\) 与 \(\mathbf{k}\)。利用 \(\mathbf{R}_i^\top \mathbf{R}_j = \mathbf{R}_{j-i}\) 证明得分仅依赖偏移 \(j - i\),并说明如何选取 \(\mathbf{q}\) 与 \(\mathbf{k}\) 使偏移 \(-31\) 处得分最大。
    2. 去掉偏置后,每个查询与键都是残差流的线性函数。词元嵌入必须包含什么,头才能生成近乎恒定的查询与键?
    3. 用 bias=False 将正文的单块模型训练三次,报告第二份副本准确率以及每个头在偏移 31 处的注意力权重。无偏置时这一捷径形成得有多可靠?它能通过周期 24 探针吗?
  4. 什么也不改变的权重。由 式 10.7.2,头在查询 \(i\) 处的输出为 \(\mathbf{W}_{\mathrm{OV}} \sum_j \alpha_{ij}\, \mathbf{h}_j\),而 softmax 使每个未掩码键上的权重 \(\alpha_{ij}\) 均严格为正。Jain 和 Wallace (2019年) 发现,在训练好的文本分类器中,迥然不同的注意力分布往往不改变预测,从而得出注意力权重不能解释预测的结论。
    1. 证明在 \(n\) 个键上给出与 \(\boldsymbol{\alpha}_i\) 相同头输出的注意力分布集合,在 \(\boldsymbol{\alpha}_i\) 附近包含一个维度至少为 \(n - 1 - d_h\) 的仿射子空间片。针对 model_two 的 63 词元输入的最后一个查询计算该下界。
    2. 第一问中的替代分布是逐输入构造的,正如 Jain 和 Wallace (2019年) 所做。Wiegreffe 和 Pinter (2019年) 指出,唯有单个训练好的模型在每个输入上都能产生此类替代分布且保持预测几乎不变,才构成对解释的反证。解释为何第一问的维度计数无法说明此类模型是否存在,并为 model_two 设计一个可判定此事的实验。
  5. [code] 置零消融与均值消融。10.7.3.3 节 的消融将头的输出置零。
    1. 解释为何置零 proj 中某头对应的列恰好移除了该头对残差流的贡献。移除一个第 1 块头后,哪些注意力模式保持不变、哪些可能改变?
    2. 训练中头的输出从不为零,因此置零会把残差流推入模型未见过的状态。均值消融改为用头 \(m\) 跨位置与序列的平均输出 \(\bar{\mathbf{o}}_m\) 替换其输出 \(\mathbf{o}_m\)。实现它:构建 bias=True 的 TinyCharLM,将 model_two 的权重复制进去(qkv 偏置置零),置零 proj 中头 \(m\) 的列,并将 proj 的偏置设为置零前这些列与 \(\bar{\mathbf{o}}_m\) 的乘积。重做正文中的消融实验:移除第 1 块的非前词元头是否仍会破坏检索?结果支持 10.7.3.3 节 中的哪一种解读?
    3. 单独移除第 2 块第二强的归纳头。将两次单头移除导致的后续副本损失增量之和,与两头同时移除时的损失增量对比。这一对比揭示了各头如何分担工作?
    4. 均值消融消除了 表 10.7.1 中的哪些局限,又留下了哪些?
  6. [code] 权重中的 K-组合。● 归纳头的匹配之所以有效,是因为第 2 块的 QK 电路读取了第 1 块 OV 电路写入残差流的信息。
    1. 对 model_two 中第 1 块头 \(m\) 与第 2 块头 \(m'\) 的每一对,计算 \(64 \times 64\) 矩阵 \[\mathbf{E}\, \mathbf{W}_{\mathrm{QK}}^{2m'}\, \mathbf{W}_{\mathrm{OV}}^{1m}\, \mathbf{E}^\top, \tag{10.7.5}\] 其元素 \((a, b)\) 将查询词元 \(a\) 与前驱为 \(b\) 的键打分。仿照 式 10.7.4 对复制的检验,测量最大元素位于对角线上的行占比。
    2. 与同一批第 2 块头的直接路径 \(\mathbf{E}\, \mathbf{W}_{\mathrm{QK}}^{2m'}\, \mathbf{E}^\top\) 对比。哪些头对承担了匹配任务?它们与 head_scores 基于注意力的得分是否吻合?
    3. 上述计算忽略了 RoPE 在 QK 电路内部施加的旋转。对固定偏移纳入相对旋转 \(\mathbf{R}_{j-i}\),检验在偏移 \(-23\) 处这样做是否会改变头对的排序。
  7. [code] 执行梯度步的注意力头。● 归纳头通过复制从上下文学习;模型也能从上下文的带标签样本中推断规则。设一条序列包含样本对 \((\mathbf{x}_i, y_i)\)(\(i = 1, \ldots, n\)),其中 \(\mathbf{x}_i \in \mathbb{R}^p\) 服从标准正态分布,\(y_i = \mathbf{w}^\top \mathbf{x}_i\)(每条序列独立重抽向量 \(\mathbf{w}\)),末尾接一个待预测标签的查询 \(\mathbf{x}_q\)。
    1. 证明从 \(\mathbf{w} = \mathbf{0}\) 出发、以学习率 \(\eta\) 在 \(\frac{1}{2}\sum_i (y_i - \mathbf{w}^\top \mathbf{x}_i)^2\) 上走一步梯度下降,预测结果为 \(\hat{y}_q = \eta \sum_i y_i\, \mathbf{x}_i^\top \mathbf{x}_q\)。将其解读为无 softmax 的注意力:什么充当查询、键与值?将其与 10.6 节 中特征映射 \(\phi(\mathbf{x}) = \mathbf{x}\) 的线性注意力对比。
    2. 为每个样本赋予词元 \(\mathbf{z}_i = [\mathbf{x}_i; y_i] \in \mathbb{R}^{p+1}\),为查询赋予词元 \(\mathbf{z}_q = [\mathbf{x}_q; 0]\)。为一个无 softmax 的头选取查询、键与值映射,使其在查询词元处的输出恰为 \(\hat{y}_q\)。为何查询词元同时关注自身并无大碍?实现该头并与梯度步核对。该头的权重依赖 \(\mathbf{w}\) 吗?
    3. 取 \(\eta = 1/n\),证明该步给出 \(\mathbf{w}_1 = \big(\frac{1}{n}\sum_i \mathbf{x}_i \mathbf{x}_i^\top\big) \mathbf{w}\),且 \(\mathbb{E}\,\|\mathbf{w}_1 - \mathbf{w}\|^2 = \frac{p+1}{n}\|\mathbf{w}\|^2\)。(提示:对标准正态 \(\mathbf{x}\),\(\mathbb{E}[(\mathbf{x}^\top \mathbf{w})^2 \|\mathbf{x}\|^2] = (p+2)\|\mathbf{w}\|^2\)。)由此得出结论:\(\hat{y}_q\) 相对于 \(y_q\) 方差的期望平方误差为 \((p+1)/n\)。
    4. 取 \(p = 8\),在 \(n = 10\)、100 与 1000 上跨 500 条序列测量相对误差,并与理论预测 \(9/n\) 对比。在 \(n = 10\) 处,该头与恒预测零相比如何?
  8. [extended] 文本中的归纳头。●● Olsson 等 (2022年) 将语言模型中归纳头的形成与上下文学习的陡峭增益联系起来,后者用上下文早期位置到晚期位置的损失降幅度量。在 10.4.5.2 节 的字节级模型上检验这一点。
    1. 在 10.4.5.2 节 的 WikiText-103 字节上,分 30 轮每轮 100 步 d2l.train_steps 训练 pos='rope' 的 d2l.TinyCharLM。每轮结束后记录两个量:一是用 head_scores 在文本词表上模式长度 16 至 32 的重复随机序列上算出的第 2 块各头最大归纳目标得分;二是上下文增益,即目标位置 0 至 15 的验证损失减去位置 96 至 127 的验证损失。
    2. 将两个量随训练步数的变化绘制在一起。归纳得分与上下文增益是否在同一窗口内攀升?
    3. 训练结束后,用 ablate 移除归纳得分最高的第 2 块头,重新测量上下文增益与验证损失。这些头承载了多大比例的增益?
    4. 重复随机序列除重复外别无结构,而真实文本以不规则距离重复词与短语。如果文本中不含任何重复单词,你的哪些结果会发生变化?为什么?

讨论