13.3 Rotary Position Embeddings
The 2017 transformer adds a sinusoidal or learned vector to each token embedding, as you saw in Positional encodings: sinusoidal, learned, so position enters once, at the bottom, mixed into the content. SmolLM2 has no position embedding at all: its checkpoint has no wpe table, and a model that ignores position cannot tell “dog bites man” from “man bites dog”. The position goes in inside every attention layer, by rotating the queries and keys.
Concepts from other sections (10)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- frequency ladder: the geometric sequence of angular speeds, from 1 down to about . Read more: 11.4 Positional encodings: sinusoidal, learned
- YaRN: a per-pair ramp between keeping and dividing frequencies, by turns over the trained context, plus a temperature . Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- Complex number: a point of the plane with the multiplication defined by . Read more: 6.2 Trigonometry, rotations, complex numbers, and Euler’s formula in Mathematics
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all - Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- absolute position: , the position of a query row in the whole sequence rather than in the current call. Read more: 22.5 FlashAttention forward in C
- M-RoPE: Qwen2-VL’s multimodal RoPE, giving each token three position ids . Read more: 14.2 2D RoPE and M-RoPE
Load SmolLM2 without that rotation and the logits are garbage; rotate the wrong pairs and they are subtly wrong. This section builds rotary position embeddings (RoPE) exactly as Hugging Face does, in both layouts real checkpoints use, with partial rotary for models that rotate only part of each head.
The mathematics comes from Mathematics: Trigonometry, rotations, complex numbers, and Euler’s formula supplies the 2D rotation and rotate_pairs, and Sequences, geometric series, and frequency ladders explains the frequency ladder. In code you will use F.concat, F.stack, and F.reshape from The op library and gradcheck_all and Tensor indexing from Tensor, broadcasting backward, and no_grad. The reference solution is rope.py, with rope_cos_sin, apply_rope, and RopeSpec, against the contract course/contracts/py/tinyllm/modern/rope.pyi.
Learning objectives
- Show that rotating queries and keys by position-proportional angles makes every score depend only on the offset between positions.
- Rotate a vector by hand in both the half and interleaved layouts and explain why they are one rotation on a permuted vector.
- Build cos and sin tables that match Hugging Face to position 65535, including YaRN’s attention scaling.
- Implement partial rotary and explain why the backward is the inverse rotation.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| one head’s query and key | float32[d_h] | |
| , , | token positions | int |
rotary_dim: how many entries rotate, even, | int | |
inverse frequency of pair , (inv_freq) | float[r/2] | |
| the 2D rotation | ||
| rotate pair by for every | ||
attention_scaling (YaRN, see Context extension) | float |
Rotations and relative position
Section titled “Rotations and relative position”You already know three facts about : it keeps lengths, , and . RoPE splits into pairs and rotates pair of the token at position by . For a query at and a key at , pair by pair:
The score depends on only. Attention gets relative position for free, inside the dot product, and at no parameter cost. The frequencies form a geometric ladder: pair 0 turns once per positions, while the last pair barely moves over the whole context. Fast pairs resolve nearby order and slow pairs distinguish far positions.
Two layouts
Section titled “Two layouts”The math says “rotate pairs” but not which entries form a pair. That is a convention fixed by how the weights were trained, and real checkpoints use two:
- half (
rotate_half; Hugging Face Llama, Mistral, Qwen, SmolLM2, gpt-oss): pair is . - interleaved (the RoFormer paper, Meta’s original Llama code): pair is , read as one complex number multiplied by .
Rotating pair by gives in either layout. Reorder the entries into and the interleaved rotation becomes the half rotation. Hugging Face converts Meta’s checkpoints by permuting the rows of q_proj and k_proj exactly this way, so their projections produce half-layout vectors directly.
Computing the angles
Section titled “Computing the angles”rope_cos_sin(positions, inv_freq, s) returns one cosine and one sine per pair, shape positions.shape + (r/2,). The angle is computed as Hugging Face does: one float32 product of float32(p) and float32(θ_i). Precision matters more here than it looks. At position 65535 the float32 spacing is about 0.004, so the angle itself is known only to a few thousandths of a radian; computing it in float16 (spacing 32 at that position, and 65535 overflows) destroys it.
Both tables are multiplied by , so the query and the key each grow by and every score by . That is YaRN’s temperature, which Context extension derives.
Partial rotary and the backward
Section titled “Partial rotary and the backward”GPT-NeoX and Phi rotate only the first entries of each head and leave the other unchanged; those entries carry content with no position at all. apply_rope(x, cos, sin, layout, rotary_dim=r) rotates x[..., :r] and concatenates x[..., r:] back unchanged.
The backward needs no new idea. is linear and orthogonal, so the gradient with respect to is : the upstream gradient rotated back, which is apply_rope(g, cos, -sin). Building apply_rope from indexing, products with constant tables, F.concat, and F.stack gives exactly that through autograd.
Working it by hand
Section titled “Working it by hand”Take , , position , and . The angles are and radians, with , , , .
In the half layout, pair 0 is , which rotated by 1 becomes . Pair 1 is , which rotated by 0.01 becomes . Writing pair 0 back to entries 0 and 2 and pair 1 to entries 1 and 3 gives .
In the interleaved layout, pair 0 is , giving , and pair 1 is , giving . The output is .
The same two rotations act on different entries.
The interface
Section titled “The interface”def rope_cos_sin(positions, inv_freq, attention_scaling=1.0) -> tuple[NDArray, NDArray]: ... # float32 [..., r/2]def apply_rope(x: Tensor, cos, sin, layout="half", rotary_dim=None) -> Tensor: ... # [..., d_h]@dataclassclass RopeSpec: inv_freq: NDArray; attention_scaling: float; layout: str; rotary_dim: intrope_cos_sin builds the tables from integer positions; apply_rope rotates a tensor with them; RopeSpec bundles the per-model settings so an attention layer can receive one object.
Building it step by step
Section titled “Building it step by step”Start from the requirement: a score must depend on only. Rotations compose by adding angles, so rotating each pair by an angle linear in position, , gives exactly that. Nothing about the rotation is learned, so the module has no parameters.
The angles depend on positions and frequencies, never on the data, so they can be computed once as two tables, and , of shape positions.shape + (r/2,). There is one entry per pair, not per element, because both elements of a pair share an angle. The tables must match Hugging Face bit for bit at long positions, which fixes the arithmetic: one float32 product float32(p) * float32(θ_i), then cos and sin. YaRN scales every score by ; scaling both tables by scales and each by , so the score picks up and no other code changes.
The rotation itself is in both layouts. The layouts differ only in where and come from, so the solution is one formula and two ways of slicing. The backward must be the inverse rotation; if the forward is written only from slicing, elementwise products with constant tables, F.concat, F.stack, and F.reshape, autograd composes their backwards into exactly . No custom backward is needed, and none can be wrong. Partial rotary means “the first entries rotate, the rest pass through”, so it is one slice and one concat around the full-rotary case.
The tables
Section titled “The tables”Validation comes first, because the tables are built from integers that come from callers (a decoding loop, a packed batch), and a float position like 2.5 is always a wiring bug.
def rope_cos_sin(positions, inv_freq, attention_scaling=1.0): p = np.asarray(positions) # positions must be whole numbers >= 0; a fractional or negative one is a bug upstream if p.size and (p.dtype.kind not in "iuf" or np.any(p != np.round(p))): raise ValueError(f"positions must be integers, got {p.dtype}") if p.size and p.min() < 0: raise ValueError(f"positions must be >= 0, got min {p.min()}") f = np.asarray(inv_freq) if f.ndim != 1: raise ValueError(f"inv_freq must be 1-D, got shape {f.shape}") # One float32 product per (position, pair), as HF's rotary embedding does # (positions.float() * inv_freq.float()); then cos and sin of it. # The trailing [..., None] broadcasts any positions shape against r/2 pairs. angle = p.astype(np.float32)[..., None] * f.astype(np.float32) s = np.float32(attention_scaling) # scale BOTH tables: q and k each grow by s, every score by s^2 (YaRN) return (np.cos(angle) * s).astype(np.float32), (np.sin(angle) * s).astype(np.float32)positions can be any shape: [T] for one sequence, [B, T] for per-row positions in a packed or left-padded batch, [1] for one decoding step. The output shape positions.shape + (r/2,) then broadcasts against x[..., r/2] without any reshaping by the caller.
Checking rotary_dim and the tables
Section titled “Checking rotary_dim and the tables”def _rotary_dim(x, cos, sin, rotary_dim): dh = x.shape[-1] r = dh if rotary_dim is None else int(rotary_dim) # pairs need an even count; you cannot rotate more entries than the head has if r < 2 or r % 2 or r > dh: raise ValueError(...) for name, t in (("cos", cos), ("sin", sin)): # one angle per pair, and the table must broadcast over x's leading axes if t.ndim < 1 or t.shape[-1] != r // 2: raise ValueError(...) try: np.broadcast_shapes(t.shape, x.shape[:-1] + (r // 2,)) except ValueError: raise ValueError(...) from None return rThe broadcast check matters because numpy would otherwise happily broadcast a [T, r/2] table against an [H, T, r/2] slice in the wrong axis order whenever two sizes coincide, and the error would surface as wrong logits rather than an exception.
The rotation
Section titled “The rotation”def apply_rope(x, cos, sin, layout="half", rotary_dim=None): if layout not in ("half", "interleaved"): raise ValueError(...) c, s = np.asarray(cos), np.asarray(sin) r = _rotary_dim(x, c, s, rotary_dim) dh, h = x.shape[-1], r // 2 if layout == "half": # pair i is (x[i], x[i + r/2]): a is the first half, b the second a, b = x[..., :h], x[..., h:r] # rotated a goes back to the first half, rotated b to the second rot = F.concat([a * c - b * s, b * c + a * s], axis=-1) else: # pair i is (x[2i], x[2i + 1]); rotate, then interleave back a, b = x[..., 0:r:2], x[..., 1:r:2] # stack on a new last axis gives [..., r/2, 2]: (a'_0, b'_0), (a'_1, b'_1), ... pairs = F.stack([a * c - b * s, a * s + b * c], axis=-1) # flattening that axis restores the interleaved order a'_0, b'_0, a'_1, ... rot = F.reshape(pairs, x.shape[:-1] + (r,)) if r == dh: return rot # partial rotary: entries r.. pass through untouched return F.concat([rot, x[..., r:]], axis=-1)Check it against the hand example. In the half layout, , , , . Then and , which concatenated give , the hand answer. In the interleaved layout, and produce the same two rotated pairs, and the stack-then-reshape writes them as .
Every operation on x is a slice, a product with a constant numpy table, a sum, a concat, a stack, or a reshape. Each of those has a backward in the op library, and their composition is the transpose of the rotation, which is the rotation by . Both halves of each pair reach the output through x’s own slices, so both receive gradient.
The spec
Section titled “The spec”@dataclassclass RopeSpec: """How an attention layer rotates its queries and keys (L7.5, L7.6).""" inv_freq: NDArray attention_scaling: float layout: str rotary_dim: intRopeSpec bundles everything a layer needs, so that the Llama model builder can read config.json once (rope_theta, rope_scaling, partial_rotary_factor) and hand the same spec to every attention layer. The full solution is in rope.py.
Why this design
Section titled “Why this design”The tables cost to build and are shared by every head and layer; apply_rope is elementwise work. RoPE adds nothing to the parameter count and is negligible next to the scores.
The solution uses the pair-wise formula, not a matrix. Building explicitly costs per position and a matmul per token, but the matrix is block-diagonal with blocks, so the four products per pair are all the work there is. It also uses real arithmetic, not complex numbers. Meta’s code views pairs as complex numbers, which is elegant for the interleaved layout but awkward for the half layout and for autograd built on real tensors; the real formula serves both layouts with the same backward. And the angles are float32 with cached tables: computing them in float16 or bfloat16 is cheaper but wrong past a few thousand positions, and matching Hugging Face’s single float32 product is what makes the golden comparisons bit-close at 65535.
The tradeoff you accept is that the solution builds new tensors with concat and stack rather than rotating in place, which costs a copy of and per layer. Production kernels rotate in place; here clarity and a free, correct backward are worth more.
What can go wrong
Section titled “What can go wrong”A correct implementation has to pass a broad set of checks. It must reproduce the hand example in both layouts. Its cos and sin tables must match Hugging Face’s up to position 65535, which long contexts rely on, and the scaled tables must match YaRN’s for rope_scaling configs. The half layout must match Hugging Face’s apply_rotary_pos_emb with per-row positions, which is what SmolLM2’s logits depend on; the interleaved layout must match Meta’s complex-number rotation; and partial rotary must match GPT-NeoX with rotary_dim 8 of 16.
Property tests check the reasons RoPE exists: shifted query-key pairs give equal scores, norms are preserved, position 0 is the identity, and the two layouts are related by Hugging Face’s conversion permutation, which is how Meta weights load. The interleaved rotation must agree with rotate_pairs from Mathematics, so there is one definition of a rotation. A float64 gradcheck covers both layouts and partial rotary, because q_proj and k_proj learn through RoPE, and the gradient must equal the rotation by , which the later C backward relies on. RopeSpec fields must drive apply_rope, and odd or oversized rotary_dim, bad tables, and bad positions must all raise.
test_rope.py shows how to test this independently of Hugging Face. Its oracle is complex multiplication in numpy float64: form from each pair (by the layout’s rule), multiply by , and split back. It compares apply_rope for both layouts and partial rotary, checks the hand example, checks that attention_scaling multiplies both tables, that large positions stay precise, that the gradient is the inverse rotation, and that bad input raises. A complex-number oracle is a good choice because it is a second, independent definition of the same rotation: a slip in the real-valued formula (a swapped sign, a wrong pairing) cannot also appear in .
Warning: Using adjacent pairs where the checkpoint expects half pairs is the costliest mistake, because nothing fails. The model loads, scores are still relative, and every attention pattern is wrong. The solution makes
layoutexplicit, defaults it to"half", and slices[:h]and[h:r]in the half branch.
The pitfalls and how the solution avoids each:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| adjacent pairs where the checkpoint expects half pairs | the model loads and every attention pattern is wrong | layout is explicit and defaults to "half"; the half branch slices [:h] and [h:r] |
| rotating by (a sign slip in sin) | relative scores still look fine; the weights disagree | the rotated first entry is a * c - b * s, the second b * c + a * s, as in the hand example |
| partial rotary on the wrong entries | GPT-NeoX-style models degrade quietly | rotates only x[..., :r] and concatenates x[..., r:] back unchanged |
| angles in float16 | positions past 2048 round to even numbers; 65535 overflows | one float32 product float32(p) * float32(θ) |
| scaling only the cosine | YaRN scores are not times larger | multiplies both tables by s |
| reading half of each pair as a constant | k_proj learns from half its gradient | both a and b are slices of the tensor x, so autograd routes gradient to both |
| leaving the interleaved output in half order | the next layer reads permuted features | stacks on a new last axis and reshapes, restoring |
Where this leads
Section titled “Where this leads”RoPE is everywhere from here on. Context extension rescales inv_freq and supplies attention_scaling for rope_cos_sin. Grouped-query attention rotates and with a RopeSpec before the scores. Multi-head latent attention rotates only a decoupled rope part of each key, and sliding-window attention rotates with the same tables. In the Llama-family model, config.json’s rope_theta and rope_scaling build the spec on the way to SmolLM2-135M logits that match Hugging Face, and in KV cache and generate decoding passes each new token’s absolute position. Later, tl_rope_f32 in Elementwise kernels in C must match this implementation; 2D RoPE and M-RoPE calls rope_cos_sin per axis and apply_rope to build 2D RoPE and M-RoPE; and the Vision transformer encoder with pos='rope2d' rotates queries and keys with apply_rope.
Further reading
Section titled “Further reading”- Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding” (2021), sections 3.2 to 3.4.
- EleutherAI blog, “Rotary Embeddings: A Relative Revolution” (2021).
- Hugging Face
LlamaRotaryEmbeddingintransformers/models/llama/modeling_llama.py: caches tables and recomputes them for dynamic scaling. - vLLM
RotaryEmbedding(therotary_embeddingkernel incsrc/pos_encoding_kernels.cu): rotates q and k in place in one fused CUDA kernel, withis_neox_styleselecting the layout. - GPT-NeoX
rotary_pctand Phipartial_rotary_factorin the Hugging Face GPT-NeoX and Phi modeling files: partial rotary as a fraction from the config. - The Qwen2-VL report: multimodal RoPE (M-RoPE), with separate time, height, and width sections of the pairs.
Key terms
Section titled “Key terms”- RoPE: rotating pair of a query or key at position by , so scores depend only on relative position.
- Inverse frequency (,
inv_freq): the per-pair rotation rate, , forming a geometric ladder. - Half layout: pair is ; used by Hugging Face Llama-family checkpoints.
- Interleaved layout: pair is ; used by RoFormer and Meta’s original code.
- Partial rotary: rotating only the first entries of each head.
- Attention scaling: a factor applied to both tables, multiplying every score by .
Summary
Section titled “Summary”- RoPE rotates pair of a query or key at position by ; rotations keep lengths and add angles, so a score depends only on the offset between positions.
- The half layout pairs with , the interleaved layout pairs with ; they are one rotation on a permuted vector.
- Partial rotary rotates only the first entries and passes the rest through.
- The angle is one float32 product, as in Hugging Face; lower precision destroys long positions.
- The backward is the inverse rotation, and autograd produces it from slices, constant products, concat, stack, and reshape.
Review questions
Section titled “Review questions”- Why does the score between a rotated query and key depend only on ?
Answer
Pair by pair the score is $q_i^\top R(m\theta_i)^\top R(n\theta_i) k_i$. $R^\top = R(-\cdot)$ and rotations add angles, so this is $q_i^\top R((n-m)\theta_i) k_i$: the absolute positions cancel. - Why do
rope_cos_sintables have columns and not ?Answer
Both entries of a pair rotate by the same angle, so there is one angle per pair. The half layout uses the same table for $a$ and $b$; Hugging Face's own tables repeat it to width $r$ only because its `rotate_half` multiplies the whole vector at once. - Why multiply both cos and sin by
attention_scaling, rather than just one?Answer
Each rotated entry is a linear combination of $\cos$ and $\sin$ terms, so scaling both scales the whole rotated vector by $s$. Applied to $q$ and $k$, every score grows by $s^2$, which is YaRN's temperature. Scaling only cos would distort the rotation itself, not just its length. - Why does the solution need no hand-written backward?
Answer
The forward is built only from differentiable primitives whose backwards already exist (slicing, products with constants, concat, stack, reshape). Their composition is the transpose of the orthogonal rotation, i.e. the rotation by $-p\theta$, which is the correct gradient. - What breaks if the solution used the interleaved slicing on a SmolLM2 checkpoint?
Answer
SmolLM2 was trained (and Hugging Face-converted) for the half layout, so its `q_proj`/`k_proj` rows place pair $i$ at entries $i$ and $i + r/2$. Interleaved slicing rotates the wrong entries together; the model still runs, scores are still relative, but every attention pattern is wrong. - Why is a complex-number oracle a good independent test of
apply_rope?Answer
It defines the same rotation a second way, as $z \cdot e^{i p\theta}$ on $z = a + ib$. A swapped sign or wrong pairing in the real-valued formula cannot also appear in complex multiplication, so a disagreement exposes it.