Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

Positional encodings: sinusoidal, learned, relative, RoPE, ALiBi

Self-attention is blind to order, so Transformers add position information. The original model added fixed sinusoids, BERT and GPT learned one vector per position, Shaw et al. and T5 added learned biases depending on relative distance, RoPE rotates queries and keys so their dot product depends only on relative position, and ALiBi subtracts a penalty growing linearly with distance. The choice affects how well a model handles sequences longer than it was trained on. This page covers each scheme, its parameters and its extrapolation behaviour. In the exercises you implement sinusoids, RoPE and ALiBi and verify RoPE's relative property. You then train one causal attention layer to output the token two steps back on length 16 and test it on 32 and 64. RoPE keeps 0.993 at length 32 against 0.716 for sinusoids and 0.562 for learned positions, and one-layer ALiBi cannot learn the task at all (0.562 even at length 16).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Telling the model where each word is

Attention compares every word with every other, but it has no idea of order: “dog bites man” and “man bites dog” look the same. Positional encodings fix that. Each method adds a different kind of address:

  • a fixed pattern of waves for each position;
  • a learned label for each position;
  • information about how far apart two words are.

Methods based on relative distance tend to cope better with texts longer than any seen in training. The demo shows the classic wave pattern.

Transformer lab
Rows are positions 0–47, columns are dimensions; low dimensions oscillate fast, high ones slowly. The line shows each position's similarity to position 0, which falls off with distance.
Why engineers care

Context length is a key capability of deployed models. How positions are encoded decides whether a model can handle longer logs, documents or sensor histories than it was trained on.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Without positional encodings, attention…
  2. 2. Relative methods encode…
  3. 3. A key test of a positional encoding is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Sinusoidal (Vaswani et al.):
    • PE(pos, 2i) = sin(pos/10000^(2i/d)) and PE(pos, 2i+1) = cos(…), added to the embeddings;
    • wavelengths run from 2π to almost 2π·10000;
    • a fixed offset k is a linear map (a rotation in each sine–cosine pair).
  • Learned absolute: a table of L_max × d vectors, 393,216 parameters for BERT-base (512 × 768). Positions beyond L_max have no vector at all.
  • Relative bias (Shaw et al.; T5):
    • learned biases b(i − j) are added to attention scores;
    • T5 groups distances into 32 buckets, exact up to 8 in each direction and logarithmic up to 128.
  • RoPE (Su et al.):
    • rotate each feature pair (2i, 2i+1) of the query and key at position m by angle m·θᵢ, with θᵢ = 10000^(−2i/d);
    • since rotations compose, q_mᵀk_n depends only on m − n;
    • no parameters are added.
  • ALiBi (Press et al.):
    • add −mₕ·|i − j| to the scores of head h, with slopes 2^(−8k/H), which gives 1/2, 1/4, …, 1/256 for 8 heads;
    • no embeddings at all.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Learned position parameters for 512 positions and d = 768:
  2. 2. RoPE makes q·k depend on…
  3. 3. First ALiBi slope for 8 heads:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Positional encodings in code

Exercise 1.

  • The sinusoidal table matched its formula.
  • RoPE gave equal scores for position pairs (7, 4) and (3, 0) and preserved vector lengths.
  • ALiBi’s bias was −1.5 at distance 3 with slope 0.5.

Practice.

  • RoPE is the default in many open language models (LLaMA, Mistral, Qwen). It is applied to queries and keys inside each attention layer, not added to embeddings.
  • To extend a RoPE model’s context, rescale positions by position interpolation (Chen et al., 2023) or use NTK-aware or YaRN scaling of θ, usually with brief fine-tuning.
  • ALiBi models (BLOOM, MPT) extrapolate in perplexity to longer inputs.
  • Learned absolute positions (BERT, GPT-2) are capped at L_max.
