Katkat

Positional Information: Sinusoidal, Learned and RoPE

By the Katkat team · Updated · 8 min read

Quick overview

Learn why transformers need position information, how sinusoidal, learned and rotary (RoPE) encodings work, and how context extension methods stretch them.

Lesson 8 of 88 · AI Engineering Interview Course

After this lesson you should be able to explain why self-attention is blind to word order without extra help, and how sinusoidal, learned and rotary position encodings differ. You should also be able to work through a small RoPE calculation and describe how position interpolation, NTK-aware scaling and YaRN extend a model's context length. These are common follow-ups when an interviewer asks about long-context models.

Why attention needs position

Self-attention computes, for each token, a weighted average of value vectors, with weights from query-key dot products. Nothing in that formula depends on where a token sits. If you shuffle the input tokens, every token's output is the same vector as before, just shuffled along with the input. This property is called permutation equivariance.

So without position information, "the dog bit the man" and "the man bit the dog" produce the same set of token representations, and the model sees a bag of words. Position has to be injected explicitly. See The Transformer, Explained for Engineers for the surrounding architecture.

One nuance: a decoder-only model with a causal mask is not completely blind, because token t can only attend to t earlier tokens, which leaks a weak count signal. Research suggests this can carry some order information, but it is not a reliable replacement for explicit encoding, and production models do not rely on it.

Absolute encodings: sinusoidal and learned

The two classic designs give each position an absolute vector that is added to the token embedding once, at the input.

Sinusoidal (from "Attention Is All You Need"): for position pos and dimension pair i, the vector holds sin(pos / 10000^(2i/d)) and cos(pos / 10000^(2i/d)). Each pair is a wave with its own wavelength, from fast-changing to very slow, a bit like the digits of a counter. It has no parameters, and it can be computed for any position, including ones never seen in training. In practice, models still tend to degrade past their training length.

Learned absolute: a trainable table with one row per position, up to a fixed maximum length. For a maximum of 2,048 positions and hidden size 4,096, that is 2,048 × 4,096 = 8,388,608 parameters (about 8.4M). It is simple and flexible, but there is no row for position 2,049, so the maximum length is a hard limit. Extending it means adding new rows and training them.

Both designs mix position into the residual stream. The model then has to learn to extract relative distance ("the word 3 back") from absolute information, which is indirect.

Relative ideas and ALiBi

Language often cares more about distance between tokens than absolute index. Relative schemes put that directly into attention. One example is ALiBi, which skips position vectors entirely. It subtracts a penalty from each attention score that grows linearly with the distance between query and key, using a different fixed slope per head. It adds no parameters and was designed for "train short, test long". Most recent open models, however, settled on RoPE.

RoPE: rotary position embeddings

RoPE (from the RoFormer paper) encodes position by rotating the query and key vectors, instead of adding anything to the input.

The mechanism:

  1. Split each head's vector (size d, e.g. 128) into d/2 pairs of dimensions. Each pair is treated as a 2D point.
  2. Pair i has a base frequency θ_i = base^(-2i/d), with base commonly 10,000. This gives frequencies from fast to slow, like the sinusoidal scheme.
  3. A token at position m has pair i rotated by the angle m · θ_i.
  4. This is applied to queries and keys only, inside every attention layer. Values are left unrotated.

The key property: the dot product between a rotated query at position m and a rotated key at position n depends only on the content vectors and the offset m − n. Rotating both by their own angles leaves only the difference of angles. So attention sees relative position, even though each token is rotated by an absolute amount. There are no learned parameters, only cached cos/sin tables.

Worked example

Take one pair with θ = 1 radian per position, and let both query and key content be (1, 0).

  • Query at position m becomes (cos m, sin m). Key at position n becomes (cos n, sin n).
  • Dot product = cos m cos n + sin m sin n = cos(m − n).
Query posKey posOffsetScore
523cos 3 ≈ −0.990
1051023cos 3 ≈ −0.990
651cos 1 ≈ 0.540

The first two rows have the same offset and so the same score, regardless of absolute position. That is the relative-position property in action.

For a real head with d = 128 there are 64 pairs and θ_i = 10000^(-i/64). The fastest pair has θ_0 = 1, a wavelength of 2π ≈ 6.3 tokens. The slowest, θ_63 = 10000^(-63/64) ≈ 1.15 × 10⁻⁴, has a wavelength of about 6.283 / 1.15×10⁻⁴ ≈ 54,000 tokens. Fast pairs resolve nearby order precisely, and slow pairs distinguish coarse distances. For a hands-on version, see Implement Rotary Position Embeddings.

Practical notes: RoPE is applied before attention scores are computed, and the KV cache stores keys that are already rotated, which is fine because only the relative angle matters (see Prefill, Decode and the KV Cache). Also, libraries differ in how they pair dimensions (adjacent pairs versus first half with second half), so mixing conventions when porting weights silently breaks the model.

Comparing the options

