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 Positional Information
The sentences “dog bites man” and “man bites dog” contain the same three words. Passed through the unmasked self-attention layer of Section 10.3, they produce the exact same output vectors in permuted order, because attention weights depend solely on token content. To distinguish word order, positional information must be injected into the representation or the scoring rule.
Positional schemes fall into three main families: adding a position vector \(\mathbf{p}_i\) to each token embedding, rotating queries and keys by position-dependent angles (rotary position embeddings, RoPE), or subtracting a distance penalty from the attention scores (ALiBi). While all three distinguish positions within the training context length, they behave very differently when asked to extrapolate to longer sequences. We first formalize the permutation symmetry of self-attention, then construct and compare five positional schemes on a two-layer attention-only byte language model (TinyCharLM) trained at length \(128\) and evaluated up to length \(512\).
10.4.1 Permutation Equivariance
Let \(\mathbf{X} \in \mathbb{R}^{n \times d}\) hold \(n\) token vectors and let \(f(\mathbf{X}) = \mathrm{softmax}(\mathbf{S})\,\mathbf{X}\mathbf{W}_v\) with \(\mathbf{S} = \mathbf{X}\mathbf{W}_q(\mathbf{X}\mathbf{W}_k)^\top/\sqrt{d_h}\) denote unmasked self-attention (Section 10.3) with dropout disabled. Reordering the \(n\) tokens corresponds to multiplying \(\mathbf{X}\) from the left by an \(n \times n\) permutation matrix \(\boldsymbol{\Pi}\).
Proposition (Permutation Equivariance). For every permutation matrix \(\boldsymbol{\Pi}\), \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\).
Proof. Because linear projections act row-wise, \((\boldsymbol{\Pi}\mathbf{X})\mathbf{W} = \boldsymbol{\Pi}(\mathbf{X}\mathbf{W})\) for \(\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v\). The score matrix becomes \(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top\). Because row-wise softmax commutes with row and column permutations, \(\mathrm{softmax}(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top) = \boldsymbol{\Pi}\, \mathrm{softmax}(\mathbf{S})\, \boldsymbol{\Pi}^\top\). Multiplying by the permuted values \(\boldsymbol{\Pi}\mathbf{X}\mathbf{W}_v\) and using \(\boldsymbol{\Pi}^\top \boldsymbol{\Pi} = \mathbf{I}\) yields \(\boldsymbol{\Pi} f(\mathbf{X})\). Concatenating heads and applying \(\mathbf{W}_o\) row-wise preserves equivariance. \(\blacksquare\)
We verify permutation equivariance numerically on a four-head MultiHeadAttention layer:
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
Stacking equivariant layers or token-wise MLPs preserves equivariance. Note, however, that a causal mask breaks permutation symmetry because position \(i\) attends over \(i+1\) predecessors—an asymmetry exploited by NoPE below.
10.4.2 Absolute Position Embeddings
The original Transformer (Vaswani et al. 2017) breaks permutation symmetry at the input by adding a position vector \(\mathbf{p}_i \in \mathbb{R}^d\) (row \(i\) of \(\mathbf{P}\)) to each token embedding \(\mathbf{x}_i\): shuffling tokens maps \(\mathbf{X} + \mathbf{P}\) to \(\boldsymbol{\Pi}\mathbf{X} + \mathbf{P} \neq \boldsymbol{\Pi}(\mathbf{X} + \mathbf{P})\).
10.4.2.1 Learned Positions
Models such as BERT (Devlin et al. 2018) and GPT-2 (Radford et al. 2019) treat \(\mathbf{P} \in \mathbb{R}^{L_{\max} \times d}\) as a trainable embedding table with one parameter row per position up to a fixed maximum length \(L_{\max}\). Because rows beyond the training context length never receive gradients, a learned table cannot extrapolate to unseen positions.
10.4.2.2 Sinusoidal Encodings
To define position vectors for arbitrary lengths without learned parameters, Vaswani et al. (2017) populate row \(i\) of \(\mathbf{P}\) with sines and cosines at \(d/2\) geometrically spaced frequencies \(\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}\]
As \(\omega_m\) decreases from \(1\) radian per token (\(m = 0\)) toward \(10^{-4}\) (\(m = d/2 - 1\)), the column pairs act as a continuous analog of a binary counter: low-index columns oscillate rapidly to separate neighboring positions, while high-index columns vary slowly across broad regions.
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)])Displaying the full \(60 \times 32\) encoding matrix P as a heatmap shows how rapidly oscillating high-frequency pairs on the left transition to slowly varying low-frequency pairs on the right, much like the binary digits of an integer counter:
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 Sinusoidal Encodings as Rotations
By the trigonometric angle-addition identities, shifting position \(i\) by an offset \(\delta\) applies a \(2 \times 2\) rotation depending only on \(\delta\) to each frequency pair \((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}\]
However, because \(\mathbf{p}_i\) is added to \(\mathbf{x}_i\), the bilinear attention score with \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\) expands into four terms:
\[ \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}\]
The two cross terms couple content with absolute position (varying when \(i\) and \(j\) shift together), and even \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) depends purely on \(j - i\) only if \(\mathbf{A}\) is block-diagonal with \(2 \times 2\) scaled-rotation blocks (Exercise 2).
10.4.3 Rotary Position Embeddings
Rotary position embeddings (RoPE) (Su et al. 2024) apply position transformations multiplicatively to queries and keys so that every score depends only on the relative offset \(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}\]
Requiring \(\mathbf{R}_i^\top \mathbf{R}_j = \mathbf{R}_{j-i}\) with full-rank \(\mathbf{R}_0\) implies: (1) \(\mathbf{R}_0 = \mathbf{I}\) (from \(\mathbf{R}_0^\top \mathbf{R}_0 = \mathbf{R}_0\)); (2) \(\mathbf{R}_i^\top \mathbf{R}_i = \mathbf{I}\), so every \(\mathbf{R}_i\) is orthogonal and norm-preserving; and (3) \(\mathbf{R}_{i+j} = \mathbf{R}_i \mathbf{R}_j\), so \(\mathbf{R}_i = \mathbf{R}_1^i\). In an appropriate orthonormal basis (absorbable into \(\mathbf{W}_q, \mathbf{W}_k\)), any orthogonal matrix \(\mathbf{R}_1\) decomposes into \(2 \times 2\) planar rotations. RoPE partitions the \(d_h\) coordinates of each query and key into \(d_h/2\) pairs and rotates pair \(m\) at position \(i\) by \(i\omega_m\) with \(\omega_m = 10000^{-2m/d_h}\) (Figure 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}\]
Values are not rotated, ensuring that the layer’s output remains invariant to global position shifts. RoPE is the standard positional encoding in modern open-weights language models.
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)Shifting all positions by an arbitrary offset leaves RoPE scores identical up to float32 rounding, whereas additive sinusoidal scores change by \(O(1)\) due to the content–position cross terms of Equation 10.4.3:
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 Distance Penalties and No Encoding
Two additional schemes leave token, query, and key vectors untouched:
ALiBi (Attention with Linear Biases, (Press et al. 2022)) subtracts a linear distance penalty directly from the causal attention scores in head \(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}\]
The geometric slopes \(m_h\) (e.g., \(1/4, 1/16, 1/64, 1/256\) for \(H = 4\)) equip different heads with different recency horizons and require no fixed table size.
NoPE (No Positional Encoding, (Kazemnejad et al. 2023)) adds no positional signal at all, relying solely on the causal mask (which exposes \(i + 1\) keys at position \(i\)) to break permutation symmetry.
10.4.5 Extrapolation Beyond the Training Length
To compare how these five schemes perform in-distribution and when extrapolating to longer contexts, we train at length \(L = 128\) bytes and evaluate perplexity at lengths \(128\), \(256\), and \(512\).
10.4.5.1 The Language Model TinyCharLM
TinyCharLM embeds 256 byte values into width \(d = 128\), applies two causal self-attention blocks (\(H = 4\) heads of width \(d_h = 32\), with no MLP or normalization layers so position enters exclusively through pos), and projects back to byte logits via tied embedding weights (Press and 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]In embed, the sinusoidal table is scaled by \(1/\sqrt{d}\) so its entries match the scale of the \(\mathcal{N}(0, 0.02^2)\) token embeddings without altering the tied output logits:
@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 HIn attend, RoPE rotates queries and keys, whereas ALiBi adds the distance bias \(-m_h(i - j)\) to the pre-softmax scores:
@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 The Experiment
We train three seeds of each scheme for \(3{,}000\) AdamW steps on 128-byte windows of d2l.WikiText103 (Section 9.3.1).
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
We evaluate validation perplexity on identical validation bytes regrouped into windows of \(n \in \{128, 256, 512\}\), alongside a closed-form byte-bigram baseline.
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)
To anchor these numbers, we compute the exact byte-level bigram perplexity on the same validation windows from Laplace-smoothed empirical transition counts over the training corpus:
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
At the training length (\(n = 128\)), RoPE achieves the lowest perplexity (\(7.3\)), ahead of learned (\(9.6\)), sinusoidal (\(9.7\)–\(9.8\)), and ALiBi (\(9.9\)–\(10.0\)), all of which improve on the byte-bigram baseline (\(11.6\)); NoPE remains at the bigram level in this small two-block model.
At \(n = 512\), the three schemes whose representations encounter out-of-range values degrade sharply: learned embeddings hit untrained rows (\(128\)–\(511\)), sinusoidal slow columns take unseen values, and RoPE’s low-frequency pairs rotate to angles never seen during training. ALiBi’s perplexity remains flat at \(9.9\). To see why, we measure the fraction of attention weight that ALiBi’s four heads place on keys at distance \(\ge 128\), and compare against masking out all keys at distance \(\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
We confirm this directly with WindowedALiBi, which copies the trained ALiBi weights and hard-masks all keys at distance \(\ge 128\) (window=train_len) when evaluating at length \(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)
Removing all keys at distance \(\ge 128\) leaves ALiBi’s perplexity unchanged: its steep heads already ignore distant keys, and its gentle heads compute a broad recency-weighted average that gains nothing from bytes beyond 128. Thus a flat extrapolation curve indicates that a scheme avoids breaking on distant keys, not necessarily that it extracts long-range information from them.
10.4.5.3 Extending a Trained Model’s Context
Why does RoPE break beyond the training length \(L = 128\), and how can we repair it? For head width \(d_h = 32\), the \(16\) coordinate pairs have periods \(2\pi / \omega_m = 2\pi \cdot 10000^{m/16}\). The first \(6\) fast pairs have periods \(\le 112 < 128\) and already complete full rotations within the training window; the remaining \(10\) slow pairs have periods from \(199\) to \(35{,}000\) and rotate into unseen angular regions at \(n = 512\).
Position interpolation (Chen et al. 2023) scales all angles by \(128 / 512 = 1/4\) to map the new context range back into the trained interval \([0, 128)\). However, scaling the fast pairs without fine-tuning destroys the local phase differences used to distinguish neighboring bytes. Leaving the fast pairs untouched and scaling only the slow pairs—the core idea behind YaRN (Peng et al. 2024) and NTK-aware scaling (which increases the base \(b \mapsto b\, s^{d_h/(d_h - 2)}\))—recovers most of the extrapolation perplexity at zero training cost:
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)
Rescaling only the slow pairs cuts length-512 perplexity from about \(27\) down to about \(9\) without updating a single weight, and a brief fine-tune at the target length eliminates the remaining gap (Exercise 6).
10.4.6 Summary
Unmasked self-attention is permutation equivariant, satisfying \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\) for every token permutation \(\boldsymbol{\Pi}\). Additive position embeddings (learned or sinusoidal) break this symmetry at the input, but introduce content–position cross terms tied to absolute indices and degrade beyond the training length. Requiring attention scores to depend solely on the relative offset \(j - i\) forces orthogonal planar rotations on queries and keys (RoPE), whereas ALiBi subtracts a per-head linear distance penalty \(-m_h(i - j)\). Beyond the training window, RoPE degrades specifically in low-frequency coordinate pairs whose wavelengths exceed the training length, and selectively interpolating those slow pairs while leaving high-frequency pairs intact restores long-context performance.
10.4.7 Exercises
- Distinct positions, distinct codes. Let \(\mathbf{p}_i\) be row \(i\) of the sinusoidal table Equation 10.4.1 of width \(d\), with the frequencies \(\omega_m = 1/10000^{2m/d}\).
- Show that \[\mathbf{p}_i^\top \mathbf{p}_{i+\delta} = \sum_{m=0}^{d/2-1} \cos(\delta\,\omega_m),\] derive \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|^2\) from it, and conclude that both quantities depend on the offset \(\delta\) alone.
- Conclude that \(\mathbf{p}_i = \mathbf{p}_{i'}\) only if \((i - i')\,\omega_m\) is a multiple of \(2\pi\) for every \(m\), and that no two distinct integer positions share a row, whatever the value of
max_len. - The fastest pair has period \(2\pi\), so it nearly repeats at integer offsets close to multiples of \(2\pi\). Find the offset \(\delta < 512\) at which its angle comes closest to a multiple of \(2\pi\), and give the residual angle. For \(d = 32\), compare \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|\) at this offset with its value at \(\delta = 1\), say which pairs keep the two positions of the near repeat apart, and relate the answer to the binary counting of Section 10.4.2.2.
- Additive codes in the score. With the additive encoding of Section 10.4.2.2, a first-layer head scores the inputs at positions \(i\) and \(j\) by the four terms of Equation 10.4.3, with \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\).
- Let \(\mathbf{J}\) be the rotation of the plane by \(\pi/2\). Using Equation 10.4.2, show that the position–position term \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) depends only on \(j - i\) when \(\mathbf{A}\) is block diagonal with \(2 \times 2\) blocks \(a_m \mathbf{I} + b_m \mathbf{J}\), one per frequency pair. Exercise 1 treats \(\mathbf{A} = \mathbf{I}\). Then show that a single nonzero entry of \(\mathbf{A}\) that couples two different frequency pairs destroys this property.
- Determine when the content–position term \(\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j\) is unchanged for every shift of \(j\). Use the answer to explain the score change of the additive encoding in the shift test of Section 10.4.3, and why RoPE has no content–position term.
- [code] Where extrapolation fails. The perplexities of Section 10.4.5.2 at context 512 average the loss over all positions of each sequence.
- Check numerically that in each of the five models the logits at positions 0 to 127 of a length-512 sequence agree, up to floating-point round-off, with those computed from its first 128 tokens alone. Which two properties of
TinyCharLMguarantee this for every scheme? - Compute the validation loss at every position of the length-512 sequences for the five models, average it over windows of 16 positions, and plot it against position. For each scheme, where does the curve leave the level it holds below position 128, and does the loss jump at position 128 or grow gradually?
- Restrict every query of
models['rope']to the 128 most recent keys, itself included, by adding a band constraint to the causal mask in a subclass that overridesattend, copy the trained weights into it, and repeat the measurement. Compare the windowed curve beyond position 128 with the unwindowed curve below it. Do offsets beyond 127 account for the degradation of RoPE at context 512?
- Check numerically that in each of the five models the logits at positions 0 to 127 of a length-512 sequence agree, up to floating-point round-off, with those computed from its first 128 tokens alone. Which two properties of
- Biases that keep the symmetry. ● Suppose that a fixed matrix \(\mathbf{B} \in \mathbb{R}^{n \times n}\) is added to the score matrix \(\mathbf{S}\) of the proof before the softmax, so that the self-attention layer (Section 10.3) computes \(\mathrm{softmax}(\mathbf{S} + \mathbf{B})\, \mathbf{X}\mathbf{W}_v\).
- Show that the proposition still holds for every permutation matrix \(\boldsymbol{\Pi}\) with \(\boldsymbol{\Pi}^\top \mathbf{B} \boldsymbol{\Pi} = \mathbf{B}\).
- Find all matrices \(\mathbf{B}\) that satisfy this condition for every permutation, and describe how each of them changes the attention weights.
- Without the causal mask, the ALiBi bias of Equation 10.4.6 extends symmetrically to \(B_{ij} = -m_h\,|i - j|\). Determine the permutations that preserve this matrix, and state what the result implies for an unmasked layer that receives this bias and no other positional signal. Explain why the causal ALiBi of Equation 10.4.6 does not share this symmetry.
- Offset preference in RoPE. ● Split a query \(\mathbf{q}\) and a key \(\mathbf{k}\) into the \(d_h/2\) two-dimensional pairs \(\mathbf{q}^{(m)},
\mathbf{k}^{(m)} \in \mathbb{R}^2\) on which Equation 10.4.5 acts, and let \(\delta = j - i\) be the offset of the key position \(j\) from the query position \(i\).
- Show that the RoPE score Equation 10.4.4 equals \[\sum_{m=0}^{d_h/2-1} \|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\| \cos(\delta\,\omega_m - \psi_m), \tag{10.4.7}\] where \(\psi_m\) is the angle from \(\mathbf{k}^{(m)}\) to \(\mathbf{q}^{(m)}\) (the \(\varphi\) of Figure 10.4.1 with the opposite sign).
- Choose the angles \(\psi_m\) so that every pair contributes its maximum at the offset \(\delta = -1\), the previous token. With all products \(\|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\|\) equal to \(c\), show that the score, as a function of \(\delta\), is \(c\) times a shifted copy of the dot product \(\mathbf{p}_i^\top \mathbf{p}_{i+\delta}\) of Exercise 1 for a sinusoidal table of width \(d_h\).
- Take \(d_h = 32\) and the query at position 127, which attends to the offsets \(\delta = -127, \ldots, 0\). Let the attention logits equal these scores, with the factor \(1/\sqrt{d_h}\) absorbed into \(c\). Find the \(c\) at which the offset \(-1\) receives half of the softmax weight, and identify the offsets that compete most with it. Which pairs set the gap between the score at \(-1\) and the scores at its neighbors?
- [extended] Position interpolation. ● The last cell of Section 10.4.5.3 rescales the angles of the trained RoPE models without any training. This problem explains its result, adds the base change of NTK-aware scaling, and completes the recipe with a fine-tune.
- Show that a pair that completes a full rotation within the training offsets 0 to 127 has already met, to within \(\omega_m/2\) modulo \(2\pi\), every angle that a longer offset produces. Compute the gap of Exercise 5 between the score at offset \(-1\) and the scores at its neighbors for \(d_h = 32\), before the rescaling, after the uniform rescaling by \(128/512\), and after the rescaling of only the pairs whose period exceeds 128 positions. Relate the result to the perplexities at context 128 in the cell.
- Show that the base \(b' = b\, s^{d_h/(d_h-2)}\) leaves \(\omega_0\) unchanged and divides \(\omega_{d_h/2-1}\) by \(s\). Set
rope_baseofmodels['rope']to this base for \(s = 4\), evaluate at 128, 256, and 512 without training, and compare with the two rescalings of the cell. - Fine-tune for a few hundred steps at context 512, on
d2l.WikiText103(batch_size=16, num_steps=512), with each of the two rescalings of the cell, each starting from a copy of the trainedmodels['rope']. Re-evaluate at 128, 256, and 512, and compare with the unscaled model and with the ALiBi model of the experiment in Section 10.4.5.2 at the same lengths.