Highlights

Contents

Part IV
04

Sinusoidal Positions: A Ruler Made of Waves

A learned table stops at its last row. Waves offer a computable position rule. Different frequencies describe different scales, although evaluating a new position does not mean the model understands it.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 21A Ruler Made of Waves

Part III ended with two complaints about the learned table: it stops dead at its last row, and it treats every position as unrelated to its neighbours. In 2017, the paper that introduced the Transformer, Attention Is All You Need by Ashish Vaswani and colleagues at Google, took a different route. Instead of learning position vectors, it calculated them with a formula. A formula can be evaluated at any position, so there is no table to run out of, and a well-chosen formula can build the relationship between neighbours in from the start.

The formula uses sine and cosine waves, the smooth up-and-down curves from school trigonometry. If those feel rusty, here is all you need. A sine wave rises from 0 to 1, falls through 0 to −1-1, and comes back, forever, always between −1-1 and 1. The cosine wave is the same shape shifted by a quarter turn. How fast a wave wiggles is set by its frequency, written ω\omega (the Greek letter omega). A wave with ω=1\omega = 1 wiggles quickly; a wave with ω=0.001\omega = 0.001 crawls.

Give each pair of numbers in the position vector its own wave, from very fast to very slow, and to get the vector for position pp, read off the height of every wave at the point pp.

PE(p,2i)=sin⁡(p⋅ωi)PE(p,2i+1)=cos⁡(p⋅ωi)ωi=1100002i/d\text{PE}(p, 2i) = \sin(p \cdot \omega_i) \qquad \text{PE}(p, 2i+1) = \cos(p \cdot \omega_i) \qquad \omega_i = \frac{1}{10000^{2i/d}}

Entries come in sine/cosine pairs. Each pair has a fixed frequency, and later pairs vary more slowly. Position determines the angle at which each pair is evaluated.

EIGHT WAVES (A TOY d = 16), READ AT POSITION 7pair 00.657pair 10.800pair 20.644pair 30.220pair 40.070pair 50.022pair 60.007pair 70.002position 7010203040sin valuesfastslow
Figure 1.29Reading a position off the waves. Each lane is one wave pair (only the sine is drawn). The dashed line at position 7 crosses every wave; the heights read top to bottom become the position's vector. Fast waves change a lot between neighbours; slow waves barely move.

At one position, evaluate every pair's sine and cosine. Fast waves change strongly between neighboring rows; slow waves change little. The figure shows their combined signature.

The position vector is then added to the token vector, exactly as in Part III: xp=E[idp]+PE(p)x_p = E[\text{id}_p] + \text{PE}(p). The only change is where the second vector comes from.

#Section 22The Famous Heatmap

If you search for "positional encoding" you will meet one picture over and over. It comes from drawing many position vectors as rows of coloured cells, one row per position and one column per dimension, with colour showing the value (orange for positive, blue for negative).

SINUSOIDAL POSITION VECTORS: ROWS ARE POSITIONS 0 TO 47, COLUMNS ARE 64 DIMENSIONSpos 20047dim 0dim 63left: fast waves flip quicklyright: slow waves barely change
Figure 1.30Sinusoidal position vectors for positions 0 to 47 in a 64-dimensional model. Columns on the left come from fast waves and flip colour within a few rows; columns on the right come from slow waves and hardly change. The outlined row is position 20.

The left side flickers because those columns come from fast waves: going down one row moves the wave by a whole radian, which is enough to change its sign within a few positions. The right side looks like solid stripes because those waves are so slow that across 48 positions they barely move. Read any single row and you have one position's vector, the same kind of strip you read off the waves in Section 21. The fast columns tell nearby positions apart. The slow columns tell distant positions apart. Together they give every position a unique fingerprint.

#Section 23Clock Hands and Binary Counting

Treat each (sine, cosine) pair as the tip of a clock hand. The cosine is how far the tip is to the right of the centre and the sine is how far it is up, so the pair always sits on a circle of radius 1. Every time the position goes up by one, hand ii turns by ωi\omega_i radians. (A radian is a unit of angle; a full turn is 2π≈6.2832\pi \approx 6.283 radians.) The first hand spins fast, a whole radian per step. The fourth hand turns only 0.032 radians per step and needs about 200 steps to go once around.

POSITION 7 ON FOUR CLOCK HANDS, AND IN BINARY1.000 rad / step7 × 1.000 = 7.00 rad0.316 rad / step7 × 0.316 = 2.21 rad0.100 rad / step7 × 0.100 = 0.70 rad0.032 rad / step7 × 0.032 = 0.22 radbinary 7:0111slow bitfast bitthe last bit flips every step,the first rarely: same idea, smooth
Figure 1.31Position 7 on four clock hands. Each hand turns by its own frequency per step, so at position 7 hand 0 has turned 7 radians (a little more than one full turn) while hand 3 has turned only 0.22. The binary counter below works on the same principle with on/off digits.

Now compare it with counting in binary, the base-2 counting computers use. In binary, 7 is written 0111. The last digit flips on every step, the next one every two steps, the next every four, and the first every eight. Fast digits track small changes; slow digits track big ones; together they pin down any number. The clock hands do exactly the same job, but smoothly. Instead of jumping between 0 and 1, each hand glides around its circle. That smoothness matters, because a neural network learns more easily from quantities that change gradually.

#Section 24Why Waves, and Why These Speeds?

