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 pi\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 128128 and evaluated up to length 512512.

10.4.1 Permutation Equivariance#

Let X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} hold nn token vectors and let f(X)=softmax(S) XWvf(\mathbf{X}) = \mathrm{softmax}(\mathbf{S})\,\mathbf{X}\mathbf{W}_v with S=XWq(XWk)⊤/dh\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 nn tokens corresponds to multiplying X\mathbf{X} from the left by an n×nn \times n permutation matrix Π\boldsymbol{\Pi}.

Proposition (Permutation Equivariance). For every permutation matrix Π\boldsymbol{\Pi}, f(ΠX)=Πf(X)f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X}).

Proof. Because linear projections act row-wise, (ΠX)W=Π(XW)(\boldsymbol{\Pi}\mathbf{X})\mathbf{W} = \boldsymbol{\Pi}(\mathbf{X}\mathbf{W}) for Wq,Wk,Wv\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v. The score matrix becomes ΠSΠ⊤\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top. Because row-wise softmax commutes with row and column permutations, softmax(ΠSΠ⊤)=Π softmax(S) Π⊤\mathrm{softmax}(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top) = \boldsymbol{\Pi}\, \mathrm{softmax}(\mathbf{S})\, \boldsymbol{\Pi}^\top. Multiplying by the permuted values ΠXWv\boldsymbol{\Pi}\mathbf{X}\mathbf{W}_v and using Π⊤Π=I\boldsymbol{\Pi}^\top \boldsymbol{\Pi} = \mathbf{I} yields Πf(X)\boldsymbol{\Pi} f(\mathbf{X}). Concatenating heads and applying Wo\mathbf{W}_o row-wise preserves equivariance. ■\blacksquare

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 ii attends over i+1i+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 pi∈Rd\mathbf{p}_i \in \mathbb{R}^d (row ii of P\mathbf{P}) to each token embedding xi\mathbf{x}_i: shuffling tokens maps X+P\mathbf{X} + \mathbf{P} to ΠX+P≠Π(X+P)\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 P∈RLmax⁡×d\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 Lmax⁡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 ii of P\mathbf{P} with sines and cosines at d/2d/2 geometrically spaced frequencies ωm=10000−2m/d\omega_m = 10000^{-2m/d}:

pi,2m=sin⁡(i100002m/d),pi,2m+1=cos⁡(i100002m/d).(10.4.1)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 ωm\omega_m decreases from 11 radian per token (m=0m = 0) toward 10−410^{-4} (m=d/2−1m = 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)])

Displaying the full 60×3260 \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')

10.4.2.3 Sinusoidal Encodings as Rotations#

By the trigonometric angle-addition identities, shifting position ii by an offset δ\delta applies a 2×22 \times 2 rotation depending only on δ\delta to each frequency pair (2m,2m+1)(2m, 2m+1):

[cos⁡(δωm)sin⁡(δωm)−sin⁡(δωm)cos⁡(δωm)][pi,2mpi,2m+1]=[sin⁡((i+δ)ωm)cos⁡((i+δ)ωm)]=[pi+δ,2mpi+δ,2m+1].(10.4.2)\begin{bmatrix} \cos(\delta \omega_m) & \sin(\delta \omega_m) \\ -\sin(\delta \omega_m) & \cos(\delta \omega_m) \end{bmatrix} \begin{bmatrix} p_{i, 2m} \\ p_{i, 2m+1} \end{bmatrix} = \begin{bmatrix} \sin\left((i+\delta) \omega_m\right) \\ \cos\left((i+\delta) \omega_m\right) \end{bmatrix} = \begin{bmatrix} p_{i+\delta, 2m} \\ p_{i+\delta, 2m+1} \end{bmatrix}. \tag{10.4.2}

However, because pi\mathbf{p}_i is added to xi\mathbf{x}_i, the bilinear attention score with A=WqWk⊤/dh\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h} expands into four terms:

(xi+pi)⊤A (xj+pj)=xi⊤A xj⏟content–content+xi⊤A pj⏟content–position+pi⊤A xj⏟position–content+pi⊤A pj⏟position–position.(10.4.3)\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 ii and jj shift together), and even pi⊤A pj\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j depends purely on j−ij - i only if A\mathbf{A} is block-diagonal with 2×22 \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−ij - i:

