Positional Information
local graph
Chapter 9 — Positional Information
Section titled “Chapter 9 — Positional Information”The block from the last chapter has a strange blind spot: it cannot tell word order. Attention is a weighted sum, and a sum does not care about the order of its terms — shuffle the input tokens and the output is merely shuffled the same way. Yet “dog bites man” and “man bites dog” must mean different things. Position must be injected explicitly. This chapter covers how, from the original additive embeddings to rotary position embeddings (RoPE) — the method used by Llama, Qwen, DeepSeek, and nearly every current model — and ends with the tricks that stretch a model’s context window far beyond what it was trained on.
9.1 Absolute Positions
Section titled “9.1 Absolute Positions”The first transformers simply added a position vector to each token embedding. Two flavors existed: learned positional embeddings (a trainable vector per position, as in GPT-2) and fixed sinusoidal encodings (sines and cosines of different frequencies, as in the original transformer). Both work, but both share a weakness: they encode absolute position, so a model trained on length 1024 has never seen position 1025 and extrapolates poorly. They also bolt position onto the input once, rather than informing attention directly at every layer. Modern models abandoned them for a method that encodes relative position inside the attention operation itself.
9.2 Rotary Position Embeddings
Section titled “9.2 Rotary Position Embeddings”RoPE’s idea is elegant: instead of adding anything, rotate the query and key vectors by an angle proportional to their position. Treat each pair of dimensions as a point in a 2D plane and rotate it by mθ, where m is the token’s position and θ is a frequency that differs per dimension pair. Because rotating by mθ and then measuring the dot product against a key rotated by nθ yields a quantity that depends only on the difference (m-n)θ, the attention score between two tokens becomes a function of their relative distance — exactly what we want. Figure 9.1 shows the rotation.
[!visual-conversion] Diagram, PDF 098 (printed 100). Three arrows leave the origin of an x/y plane: “pos 0” at a small angle, “pos 1” further round, “pos 2” further still, with the angle marked “angle = m·θ”. The annotations beside it are transcribed below. The drawing (three successively rotated vectors) is described rather than redrawn.
pos 2 pos 1 ↗ ↗ pos 0 | ↗ ↗ |↗ ↗ angle = m·θ o-------------------
Each position rotates the (x, y) pair by an angle proportional to m. The score between a query at m and a key at n depends only on (m − n), so attention sees relative distance. Different dimension pairs use different θ, encoding many scales.Figure 9.1. Rotary position embedding. Each two-dimensional slice of the query/key vector is rotated by an angle proportional to the token’s position. Relative position falls out of the dot product automatically, and the scheme extrapolates far better than additive absolute embeddings.
The implementation is compact and is most cleanly expressed with complex numbers: pairs of real dimensions become complex numbers, a rotation is a complex multiply by e^{imθ}, and we precompute those unit-magnitude complex factors once. This is essentially the Llama and DeepSeek implementation.
import torch
def precompute_freqs_cis(d_head, max_seq_len, theta=10000.0): # one frequency per dimension pair; low dims rotate fast, high dims slow freqs = 1.0 / (theta ** (torch.arange(0, d_head, 2).float() / d_head)) t = torch.arange(max_seq_len).float() # positions 0..L-1 freqs = torch.outer(t, freqs) # (L, d_head/2) return torch.polar(torch.ones_like(freqs), freqs)
def apply_rotary_emb(x, freqs_cis): # x: (B, T, n_heads, d_head) -> pair up dims into complex numbers xc = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2)) xc = xc * freqs_cis[None, :, None, :] # rotate by position return torch.view_as_real(xc).flatten(-2).type_as(x) # back to realPython — rope.py: precompute rotations and apply them to q, k
In the attention module, RoPE is applied to the query and key tensors (never the value) right after their projections and before the dot product — a two-line change to the multi-head attention of Chapter 8: q = apply_rotary_emb(q, freqs) and the same for k. Because the rotation is applied at every layer, position information is available throughout the network, not just at the input. RoPE is now the near-universal default, and the base frequency theta is the knob behind most long-context extensions, as we will see in Section 9.4.
Code reference — deepseek-ai/DeepSeek-V3 (inference/model.py: precompute_freqs_cis, apply_rotary_emb) · meta-llama/llama (model.py)
The functions above match DeepSeek-V3’s and Llama’s RoPE almost line for line. DeepSeek’s MLA (Chapter 12) adds a wrinkle — a decoupled RoPE applied to a separate set of dimensions — but the rotation primitive is exactly this.
9.3 Relative Biases: ALiBi and Friends
Section titled “9.3 Relative Biases: ALiBi and Friends”RoPE is not the only relative scheme. ALiBi (Attention with Linear Biases) takes an even simpler route: add nothing to the embeddings, but subtract a penalty from each attention score proportional to the distance between query and key, with a different slope per head. Nearby tokens are favored, distant ones discounted, and — because the penalty is defined for any distance — the model extrapolates to longer sequences gracefully. ALiBi appears in some model families and long-context work; RoPE nonetheless won the mainstream, partly because its relative encoding is richer than a single linear bias. Table 9.1 places the schemes side by side.
| Scheme | How position enters | Relative? | Extrapolates? | Used by |
|---|---|---|---|---|
| Learned absolute | trainable vector added to input | no | poorly | GPT-2, early BERT |
| Sinusoidal | fixed sines/cosines added to input | no | limited | original transformer |
| RoPE | rotate q, k by angle ∝ position | yes | well (with scaling) | Llama, Qwen, DeepSeek, Mistral |
| ALiBi | distance penalty on scores | yes | well | some long-context models |
| NoPE | none (on some layers) | — | surprisingly ok | parts of Llama 4 |
Table 9.1 — Positional schemes compared
The last row is a genuine curiosity: with a causal mask, a transformer can infer some positional information even with no explicit encoding, and recent models (including parts of Llama 4) deliberately omit positional encoding on certain layers — “NoPE” — to aid length generalization. The field is still actively rethinking this supposedly settled component.
9.4 Extending the Context Window
Section titled “9.4 Extending the Context Window”A model trained at 4K tokens often needs to run at 128K or beyond. Retraining from scratch at long context is prohibitively expensive, so the standard practice is to train mostly short and then extend cheaply. Because RoPE’s behavior is governed by its rotation frequencies, the extensions are clever manipulations of those frequencies (Table 9.2).
| Method | Idea |
|---|---|
| Position Interpolation (PI) | scale positions down so a longer range maps into the trained one |
| NTK-aware scaling | increase the base frequency theta so high frequencies are preserved while low ones stretch |
| YaRN | frequency-dependent interpolation plus an attention-temperature fix; strong results with little fine-tuning |
Table 9.2 — RoPE context-extension methods
These methods, usually combined with a short fine-tuning phase on long sequences, are how models advertise 128K, 1M, and even 10M token windows (Llama 4 Scout). They are not free — quality degrades on genuinely long-range reasoning even when the model technically “fits” the context — which is why honest long-context evaluation (Chapter 29) matters and why architectures are now pursuing sparse and hybrid attention (Chapter 14) to make long context efficient as well as possible.
With position supplied, the block is finally complete: it knows what each token is, what the others are, and where they all sit. Nothing conceptual is missing. The next chapter does the satisfying part — assembles embeddings, a stack of these blocks, and an output head into a complete GPT, trains it, and generates text from it.
9.5 Worked Example: Rotary Embeddings by Hand
Section titled “9.5 Worked Example: Rotary Embeddings by Hand”Attention as defined in Chapter 7 is permutation-invariant — it has no notion of order — so position must be injected explicitly. Rotary position embeddings (RoPE) do this with a strikingly simple device: rotate each pair of features in the query and key by an angle proportional to the token’s position, with different feature pairs rotating at different frequencies:
def rope(x, pos, theta=10000.0): d = x.size(-1) freqs = pos * (theta ** (-torch.arange(0, d, 2) / d)) cos, sin = freqs.cos(), freqs.sin() x1, x2 = x[..., 0::2], x[..., 1::2] rot = torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1) return rot.flatten(-2) # interleave the rotated pairsPython — pos/rope.py: rotary position embedding
The elegance is what the rotation does inside the attention dot product. When a query at position m meets a key at position n, each rotated pair contributes a term that depends only on the angle difference m − n — so the attention score between two tokens encodes their relative distance, not their absolute positions. A model trained this way generalizes to distances and even to sequence lengths it never saw, because what it learned to use was the gap between tokens, which is the same whether the pair sits at positions 5 and 8 or at 5,005 and 5,008. This is why RoPE, and length-extension tricks built on scaling theta, underpin nearly every long-context model in the book.
Absolute rotation, relative effect RoPE rotates each token by its absolute position, but the rotations cancel in the attention dot product to leave only the relative offset. That is what lets a model trained at one length reason at another.
9.6 Context-Length Extension
Section titled “9.6 Context-Length Extension”One of RoPE’s most useful practical properties is that a model trained at a modest context length — say 4,096 tokens — can be extended to far longer contexts, 32K or 128K and beyond, without retraining from scratch. The lever is the set of rotation frequencies from Section 9.5, which determine how a token’s position maps to an angle. Manipulate those frequencies and the model can address positions it never saw in training.
Several schemes do this. The simplest, position interpolation, scales positions down so that a longer sequence’s indices fall within the range the model was trained on — squeezing 32K positions into the 4K the model understands. More refined methods (NTK-aware scaling, and YaRN) adjust the frequencies non-uniformly, stretching the low frequencies that encode long-range position while leaving the high frequencies that encode local detail intact, which preserves short-range precision better. In every case a brief fine-tune on long sequences then adapts the model to actually use the extended range. This is why frontier models can advertise 128K or million-token contexts affordably: they are trained at a shorter length where attention is cheap, then extended through RoPE manipulation and a short long-context fine-tune, rather than trained at full length throughout. The KV-cache and attention-cost concerns of Chapters 12 and 27 are what make that extended context usable once the positions are handled.
Train short, extend long RoPE’s frequencies can be rescaled so a model addresses positions beyond its training length. Position interpolation and YaRN plus a short fine-tune turn a 4K model into a 128K one — the affordable path to long context.
9.7 Why Absolute Position Embeddings Fell Out of Favor
Section titled “9.7 Why Absolute Position Embeddings Fell Out of Favor”RoPE (Section 9.5) was not the original way to inject position. The first transformers used absolute position embeddings — either a learned vector for each position, or fixed sinusoidal patterns — simply added to the token embeddings before the first layer. These work, and they powered the early models, but two weaknesses pushed the field away from them.
The first is generalization. A learned embedding for position 5,000 is meaningless if training never reached that length — the model has no representation for positions it did not see — so absolute embeddings extend poorly beyond the trained context, exactly the problem that RoPE-based extension (Section 9.6) handles gracefully. The second is the kind of information they encode. Absolute embeddings tell the model where a token sits from the start of the sequence, but what language actually depends on is mostly relative position — how far apart two tokens are, not their absolute indices. Relative schemes like RoPE encode exactly that, and the attention score between two tokens ends up depending on their separation rather than their absolute locations (Section 9.5), which is a better match for how language works. The migration from absolute to relative position is a clean example of the field discovering a superior inductive bias: not a bigger model or more data, but a representation that better reflects the structure of the problem, generalizing further and matching the data’s true dependencies. It is why nearly every current model uses a relative scheme and absolute position embeddings have largely disappeared.
Relative position is the better inductive bias Absolute embeddings cannot represent unseen positions and encode where rather than how-far. Language depends mostly on relative distance, which RoPE encodes and extends gracefully — a better fit for the problem, which is why absolute schemes faded.