Positional Information

Dive into Deep Learning · §10.4

Positional Information: Sinusoidal, Learned, RoPE, and ALiBi
permutation equivariance · absolute embeddings · rotary embeddings (RoPE) · ALiBi & NoPE · length extrapolation

Why Self-Attention Alone Is Blind to Word Order

Motivation

  • Order Blindness: The sentences “dog bites man” and “man bites dog” contain the same three words; passed through unmasked self-attention, they produce the exact same output vectors in permuted positions.
  • The Length-Extrapolation Challenge: Models like GPT-2 small learn a fixed lookup table of 1{,}024 position vectors—token 1{,}025 has no trained representation.
  • Our Goal: Inject positional information that preserves relative distance and generalizes beyond the training context length.

Theorem: Unmasked Self-Attention Is Equivariant

Permutation Symmetry

  • Permutation Equivariance: For any n \times n permutation matrix \boldsymbol{\Pi} (\boldsymbol{\Pi}^\top \boldsymbol{\Pi} = \mathbf{I}): f(\boldsymbol{\Pi}\mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})
  • Four-Step Mechanism: Row-wise projections commute with \boldsymbol{\Pi}, scores transform as \boldsymbol{\Pi}\mathbf{S}\boldsymbol{\Pi}^\top, row-wise softmax preserves \boldsymbol{\Pi}\mathbf{A}\boldsymbol{\Pi}^\top, and multiplying by \boldsymbol{\Pi}\mathbf{V} cancels \boldsymbol{\Pi}^\top\boldsymbol{\Pi} = \mathbf{I}.
  • Depth Invariance: Stacking any number of unmasked attention and MLP layers preserves permutation equivariance.

Verifying Permutation Equivariance in Code

Empirical Check

Passing 8 random token vectors through a 4-head MultiHeadAttention layer before and after a random permutation produces identical outputs up to float32 round-off:

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

Notice that a causal mask breaks permutation symmetry even without position vectors (NoPE), because query i averages over i + 1 predecessors.

Absolute Position Embeddings: Learned Tables

Absolute Encodings

  • Breaking Symmetry at the Input: Adding a position vector \mathbf{p}_i \in \mathbb{R}^d (row i of \mathbf{P}) to each token \mathbf{x}_i breaks equivariance: \boldsymbol{\Pi}\mathbf{X} + \mathbf{P} \neq \boldsymbol{\Pi}(\mathbf{X} + \mathbf{P})
  • Learned Position Tables (BERT, GPT-2): Treat \mathbf{P} \in \mathbb{R}^{L_{\max} \times d} as a free parameter matrix.
  • Zero-Gradient Extrapolation Failure: When trained at length L = 128, rows 128, \ldots, L_{\max}-1 receive zero gradient and remain random noise.

Sinusoidal Position Encodings Across Frequencies

Deterministic Absolute Codes

  • Vaswani et al. (2017) populate row i of \mathbf{P} \in \mathbb{R}^{n \times d} with sines and cosines at d/2 geometrically spaced frequencies \omega_m = 10000^{-2m/d}: p_{i, 2m} = \sin(i\,\omega_m) p_{i, 2m+1} = \cos(i\,\omega_m)
  • Geometric Wavelengths: Periods 2\pi / \omega_m progress from 2\pi \approx 6.28 tokens (m = 0) to 2\pi \times 10^4 \approx 62{,}832 tokens (m = d/2 - 1).

Sinusoids as a Continuous Binary Counter

Multi-Scale Geometry

  • Continuous Binary Counter: In binary, the least significant bit alternates every step, the next every 2 steps, the next every 4. Sinusoidal column pairs do the same smoothly on the unit circle.
  • Offset-Only Inner Product: The dot product between two sinusoidal rows depends solely on their relative offset \delta: \mathbf{p}_i^\top \mathbf{p}_{i+\delta} = \sum_{m=0}^{d/2-1} \cos(\delta\,\omega_m)

Position Shifts as 2×2 Planar Rotations