(Riq)⊤(Rjk)=q⊤Ri⊤Rjk=q⊤Rj−ikfor all i,j.(10.4.4)(\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 Ri⊤Rj=Rj−i\mathbf{R}_i^\top \mathbf{R}_j = \mathbf{R}_{j-i} with full-rank R0\mathbf{R}_0 implies: (1) R0=I\mathbf{R}_0 = \mathbf{I} (from R0⊤R0=R0\mathbf{R}_0^\top \mathbf{R}_0 = \mathbf{R}_0); (2) Ri⊤Ri=I\mathbf{R}_i^\top \mathbf{R}_i = \mathbf{I}, so every Ri\mathbf{R}_i is orthogonal and norm-preserving; and (3) Ri+j=RiRj\mathbf{R}_{i+j} = \mathbf{R}_i \mathbf{R}_j, so Ri=R1i\mathbf{R}_i = \mathbf{R}_1^i. In an appropriate orthonormal basis (absorbable into Wq,Wk\mathbf{W}_q, \mathbf{W}_k), any orthogonal matrix R1\mathbf{R}_1 decomposes into 2×22 \times 2 planar rotations. RoPE partitions the dhd_h coordinates of each query and key into dh/2d_h/2 pairs and rotates pair mm at position ii by iωmi\omega_m with ωm=10000−2m/dh\omega_m = 10000^{-2m/d_h} (Figure 10.4.1):

Ri=[R(iω0)⋱R(iωdh/2−1)],R(α)=[cos⁡α−sin⁡αsin⁡αcos⁡α].(10.4.5)\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.

Figure 10.4.1:

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 (2θ+φ2\theta + \varphi in both panels), and hence the attention score, unchanged. Here θ=ωm\theta = \omega_m is the angle by which pair mm turns per position, and φ\varphi 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 O(1)O(1) 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 h∈{1,…,H}h \in \{1, \ldots, H\}:
scoreij=qi⊤kjdh−mh (i−j),mh=2−8h/H.(10.4.6)\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 mhm_h (e.g., 1/4,1/16,1/64,1/2561/4, 1/16, 1/64, 1/256 for H=4H = 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+1i + 1 keys at position ii) 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=128L = 128 bytes and evaluate perplexity at lengths 128128, 256256, and 512512.

10.4.5.1 The Language Model TinyCharLM#

TinyCharLM embeds 256 byte values into width d=128d = 128, applies two causal self-attention blocks (H=4H = 4 heads of width dh=32d_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]

In embed, the sinusoidal table is scaled by 1/d1/\sqrt{d} so its entries match the scale of the N(0,0.022)\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

In attend, RoPE rotates queries and keys, whereas ALiBi adds the distance bias −mh(i−j)-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

10.4.5.2 The Experiment#

We train three seeds of each scheme for 3,0003{,}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

We evaluate validation perplexity on identical validation bytes regrouped into windows of n∈{128,256,512}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)

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 (n=128n = 128), RoPE achieves the lowest perplexity (7.37.3), ahead of learned (9.69.6), sinusoidal (9.79.7--9.89.8), and ALiBi (9.99.9--10.010.0), all of which improve on the byte-bigram baseline (11.611.6); NoPE remains at the bigram level in this small two-block model.

At n=512n = 512, the three schemes whose representations encounter out-of-range values degrade sharply: learned embeddings hit untrained rows (128128--511511), 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.99.9. To see why, we measure the fraction of attention weight that ALiBi's four heads place on keys at distance ≥128\ge 128, and compare against masking out all keys at distance ≥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

We confirm this directly with WindowedALiBi, which copies the trained ALiBi weights and hard-masks all keys at distance ≥128\ge 128 (window=train_len) when evaluating at length T=512T = 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)

Removing all keys at distance ≥128\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=128L = 128, and how can we repair it? For head width dh=32d_h = 32, the 1616 coordinate pairs have periods 2π/ωm=2π⋅10000m/162\pi / \omega_m = 2\pi \cdot 10000^{m/16}. The first 66 fast pairs have periods ≤112<128\le 112 \lt 128 and already complete full rotations within the training window; the remaining 1010 slow pairs have periods from 199199 to 35,00035{,}000 and rotate into unseen angular regions at n=512n = 512.

Position interpolation (Chen et al., 2023) scales all angles by 128/512=1/4128 / 512 = 1/4 to map the new context range back into the trained interval [0,128)[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↦b sdh/(dh−2)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)

Rescaling only the slow pairs cuts length-512 perplexity from about 2727 down to about 99 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(ΠX)=Πf(X)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−ij - i forces orthogonal planar rotations on queries and keys (RoPE), whereas ALiBi subtracts a per-head linear distance penalty −mh(i−j)-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#

  1. Distinct positions, distinct codes. Let pi\mathbf{p}_i be row ii of the sinusoidal table (10.4.1) of width dd, with the frequencies ωm=1/100002m/d\omega_m = 1/10000^{2m/d}.
    1. Show that
pi⊤pi+δ=∑m=0d/2−1cos⁡(δ ωm),\mathbf{p}_i^\top \mathbf{p}_{i+\delta} = \sum_{m=0}^{d/2-1} \cos(\delta\,\omega_m),

