Positional Encoding: Sinusoidal, Learned, RoPE and ALiBi
Self-attention is blind to order: permute the tokens and the outputs are permuted the same way. Building a Transformer Block fixed that the classic way, by adding a sinusoidal or learned position vector to each token embedding, and checked that sinusoidal vectors have a dot product that depends only on the distance. For language models the position scheme matters more than it first seems: it decides whether a model trained on 4096 tokens can read 16,000, how fast attention to far-away tokens fades, and how many parameters are spent on positions. This lesson implements the schemes that modern models actually use, RoPE (Llama, Mistral, Qwen, GPT-NeoX) and ALiBi (BLOOM, MPT), looks at T5's relative bias, inspects the learned tables of BERT and GPT-2, and measures why extending the context is hard. The math background is in Positional Encodings.
Absolute versus relative
Two families:
- Absolute schemes give each position a vector , added to the input once: . Sinusoidal (the 2017 transformer) and learned tables (BERT, GPT-2, ViT) are absolute.
- Relative schemes change the attention score between query position and key position so that it depends on , in every layer. "The word two tokens back" is what language mostly needs; "the word at position 517" rarely is.
Adding to the input does not make scores relative. With projections, the score is
and the mixed terms depend on and separately. RoPE was designed so that the score depends on content and on only.
RoPE: rotate queries and keys
Rotary position embedding (Su et al., 2021) splits the dimensions of a query or key into pairs and rotates pair by the angle , with the same frequencies as the sinusoidal scheme, :
Write for the block-diagonal matrix of all these rotations. Rotations compose by adding angles, and the transpose of a rotation is the rotation backwards, so
which depends on the positions only through . Nothing is added to the input; the rotation is applied to and (never to ) inside every attention layer, after the projections. It has no parameters, and vector lengths are unchanged. The example implements it, checks the relative property and compares with additive positions.
import numpy as np
def rope(x, pos, base=10000.0):
"""Rotate each pair (x[2i], x[2i+1]) of x (T, d) by the angle pos * base**(-2i/d)."""
d = x.shape[-1]
inv_freq = base ** (-np.arange(0, d, 2) / d) # (d/2,) one frequency per pair
ang = np.asarray(pos, dtype=float)[:, None] * inv_freq # (T, d/2)
cos, sin = np.cos(ang), np.sin(ang)
x1, x2 = x[..., 0::2], x[..., 1::2]
out = np.empty_like(x)
out[..., 0::2] = x1 * cos - x2 * sin
out[..., 1::2] = x1 * sin + x2 * cos
return out
rng = np.random.default_rng(0)
d = 16
q, k = rng.normal(size=(1, d)), rng.normal(size=(1, d))
def score(m, n): # query at position m, key at position n
return (rope(q, [m]) @ rope(k, [n]).T).item()
print("q.k without positions:", round((q @ k.T).item(), 4))
print("m - n = 3:", [round(score(m, m - 3), 4) for m in (3, 10, 500)])
print("m - n = -3:", [round(score(m, m + 3), 4) for m in (0, 10, 500)])
print("norm kept:", np.allclose(np.linalg.norm(rope(q, [123])), np.linalg.norm(q)))
# The same rotation as complex multiplication: pair (a, b) -> (a + ib) * e^{i * angle}.
z = (q[0, 0::2] + 1j * q[0, 1::2]) * np.exp(1j * 7 * 10000.0 ** (-np.arange(0, d, 2) / d))
print("complex form agrees:", np.allclose(np.stack([z.real, z.imag], 1).ravel(), rope(q, [7])[0]))
# Additive positions do NOT give a function of m - n once projections are involved.
def sinusoidal(pos, E):
ang = np.asarray(pos, dtype=float)[:, None] / 10000 ** (np.arange(0, E, 2) / E)
pe = np.zeros((len(pos), E)); pe[:, 0::2] = np.sin(ang); pe[:, 1::2] = np.cos(ang)
return pe
Wq, Wk = rng.normal(0, d ** -0.5, (d, d)), rng.normal(0, d ** -0.5, (d, d))
add = lambda m, n: (((q + sinusoidal([m], d)) @ Wq) @ ((k + sinusoidal([n], d)) @ Wk).T).item()
print("additive, m - n = 3:", [round(add(m, m - 3), 4) for m in (3, 10, 500)])
# Long-range decay: with q = k = all ones, the score shrinks (on average) with the distance.
ones = np.ones((1, 64))
for dist in (0, 1, 4, 16, 64, 256, 1024):
print(f"distance {dist:4d}: score {(rope(ones, [dist]) @ rope(ones, [0]).T).item():6.2f}")q.k without positions: 2.4724
m - n = 3: [2.7754, 2.7754, 2.7754]
m - n = -3: [1.9194, 1.9194, 1.9194]
norm kept: True
complex form agrees: True
additive, m - n = 3: [2.6561, -0.5814, 0.8506]
distance 0: score 64.00
distance 1: score 61.83
distance 4: score 47.87
distance 16: score 38.75
distance 64: score 27.81
distance 256: score 22.64
distance 1024: score 16.83
What the output shows:
- The score of the same and is 2.7754 whether the query is at position 3, 10 or 500, as long as the key is 3 positions earlier. With the key 3 positions later it is a different number (1.9194): RoPE distinguishes left from right, unlike the symmetric dot product of two sinusoidal vectors.
- In complex numbers, RoPE is multiplying each pair by , which is how many implementations write it.
- With added sinusoidal positions and projections, the same distance 3 gives 2.6561, and 0.8506 at different absolute positions.
- With , the score falls from 64 at distance 0 to 16.83 at distance 1024: high-frequency pairs rotate out of alignment quickly, so far-away keys get smaller scores on average. This built-in long-range decay is a mild preference for nearby tokens, not a hard cut-off; learned , can still pick out a distant token.
In practice RoPE is applied to the reshaped heads, (B, h, T, d_h), with cos and sin tables precomputed once for all positions. Some implementations pair dimension with ("rotate half") instead of with . Both are valid, but pretrained weights only work with the pairing they were trained with, a classic porting bug.
ALiBi: a distance penalty instead of a rotation
ALiBi (Press et al., 2022, "Train Short, Test Long") is even simpler: add nothing to the embeddings, rotate nothing, and subtract a penalty proportional to the distance from each score:
Each head gets its own fixed slope : steep heads look locally, flat heads look far. There are no parameters, and a distance never seen in training is just a larger penalty, which is why ALiBi extrapolates to longer inputs better than sinusoidal or learned positions. The example also implements T5's relative bias (Raffel et al., 2020): every head learns one scalar bias per bucket of relative distance, with exact buckets for small distances and logarithmically wider ones for large distances, all distances beyond max_distance sharing the last bucket.
import numpy as np
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def alibi_slopes(h): # geometric sequence 2^(-8/h), 2^(-16/h), ... (h a power of 2)
return 2.0 ** (-8.0 * np.arange(1, h + 1) / h)
def alibi_bias(T, h): # (h, T, T): -slope * (i - j) for keys j <= i, -inf for j > i
i, j = np.arange(T)[:, None], np.arange(T)[None, :]
dist = (i - j).astype(float)
bias = -alibi_slopes(h)[:, None, None] * dist
return np.where(j <= i, bias, -np.inf)
h = 8
print("slopes:", [round(float(s), 4) for s in alibi_slopes(h)])
B = alibi_bias(6, h)
print("head 1 bias, query 6:", (np.round(B[0, 5], 2) + 0.0).tolist())
# A query whose content scores are all equal: the bias alone decides the weights.
T = 64
B = alibi_bias(T, h)
for head in (0, 3, 7):
w = softmax(B[head, -1]) # last query, all 64 keys visible
near = int(np.searchsorted(np.cumsum(w[::-1]), 0.5)) + 1
print(f"head {head + 1}: weight on itself {w[-1]:.3f}, half the weight within the last {near} tokens")
# T5-style relative bias: distances -> buckets (exact for small, log-spaced for large), one learned bias per bucket.
def t5_bucket(rel, num_buckets=32, max_distance=128): # bidirectional, as in the T5 encoder
nb = num_buckets // 2
ret = (rel > 0).astype(int) * nb # keys after the query use the upper half
n = np.abs(rel)
max_exact = nb // 2
large = max_exact + (np.log(np.maximum(n, 1) / max_exact) / np.log(max_distance / max_exact)
* (nb - max_exact)).astype(int)
large = np.minimum(large, nb - 1)
return ret + np.where(n < max_exact, n, large)
rel = np.array([-300, -128, -64, -20, -8, -7, -1, 0, 1, 2, 7, 8, 20, 64, 128, 300])
print("relative positions:", rel.tolist())
print("buckets: ", t5_bucket(rel).tolist())slopes: [0.5, 0.25, 0.125, 0.0625, 0.0312, 0.0156, 0.0078, 0.0039]
head 1 bias, query 6: [-2.5, -2.0, -1.5, -1.0, -0.5, 0.0]
head 1: weight on itself 0.393, half the weight within the last 2 tokens
head 4: weight on itself 0.062, half the weight within the last 11 tokens
head 8: weight on itself 0.018, half the weight within the last 31 tokens
relative positions: [-300, -128, -64, -20, -8, -7, -1, 0, 1, 2, 7, 8, 20, 64, 128, 300]
buckets: [15, 15, 14, 10, 8, 7, 1, 0, 17, 18, 23, 24, 26, 30, 31, 31]
With 8 heads the slopes run from to . For a query whose content scores are all equal, so that only the bias acts, head 1 puts 0.393 of its weight on the current token and half of its weight within the last 2 tokens; head 8 spreads half its weight over the last 31 tokens. In real use the content term is added on top, so a strong match can still win over a long distance.
The T5 buckets: distances 0 to 7 each have their own bucket (0 to 7 for keys before the query, 16 to 23 after it); 8 to 127 are spread logarithmically over 8 more buckets; everything from 128 on shares bucket 15 (or 31). A distance of 300 and of 3000 look the same to T5, which is one reason it handles long inputs gracefully but coarsely.
Learned absolute positions in BERT and GPT-2
BERT and GPT-2 learn a table of position vectors, one row per position, trained like word embeddings. The recorded example looks at the tables of the two small models cached in the course image and at what happens past the end of the table; the last line checks our NumPy T5 buckets against the function inside Transformers (which needs no T5 weights).
import numpy as np
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
from transformers.models.t5.modeling_t5 import T5Attention
from transformers.utils import logging
logging.set_verbosity_error()
bert = AutoModel.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
gpt2 = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")
P = bert.embeddings.position_embeddings.weight.detach()
print("BERT position_embeddings:", tuple(P.shape), " max_position_embeddings:", bert.config.max_position_embeddings)
print("GPT-2 wpe:", tuple(gpt2.transformer.wpe.weight.shape), " n_positions:", gpt2.config.n_positions)
# What did BERT learn? Neighbouring positions get similar vectors, distant ones do not.
cos = F.cosine_similarity
for dist in (1, 2, 8, 32, 128):
sims = cos(P[:512 - dist], P[dist:], dim=-1)
print(f"mean cosine of positions {dist:3d} apart: {sims.mean().item():.3f}")
# Longer than the table: BERT cannot embed position 512.
tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
ids = tok("word " * 600, return_tensors="pt")["input_ids"]
print("600 words ->", ids.shape[1], "tokens")
try:
bert(ids)
except Exception as e:
print("forward fails:", type(e).__name__)
ids = tok("word " * 600, truncation=True, max_length=512, return_tensors="pt")["input_ids"]
print("with truncation:", tuple(bert(ids).last_hidden_state.shape))
# Our NumPy T5 bucket function against the one in Transformers.
def t5_bucket(rel, num_buckets=32, max_distance=128):
nb = num_buckets // 2
ret = (rel > 0).astype(int) * nb
n = np.abs(rel)
max_exact = nb // 2
large = max_exact + (np.log(np.maximum(n, 1) / max_exact) / np.log(max_distance / max_exact)
* (nb - max_exact)).astype(int)
return ret + np.where(n < max_exact, n, np.minimum(large, nb - 1))
rel = np.arange(-300, 301)
hf = T5Attention._relative_position_bucket(torch.tensor(rel), bidirectional=True, num_buckets=32, max_distance=128)
print("NumPy buckets == Transformers buckets for -300..300:", bool((hf.numpy() == t5_bucket(rel)).all()))BERT position_embeddings: (512, 128) max_position_embeddings: 512
GPT-2 wpe: (1024, 2) n_positions: 1024
mean cosine of positions 1 apart: 0.896
mean cosine of positions 2 apart: 0.675
mean cosine of positions 8 apart: 0.457
mean cosine of positions 32 apart: 0.244
mean cosine of positions 128 apart: 0.020
600 words -> 602 tokens
forward fails: RuntimeError
with truncation: (1, 512, 128)
NumPy buckets == Transformers buckets for -300..300: True
- BERT's table is (512 positions, hidden size 128): 65,536 parameters, 1.5% of this small model. In BERT-base () it is 393,216. The GPT-2-shaped test model has a table (its width is only 2); real GPT-2 small has .
- The learned vectors are smooth: positions 1 apart have a mean cosine similarity of 0.896, 8 apart 0.457, 128 apart 0.020. Nobody told the model that positions are ordered; it learned that nearby positions behave alike from the data, a coarse version of what sinusoids build in.
- 600 words become 602 tokens (with
[CLS]and[SEP]) and the forward pass fails with aRuntimeError(the model's 512-long buffers of position and token-type ids cannot be expanded to 602). Withtruncation=True, max_length=512it runs and returns 512 vectors. Long documents are split into 512-token windows (with some overlap) and the per-window results combined. - The NumPy bucket function agrees with T5's for every relative position from to 300.
Extending the context
Long-context models are rarely trained at full length from the start: attention costs , and most text is short. The usual recipe is to pretrain at, say, 4096 tokens and extend later. Why that is not free with RoPE, and what the fixes do:
import numpy as np
d, base, L_train = 128, 10000.0, 4096
inv_freq = base ** (-np.arange(0, d, 2) / d) # 64 rotation frequencies, radians per position
turns = L_train * inv_freq / (2 * np.pi) # full turns each pair makes over the training length
print(f"fastest pair: {inv_freq[0]:.3f} rad/token, slowest: {inv_freq[-1]:.2e} rad/token")
print("pairs that make a full turn within 4096 tokens:", int((turns >= 1).sum()), "of", d // 2)
# The slow pairs have only seen angles in [0, L_train * freq]. At 4x the length they see new angles.
slow = inv_freq[-1]
print(f"slowest pair: max angle seen in training {L_train * slow:.3f} rad, at 16384 tokens {4 * L_train * slow:.3f} rad")
# Position interpolation: squeeze positions by L_train / L_new, so every angle stays in the trained range.
L_new = 4 * L_train
scale = L_train / L_new
print(f"with interpolation (x{scale}): angle at 16384 = {L_new * scale * slow:.3f} rad, "
f"neighbouring tokens now {scale * inv_freq[0]:.3f} rad apart instead of {inv_freq[0]:.3f}")
# NTK-style scaling instead raises the base: fast pairs (local detail) barely change, slow pairs are stretched.
new_base = base * (L_new / L_train) ** (d / (d - 2))
f2 = new_base ** (-np.arange(0, d, 2) / d)
print(f"new base {new_base:.0f}: fastest pair x{f2[0] / inv_freq[0]:.3f}, slowest pair x{f2[-1] / inv_freq[-1]:.3f}")
# A learned table simply has no row for unseen positions.
table = np.zeros((512, 8))
try:
table[np.arange(600)]
except IndexError as e:
print("learned table, position 600:", e)fastest pair: 1.000 rad/token, slowest: 1.15e-04 rad/token
pairs that make a full turn within 4096 tokens: 46 of 64
slowest pair: max angle seen in training 0.473 rad, at 16384 tokens 1.892 rad
with interpolation (x0.25): angle at 16384 = 0.473 rad, neighbouring tokens now 0.250 rad apart instead of 1.000
new base 40890: fastest pair x1.000, slowest pair x0.250
learned table, position 600: index 512 is out of bounds for axis 0 with size 512
- With (a common head size) the fastest pair turns 1 radian per token, the slowest . In 4096 training tokens 46 of the 64 pairs complete at least one full turn, so the model has seen every angle they can take. The other 18 have not: the slowest pair only reached 0.473 rad in training and would reach 1.892 rad at 16,384 tokens, values its weights never saw. Perplexity typically explodes just past the training length.
- Position interpolation (Chen et al., 2023) divides positions by 4: every angle at 16,384 stays within the trained range, but neighbouring tokens are now only 0.25 rad apart in the fastest pair, which blurs local order. A short fine-tune at the new length repairs most of that.
- NTK-aware scaling raises the base (here to 40,890) instead: the fastest pair is unchanged, the slowest is slowed by exactly the factor 4. YaRN, used for many long-context Llama and Qwen variants, refines this per frequency band and adds a temperature on the scores.
- A learned table simply has no row 600 (the index error); BERT's maximum of 512 tokens is that table's size.
| Scheme | Where | Parameters | Relative? | Beyond the training length | Used by |
|---|---|---|---|---|---|
| Sinusoidal | added to input | none | no (dot products of alone are) | defined, but behaves poorly | original transformer |
| Learned | added to input | no | impossible (no row) | BERT, GPT-2, ViT | |
| T5 bias | added to scores | buckets heads | yes, bucketed | far distances share one bucket | T5 |
| RoPE | rotates , | none | yes | needs interpolation or base scaling | Llama, Mistral, Qwen, GPT-NeoX |
| ALiBi | added to scores | none | yes | extrapolates reasonably | BLOOM, MPT |
Pitfalls
- Positions applied twice. RoPE models must not also add a position table to the input. Conversely, a model trained with additive positions breaks if you forget them.
- The wrong RoPE pairing or base. Interleaved pairs versus "rotate half", or base 10,000 versus 500,000 (Llama 3 uses a larger base): the model loads without error and produces garbage.
- RoPE on the values. Only queries and keys are rotated; values carry content.
- Off-by-one positions with a cache or left padding. In generation, the new token's position is the number of tokens already in the cache, and left-padded sequences need
position_idsthat start at their first real token. Wrong positions degrade output quietly. - Feeding more than the table length to BERT or GPT-2. Truncate (
truncation=True, max_length=512) or use a sliding window. - Trusting a long context window blindly. A model that accepts 128k tokens may still use the middle of a long input poorly ("lost in the middle"); measure retrieval at the lengths you need.
Practice
- In
pe1.py, change the base from 10,000 to 100. Does the relative property still hold? What happens to the long-range decay?
Answer
The relative property holds for any base: it only uses . With base 100 all pairs rotate much faster: for the score drops to about 15 by distance 16 and hovers around 0 from distance 64 on (positive and negative), instead of decaying slowly to 16.83 at 1024. The slow pairs that let RoPE tell long distances apart are gone.
- With ALiBi and 16 heads, what are the first and last slopes? Using the 8-head output, estimate how far back half the weight of head 1 reaches when all content scores are equal.
Answer
: the first is , the last . For 8 heads, head 1 (slope ) has half its weight within the last 2 tokens.
- Using the T5 bucket function, which bucket does a key 50 positions after the query fall in, and which bucket does a key 1000 positions before it fall in?
Answer
For : upper half, so . For : distance beyond 128, so the last bucket of the lower half, 15.
- A model was pretrained with RoPE at 2048 tokens and . You want 8192 tokens with position interpolation. By what factor are positions scaled, and what is the new angle between neighbouring tokens in the fastest pair?
Answer
Positions are multiplied by ; the fastest pair's angle per token goes from 1 rad to 0.25 rad.
Test yourself
RoPE is applied to…
- the input embeddings, once
- the queries and keys, inside every attention layer
- the values only
- the output logits
Why does depend only on ?
- Because rotations preserve the norm
- Because : a rotation backwards by followed by a rotation by
- Because the frequencies are small
- Because
What does ALiBi add to the attention score of query and key ?
- A learned bias per bucket
- with a fixed slope per head
- A sinusoid of
- Nothing; it rotates the keys
BERT raises an error on a 700-token input. Why?
- Its vocabulary is too small
- Its learned position table has 512 rows, so position 512 has no vector
- Attention is
- The tokenizer refuses long text
Position interpolation extends a RoPE model's context by…
- adding new rows to the position table
- scaling the positions down so all angles stay in the range seen in training
- removing the slow frequency pairs
- switching to ALiBi