Trigonometric Shift Identity

  • Linear Offset Operator: By angle-addition identities, shifting i \mapsto i + \delta applies a 2 \times 2 rotation depending only on \delta: \begin{bmatrix} \cos(\delta \omega_m) & \sin(\delta \omega_m) \\ -\sin(\delta \omega_m) & \cos(\delta \omega_m) \end{bmatrix} \begin{bmatrix} \sin(i \omega_m) \\ \cos(i \omega_m) \end{bmatrix} = \begin{bmatrix} p_{i+\delta, 2m} \\ p_{i+\delta, 2m+1} \end{bmatrix}
  • Relative Offsets Live Inside \mathbf{P}: For every frequency pair m, the code at i + \delta is a fixed linear rotation of the code at i.

Why Adding Position Vectors Pollutes the Score

The Four-Term Expansion

  • Expanding (\mathbf{x}_i + \mathbf{p}_i)^\top \mathbf{A}\,(\mathbf{x}_j + \mathbf{p}_j) with \mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h} produces four bilinear terms.
  • Absolute Cross-Term Coupling: The cross terms \mathbf{x}_i^\top \mathbf{A}\,\mathbf{p}_j and \mathbf{p}_i^\top \mathbf{A}\,\mathbf{x}_j couple token content directly with absolute position vectors, varying whenever i and j shift together.
  • Cross-Frequency Mixing: Even \mathbf{p}_i^\top \mathbf{A}\,\mathbf{p}_j loses shift invariance when \mathbf{A} mixes different frequency pairs.

Deriving RoPE from Relative-Offset Invariance

Rotary Position Embeddings (RoPE)

Instead of adding \mathbf{p}_i to \mathbf{x}_i, Rotary Position Embeddings (Su et al., 2021) transform queries and keys multiplicatively via matrices \mathbf{R}_i so that every inner product depends solely on 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} \qquad \forall\, i, j

  • 1. Identity at Zero (i = j = 0): \mathbf{R}_0^\top \mathbf{R}_0 = \mathbf{R}_0; requiring full rank forces \mathbf{R}_0 = \mathbf{I}.
  • 2. Orthogonality (i = j): \mathbf{R}_i^\top \mathbf{R}_i = \mathbf{R}_0 = \mathbf{I}, so every \mathbf{R}_i is orthogonal and preserves query/key norms.
  • 3. Group Homomorphism: \mathbf{R}_{-i} = \mathbf{R}_i^\top and \mathbf{R}_{i+j} = \mathbf{R}_i \mathbf{R}_j, which forces \mathbf{R}_i = \mathbf{R}_1^i (powers of one orthogonal generator \mathbf{R}_1, decomposing into 2 \times 2 planar rotations).

RoPE: Block-Diagonal 2×2 Planar Rotations

Geometry of RoPE

  • Partition \mathbf{q}, \mathbf{k} \in \mathbb{R}^{d_h} into d_h/2 coordinate pairs (2m, 2m+1) and rotate pair m at position i by angle i\,\omega_m with \omega_m = 10000^{-2m/d_h}: R(i\omega_m) = \begin{bmatrix} \cos(i\omega_m) & -\sin(i\omega_m) \\ \sin(i\omega_m) & \cos(i\omega_m) \end{bmatrix}
  • Shift Invariance: Shifting both positions by +3 rotates \mathbf{q} and \mathbf{k} by the exact same angle 3\omega_m, leaving the angle between them (and their dot product) unchanged.
  • Values Stay Unrotated: Only queries and keys are rotated, keeping value vectors shift-invariant.

RoPE rotates each 2D feature pair by an angle proportional to position, preserving relative angles under shifts.

Implementing RoPE and Testing Shift Invariance

Code & Verification

  • rope splits even (0::2) and odd (1::2) coordinates, applies the 2 \times 2 rotation using float32 angles cast to x.dtype, and interleaves the pairs back.
  • Shifting all 32 positions by 1, 17, or 480 changes RoPE scores by at most float32 round-off (\sim 10^{-6}), whereas additive sinusoidal scores change by 2.7.
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

Distance Penalties (ALiBi) and Mask-Only (NoPE)