def apply_rope(x, pos):                      # x: (..., L, d), pos: (L,)
    th = 10000 ** (-torch.arange(0, x.shape[-1], 2) / x.shape[-1])
    ang = pos[:, None] * th; c, s = ang.cos(), ang.sin()
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], -1).flatten(-2)
🐍 Exercise 1: positional encodings
Implement sinusoidal encodings, RoPE and ALiBi biases; verify RoPE depends only on relative position.
📝 Quick check (Level 2)
0/3 answered
  1. 1. RoPE is applied to…
  2. 2. A method to extend RoPE context:
  3. 3. Models with ALiBi:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why relative position helps extrapolation.

  • Absolute schemes tie behaviour to specific indices. A model trained on positions 0–15 has never seen position 40: its learned vector is untrained, or its sinusoid phases are new combinations.
  • Relative schemes depend on distances, which recur at every length. A rule like “look two back” is the same at position 5 or 50.

RoPE’s property.

  • With rotation matrices R_m, (R_m q)ᵀ(R_n k) = qᵀR(n−m)k, a function of the offset only.
  • High-frequency pairs encode fine position and low-frequency pairs coarse position.
  • Unseen large offsets still produce new angles for low frequencies, which limits extrapolation far beyond training.

ALiBi’s bias is monotone.

  • A penalty growing with distance favours recent tokens: an inductive bias towards recency.
  • In a single layer with no other position signal, it cannot prefer distance 2 over distances 0 and 1, since closer tokens are always penalised less.
  • Deep ALiBi models can recover such patterns across layers (for instance from causal-mask counting), which is consistent with their good long-input perplexity in the paper.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Absolute schemes struggle beyond training length because…
  2. 2. (R_m q)ᵀ(R_n k) equals…
  3. 3. ALiBi's bias favours…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Which encodings extrapolate?

History.

  • A. Vaswani et al. (2017) introduced sinusoids. BERT and GPT used learned positions.
  • P. Shaw, J. Uszkoreit and A. Vaswani added relative position representations (2018). Transformer-XL (2019) and T5 (2020) used relative schemes.
  • J. Su et al. introduced RoPE (RoFormer, 2021).
  • O. Press, N. Smith and M. Lewis introduced ALiBi, “Train short, test long” (ICLR 2022).

Exercise 2.

  • Model: one causal attention layer (4 heads, d = 32) with the NumPy Transformer from E12-1, extended with RoPE and ALiBi (gradients checked numerically).
  • Task: output the token two steps back, trained for 300 steps on length 16.
  • Test: sequences of length 16, 32 and 64.
encoding length 16 (trained) 32 64
none 0.387 0.322 0.275
learned 1.000 0.562 0.363
sinusoidal 1.000 0.716 0.540
RoPE 1.000 0.993 0.646
ALiBi 0.562 0.500 0.451

A second seed gave the same picture: RoPE 1.0, 1.0 and 0.70; learned 1.0, 0.57 and 0.37.

  • RoPE extrapolates best: almost perfect at twice the training length, because “two back” is the same rotation offset everywhere. It still degrades at 4 times the length, where low-frequency angles are new.
  • Learned positions fail beyond training, since positions 16–63 were never trained. Sinusoids are in between.
  • One-layer ALiBi cannot learn this rule at all. Its penalty grows with distance, so it always prefers the current and previous token over the one two back. This is a limit of a single layer, not a verdict on ALiBi in deep language models.
  • With no encoding, the causal mask alone gives a little position signal (0.39 against chance 0.17).
🐍 Exercise 2 (research): which encodings extrapolate?
Train one causal attention layer with five positional schemes on length 16 and test on 32 and 64.

Positional encodings in AI, robotics and aerospace

  • Long telemetry: relative encodings help models trained on short windows run on longer missions.
  • Irregular sampling: time stamps can replace integer positions in sinusoidal or rotary encodings for unevenly sampled sensors.
  • Spatial data: 2-D and 3-D versions of sinusoidal and rotary encodings give image patches and point clouds their geometry.

References

  1. A. Vaswani et al. (2017). “Attention is all you need.” Proc. NeurIPS.
  2. P. Shaw, J. Uszkoreit, A. Vaswani (2018). “Self-attention with relative position representations.” Proc. NAACL.
  3. J. Su et al. (2021). “RoFormer: enhanced Transformer with rotary position embedding.” arXiv:2104.09864.
  4. O. Press, N. A. Smith, M. Lewis (2022). “Train short, test long: attention with linear biases enables input length extrapolation.” Proc. ICLR.
  5. S. Chen et al. (2023). “Extending context window of large language models via positional interpolation.” arXiv:2306.15595.