derive ∥pi−pi+δ∥2\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|^2 from it, and conclude that both quantities depend on the offset δ\delta alone.

  1. Conclude that pi=pi′\mathbf{p}_i = \mathbf{p}_{i'} only if (i−i′) ωm(i - i')\,\omega_m is a multiple of 2π2\pi for every mm, and that no two distinct integer positions share a row, whatever the value of max_len.
  2. The fastest pair has period 2π2\pi, so it nearly repeats at integer offsets close to multiples of 2π2\pi. Find the offset δ<512\delta \lt 512 at which its angle comes closest to a multiple of 2π2\pi, and give the residual angle. For d=32d = 32, compare ∥pi−pi+δ∥\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\| at this offset with its value at δ=1\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.
  1. Additive codes in the score. With the additive encoding of Section 10.4.2.2, a first-layer head scores the inputs at positions ii and jj by the four terms of (10.4.3), with A=WqWk⊤/dh\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}.

    1. Let J\mathbf{J} be the rotation of the plane by π/2\pi/2. Using (10.4.2), show that the position--position term pi⊤A pj\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j depends only on j−ij - i when A\mathbf{A} is block diagonal with 2×22 \times 2 blocks amI+bmJa_m \mathbf{I} + b_m \mathbf{J}, one per frequency pair. Exercise 1 treats A=I\mathbf{A} = \mathbf{I}. Then show that a single nonzero entry of A\mathbf{A} that couples two different frequency pairs destroys this property.
    2. Determine when the content--position term xi⊤A pj\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j is unchanged for every shift of jj. 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.
  2. [code] Where extrapolation fails. The perplexities of Section 10.4.5.2 at context 512 average the loss over all positions of each sequence.

    1. 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 TinyCharLM guarantee this for every scheme?
    2. 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?
    3. 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 overrides attend, 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?
  3. Biases that keep the symmetry. ● Suppose that a fixed matrix B∈Rn×n\mathbf{B} \in \mathbb{R}^{n \times n} is added to the score matrix S\mathbf{S} of the proof before the softmax, so that the self-attention layer (Section 10.3) computes softmax(S+B) XWv\mathrm{softmax}(\mathbf{S} + \mathbf{B})\, \mathbf{X}\mathbf{W}_v.

    1. Show that the proposition still holds for every permutation matrix Π\boldsymbol{\Pi} with Π⊤BΠ=B\boldsymbol{\Pi}^\top \mathbf{B} \boldsymbol{\Pi} = \mathbf{B}.
    2. Find all matrices B\mathbf{B} that satisfy this condition for every permutation, and describe how each of them changes the attention weights.
    3. Without the causal mask, the ALiBi bias of (10.4.6) extends symmetrically to Bij=−mh ∣i−j∣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 (10.4.6) does not share this symmetry.
  4. Offset preference in RoPE. ● Split a query q\mathbf{q} and a key k\mathbf{k} into the dh/2d_h/2 two-dimensional pairs q(m),k(m)∈R2\mathbf{q}^{(m)}, \mathbf{k}^{(m)} \in \mathbb{R}^2 on which (10.4.5) acts, and let δ=j−i\delta = j - i be the offset of the key position jj from the query position ii.

    1. Show that the RoPE score (10.4.4) equals
∑m=0dh/2−1∥q(m)∥ ∥k(m)∥cos⁡(δ ωm−ψm),(10.4.7)\sum_{m=0}^{d_h/2-1} \|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\| \cos(\delta\,\omega_m - \psi_m), \tag{10.4.7}

where ψm\psi_m is the angle from k(m)\mathbf{k}^{(m)} to q(m)\mathbf{q}^{(m)} (the φ\varphi of Figure 10.4.1 with the opposite sign).

  1. Choose the angles ψm\psi_m so that every pair contributes its maximum at the offset δ=−1\delta = -1, the previous token. With all products ∥q(m)∥ ∥k(m)∥\|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\| equal to cc, show that the score, as a function of δ\delta, is cc times a shifted copy of the dot product pi⊤pi+δ\mathbf{p}_i^\top \mathbf{p}_{i+\delta} of Exercise 1 for a sinusoidal table of width dhd_h.
  2. Take dh=32d_h = 32 and the query at position 127, which attends to the offsets δ=−127,…,0\delta = -127, \ldots, 0. Let the attention logits equal these scores, with the factor 1/dh1/\sqrt{d_h} absorbed into cc. Find the cc at which the offset −1-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-1 and the scores at its neighbors?
  1. [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.
    1. Show that a pair that completes a full rotation within the training offsets 0 to 127 has already met, to within ωm/2\omega_m/2 modulo 2π2\pi, every angle that a longer offset produces. Compute the gap of Exercise 5 between the score at offset −1-1 and the scores at its neighbors for dh=32d_h = 32, before the rescaling, after the uniform rescaling by 128/512128/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.
    2. Show that the base b′=b sdh/(dh−2)b' = b\, s^{d_h/(d_h-2)} leaves ω0\omega_0 unchanged and divides ωdh/2−1\omega_{d_h/2-1} by ss. Set rope_base of models['rope'] to this base for s=4s = 4, evaluate at 128, 256, and 512 without training, and compare with the two rescalings of the cell.
    3. 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 trained models['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.

Discussions