Alternative Schemes

  • ALiBi (Press et al., 2022): Subtracts a linear distance penalty from pre-softmax causal scores in head h: \mathrm{score}_{ij}^{(h)} = \frac{\mathbf{q}_i^\top \mathbf{k}_j}{\sqrt{d_h}} - m_h\,(i - j), \quad m_h = 2^{-8h/H}
  • Multi-Horizon Slopes: Steep heads (m_1 = 1/4) focus locally, while gentle heads (m_4 = 1/256) integrate broadly.
  • NoPE (Kazemnejad et al., 2023): Relies purely on the causal mask (exposing i + 1 keys at position i) to break symmetry.

Five Positional Schemes in TinyCharLM

Experimental Architecture

  • Benchmark Model (TinyCharLM): Two-block attention-only byte language model (d = 128, H = 4, d_h = 32, tied output head) trained on WikiText-103 at n = 128.
  • Input Schemes (learned, sinusoidal): Add position vectors once inside embed(X).
  • Attention-Layer Schemes (rope, alibi, none): Leave embeddings untouched and act inside every block’s attend call.

Implementing embed, alibi, and attend

TinyCharLM Implementation

RoPE rotates q and k in every block; ALiBi adds the bias -m_h * (i - j) to the scores:

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])

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

Train Short (128), Test Long (128, 256, 512)

Extrapolation Benchmark

After training 3 seeds of each scheme for 3{,}000 AdamW steps at context n = 128, we evaluate validation byte perplexity on identical WikiText-103 bytes regrouped into windows of n \in \{128, 256, 512\}:

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)
byte bigram: perplexity 11.6

Analyzing In-Range vs. Out-of-Range Perplexity

Why Extrapolation Fails

Because causal masking ensures positions 0 \ldots 127 compute identical logits regardless of total window length, every perplexity increase at n \in \{256, 512\} comes from positions \ge 128:

  • RoPE Wins In-Range (7.3 at n = 128) but Degrades at 512 (\approx 27): Pure offset rotations give the strongest inductive bias within the trained window, but at offsets > 127 low-frequency pairs rotate into angular sectors never seen during training.
  • Learned (9.6 \to 20–25) & Sinusoidal (\approx 9.7 \to \approx 15.5): Learned embeddings hit random untrained rows 128 \ldots 511; sinusoidal slow columns take novel combinations that conflict with content–position cross terms.
  • NoPE Stalls at the Byte-Bigram Baseline (11.6): Without an explicit position code, a two-block attention-only model predicts almost entirely from the current byte in the residual stream.

Pitfall: Does Flat Perplexity Mean Long-Range Use?

Probing ALiBi Beyond the Window

ALiBi’s perplexity stays completely flat at \approx 9.9 from n = 128 to n = 512. Does ALiBi actually extract useful information from bytes \ge 128 positions back, or does it simply ignore them?

      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
        all keys: perplexity at 512   9.9 (9.7-9.9)
 keys < 128 back: perplexity at 512   9.9 (9.7-9.9)

Diagnostic Note: Hard-masking out all keys at distance \ge 128 (WindowedALiBi) leaves ALiBi’s perplexity at 512 unchanged (9.9). Steep heads (1, 2) assign 0.000 weight beyond 128, while gentle heads (3, 4) compute a broad recency average. A flat extrapolation curve shows that a scheme avoids breaking on distant keys, not that it retrieves from them.

Why RoPE Breaks: Fast vs. Slow Frequency Pairs

Frequency Decomposition

  • 6 Fast Pairs (m = 0 \ldots 5, periods \le 112 < 128): Complete full 2\pi revolutions within the 128-byte training window; every angle at offset 400 was already seen modulo 2\pi.
  • 10 Slow Pairs (m = 6 \ldots 15, periods 199 to 35{,}000 > 128): Rotate into unseen angular regions at n = 512, corrupting QK dot products.
  • Selective Slow-Pair Scaling: Keep fast pairs at scale 1.0 (preserving local byte phases) and scale only slow pairs by 128/512 = 0.25.

Zero-Shot Context Extension by Scaling Slow Pairs

Selective Interpolation

Leaving the 6 fast pairs untouched (scale = 1.0) and multiplying only the 10 slow pairs by 128/512 = 0.25 repairs length-512 perplexity from \approx 27 down to \approx 9 without updating a single model weight:

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)