SchemeWhere appliedParametersPosition typeBeyond training length
SinusoidalAdded at inputNoneAbsoluteComputable, but quality usually drops
Learned absoluteAdded at inputmax_len × dAbsoluteNo row exists; hard limit
ALiBiBias on attention scoresNoneRelative (distance penalty)Designed to degrade gracefully
RoPERotates Q and K in every layerNoneRelative via rotationOut-of-distribution angles unless adjusted

Context extension tricks

A RoPE model trained on 4,096 tokens does badly at 16,384, even though nothing is "missing" mechanically. The reason is that the slow pairs reach rotation angles never seen during training.

Using the numbers above: the slowest pair (θ ≈ 1.1548 × 10⁻⁴) reaches at most 4,095 × 1.1548×10⁻⁴ ≈ 0.47 rad in training. At position 16,383 it reaches 16,383 × 1.1548×10⁻⁴ ≈ 1.89 rad, a value the model never saw. Extension methods avoid this by keeping angles inside the trained range:

MethodWhat it changesNotes
Position interpolationDivides every position by the scale factor sNeeds a short fine-tune; loses resolution on fast pairs
NTK-aware scalingRaises the RoPE base instead of scaling positionsOften usable with little or no fine-tuning
YaRNTreats each frequency differently, plus an attention temperature adjustmentTypically needs less fine-tuning than plain interpolation

Position interpolation, with numbers. Trained length 4,096, target 16,384, so s = 4. Position m is fed to RoPE as m / 4. Position 10,000 becomes 2,500, and position 16,383 becomes about 4,096, inside the trained range. The cost is resolution: for the fastest pair, neighbouring tokens used to differ by 1 rad and now differ by 0.25 rad, so the model must learn to distinguish positions that are squeezed closer together. That is why a brief fine-tune is normally used.

NTK-aware scaling. Instead of squeezing all positions equally, change the base to base × s^(d/(d−2)). For d = 128, s = 4: 4^(128/126) ≈ 4.089, so the new base is about 40,900. Check the effect: the fastest pair has θ_0 = 1 regardless of base, so local precision is untouched. The slowest pair (exponent 2i/d = 126/128) is divided by exactly s, as if interpolated. Frequencies in between are scaled progressively. High frequencies are preserved and low frequencies are stretched.

YaRN refines this by blending interpolated and unmodified frequencies according to wavelength, and by rescaling attention logits slightly to compensate for the longer span. Treat it as "NTK-style per-frequency handling, plus a temperature fix".

Two caveats. First, stretching positions does not guarantee the model uses long inputs well; accuracy on information in the middle of a long prompt can still lag, as covered in Context Windows: Limits, Cost and Long-Context Behaviour. Second, positions are only part of the cost: the KV cache and attention compute still grow with length.

How does this come up in interviews?

1. Why does a transformer need positional encoding? Attention is permutation-equivariant: reordering the input only reorders the outputs, so word order is lost. Position information must be injected, either added to the embeddings or applied inside attention. The causal mask leaks only a weak signal and is not enough on its own.

2. How does RoPE work, and why is it called relative? RoPE rotates each 2D pair of the query and key by an angle proportional to token position, with a different frequency per pair. Because the dot product of two rotated vectors depends only on the difference of their angles, the score depends on the offset m − n. It applies to Q and K only, adds no parameters, and happens in every layer.

3. A model was trained on 4K tokens and you need 16K. What do you do? Scale RoPE so angles stay in the trained range. With position interpolation, divide positions by 4; with NTK-aware scaling or YaRN, change the frequencies per-band. Then fine-tune briefly on long sequences and evaluate with retrieval-style long-context tests, not just perplexity.

4. Compare learned absolute embeddings with sinusoidal ones. Both are added at the input. Sinusoidal has no parameters and can be computed for any position, but quality typically still falls off past the training length. Learned tables have max_len × d parameters and a hard cap on length.

5. Why do long-context models still fail on long inputs after extending positions? Position scaling only makes long inputs representable. The model still has to learn to attend across them, and training data with truly long-range dependencies is limited. Memory also grows, because the KV cache scales with sequence length.

Common mistakes

  • Saying RoPE is added to the embeddings. It rotates queries and keys inside attention, not the input.
  • Claiming RoPE rotates values. Only Q and K are rotated.
  • Calling sinusoidal encodings "learned", or saying they extrapolate perfectly. They can be computed for any position, but quality still usually degrades.
  • Treating context extension as free. Interpolation reduces resolution on fast frequencies and generally needs fine-tuning and evaluation.
  • Confusing a longer position range with better long-context use, or forgetting the KV cache memory cost.
  • Mixing RoPE pairing conventions (adjacent versus half-split) when loading weights, producing silently wrong outputs.
  • Forgetting that the same θ_0 = 1 fastest frequency is unchanged by NTK-aware base scaling; only the lower frequencies are stretched.

For implementation practice, see Implement Multi-Head Attention alongside the RoPE exercise.