10.4  位置情報

“dog bites man” と “man bites dog” という 2 つの文は、同じ 3 つの単語からなっている。これらを 10.3 節 のマスクなし自己アテンション層に通すと、順序が入れ替わっただけのまったく同じ出力ベクトルが得られる。アテンション重みがトークンの内容のみに依存するためである。語順を区別するには、表現またはスコア計算規則に位置情報を注入しなければならない。

位置情報の導入手法は大きく 3 つの系統に分けられる。各トークン埋め込みに位置ベクトル \(\mathbf{p}_i\) を加算する手法、位置に応じた角度でクエリとキーを回転させる手法(回転位置埋め込み(rotary position embeddings、RoPE))、そしてアテンションスコアから距離ペナルティを減算する手法(ALiBi)である。これら 3 系統はいずれも訓練コンテキスト長の内側では位置を区別できるが、より長い系列への外挿(extrapolation)を求められると大きく異なる振る舞いを示す。本節ではまず自己アテンションの置換対称性(permutation symmetry)を定式化し、続いて長さ \(128\) で訓練して最大長 \(512\) まで評価する 2 層のアテンションのみのバイト言語モデル(TinyCharLM)上で 5 つの位置表現手法を構築・比較する。

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})\) が成り立つ。

証明。線形射影は行ごとに作用するため、\((\boldsymbol{\Pi}\mathbf{X})\mathbf{W} = \boldsymbol{\Pi}(\mathbf{X}\mathbf{W})\) が \(\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v\) のそれぞれについて成り立つ。したがって、スコア行列は \(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top\) となる。行ごとのソフトマックスは行および列の置換と可換であるため、\(\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\)

4 ヘッドの MultiHeadAttention 層上で、置換同変性(permutation equivariance)を数値的に確認しよう。

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}')
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

同変な層やトークンごとの多層パーセプトロン(MLP)を積み重ねても同変性は保たれる。ただし、因果マスク(causal mask)を導入すると位置 \(i\) が \(i+1\) 個の先行要素を参照するようになるため、置換対称性が破れる。後述する NoPE はこの非対称性を利用している。

10.4.2 絶対位置埋め込み

オリジナルの Transformer (Vaswani ほか 2017年) は、位置ベクトル \(\mathbf{p}_i \in \mathbb{R}^d\)(第 \(i\) 行にあたる \(\mathbf{P}\) の行)を各トークン埋め込み \(\mathbf{x}_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}\) まで位置ごとに 1 つのパラメータ行を持つ訓練可能な埋め込みテーブル(embedding table)として扱う。訓練コンテキスト長を超える行は一度も勾配を受け取らないため、学習型のテーブルは未知の位置へ外挿できない。

10.4.2.2 正弦波エンコーディング

学習パラメータを用いずに任意の長さに対する位置ベクトルを定義するため、Vaswani ほか (2017年) は位置 \(i\) に対応する \(\mathbf{P}\) の行に、等比的に配置された \(d/2\) 個の周波数 \(\omega_m = 10000^{-2m/d}\) における正弦と余弦を格納する。

\[ 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\) だけシフトすると、\(2 \times 2\) 回転(\(\delta\) のみに依存)が各周波数ペア \((2m, 2m+1)\) に適用される。

\[ \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}\) を用いた双線形のアテンションスコアは 4 つの項に展開される。

\[ \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}\]