Uniformly scaling all pairs (all pairs) without fine-tuning ruins local byte resolution across every context length (\sim 40\text{--}41 perplexity, worse than a bigram), whereas selective slow-pair scaling preserves local phases and compresses only out-of-distribution slow angles.

Production Recipes: YaRN and NTK-Aware Scaling

Long-Context LLM Engineering

Modern open-weights language models extend RoPE contexts from 4\text{K}/8\text{K} to 128\text{K}+ using two closely related frequency-scaling techniques:

  • NTK-Aware Base Scaling: Replaces the RoPE base b = 10000 with b' = b \cdot s^{d_h / (d_h - 2)} for context extension factor s = L_{\textrm{new}} / L_{\textrm{train}}.
    • Pair m = 0 keeps frequency \omega_0 = (b')^0 = 1 radian/token (local resolution preserved).
    • The slowest pair m = (d_h - 2)/2 has its frequency divided by (b'/b)^{(d_h-2)/d_h} = s, fitting the s-fold longer context into its trained angular arc.
  • YaRN (Yet another RoPE extensioN, Peng et al., 2024): Keeps fast frequencies unchanged (\text{scale} = 1), linearly interpolates slow frequencies (\text{scale} = 1/s), blends intermediate frequencies with a smooth ramp, and applies a softmax temperature scale, followed by a brief fine-tune.

Concept Check: Symmetry, RoPE, and Extrapolation

Check Your Understanding

Test your grasp of positional encodings and context extension:

  1. Relative Angle in RoPE: Pair m = 0 rotates by \omega_0 = 1\text{ rad/token}. If a query and key share identical unrotated pair-0 vectors, what angle separates their pair-0 vectors when the query is at i = 3 and the key is at j = 5? What if i = 1{,}003 and j = 1{,}005?
  2. Additive Cross-Terms: In (\mathbf{x}_i + \mathbf{p}_i)^\top \mathbf{A}\,(\mathbf{x}_j + \mathbf{p}_j), which terms change when we shift both tokens by +17 positions (i \mapsto i+17, j \mapsto j+17)?
  3. NTK-Aware Base Calculation: To extend a head of width d_h = 64 from 4\text{K} to 16\text{K} tokens (s = 4) via NTK-aware scaling from base b = 10{,}000, what is the new base b'?

Answers:

  1. 2\text{ radians} in both cases ((5 - 3)\omega_0 = (1005 - 1003)\omega_0 = 2). Only the relative offset j - i affects the angle and dot product.
  2. The content–position cross terms \mathbf{x}_i^\top\mathbf{A}\mathbf{p}_j and \mathbf{p}_i^\top\mathbf{A}\mathbf{x}_j (and \mathbf{p}_i^\top\mathbf{A}\mathbf{p}_j unless \mathbf{A} is block-diagonal with 2 \times 2 scaled rotations).
  3. b' = 10{,}000 \times 4^{64/62} \approx 41{,}826, which keeps \omega_0 = 1 unchanged while dividing the slowest frequency \omega_{31} by 4.

Summary: Positional Information in Attention

Key Takeaways

Scheme Injection Rule Relative-Offset Invariant? In-Range PPL (128) Extrap PPL (512) Primary Strength & Limitation
NoPE Causal mask j \le i only N/A \approx 11.7 \approx 11.8 Zero overhead, but weak position resolution in shallow models
Learned \mathbf{x}_i + \mathbf{p}_i (trainable table) No 9.6 20–25 Simple, flexible in-range; rows \ge L_{\textrm{train}} receive zero gradient
Sinusoidal \mathbf{x}_i + \mathbf{p}_i/\sqrt{d} (fixed sines) No (cross terms) \approx 9.7 \approx 15.5 Parameter-free counter; additive cross terms break under shifts
ALiBi s_{ij} - m_h(i - j) Yes \approx 10 9.9 Flat extrapolation via recency bias; attenuates distant keys
RoPE (\mathbf{R}_i\mathbf{q}_i)^\top(\mathbf{R}_j\mathbf{k}_j) = \mathbf{q}_i^\top\mathbf{R}_{j-i}\mathbf{k}_j Yes (exact) 7.3 \approx 27 \to \mathbf{\approx 9}^* Best in-range quality; *slow-pair / YaRN scaling repairs long contexts