attention = d2l.MultiHeadAttention(num_hiddens=64, num_heads=4)
X = torch.randn(1, 8, 64)
perm = torch.randperm(8)
Y = attention(X, X, X)
Y_perm = attention(X[:, perm], X[:, perm], X[:, perm])
print(f'max |Y[perm] - Y_perm|: {(Y[:, perm] - Y_perm).abs().max():.2e}')10.4 位置信息
句子“dog bites man”与“man bites dog”包含完全相同的三个词。经过 10.3 节 的无掩码自注意力层后,它们只会按置换后的顺序产生完全相同的输出向量,因为注意力权重仅依赖词元内容。为了区分词序,必须向表征或打分规则中注入位置信息。
位置方案主要分为三大类:向每个词元嵌入加上位置向量 \(\mathbf{p}_i\)、按位置相关的角度旋转查询与键(旋转位置嵌入,RoPE),或从注意力得分中减去距离惩罚(ALiBi)。尽管三者在训练上下文长度内都能区分位置,但在要求外推至更长序列时表现大相径庭。我们首先形式化自注意力的置换对称性,随后在一个训练于长度 \(128\)、评估至长度 \(512\) 的两层纯注意力字节语言模型(TinyCharLM)上构建并对比五种位置方案。
10.4.1 置换等变性
设 \(\mathbf{X} \in \mathbb{R}^{n \times d}\) 存有 \(n\) 个词元向量,记 \(f(\mathbf{X}) = \mathrm{softmax}(\mathbf{S})\,\mathbf{X}\mathbf{W}_v\)(其中 \(\mathbf{S} = \mathbf{X}\mathbf{W}_q(\mathbf{X}\mathbf{W}_k)^\top/\sqrt{d_h}\))为关闭暂退法的无掩码自注意力(10.3 节)。重排 \(n\) 个词元对应从左侧给 \(\mathbf{X}\) 乘上一个 \(n \times n\) 置换矩阵 \(\boldsymbol{\Pi}\)。
命题(置换等变性):对任意置换矩阵 \(\boldsymbol{\Pi}\),均有 \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\)。
证明:由于线性投影逐行作用,对 \(\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v\) 均有 \((\boldsymbol{\Pi}\mathbf{X})\mathbf{W} = \boldsymbol{\Pi}(\mathbf{X}\mathbf{W})\)。得分矩阵变为 \(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top\)。因逐行 softmax 与行列置换可交换,\(\mathrm{softmax}(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top) = \boldsymbol{\Pi}\, \mathrm{softmax}(\mathbf{S})\, \boldsymbol{\Pi}^\top\)。右乘置换后的值 \(\boldsymbol{\Pi}\mathbf{X}\mathbf{W}_v\) 并利用 \(\boldsymbol{\Pi}^\top \boldsymbol{\Pi} = \mathbf{I}\),即得 \(\boldsymbol{\Pi} f(\mathbf{X})\)。拼接多头并逐行施加 \(\mathbf{W}_o\) 保持等变性。\(\blacksquare\)
下面在四头 MultiHeadAttention 层上数值验证置换等变性:
max |Y[perm] - Y_perm|: 1.08e-07
attention = d2l.MultiHeadAttention(num_hiddens=64, num_heads=4,
rngs=nnx.Rngs(d2l.get_key()))
key_X, key_perm = jax.random.split(d2l.get_key())
X = jax.random.normal(key_X, (1, 8, 64))
perm = jax.random.permutation(key_perm, 8)
Y = attention(X, X, X)
Y_perm = attention(X[:, perm], X[:, perm], X[:, perm])
print(f'max |Y[perm] - Y_perm|: {jnp.abs(Y[:, perm] - Y_perm).max():.2e}')max |Y[perm] - Y_perm|: 0.00e+00
堆叠等变层或逐词元多层感知机均保持等变性。不过注意,因果掩码会打破置换对称性,因为位置 \(i\) 关注 \(i+1\) 个前驱——下文的 NoPE 正是利用了这种不对称性。
10.4.2 绝对位置嵌入
原始 Transformer (Vaswani 等 2017年) 通过在输入端给每个词元嵌入 \(\mathbf{x}_i\) 加上位置向量 \(\mathbf{p}_i \in \mathbb{R}^d\)(\(\mathbf{P}\) 的第 \(i\) 行)来打破置换对称性:打乱词元会将 \(\mathbf{X} + \mathbf{P}\) 映为 \(\boldsymbol{\Pi}\mathbf{X} + \mathbf{P} \neq \boldsymbol{\Pi}(\mathbf{X} + \mathbf{P})\)。
10.4.2.1 学得的位置
BERT (Devlin 等 2018年) 与 GPT-2 (Radford 等 2019年) 等模型将 \(\mathbf{P} \in \mathbb{R}^{L_{\max} \times d}\) 视作可训练嵌入表,直到固定最大长度 \(L_{\max}\) 为止每个位置各占一行参数。由于超出训练上下文长度的行从未收到梯度,学得的位置表无法外推至未见过的位置。
10.4.2.2 正弦编码
为了在无学习参数的情况下为任意长度定义位置向量,Vaswani 等 (2017年) 以 \(d/2\) 个按几何级数排布的频率 \(\omega_m = 10000^{-2m/d}\) 的正弦与余弦填充 \(\mathbf{P}\) 的第 \(i\) 行:
\[ p_{i, 2m} = \sin\left(\frac{i}{10000^{2m/d}}\right), \qquad p_{i, 2m+1} = \cos\left(\frac{i}{10000^{2m/d}}\right). \tag{10.4.1}\]
随着 \(\omega_m\) 从每词元 \(1\) 弧度(\(m = 0\))递减至 \(10^{-4}\)(\(m = d/2 - 1\)),各列对充当二进制计数器的连续类比:低索引列高频振荡以区分相邻位置,高索引列则在广阔区域内缓慢变化。
def sinusoidal_encoding(max_len, num_hiddens):
"""The (max_len, num_hiddens) table of sinusoidal position codes."""
theta = torch.arange(max_len)[:, None] / 10000 ** (
torch.arange(0, num_hiddens, 2) / num_hiddens)
return torch.stack([torch.sin(theta), torch.cos(theta)],
-1).reshape(max_len, num_hiddens)
P = sinusoidal_encoding(60, 32)
d2l.plot(torch.arange(60), P[:, 6:10].T, xlabel='position',
figsize=(6, 2.5), legend=[f'column {d}' for d in range(6, 10)])def sinusoidal_encoding(max_len, num_hiddens):
"""The (max_len, num_hiddens) table of sinusoidal position codes."""
theta = jnp.arange(max_len)[:, None] / 10000 ** (
jnp.arange(0, num_hiddens, 2) / num_hiddens)
return jnp.stack([jnp.sin(theta), jnp.cos(theta)],
-1).reshape(max_len, num_hiddens)
P = sinusoidal_encoding(60, 32)
d2l.plot(jnp.arange(60), P[:, 6:10].T, xlabel='position',
figsize=(6, 2.5), legend=[f'column {d}' for d in range(6, 10)])将完整的 \(60 \times 32\) 编码矩阵 P 绘制成热力图,可见左侧快速振荡的高频对如何平滑过渡到右侧缓慢变化的低频对,恰似整数计数器的二进制各位:
d2l.show_heatmaps(P[None, None], xlabel='column (encoding dimension)',
ylabel='row (position)', figsize=(3.5, 4), cmap='Blues')d2l.show_heatmaps(P[None, None], xlabel='column (encoding dimension)',
ylabel='row (position)', figsize=(3.5, 4), cmap='Blues')10.4.2.3 作为旋转的正弦编码
由三角函数的和角恒等式,将位置 \(i\) 平移偏移量 \(\delta\) 等价于对每个频率对 \((2m, 2m+1)\) 施加一个仅依赖 \(\delta\) 的 \(2 \times 2\) 旋转:
\[ \begin{bmatrix} \cos(\delta \omega_m) & \sin(\delta \omega_m) \\ -\sin(\delta \omega_m) & \cos(\delta \omega_m) \end{bmatrix} \begin{bmatrix} p_{i, 2m} \\ p_{i, 2m+1} \end{bmatrix} = \begin{bmatrix} \sin\left((i+\delta) \omega_m\right) \\ \cos\left((i+\delta) \omega_m\right) \end{bmatrix} = \begin{bmatrix} p_{i+\delta, 2m} \\ p_{i+\delta, 2m+1} \end{bmatrix}. \tag{10.4.2}\]
然而,由于 \(\mathbf{p}_i\) 是加到 \(\mathbf{x}_i\) 上的,记 \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\),双线性注意力得分会展开为四项:
\[ \begin{aligned} (\mathbf{x}_i + \mathbf{p}_i)^\top \mathbf{A}\, (\mathbf{x}_j + \mathbf{p}_j) &= \underbrace{\mathbf{x}_i^\top \mathbf{A}\, \mathbf{x}_j}_{\textrm{content--content}} + \underbrace{\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j}_{\textrm{content--position}} \\ &\quad + \underbrace{\mathbf{p}_i^\top \mathbf{A}\, \mathbf{x}_j}_{\textrm{position--content}} + \underbrace{\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j}_{\textrm{position--position}}. \end{aligned} \tag{10.4.3}\]
两个交叉项将内容与绝对位置耦合在一起(当 \(i\) 与 \(j\) 同步平移时会变化),甚至连 \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) 也唯有当 \(\mathbf{A}\) 是由 \(2 \times 2\) 缩放旋转块构成的块对角矩阵时才纯粹依赖 \(j - i\)(2)。
10.4.3 旋转位置嵌入
旋转位置嵌入(RoPE)(Su 等 2024年) 以乘法方式对查询与键施加位置变换,使每个得分严格仅依赖相对偏移 \(j - i\):
\[ (\mathbf{R}_i \mathbf{q})^\top (\mathbf{R}_j \mathbf{k}) = \mathbf{q}^\top \mathbf{R}_i^\top \mathbf{R}_j \mathbf{k} = \mathbf{q}^\top \mathbf{R}_{j-i} \mathbf{k} \quad \textrm{for all } i, j. \tag{10.4.4}\]
要求 \(\mathbf{R}_i^\top \mathbf{R}_j = \mathbf{R}_{j-i}\) 且 \(\mathbf{R}_0\) 满秩会推出:(1) \(\mathbf{R}_0 = \mathbf{I}\)(由 \(\mathbf{R}_0^\top \mathbf{R}_0 = \mathbf{R}_0\));(2) \(\mathbf{R}_i^\top \mathbf{R}_i = \mathbf{I}\),因此每个 \(\mathbf{R}_i\) 都是正交且保范数的;(3) \(\mathbf{R}_{i+j} = \mathbf{R}_i \mathbf{R}_j\),从而 \(\mathbf{R}_i = \mathbf{R}_1^i\)。在恰当的标准正交基(可吸收进 \(\mathbf{W}_q, \mathbf{W}_k\))下,任意正交矩阵 \(\mathbf{R}_1\) 都分解为 \(2 \times 2\) 平面旋转。RoPE 将每个查询与键的 \(d_h\) 个坐标划分为 \(d_h/2\) 对,并在位置 \(i\) 处将第 \(m\) 对旋转 \(i\omega_m\),其中 \(\omega_m = 10000^{-2m/d_h}\)(图 10.4.1):
\[ \begin{aligned} \mathbf{R}_i &= \begin{bmatrix} R(i\omega_0) & & \\ & \ddots & \\ & & R(i\omega_{d_h/2-1}) \end{bmatrix}, \\ R(\alpha) &= \begin{bmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{bmatrix}. \end{aligned} \tag{10.4.5}\]
值向量不作旋转,确保层的输出对全局位置平移保持不变。RoPE 已成为现代开源权重语言模型的标准位置编码。
def rope_tables(n, d, offset=0, base=10000.0, scale=None,
device=None):
"""Cosines and sines, each (n, d/2), of the angles of the positions
offset, ..., offset + n - 1."""
pos = torch.arange(n, dtype=torch.float32, device=device) + offset
omega = base ** (-torch.arange(0, d, 2, device=device) / d)
if scale is not None: # One angle factor per pair, shape (d/2,)
omega = omega * scale
theta = pos[:, None] * omega[None, :]
return torch.cos(theta), torch.sin(theta)
def rope(x, offset=0, base=10000.0, scale=None, tables=None):
"""Rotate feature pairs of x (..., num_steps, d) by position angles;
tables from rope_tables take the place of offset, base, and scale."""
if tables is None:
tables = rope_tables(*x.shape[-2:], offset, base, scale, x.device)
# Angles in fp32, tables in the dtype of x: bf16 queries stay bf16
cos, sin = (u.to(x.dtype) for u in tables)
x1, x2 = x[..., 0::2], x[..., 1::2]
return torch.stack([x1 * cos - x2 * sin,
x1 * sin + x2 * cos], -1).flatten(-2)def rope_tables(n, d, offset=0, base=10000.0, scale=None):
"""Cosines and sines, each (n, d/2), of the angles of the positions
offset, ..., offset + n - 1."""
pos = jnp.arange(n, dtype=jnp.float32) + offset
omega = base ** (-jnp.arange(0, d, 2) / d)
if scale is not None: # One angle factor per pair, shape (d/2,)
omega = omega * scale
theta = pos[:, None] * omega[None, :]
return jnp.cos(theta), jnp.sin(theta)
def rope(x, offset=0, base=10000.0, scale=None, tables=None):
"""Rotate feature pairs of x (..., num_steps, d) by position angles;
tables from rope_tables take the place of offset, base, and scale."""
if tables is None:
tables = rope_tables(*x.shape[-2:], offset, base, scale)
# Angles in fp32, tables in the dtype of x: bf16 queries stay bf16
cos, sin = (u.astype(x.dtype) for u in tables)
x1, x2 = x[..., 0::2], x[..., 1::2]
return jnp.stack([x1 * cos - x2 * sin,
x1 * sin + x2 * cos], -1).reshape(x.shape)将所有位置平移任意偏移量后,RoPE 得分在 float32 舍入误差内完全不变,而加性正弦得分因 式 10.4.3 中的内容–位置交叉项而发生 \(O(1)\) 变化:
T, d = 32, 64
q, k = torch.randn(T, d), torch.randn(T, d)
scores = lambda off: rope(q, off) @ rope(k, off).T / math.sqrt(d)
for off in (1, 17, 480):
print(f'RoPE, all positions shifted by {off:>3}: max score change '
f'{(scores(off) - scores(0)).abs().max():.1e}')
P = sinusoidal_encoding(600, d)
added = lambda off: (q + P[off:off+T]) @ (k + P[off:off+T]).T / math.sqrt(d)
print(f'additive sinusoidal, shifted by 17: max score change '
f'{(added(17) - added(0)).abs().max():.1e}')RoPE, all positions shifted by 1: max score change 2.0e-06
RoPE, all positions shifted by 17: max score change 2.1e-06
RoPE, all positions shifted by 480: max score change 1.5e-05
additive sinusoidal, shifted by 17: max score change 2.7e+00
T, d = 32, 64
key_q, key_k = jax.random.split(d2l.get_key())
q, k = jax.random.normal(key_q, (T, d)), jax.random.normal(key_k, (T, d))
# Full float32 matmuls: GPU default (TF32) round-off would hide the check
dot = lambda a, b: jnp.matmul(a, b.T, precision='highest') / math.sqrt(d)
scores = lambda off: dot(rope(q, off), rope(k, off))
for off in (1, 17, 480):
print(f'RoPE, all positions shifted by {off:>3}: max score change '
f'{jnp.abs(scores(off) - scores(0)).max():.1e}')
P = sinusoidal_encoding(600, d)
added = lambda off: dot(q + P[off:off+T], k + P[off:off+T])
print(f'additive sinusoidal, shifted by 17: max score change '
f'{jnp.abs(added(17) - added(0)).max():.1e}')RoPE, all positions shifted by 1: max score change 2.1e-06
RoPE, all positions shifted by 17: max score change 2.1e-06
RoPE, all positions shifted by 480: max score change 1.9e-05
additive sinusoidal, shifted by 17: max score change 2.8e+00
10.4.4 距离惩罚与无位置编码
另外两种方案完全不改动词元、查询与键向量:
ALiBi(Attention with Linear Biases,(Press 等 2022年))直接从头 \(h \in \{1, \ldots, H\}\) 的因果注意力得分中减去线性距离惩罚:
\[ \mathrm{score}_{ij} = \frac{\mathbf{q}_i^\top \mathbf{k}_j}{\sqrt{d_h}} - m_h\,(i - j), \qquad m_h = 2^{-8h/H}. \tag{10.4.6}\]
几何斜率 \(m_h\)(例如 \(H = 4\) 时为 \(1/4, 1/16, 1/64, 1/256\))为不同头赋予不同的近因视界,且无需固定表长。
NoPE(No Positional Encoding,(Kazemnejad 等 2023年))完全不添加任何位置信号,仅依靠因果掩码(在位置 \(i\) 暴露 \(i + 1\) 个键)打破置换对称性。
10.4.5 超越训练长度的外推
为了对比这五种方案在分布内以及外推至更长上下文时的表现,我们在长度 \(L = 128\) 字节上训练,并在长度 \(128\)、\(256\) 与 \(512\) 上评估困惑度。
10.4.5.1 语言模型 TinyCharLM
TinyCharLM 将 256 个字节值嵌入到宽度 \(d = 128\),施加两个因果自注意力块(\(H = 4\) 个宽度为 \(d_h = 32\) 的头,不含多层感知机或规范化层,使位置信息仅经由 pos 进入),再通过绑定嵌入权重投影回字节对数几率 (Press 和 Wolf 2017年)。
class TinyCharLM(nn.Module):
"""Attention-only language model."""
def __init__(self, vocab_size, num_hiddens=128, num_heads=4, num_blks=2,
pos='rope', max_len=512, bias=False):
super().__init__()
assert pos in ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
self.num_heads, self.pos = num_heads, pos
self.token_emb = nn.Embedding(vocab_size, num_hiddens)
nn.init.normal_(self.token_emb.weight, std=0.02)
if pos == 'learned':
self.pos_emb = nn.Embedding(max_len, num_hiddens)
nn.init.normal_(self.pos_emb.weight, std=0.02)
if pos == 'sinusoidal':
self.register_buffer('P', sinusoidal_encoding(max_len,
num_hiddens))
if pos == 'rope': # Base and per-pair angle factors of the rotation
self.rope_base = 10000.0
self.register_buffer('rope_scale',
torch.ones(num_hiddens // num_heads // 2))
self.blks = nn.ModuleList([nn.ModuleDict(dict(
qkv=nn.Linear(num_hiddens, 3 * num_hiddens, bias=bias),
proj=nn.Linear(num_hiddens, num_hiddens, bias=bias)))
for _ in range(num_blks)])
def stream(self, X, num_blks=None):
"""Residual stream after the first num_blks blocks (default: all),
and the attention weights of those blocks."""
H, maps = self.embed(X), []
for blk in self.blks[:num_blks]:
out, weights = self.attend(blk, H)
H, maps = H + out, maps + [weights]
return H, maps
def forward(self, X):
return F.linear(self.stream(X)[0], self.token_emb.weight) # Tied
def attention_weights(self, X):
"""Per-block attention maps, each (batch, num_heads, T, T)."""
return self.stream(X)[1]class TinyCharLM(nnx.Module):
"""Attention-only language model."""
def __init__(self, vocab_size, num_hiddens=128, num_heads=4, num_blks=2,
pos='rope', max_len=512, bias=False, *, rngs):
assert pos in ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
self.num_heads, self.pos = num_heads, pos
init = nnx.initializers.normal(0.02)
self.token_emb = d2l.Embed(vocab_size, num_hiddens,
embedding_init=init, rngs=rngs)
if pos == 'learned':
self.pos_emb = nnx.Embed(max_len, num_hiddens,
embedding_init=init, rngs=rngs)
if pos == 'sinusoidal':
self.P = nnx.Cache(sinusoidal_encoding(max_len, num_hiddens))
if pos == 'rope': # Base and per-pair angle factors of the rotation
self.rope_base = 10000.0
self.rope_scale = nnx.Cache(
jnp.ones(num_hiddens // num_heads // 2))
self.blks = nnx.List([nnx.Dict(
qkv=d2l.Linear(num_hiddens, 3 * num_hiddens, use_bias=bias,
rngs=rngs),
proj=d2l.Linear(num_hiddens, num_hiddens, use_bias=bias,
rngs=rngs))
for _ in range(num_blks)])
def stream(self, X, num_blks=None):
"""Residual stream after the first num_blks blocks (default: all),
and the attention weights of those blocks."""
H, maps = self.embed(X), []
for blk in self.blks[:num_blks]:
out, weights = self.attend(blk, H)
H, maps = H + out, maps + [weights]
return H, maps
def __call__(self, X):
return self.token_emb.attend(self.stream(X)[0]) # Tied output head
def attention_weights(self, X):
"""Per-block attention maps, each (batch, num_heads, T, T)."""
return self.stream(X)[1]在 embed 中,正弦表按 \(1/\sqrt{d}\) 缩放,使其元素尺度与 \(\mathcal{N}(0, 0.02^2)\) 词元嵌入匹配,且不改变绑定输出对数几率:
@d2l.add_to_class(TinyCharLM)
def embed(self, X):
"""Token embeddings plus the absolute position code, if any."""
H = self.token_emb(X)
if self.pos == 'learned':
H = H + self.pos_emb(torch.arange(X.shape[1], device=X.device))
if self.pos == 'sinusoidal': # Table scaled to the token embeddings
H = H + self.P[:X.shape[1]] / math.sqrt(H.shape[-1])
return H@d2l.add_to_class(TinyCharLM)
def embed(self, X):
"""Token embeddings plus the absolute position code, if any."""
H = self.token_emb(X)
if self.pos == 'learned':
H = H + self.pos_emb(jnp.arange(X.shape[1]))
if self.pos == 'sinusoidal': # Table scaled to the token embeddings
H = H + self.P[:X.shape[1]] / math.sqrt(H.shape[-1])
return H在 attend 中,RoPE 旋转查询与键,而 ALiBi 向 softmax 前得分加上距离偏置 \(-m_h(i - j)\):
@d2l.add_to_class(TinyCharLM)
def alibi(self, T, device):
"""ALiBi bias -m_h (i - j) of every head, (num_heads, T, T)."""
h = torch.arange(1, self.num_heads + 1, device=device)
slopes = 2.0 ** (-8.0 * h / self.num_heads)
pos = torch.arange(T, device=device, dtype=torch.float32)
return slopes[:, None, None] * (pos[None, :] - pos[:, None])
@d2l.add_to_class(TinyCharLM)
def attend(self, blk, H):
"""Output of attention block blk on the stream H, and its weights."""
B, T, D = H.shape
q, k, v = blk['qkv'](H).chunk(3, -1)
q, k, v = (u.reshape(B, T, self.num_heads, -1).transpose(1, 2)
for u in (q, k, v))
if self.pos == 'rope':
q = rope(q, base=self.rope_base, scale=self.rope_scale)
k = rope(k, base=self.rope_base, scale=self.rope_scale)
scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
if self.pos == 'alibi':
scores = scores + self.alibi(T, H.device)
weights = d2l.masked_softmax(scores, d2l.causal_mask(T, device=H.device))
out = (weights @ v).transpose(1, 2).reshape(B, T, D)
return blk['proj'](out), weights@d2l.add_to_class(TinyCharLM)
def alibi(self, T):
"""ALiBi bias -m_h (i - j) of every head, (num_heads, T, T)."""
h = jnp.arange(1, self.num_heads + 1)
slopes = 2.0 ** (-8.0 * h / self.num_heads)
pos = jnp.arange(T, dtype=jnp.float32)
return slopes[:, None, None] * (pos[None, :] - pos[:, None])
@d2l.add_to_class(TinyCharLM)
def attend(self, blk, H):
"""Output of attention block blk on the stream H, and its weights."""
B, T, D = H.shape
q, k, v = jnp.split(blk['qkv'](H), 3, axis=-1)
q, k, v = (u.reshape(B, T, self.num_heads, -1).swapaxes(1, 2)
for u in (q, k, v))
if self.pos == 'rope':
q = rope(q, base=self.rope_base, scale=self.rope_scale[...])
k = rope(k, base=self.rope_base, scale=self.rope_scale[...])
scores = q @ k.swapaxes(-2, -1) / math.sqrt(q.shape[-1])
if self.pos == 'alibi':
scores = scores + self.alibi(T)
weights = d2l.masked_softmax(scores, d2l.causal_mask(T))
out = (weights @ v).swapaxes(1, 2).reshape(B, T, D)
return blk['proj'](out), weights10.4.5.2 实验
我们在 d2l.WikiText103(9.3.1 节)的 128 字节窗口上,为每种方案用三个种子各训练 \(3{,}000\) 步 AdamW。
data = d2l.WikiText103(batch_size=64, num_steps=128)
schemes = ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
def train_tiny(**kwargs):
"""A TinyCharLM after 3000 steps, and its final training loss."""
model = TinyCharLM(len(data.vocab), **kwargs)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3,
weight_decay=0.0)
return model, d2l.final_loss(d2l.train_steps(model, data, optimizer,
3000))
runs = {} # Three independently initialized models per scheme
for pos in schemes:
trained = [train_tiny(pos=pos) for _ in range(3)]
runs[pos] = [model for model, _ in trained]
print(f'{pos:>10}: final training loss '
+ ', '.join(f'{loss:.2f}' for _, loss in trained))
models = {pos: ms[0] for pos, ms in runs.items()} # The first run of each learned: final training loss 2.28, 2.27, 2.26
sinusoidal: final training loss 2.26, 2.28, 2.29
rope: final training loss 2.02, 2.00, 1.99
alibi: final training loss 2.31, 2.29, 2.31
none: final training loss 2.45, 2.46, 2.47
data = d2l.WikiText103(batch_size=64, num_steps=128)
schemes = ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
def train_tiny(**kwargs):
"""A TinyCharLM after 3000 steps, and its final training loss."""
model = TinyCharLM(len(data.vocab), **kwargs,
rngs=nnx.Rngs(d2l.get_key()))
optimizer = nnx.Optimizer(model, optax.adamw(1e-3, weight_decay=0.0),
wrt=nnx.Param)
return model, d2l.final_loss(d2l.train_steps(model, data, optimizer,
3000))
runs = {} # Three independently initialized models per scheme
for pos in schemes:
trained = [train_tiny(pos=pos) for _ in range(3)]
runs[pos] = [model for model, _ in trained]
print(f'{pos:>10}: final training loss '
+ ', '.join(f'{loss:.2f}' for _, loss in trained))
models = {pos: ms[0] for pos, ms in runs.items()} # The first run of each learned: final training loss 2.26, 2.26, 2.29
sinusoidal: final training loss 2.34, 2.22, 2.32
rope: final training loss 2.00, 2.02, 1.98
alibi: final training loss 2.29, 2.30, 2.31
none: final training loss 2.47, 2.45, 2.47
我们在重新分组为 \(n \in \{128, 256, 512\}\) 窗口的同一批验证字节上评估验证困惑度,并与闭式字节二元语法基线对比。
train_len, batch = data.num_steps, 16
contexts = (train_len, 2 * train_len, 4 * train_len)
block = batch * max(contexts) # Whole minibatches at every context
num_bytes = (len(data.val) - 1) // block * block
X, Y = data.windows(data.val, range(0, num_bytes, train_len))
eval_sets = {}
for n in contexts: # The same bytes, regrouped into windows of n
Xn, Yn = X.reshape(-1, n), Y.reshape(-1, n)
eval_sets[n] = [(Xn[i:i + batch], Yn[i:i + batch])
for i in range(0, len(Xn), batch)]
def perplexities(model):
return [d2l.lm_perplexity(model, eval_sets[n]) for n in contexts]
def mean_range(values):
"""Mean and (min-max) of the runs, one column of the table."""
return f'{np.mean(values):5.1f} ({min(values):.1f}-{max(values):.1f})'
ppls = {pos: [perplexities(model) for model in ms] for pos, ms in runs.items()}
print(f'{num_bytes:,} validation bytes, mean (min-max) of three runs')
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for pos in schemes: # zip(*...) turns runs x contexts into contexts x runs
print(f'{pos:>10}: '
+ ''.join(f'{mean_range(col):>18}' for col in zip(*ppls[pos])))1,138,688 validation bytes, mean (min-max) of three runs
context: 128 256 512
learned: 9.6 (9.5-9.7) 15.3 (14.9-15.8) 19.7 (18.7-21.1)
sinusoidal: 9.7 (9.4-9.9) 12.8 (12.5-13.3) 15.3 (14.7-15.9)
rope: 7.3 (7.2-7.4) 11.8 (10.5-13.6) 27.0 (18.4-35.5)
alibi: 9.9 (9.8-10.0) 9.9 (9.8-10.0) 9.9 (9.7-9.9)
none: 11.6 (11.5-11.7) 11.7 (11.6-11.8) 11.8 (11.8-11.8)
train_len, batch = data.num_steps, 16
contexts = (train_len, 2 * train_len, 4 * train_len)
block = batch * max(contexts) # Whole minibatches at every context
num_bytes = (len(data.val) - 1) // block * block
X, Y = data.windows(data.val, range(0, num_bytes, train_len))
eval_sets = {}
for n in contexts: # The same bytes, regrouped into windows of n
Xn, Yn = X.reshape(-1, n), Y.reshape(-1, n)
eval_sets[n] = [(Xn[i:i + batch], Yn[i:i + batch])
for i in range(0, len(Xn), batch)]
def perplexities(model):
return [d2l.lm_perplexity(model, eval_sets[n]) for n in contexts]
def mean_range(values):
"""Mean and (min-max) of the runs, one column of the table."""
return f'{np.mean(values):5.1f} ({min(values):.1f}-{max(values):.1f})'
ppls = {pos: [perplexities(model) for model in ms] for pos, ms in runs.items()}
print(f'{num_bytes:,} validation bytes, mean (min-max) of three runs')
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for pos in schemes: # zip(*...) turns runs x contexts into contexts x runs
print(f'{pos:>10}: '
+ ''.join(f'{mean_range(col):>18}' for col in zip(*ppls[pos])))1,138,688 validation bytes, mean (min-max) of three runs
context: 128 256 512
learned: 9.6 (9.4-9.7) 18.0 (15.3-20.7) 25.4 (19.8-31.8)
sinusoidal: 9.8 (9.1-10.3) 12.9 (12.4-13.4) 15.7 (14.3-16.5)
rope: 7.3 (7.2-7.4) 12.4 (12.2-12.7) 27.4 (27.0-28.0)
alibi: 10.0 (9.9-10.0) 9.9 (9.8-10.0) 9.9 (9.8-9.9)
none: 11.7 (11.6-11.7) 11.8 (11.8-11.8) 11.9 (11.9-11.9)
为锚定这些数值,我们基于训练语料上经拉普拉斯平滑的经验转移计数,在同一批验证窗口上计算精确的字节级二元语法困惑度:
V = len(data.vocab)
counts = np.ones((V, V)) # Byte pair counts, plus one for unseen pairs
for s in range(0, len(data.train) - 1, 10**7): # Chunks of 10^7 bytes
a = data.train[s:s + 10**7 + 1].astype(np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V).reshape(V, V)
bigram = counts / counts.sum(1, keepdims=True) # P(next byte | this byte)
x, y = np.asarray(X).reshape(-1), np.asarray(Y).reshape(-1)
print(f'byte bigram: perplexity {np.exp(-np.log(bigram[x, y]).mean()):.1f}')byte bigram: perplexity 11.6
V = len(data.vocab)
counts = np.ones((V, V)) # Byte pair counts, plus one for unseen pairs
for s in range(0, len(data.train) - 1, 10**7): # Chunks of 10^7 bytes
a = data.train[s:s + 10**7 + 1].astype(np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V).reshape(V, V)
bigram = counts / counts.sum(1, keepdims=True) # P(next byte | this byte)
x, y = np.asarray(X).reshape(-1), np.asarray(Y).reshape(-1)
print(f'byte bigram: perplexity {np.exp(-np.log(bigram[x, y]).mean()):.1f}')byte bigram: perplexity 11.6
在训练长度(\(n = 128\))处,RoPE 取得最低困惑度(\(7.3\)),领先学得位置(\(9.6\))、正弦编码(\(9.7\)–\(9.8\))与 ALiBi(\(9.9\)–\(10.0\)),四者均优于字节二元语法基线(\(11.6\));而 NoPE 在这个小型两块模型上停留在二元语法水平。
在 \(n = 512\) 处,表征遇到越界值的三种方案均急剧退化:学得嵌入命中未训练行(\(128\)–\(511\)),正弦慢频列取到未见过的值,RoPE 的低频对旋转到训练中从未见过的角度。ALiBi 的困惑度则平稳保持在 \(9.9\)。为了查明原因,我们测量 ALiBi 四个头落在距离 \(\ge 128\) 的键上的注意力权重占比,并与硬屏蔽所有距离 \(\ge 128\) 的键作对比:
alibi_model, T = models['alibi'], max(contexts)
device = next(alibi_model.parameters()).device
X_eval = eval_sets[T][0][0].to(device) # 16 windows of 512 bytes
i = torch.arange(T, device=device)
far = i[:, None] - i[None, :] >= train_len # Offsets never trained on
def far_weight(weights):
"""Per head: mean weight on far keys, over queries from train_len on."""
return (weights * far).sum(-1)[..., train_len:].mean((0, -1)).tolist()
with torch.inference_mode():
maps = alibi_model.attention_weights(X_eval)
bias_only = d2l.masked_softmax(alibi_model.alibi(T, device)[None],
d2l.causal_mask(T, device=device))
print(f'{"head":>10}: ' + ''.join(f'{h:>9}' for h in range(1, 5)))
for name, weights in [('bias alone', bias_only)] + [
(f'block {b}', w) for b, w in enumerate(maps, 1)]:
print(f'{name:>10}: ' + ''.join(f'{w:9.3f}' for w in far_weight(weights))) head: 1 2 3 4
bias alone: 0.000 0.000 0.115 0.401
block 1: 0.000 0.000 0.115 0.400
block 2: 0.000 0.000 0.111 0.395
alibi_model, T = models['alibi'], max(contexts)
X_eval = eval_sets[T][0][0] # 16 windows of 512 bytes
i = jnp.arange(T)
far = i[:, None] - i[None, :] >= train_len # Offsets never trained on
def far_weight(weights):
"""Per head: mean weight on far keys, over queries from train_len on."""
return (weights * far).sum(-1)[..., train_len:].mean((0, -1)).tolist()
maps = alibi_model.attention_weights(X_eval)
bias_only = d2l.masked_softmax(alibi_model.alibi(T)[None], d2l.causal_mask(T))
print(f'{"head":>10}: ' + ''.join(f'{h:>9}' for h in range(1, 5)))
for name, weights in [('bias alone', bias_only)] + [
(f'block {b}', w) for b, w in enumerate(maps, 1)]:
print(f'{name:>10}: ' + ''.join(f'{w:9.3f}' for w in far_weight(weights))) head: 1 2 3 4
bias alone: 0.000 0.000 0.115 0.401
block 1: 0.000 0.000 0.115 0.401
block 2: 0.000 0.001 0.119 0.390
我们通过 WindowedALiBi 直接证实这一点:它复制训练好的 ALiBi 权重,并在长度 \(T = 512\) 上评估时硬屏蔽所有距离 \(\ge 128\) 的键(window=train_len):
class WindowedALiBi(TinyCharLM):
"""ALiBi whose queries see only the window most recent keys."""
def __init__(self, *args, window, **kwargs):
super().__init__(*args, **kwargs)
self.window = window
def alibi(self, T, device):
i = torch.arange(T, device=device)
return super().alibi(T, device).masked_fill(
i[:, None] - i[None, :] >= self.window, -math.inf)
full, windowed = [], []
for model in runs['alibi']:
model_w = WindowedALiBi(len(data.vocab), pos='alibi',
window=train_len).to(device)
model_w.load_state_dict(model.state_dict()) # Same trained weights
full.append(d2l.lm_perplexity(model, eval_sets[T]))
windowed.append(d2l.lm_perplexity(model_w, eval_sets[T]))
for name, ppl in ('all keys', full), (f'keys < {train_len} back', windowed):
print(f'{name:>16}: perplexity at {T} {mean_range(ppl)}') all keys: perplexity at 512 9.9 (9.7-9.9)
keys < 128 back: perplexity at 512 9.9 (9.7-9.9)
class WindowedALiBi(TinyCharLM):
"""ALiBi whose queries see only the window most recent keys."""
def __init__(self, *args, window, **kwargs):
super().__init__(*args, **kwargs)
self.window = window
def alibi(self, T):
i = jnp.arange(T)
return jnp.where(i[:, None] - i[None, :] >= self.window, -jnp.inf,
super().alibi(T))
full, windowed = [], []
for model in runs['alibi']:
model_w = WindowedALiBi(len(data.vocab), pos='alibi', window=train_len,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(model_w, nnx.state(model)) # Same trained weights
full.append(d2l.lm_perplexity(model, eval_sets[T]))
windowed.append(d2l.lm_perplexity(model_w, eval_sets[T]))
for name, ppl in ('all keys', full), (f'keys < {train_len} back', windowed):
print(f'{name:>16}: perplexity at {T} {mean_range(ppl)}') all keys: perplexity at 512 9.9 (9.8-9.9)
keys < 128 back: perplexity at 512 9.9 (9.8-9.9)
移除所有距离 \(\ge 128\) 的键后,ALiBi 的困惑度丝毫未变:陡峭头本就忽略远距键,缓和头则计算宽近因加权平均,从 128 之外的字节中毫无收获。由此可见,平坦的外推曲线说明方案在远距键上没有崩溃,而未必说明它从中提取了长程信息。
10.4.5.3 扩展已训练模型的上下文
RoPE 为何在训练长度 \(L = 128\) 之外失效,又该如何修复?对头宽度 \(d_h = 32\),\(16\) 个坐标对的周期为 \(2\pi / \omega_m = 2\pi \cdot 10000^{m/16}\)。前 \(6\) 个快频对周期 \(\le 112 < 128\),在训练窗口内早已转完完整圆周;其余 \(10\) 个慢频对周期从 \(199\) 到 \(35{,}000\),在 \(n = 512\) 处会转入未曾见过的角度区域。
位置插值 (Chen 等 2023年) 将所有角度按 \(128 / 512 = 1/4\) 缩放,把新上下文范围映射回已训练区间 \([0, 128)\)。但未经微调就缩放快频对会破坏区分相邻字节所需的局部相位差。保持快频对不变而仅缩放慢频对——正是 YaRN (Peng 等 2024年) 与 NTK 感知缩放(增大基频 \(b \mapsto b\, s^{d_h/(d_h - 2)}\))的核心思想——无需任何训练开销即可挽回绝大部分外推困惑度:
rope_model = models['rope']
d_head = 2 * rope_model.rope_scale.numel()
periods = (2 * math.pi
* rope_model.rope_base ** (torch.arange(0, d_head, 2) / d_head))
slow = periods > train_len
print(f'{int(slow.sum())} of {d_head // 2} pairs have periods above '
f'{train_len}')
ones = torch.ones(d_head // 2)
shrink = train_len / max(contexts) # Longest context into the trained one
factors = {'unscaled': ones, 'all pairs': ones * shrink,
'slow pairs': torch.where(slow, ones * shrink, ones)}
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for name, factor in factors.items(): # Each of the three trained RoPE runs
ppl = []
for rope_model in runs['rope']:
rope_model.rope_scale.copy_(factor)
ppl.append(perplexities(rope_model))
rope_model.rope_scale.copy_(ones)
print(f'{name:>10}: ' + ''.join(f'{mean_range(col):>18}'
for col in zip(*ppl)))10 of 16 pairs have periods above 128
context: 128 256 512
unscaled: 7.3 (7.2-7.4) 11.8 (10.5-13.6) 27.0 (18.4-35.5)
all pairs: 40.5 (37.9-43.4) 40.7 (38.2-43.6) 40.8 (38.3-43.7)
slow pairs: 8.0 (7.8-8.2) 8.5 (8.2-8.7) 8.8 (8.5-9.1)
rope_model = models['rope']
d_head = 2 * rope_model.rope_scale.shape[0]
periods = (2 * math.pi
* rope_model.rope_base ** (jnp.arange(0, d_head, 2) / d_head))
slow = periods > train_len
print(f'{int(slow.sum())} of {d_head // 2} pairs have periods above '
f'{train_len}')
ones = jnp.ones(d_head // 2)
shrink = train_len / max(contexts) # Longest context into the trained one
factors = {'unscaled': ones, 'all pairs': ones * shrink,
'slow pairs': jnp.where(slow, ones * shrink, ones)}
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for name, factor in factors.items(): # Each of the three trained RoPE runs
ppl = []
for rope_model in runs['rope']:
rope_model.rope_scale[...] = factor
ppl.append(perplexities(rope_model))
rope_model.rope_scale[...] = ones
print(f'{name:>10}: ' + ''.join(f'{mean_range(col):>18}'
for col in zip(*ppl)))10 of 16 pairs have periods above 128
context: 128 256 512
unscaled: 7.3 (7.2-7.4) 12.4 (12.2-12.7) 27.4 (27.0-28.0)
all pairs: 39.7 (33.3-50.6) 40.1 (33.6-51.2) 40.2 (33.7-51.4)
slow pairs: 8.1 (7.9-8.5) 8.7 (8.3-9.5) 9.1 (8.6-10.1)
仅重缩放慢频对就能在不更新任何权重的情况下,将长度 512 的困惑度从约 \(27\) 降至约 \(9\),随后在目标长度上短暂微调即可消除剩余差距(6)。
10.4.6 小结
无掩码自注意力具有置换等变性,对任意词元置换 \(\boldsymbol{\Pi}\) 均满足 \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\)。加性位置嵌入(学得或正弦)在输入端打破了这种对称性,却引入与绝对索引绑定的内容–位置交叉项,且在超出训练长度时退化。要求注意力得分严格仅依赖相对偏移 \(j - i\) 迫使查询与键采用正交平面旋转(RoPE),而 ALiBi 则减去逐头线性距离惩罚 \(-m_h(i - j)\)。在训练窗口之外,RoPE 的退化专门发生在波长超过训练长度的低频坐标对上;选择性插值这些慢频对同时保持高频对不变,即可恢复长上下文性能。
10.4.7 练习
- 不同位置,不同编码。设 \(\mathbf{p}_i\) 为宽度 \(d\)、频率 \(\omega_m = 1/10000^{2m/d}\) 的正弦表 式 10.4.1 的第 \(i\) 行。
- 证明 \[\mathbf{p}_i^\top \mathbf{p}_{i+\delta} = \sum_{m=0}^{d/2-1} \cos(\delta\,\omega_m),\] 据此推导 \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|^2\),并得出结论:两者均仅依赖偏移量 \(\delta\)。
- 由此推出,\(\mathbf{p}_i = \mathbf{p}_{i'}\) 当且仅当对每个 \(m\) 均有 \((i - i')\,\omega_m\) 为 \(2\pi\) 的整数倍,因此无论
max_len取何值,任意两个不同的整数位置都不会共享同一行。 - 最快对的周期为 \(2\pi\),因此在接近 \(2\pi\) 倍数的整数偏移处会近似重复。找出满足 \(\delta < 512\) 且其角度最接近 \(2\pi\) 倍数的偏移,并给出残余角度。对 \(d = 32\),将该偏移处的 \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|\) 与 \(\delta = 1\) 处的值对比,指出哪些频率对拉开了这两个近似重复位置,并将答案与 10.4.2.2 节 中的二进制计数联系起来。
- 得分中的加性编码。采用 10.4.2.2 节 的加性编码时,首层注意力头按 式 10.4.3 的四项对位置 \(i\) 与 \(j\) 的输入打分,其中 \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\)。
- 设 \(\mathbf{J}\) 为平面逆时针旋转 \(\pi/2\) 的矩阵。利用 式 10.4.2 证明:当 \(\mathbf{A}\) 是由每频率对一个 \(2 \times 2\) 块 \(a_m \mathbf{I} + b_m \mathbf{J}\) 构成的块对角矩阵时,位置–位置项 \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) 仅依赖 \(j - i\)。1 处理的是 \(\mathbf{A} = \mathbf{I}\) 的情形。接着证明,只要 \(\mathbf{A}\) 中存在单个耦合两个不同频率对的非零元素,该性质就会被破坏。
- 确定内容–位置项 \(\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j\) 在 \(j\) 任意平移下保持不变的条件。据此解释 10.4.3 节 平移测试中加性编码的得分变化,以及为何 RoPE 不存在内容–位置项。
- [code] 外推在何处失效。10.4.5.2 节 中上下文长度 512 处的困惑度是对每条序列所有位置的损失取平均。
- 数值验证五种模型各自在长度 512 序列的位置 0 到 127 处的对数几率,在浮点舍入误差内与仅由其前 128 个词元算出的对数几率完全一致。
TinyCharLM的哪两条性质对每种方案都保证了这一点? - 计算五种模型在长度 512 序列每个位置上的验证损失,按每 16 个位置窗口取平均并绘制损失随位置的变化曲线。对每种方案,曲线在何处偏离位置 128 以下的水平?损失是在位置 128 处跳变还是逐步增长?
- 通过在重写
attend的子类中为因果掩码添加带状约束,将models['rope']的每个查询限制在最近的 128 个键(含自身),复制训练好的权重并重复测量。将位置 128 之后的窗口化曲线与 128 之前的无窗口曲线对比。超过 127 的偏移是否解释了 RoPE 在上下文 512 处的退化?
- 数值验证五种模型各自在长度 512 序列的位置 0 到 127 处的对数几率,在浮点舍入误差内与仅由其前 128 个词元算出的对数几率完全一致。
- 保持对称性的偏置。● 设在 softmax 之前向证明中的得分矩阵 \(\mathbf{S}\) 加上固定矩阵 \(\mathbf{B} \in \mathbb{R}^{n \times n}\),使自注意力层(10.3 节)计算 \(\mathrm{softmax}(\mathbf{S} + \mathbf{B})\, \mathbf{X}\mathbf{W}_v\)。
- 证明对任意满足 \(\boldsymbol{\Pi}^\top \mathbf{B} \boldsymbol{\Pi} = \mathbf{B}\) 的置换矩阵 \(\boldsymbol{\Pi}\),置换等变性命题依然成立。
- 找出对所有置换都满足该条件的全部矩阵 \(\mathbf{B}\),并描述每一种如何改变注意力权重。
- 去掉因果掩码后,式 10.4.6 的 ALiBi 偏置对称扩展为 \(B_{ij} = -m_h\,|i - j|\)。确定保持该矩阵不变的置换,并说明这对仅接收该偏置而无其他位置信号的无掩码层意味着什么。解释为何 式 10.4.6 中的因果 ALiBi 不具备这种对称性。
- RoPE 中的偏移偏好。● 将查询 \(\mathbf{q}\) 与键 \(\mathbf{k}\) 拆分为 式 10.4.5 作用的 \(d_h/2\) 个二维对 \(\mathbf{q}^{(m)}, \mathbf{k}^{(m)} \in \mathbb{R}^2\),记 \(\delta = j - i\) 为键位置 \(j\) 相对查询位置 \(i\) 的偏移。
- 证明 RoPE 得分 式 10.4.4 等于 \[\sum_{m=0}^{d_h/2-1} \|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\| \cos(\delta\,\omega_m - \psi_m), \tag{10.4.7}\] 其中 \(\psi_m\) 为从 \(\mathbf{k}^{(m)}\) 到 \(\mathbf{q}^{(m)}\) 的夹角(即 图 10.4.1 中的 \(\varphi\) 取反号)。
- 选择角度 \(\psi_m\) 使每一对都在偏移 \(\delta = -1\)(前一词元)处达到最大值。设所有乘积 \(\|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\|\) 均等于 \(c\),证明作为 \(\delta\) 的函数,该得分等于宽度为 \(d_h\) 的正弦表在 1 中的点积 \(\mathbf{p}_i^\top \mathbf{p}_{i+\delta}\) 平移后的 \(c\) 倍。
- 取 \(d_h = 32\) 与位置 127 处的查询(关注偏移 \(\delta = -127, \ldots, 0\))。令注意力对数几率等于上述得分(因子 \(1/\sqrt{d_h}\) 吸收进 \(c\))。找出使偏移 \(-1\) 获得一半 softmax 权重的 \(c\),并辨明与它竞争最激烈的偏移。哪些频率对决定了 \(-1\) 处得分与其近邻得分之间的差距?
- [extended] 位置插值。● 10.4.5.3 节 的最后一个代码单元在不做任何训练的情况下重缩放了已训练 RoPE 模型的角度。本题解释该结果,补充 NTK 感知缩放的基频变更,并用微调补全方案。
- 证明在训练偏移 0 到 127 内完成整周旋转的频率对,在模 \(2\pi\) 意义下早已以不超过 \(\omega_m/2\) 的误差遇到过任意更长偏移产生的所有角度。对 \(d_h = 32\),分别计算重缩放前、按 \(128/512\) 均匀重缩放后以及仅重缩放周期大于 128 位置的频率对后,5 中偏移 \(-1\) 处得分与其近邻得分之差,并将结果与代码单元中上下文 128 处的困惑度联系起来。
- 证明基频 \(b' = b\, s^{d_h/(d_h-2)}\) 保持 \(\omega_0\) 不变并将 \(\omega_{d_h/2-1}\) 除以 \(s\)。针对 \(s = 4\) 将
models['rope']的rope_base设为该基频,不经训练直接在 128、256 与 512 上评估,并与代码单元中的两种重缩放对比。 - 分别从训练好的
models['rope']副本出发,采用代码单元中的两种重缩放方案,在d2l.WikiText103(batch_size=16, num_steps=512)上以长度 512 微调几百步。重新在 128、256 与 512 上评估,并与未缩放模型以及 10.4.5.2 节 中的 ALiBi 模型在相同长度下对比。