2 つの交差項は内容と絶対位置(absolute position)を結合しており(\(i\) と \(j\) が一緒にシフトすると値が変化する)、さらに \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) でさえも純粋に \(j - i\) のみに依存するのは、\(\mathbf{A}\) が \(2 \times 2\) のスケール付き回転ブロックからなるブロック対角行列である場合に限られる(演習問題 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\) となる。適切な正規直交基底(orthonormal basis、\(\mathbf{W}_q, \mathbf{W}_k\) に吸収可能)のもとで、任意の直交行列 \(\mathbf{R}_1\) は \(2 \times 2\) の平面回転へと分解される。RoPE は、各クエリとキーの \(d_h\) 個の座標を \(d_h/2\) 組のペアに分割し、ペア \(m\) を位置 \(i\) において角度 \(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 は、現代のオープンウェイトの言語モデルにおける標準的な位置エンコーディング(positional encoding)である。

図 10.4.1: 回転埋め込みは、クエリとキーの 2 次元特徴ペアのそれぞれを位置に比例する角度だけ回転させる。両方の位置を同じ量(ここでは 3)だけシフトすると、両ベクトルが一緒に回転するため、両者のなす角(どちらのパネルでも \(2\theta + \varphi\))、ひいてはアテンションスコアは変化しない。ここで、\(\theta = \omega_m\) はペア \(m\) が位置ごとに回転する角度であり、\(\varphi\) は回転前のクエリとキーのなす角である。
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 距離ペナルティとエンコーディングなし

さらに別の 2 つの手法では、トークン、クエリ、キーの各ベクトルには一切手を加えない。

  • ALiBi(Attention with Linear Biases、(Press ほか 2022年))は、ヘッド \(h \in \{1, \ldots, H\}\) における因果アテンション(causal attention)のスコアから線形の距離ペナルティを直接減算する。

    \[ \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\)(たとえば \(1/4, 1/16, 1/64, 1/256\)、\(H = 4\) の場合)によってヘッドごとに異なる直近ホライズンが与えられ、固定のテーブルサイズを必要としない。

  • NoPE(No Positional Encoding、(Kazemnejad ほか 2023年))は位置信号を一切加えず、因果マスク(\(i + 1\) 個のキーを位置 \(i\) で参照可能にする)のみに頼って置換対称性を破る。

10.4.5 訓練長を超える外挿

これら 5 つの手法が分布内(in-distribution)およびより長いコンテキストへ外挿する際にどのように振る舞うかを比較するため、長さ \(L = 128\) バイトで訓練し、長さ \(128\)、\(256\)、\(512\) でパープレキシティを評価する。

10.4.5.1 言語モデル TinyCharLM

TinyCharLM は 256 個のバイト値を幅 \(d = 128\) に埋め込み、2 つの因果自己アテンションブロック(\(H = 4\) 個のヘッド、各幅 \(d_h = 32\) であり、位置情報が pos のみから入るように MLP や正規化層は設けない)を適用したのち、共有された埋め込み重みを用いてバイトロジットへと射影する (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 はソフトマックス前のスコアに距離バイアス \(-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), weights

10.4.5.2 実験

d2l.WikiText103(9.3.1 節)の 128 バイトウィンドウ上で、各手法につき 3 つのシードを \(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\))より改善しているが、この小さな 2 ブロックモデルでは NoPE はバイグラムの水準にとどまる。

\(n = 512\) では、表現が訓練範囲外の値に遭遇する 3 つの手法が急激に劣化する。すなわち、学習型埋め込みは未訓練の行(\(128\)〜\(511\))にあたり、正弦波の低速な列は未知の値をとり、RoPE の低周波ペアは訓練中に一度も現れなかった角度へと回転する。一方、ALiBi のパープレキシティは \(9.9\) のまま平坦に保たれる。その理由を調べるため、ALiBi の 4 つのヘッドが距離 \(\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 の重みをコピーし、距離 \(\ge 128\)(window=train_len)のすべてのキーをハードマスクして長さ \(T = 512\) で評価する。

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\) であり、訓練ウィンドウ内で既に 1 周以上の回転を完了している。一方、残りの \(10\) 組の低速ペアは周期が \(199\) から \(35{,}000\) に及び、\(n = 512\) では未知の角度領域へと回転してしまう。

位置補間(position interpolation)では (Chen ほか 2023年)、すべての角度を \(128 / 512 = 1/4\) 倍にスケーリングして、新しいコンテキスト範囲を訓練済み区間 \([0, 128)\) に写し戻す。しかし、ファインチューニングなしに高速ペアまでスケーリングすると、隣接バイトの区別に使われている局所的な位相差が損なわれる。高速ペアには手を加えず低速ペアのみをスケーリングする手法は、YaRN (Peng ほか 2024年) や NTK 考慮スケーリング(NTK-aware scaling、基数を \(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)

低速ペアのみを再スケーリングすると、重みを 1 つも更新することなく長さ 512 でのパープレキシティが約 \(27\) から約 \(9\) へと低下し、目標長で短時間のファインチューニングを行えば残りの差も解消される(演習問題 6)。

10.4.6 まとめ

マスクなし自己アテンションは置換同変であり、\(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\) を任意のトークン置換 \(\boldsymbol{\Pi}\) に対して満たす。加算型の位置埋め込み(学習型または正弦波)は入力段階でこの対称性を破るが、絶対インデックスに結びついた内容・位置の交差項を生じさせ、訓練長を超えると劣化する。アテンションスコアが相対オフセット \(j - i\) のみに依存することを要請すると、クエリとキーに対する直交平面回転(RoPE)が導かれるのに対し、ALiBi はヘッドごとの線形距離ペナルティ \(-m_h(i - j)\) を減算する。訓練ウィンドウを超えると、RoPE は特に波長が訓練長を上回る低周波の座標ペアにおいて劣化するが、高周波ペアをそのまま残しつつこれらの低速ペアを選択的に補間することで、長文脈での性能が回復する。

10.4.7 演習問題

  1. 異なる位置と異なる符号。\(\mathbf{p}_i\) を、第 \(i\) 行として正弦波テーブル 式 10.4.1(幅 \(d\)、周波数 \(\omega_m = 1/10000^{2m/d}\))から取り出した行ベクトルとする。
    1. 次式を示し、 \[\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\) のみに依存することを結論づけよ。
    2. \(\mathbf{p}_i = \mathbf{p}_{i'}\) が成り立つのは \((i - i')\,\omega_m\) が \(2\pi\) の倍数である(すべての \(m\) について)場合に限られること、したがって max_len の値にかかわらず、相異なる 2 つの整数位置が同じ行を共有することはないことを結論づけよ。
    3. 最も速いペアは周期 \(2\pi\) を持つため、\(2\pi\) の倍数に近い整数オフセットでほぼ同じ値を繰り返す。オフセット \(\delta < 512\) のうち、その角度が \(2\pi\) の倍数に最も近づくものを求め、残差(residual)の角度を示せ。\(d = 32\) の場合について、このオフセットにおける \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|\) を \(\delta = 1\) における値と比較し、ほぼ反復する 2 つの位置をどのペアが引き離しているかを述べ、その答えを 10.4.2.2 節 の二進カウンタと関連づけよ。
  2. スコアにおける加算型符号。10.4.2.2 節 の加算型エンコーディングを用いるとき、第 1 層のヘッドは位置 \(i\) と \(j\) の入力に対し、式 10.4.3 の 4 つの項(ただし \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\))によってスコアを計算する。
    1. \(\mathbf{J}\) を平面上の \(\pi/2\) 回転とする。式 10.4.2 を用いて、位置・位置の項 \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) は、\(j - i\) のみに依存することを、\(\mathbf{A}\) が周波数ペアごとに 1 つの \(2 \times 2\) ブロック \(a_m \mathbf{I} + b_m \mathbf{J}\) を持つブロック対角行列である場合について示せ。演習問題 1 は \(\mathbf{A} = \mathbf{I}\) の場合を扱っている。次に、異なる 2 つの周波数ペアを結合する \(\mathbf{A}\) の非ゼロ要素が 1 つでもあると、この性質が損なわれることを示せ。
    2. 内容・位置の項 \(\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j\) が \(j\) のあらゆるシフトに対して変化しない条件を求めよ。その答えを用いて、10.4.3 節 のシフト実験における加算型エンコーディングのスコア変化と、RoPE に内容・位置の項が存在しない理由を説明せよ。
  3. [code] どこで外挿が破綻するか。10.4.5.2 節 におけるコンテキスト 512 でのパープレキシティは、各系列のすべての位置にわたって損失を平均したものである。
    1. 5 つのモデルそれぞれにおいて、長さ 512 の系列の位置 0 から 127 におけるロジットが、先頭の 128 トークンのみから計算したロジットと浮動小数点の丸め誤差の範囲で一致することを数値的に確認せよ。TinyCharLM のどの 2 つの性質が、すべての手法に対してこれを保証しているか。
    2. 5 つのモデルについて長さ 512 の系列の各位置における検証損失を計算し、16 位置ごとのウィンドウで平均して位置に対してプロットせよ。各手法について、曲線はどの位置で位置 128 未満で保っていた水準から離れるか。また、損失は位置 128 で不連続に跳ね上がるか、それとも徐々に増大するか。
    3. models['rope'] のすべてのクエリが自身を含む直近 128 個のキーのみを参照するよう、attend をオーバーライドするサブクラスで因果マスクに帯状の制約を追加し、訓練済みの重みをコピーして同じ計測を繰り返せ。位置 128 以降のウィンドウ制限付き曲線と、それより前の制限なし曲線とを比較せよ。127 を超えるオフセットは、コンテキスト 512 における RoPE の劣化を説明するか。
  4. 対称性を保つバイアス。 ● 証明中のソフトマックス前のスコア行列に対し、固定行列 \(\mathbf{B} \in \mathbb{R}^{n \times n}\) を \(\mathbf{S}\) に加算して、自己アテンション層(10.3 節)が \(\mathrm{softmax}(\mathbf{S} + \mathbf{B})\, \mathbf{X}\mathbf{W}_v\) を計算するものとする。
    1. 置換行列 \(\boldsymbol{\Pi}\) が \(\boldsymbol{\Pi}^\top \mathbf{B} \boldsymbol{\Pi} = \mathbf{B}\) を満たす限り、命題が依然として成り立つことを示せ。
    2. すべての置換に対してこの条件を満たす行列 \(\mathbf{B}\) をすべて求め、そのそれぞれがアテンション重みをどのように変化させるかを述べよ。
    3. 因果マスクがない場合、式 10.4.6 の ALiBi バイアスは対称な形 \(B_{ij} = -m_h\,|i - j|\) へと拡張される。この行列を保つ置換をすべて求め、このバイアス以外に一切の位置信号を受け取らないマスクなし層に対してその結果が何を意味するかを述べよ。また、式 10.4.6 の因果的な ALiBi がこの対称性を共有しない理由を説明せよ。
  5. RoPE におけるオフセット選好。 ● クエリ \(\mathbf{q}\) とキー \(\mathbf{k}\) を、\(d_h/2\) 組の 2 次元ペア \(\mathbf{q}^{(m)}, \mathbf{k}^{(m)} \in \mathbb{R}^2\)(式 10.4.5 が作用する単位)に分割し、\(\delta = j - i\) をキー位置 \(j\) のクエリ位置 \(i\) からのオフセットとする。
    1. 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)}\) への角度(符号を反転させた \(\varphi\)、図 10.4.1 参照)である。
    2. 角度 \(\psi_m\) を、すべてのペアが直前のトークンであるオフセット \(\delta = -1\) で最大の寄与を与えるように選べ。すべての積 \(\|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\|\) が \(c\) に等しいとき、スコアは \(\delta\) の関数として、\(c\) とドット積 \(\mathbf{p}_i^\top \mathbf{p}_{i+\delta}\)(演習問題 1 における幅 \(d_h\) の正弦波テーブルのもの)をシフトしたものの積になることを示せ。
    3. \(d_h = 32\) とし、位置 127 にあるクエリ(オフセット \(\delta = -127, \ldots, 0\) を参照する)を考える。係数 \(1/\sqrt{d_h}\) を \(c\) に吸収させ、アテンションロジットがこれらのスコアに等しいとする。このとき、\(c\) の値として、オフセット \(-1\) がソフトマックス重みの半分を受け取るようなものを求め、それと最も強く競合するオフセットを特定せよ。オフセット \(-1\) でのスコアとその隣接オフセットでのスコアとの差を決定づけているのはどのペアか。
  6. [extended] 位置補間。 ● 10.4.5.3 節 の最後のコードセルでは、訓練済みの RoPE モデルの角度を一切の追加訓練なしに再スケーリングしている。本問ではその結果の理由を解明し、NTK 考慮スケーリングの基数変更を加え、最後にファインチューニングによって手法を完成させる。
    1. 訓練オフセット 0 から 127 の範囲内で 1 回転を完了するペアは、より長いオフセットが生み出す任意の角度に対し、\(\omega_m/2\) 以内の差(\(2\pi\) を法として)で既に出会っていることを示せ。演習問題 5 におけるオフセット \(-1\) のスコアとその隣接オフセットのスコアとの差を、\(d_h = 32\) の場合について、再スケーリング前、\(128/512\) による一様な再スケーリング後、および周期が 128 位置を超えるペアのみを再スケーリングした後のそれぞれで計算せよ。その結果を、コードセル内のコンテキスト 128 におけるパープレキシティと関連づけよ。
    2. 基数 \(b' = b\, s^{d_h/(d_h-2)}\) が \(\omega_0\) を不変に保ちつつ \(\omega_{d_h/2-1}\) を \(s\) で割ることを示せ。属性 rope_base(models['rope'] 内)を \(s = 4\) に対するこの基数に設定し、訓練せずに長さ 128、256、512 で評価して、同セルの 2 つの再スケーリング手法と比較せよ。
    3. コンテキスト 512 のもと、d2l.WikiText103(batch_size=16, num_steps=512) 上で同セルの 2 つの再スケーリング手法のそれぞれについて(いずれも訓練済み models['rope'] のコピーを初期値として)数百ステップだけファインチューニングせよ。長さ 128、256、512 で再評価し、スケーリングなしのモデルおよび 10.4.5.2 節 の実験における同じ長さでの ALiBi モデルと比較せよ。

ディスカッション