Why not just use the plain number, 0, 1, 2, 3, as the position? Two reasons. First, scale: by position 1,000 the number would be enormous compared to the token vector's entries, which are around 1, and it would swamp the meaning. Waves always stay between −1-1 and 1. Second, information: a single number gives the network one dimension to work with, and comparing two positions would require the network to learn subtraction. Waves spread position across many dimensions and, as the next section shows, make comparison almost free.

The geometric ladder

Wavelength is the positional interval for one full cycle. Successive frequencies form a geometric progression, so the pairs cover several distance scales.

WAVELENGTHS FOR d = 512, BASE 10,000 (TOKENS PER FULL TURN, LOG SCALE)1101001,00010,000100,0006.3pair 019.9pair 3262.8pair 64199pair 96628pair 1281,987pair 1606,283pair 19219,869pair 22460,611pair 255each step of 32 pairs is the same ×3.16 jump: a geometric ladder
Figure 1.32Wavelengths of the 256 wave pairs in a 512-wide model, sampled every 32 pairs, on a log scale. They run from 6.3 tokens to about 60,600 tokens in even multiplicative steps.

That range is the point. Some waves resolve "the word right next to me" and others resolve "something thousands of words back". The number 10,000 is called the base, and it sets how slow the slowest wave is. There is nothing magic about it. Models that need very long contexts raise it so the slowest waves stretch further; Unit II shows Llama 3 using 500,000 for exactly that reason.

#Section 25The Dot Product Only Cares About Distance

A sine/cosine pair compares two angles through their difference. Summing the pairs gives a position-vector comparison that depends on the gap rather than the starting point.

PE(p)⋅PE(p+k)=∑i=0d/2−1cos⁡(k ωi)\text{PE}(p) \cdot \text{PE}(p + k) = \sum_{i=0}^{d/2 - 1} \cos(k \, \omega_i)

Look for pp on the right-hand side. It is not there. The similarity between two positions depends only on the gap kk, never on where you start. "Two words apart" produces the same similarity at the start of a text and deep inside it.

The figure shows similarity across gaps. Nearby positions tend to have similar signatures, but the oscillating waves do not imply strictly monotonic similarity.

SIMILARITY OF PE(p) AND PE(p + k), d = 512, AS A FUNCTION OF THE GAP kgap kdot product ÷ 256k=1: 0.97k=10: 0.68k=50: 0.51-100-50050100identical curve for p = 0,p = 100 or p = 500
Figure 1.33Similarity between the position vectors of p and p + k, divided by its maximum. It peaks at k = 0 and falls smoothly with distance, and the curve is identical whatever p you start from.

A shift is a rotation

Why does pp cancel? Go back to the clock picture. Moving forward kk positions turns hand ii by kωik\omega_i, whatever angle it started at. So the angle between the hand at position pp and the hand at position p+kp + k is always kωik\omega_i. Spin both hands forward together and the angle between them does not change. The dot product of two unit arrows is the cosine of the angle between them, so it does not change either.

ONE (sin, cos) PAIR IS A POINT ON A CIRCLE; MOVING k STEPS TURNS IT BY k·ωp = 2p = 5angle between = 3 × 0.3 = 0.9 radp = 10p = 13angle between = 3 × 0.3 = 0.9 radboth arrows moved,the gap did not
Figure 1.34One wave pair as a point on a circle. Moving three positions turns the point by the same angle whether you start at position 2 or position 10. The arrows move; the gap between them does not.

This picture leads to Part V. "Moving forward in position is a rotation" is exactly what RoPE takes and applies in a smarter place. Sinusoidal positions have the rotation property but then throw it partly away by adding the position vector to the token vector, which mixes the two and muddies the clean distance-only comparison once the vectors pass through the model's learned weights. RoPE keeps the rotation and never adds.

#Section 26”Works at Any Length” Is Only Half True

Since the formula can be evaluated at any number, sinusoidal positions were often described as working for sequences of any length. Sort of. The model can certainly compute a vector for position 10,000. But if it only ever trained on 1,024 positions, the combinations of wave heights that appear past 1,024 are combinations it has never seen, and every layer has learned to interpret only the ones it saw. In practice, quality degrades past the training length, often quickly. Being able to compute a vector is not the same as understanding it.

COMPUTABLE IS NOT THE SAME AS LEARNED (ILLUSTRATIVE)positionloss at that positiontraining length05121,0241,5362,048vectors exist out here,the model never learned them
Figure 1.35The typical result of running past the training length. Loss is flat inside the trained range and climbs once positions go beyond it. (Illustrative.)

Sharp edges of sinusoidal positions

Position and meaning share lanes. The position wave is added on top of the token’s vector, in the same 512 numbers, so every layer has to untangle “what” from “where”. The model can do this, but it is a tax. RoPE avoids the mixing entirely.

Slow lanes are nearly constant, and that is fine. The slowest waves barely change across a normal text, so those entries are almost the same for every position. They are not wasted: the model can use those dimensions mostly for token meaning.

Interleaved or split halves. Some code places sine and cosine side by side (sin, cos, sin, cos, as in the formula). Other code puts all the sines first and all the cosines after. Both are fine, but loading weights trained one way into code written the other way scrambles every position.

Precision at huge positions. At position 100,000 the angle for the fastest wave is 100,000 radians. In 16-bit floating point, numbers that large carry very few digits after the decimal point, so the rounding error in the angle is bigger than the wave’s whole period and the sine comes out as noise. Compute angles in 32-bit precision and only convert the final sine and cosine.