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
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 and evaluated up to length .
10.4.1 Permutation Equivariance#
Let hold token vectors and let with denote unmasked self-attention (Section 10.3) with dropout disabled. Reordering the tokens corresponds to multiplying from the left by an permutation matrix .
Proposition (Permutation Equivariance). For every permutation matrix , .
Proof. Because linear projections act row-wise, for . The score matrix becomes . Because row-wise softmax commutes with row and column permutations, . Multiplying by the permuted values and using yields . Concatenating heads and applying row-wise preserves equivariance.
We verify permutation equivariance numerically on a four-head
MultiHeadAttention layer:
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
Stacking equivariant layers or token-wise MLPs preserves equivariance. Note, however, that a causal mask breaks permutation symmetry because position attends over 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 (row of ) to each token embedding : shuffling tokens maps to .
10.4.2.1 Learned Positions#
Models such as BERT (Devlin et al., 2018) and GPT-2 (Radford et al., 2019) treat as a trainable embedding table with one parameter row per position up to a fixed maximum length . 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 of with sines and cosines at geometrically spaced frequencies :
As decreases from radian per token () toward (), 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)])Displaying the full 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')10.4.2.3 Sinusoidal Encodings as Rotations#
By the trigonometric angle-addition identities, shifting position by an offset applies a rotation depending only on to each frequency pair :
However, because is added to , the bilinear attention score with expands into four terms:
The two cross terms couple content with absolute position (varying when and shift together), and even depends purely on only if is block-diagonal with 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 :
Requiring with full-rank implies: (1) (from ); (2) , so every is orthogonal and norm-preserving; and (3) , so . In an appropriate orthonormal basis (absorbable into ), any orthogonal matrix decomposes into planar rotations. RoPE partitions the coordinates of each query and key into pairs and rotates pair at position by with (Figure 10.4.1):
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.
Rotary embeddings rotate each two-dimensional feature pair of the query and the key by an angle proportional to position. Shifting both positions by the same amount, here by 3, rotates both vectors together and leaves the angle between them ( in both panels), and hence the attention score, unchanged. Here is the angle by which pair turns per position, and is the angle between the unrotated query and key.
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)Shifting all positions by an arbitrary offset leaves RoPE scores identical up to float32 rounding, whereas additive sinusoidal scores change by due to the content--position cross terms of (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
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 :
The geometric slopes (e.g., for ) 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 keys at position ) 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 bytes and evaluate perplexity at lengths , , and .
10.4.5.1 The Language Model TinyCharLM#
TinyCharLM embeds 256 byte values into width , applies two causal
self-attention blocks ( heads of width , 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]In embed, the sinusoidal table is scaled by so its entries
match the scale of the 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 HIn attend, RoPE rotates queries and keys, whereas ALiBi adds the distance
bias 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), weights10.4.5.2 The Experiment#
We train three seeds of each scheme for 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
We evaluate validation perplexity on identical validation bytes regrouped into windows of , 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)
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
At the training length (), RoPE achieves the lowest perplexity (), ahead of learned (), sinusoidal (--), and ALiBi (--), all of which improve on the byte-bigram baseline (); NoPE remains at the bigram level in this small two-block model.
At , the three schemes whose representations encounter out-of-range values degrade sharply: learned embeddings hit untrained rows (--), 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 . To see why, we measure the fraction of attention weight that ALiBi's four heads place on keys at distance , and compare against masking out all keys at distance :
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
We confirm this directly with WindowedALiBi, which copies the trained ALiBi weights and hard-masks all keys at distance (window=train_len) when evaluating at length :
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)
Removing all keys at distance 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 , and how can we repair it? For head width , the coordinate pairs have periods . The first fast pairs have periods and already complete full rotations within the training window; the remaining slow pairs have periods from to and rotate into unseen angular regions at .
Position interpolation (Chen et al., 2023) scales all angles by to map the new context range back into the trained interval . 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 )—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)
Rescaling only the slow pairs cuts length-512 perplexity from about down to about 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 for every token permutation . 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 forces orthogonal planar rotations on queries and keys (RoPE), whereas ALiBi subtracts a per-head linear distance penalty . 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 be row of
the sinusoidal table (10.4.1) of width , with the
frequencies .
- Show that
derive from it, and conclude that both quantities depend on the offset alone.
- Conclude that only if
is a multiple of for every , and that
no two distinct integer positions share a row, whatever the value of
max_len. - The fastest pair has period , so it nearly repeats at integer offsets close to multiples of . Find the offset at which its angle comes closest to a multiple of , and give the residual angle. For , compare at this offset with its value at , 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 and by the four terms of (10.4.3), with .
- Let be the rotation of the plane by . Using (10.4.2), show that the position--position term depends only on when is block diagonal with blocks , one per frequency pair. Exercise 1 treats . Then show that a single nonzero entry of that couples two different frequency pairs destroys this property.
- Determine when the content--position term is unchanged for every shift of . 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 is added to the score matrix of the proof before the softmax, so that the self-attention layer (Section 10.3) computes .
- Show that the proposition still holds for every permutation matrix with .
- Find all matrices 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 (10.4.6) extends symmetrically to . 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 (10.4.6) does not share this symmetry.
-
Offset preference in RoPE. ● Split a query and a key into the two-dimensional pairs on which (10.4.5) acts, and let be the offset of the key position from the query position .
- Show that the RoPE score (10.4.4) equals
where is the angle from to (the of Figure 10.4.1 with the opposite sign).
- Choose the angles so that every pair contributes its maximum at the offset , the previous token. With all products equal to , show that the score, as a function of , is times a shifted copy of the dot product of Exercise 1 for a sinusoidal table of width .
- Take and the query at position 127, which attends to the offsets . Let the attention logits equal these scores, with the factor absorbed into . Find the at which the offset receives half of the softmax weight, and identify the offsets that compete most with it. Which pairs set the gap between the score at 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 modulo , every angle that a longer offset produces. Compute the gap of Exercise 5 between the score at offset and the scores at its neighbors for , before the rescaling, after the uniform rescaling by , 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 leaves
unchanged and divides by . Set
rope_baseofmodels['rope']to this base for , 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.