Each position, a handful of clocks

Each position, a handful of clocks

29 min read

Multi-head attention completed the layer: hh ways of looking at the sentence, concatenated and projected back for the price of one. What no number of heads can give X\mathbf{X} is a first row and a last, so the order has to be written into every row before the layer reads it. What gets written there is this lesson's subject.

The easy answers fail in three ways, and they are worth looking at because between them they describe what is needed. Writing the position number into a coordinate breaks the scale: at position 300300 that coordinate is worth 300300 while the rest of the vector moves between −1-1 and 11, and it flattens any dot product it enters. Dividing it by the sentence length, pos/T\text{pos}/T, fixes the scale and spoils something else: the 0.50.5 of an eight-token sentence would point at the fourth token and that of a three-hundred-token text at the hundred and fiftieth, and it would be the same coordinate with the same value. And learning one vector per position, a table like the embeddings', works (some models do it) at the price of the table having exactly as many rows as positions seen in training, and of positions 77 and 88 being two rows with no relation between them: nothing says they are neighbours.

That last flaw is the one that points at what is really wanted. Think of an analogue clock. The second hand goes round once a minute: it tells two consecutive seconds apart without trouble, but at 10:00:05 and at 10:01:05 it is in the same place. The hour hand does the opposite: from one second to the next it barely moves, so it doesn't tell neighbours apart, but it never mistakes ten o'clock for four. No hand on its own will do, and the three together pick out an instant without ambiguity within twelve hours.

The clock has a second property as well, and it is the one this lesson ends up proving: letting ten minutes pass turns each hand through a fixed angle, whatever the time. From 3:00 to 3:10 the minute hand covers a sixth of a turn, and from 8:40 to 8:50 it covers exactly the same. The paper's encoding is a handful of clocks like that, each with a single hand: each pair of coordinates is a hand, each turns at its own speed, and the token's position plays the part of the time. The sine and the cosine are, literally, where the tip is: measuring the angle from twelve o'clock, the sine says how far the tip lies to the right and the cosine how far up.

A ladder of wavelengths

The paper defines the positional encoding entry by entry, with pos\text{pos} as the index of the position (it is the tt of the rest of the course, written with the paper's letter) and with PE\text{PE} for positional encoding:

PE(pos, 2i)=sin⁡(pos10 0002i/dmodel),PE(pos, 2i+1)=cos⁡(pos10 0002i/dmodel)\begin{aligned} \text{PE}_{(\text{pos},\,2i)} &= \sin\left(\frac{\text{pos}}{10\,000^{2i/d_{\text{model}}}}\right), \\[4pt] \text{PE}_{(\text{pos},\,2i+1)} &= \cos\left(\frac{\text{pos}}{10\,000^{2i/d_{\text{model}}}}\right) \end{aligned}

for i=0,1,…,dmodel/2−1i = 0, 1, \dots, d_{\text{model}}/2 - 1. Read it slowly, because the structure is in the indices: the coordinates come in pairs, pair ii takes up coordinates 2i2i and 2i+12i+1, and the two share the same argument. Let's call that divisor, inverted, ωi\omega_i; it is how far the pair turns for each position you move forward:

ωi=110 0002i/dmodel,2πωi=2π⋅10 0002i/dmodel.\omega_i = \frac{1}{10\,000^{2i/d_{\text{model}}}}, \qquad \frac{2\pi}{\omega_i} = 2\pi \cdot 10\,000^{2i/d_{\text{model}}}.

On the right is the wavelength: how many positions that pair takes to come back to the same place. Pair 00 has ω0=1\omega_0 = 1 and comes back every 2π≈6.282\pi \approx 6.28 positions; the last one stays below 10 000⋅2π10\,000 \cdot 2\pi, because its exponent never reaches 11: the last pair is i=dmodel/2−1i = d_{\text{model}}/2 - 1, so the exponent stops at 1−2/dmodel1 - 2/d_{\text{model}}. With dmodel=512d_{\text{model}} = 512 that is about 60 60060\,600 positions, which over any text is a band that barely moves. Between the two, the wavelengths grow by multiplying by the same factor every time: they form a geometric progression, and that is the ladder the section is named after. On the clock, pair 00 is the second hand and the last pair an hour hand that takes far longer to go round.

What comes out of this is a matrix PE∈RT×dmodel\text{PE} \in \mathbb{R}^{T \times d_{\text{model}}} whose row pos\text{pos} is PEpos⊤\text{PE}_{\text{pos}}^{\top}, exactly the shape of the X\mathbf{X} of the last three lessons. And the two are joined by adding:

xt=ewt+PEt.\mathbf{x}_t = \mathbf{e}_{w_t} + \text{PE}_t.

Notice that the first flaw has gone away on its own: sine and cosine live in [−1,1][-1, 1] whatever happens to TT, so the encoding of position 33 and that of position 3 0003\,000 are the same size. So has the second, for a different reason: TT appears nowhere in the formula, so position 55 is encoded the same way in a short sentence as in a long text.

Adding instead of concatenating is a decision, and what it costs deserves saying out loud. Concatenating would keep the coordinates of meaning and those of position apart by construction, and it would be paid for in width: setting aside 6464 of the 512512 for position leaves 448448 for everything else. Adding costs no width at all, and in exchange the two signals share the same coordinates and nothing guarantees they can be pulled apart again. What there is in its favour is that WQ\mathbf{W}^Q and WK\mathbf{W}^K are learned and can keep some directions and not others, and that the encoding has a structure very much its own that a trained embedding has no reason to imitate. Plausible, then; not proven.

Shifting by a fixed distance is turning through a fixed angle

Of the three flaws from the start, the third remains, and it was the one that really asked for something: that two neighbouring positions look alike, and look alike to the same degree wherever they are. Here it can be proved, and it takes three lines.

Fix a shift kk and keep a single pair. The angle-addition formulas say what happens to that pair when it moves forward kk positions:

sin⁡(ωi(pos+k))=cos⁡(ωik) sin⁡(ωipos)+sin⁡(ωik) cos⁡(ωipos),cos⁡(ωi(pos+k))=−sin⁡(ωik) sin⁡(ωipos)+cos⁡(ωik) cos⁡(ωipos).\begin{aligned} \sin\left(\omega_i(\text{pos}+k)\right) &= \cos(\omega_i k)\,\sin(\omega_i \text{pos}) + \sin(\omega_i k)\,\cos(\omega_i \text{pos}), \\[2pt] \cos\left(\omega_i(\text{pos}+k)\right) &= -\sin(\omega_i k)\,\sin(\omega_i \text{pos}) + \cos(\omega_i k)\,\cos(\omega_i \text{pos}). \end{aligned}

I have written the factors in that order on purpose, because that way the two lines are already a matrix product. The new coordinates are a combination of the two old ones, and the coefficients of that combination are four numbers that look only at ωi\omega_i and kk:

[PE(pos+k, 2i)PE(pos+k, 2i+1)]=[cos⁡(ωik)sin⁡(ωik)−sin⁡(ωik)cos⁡(ωik)][PE(pos, 2i)PE(pos, 2i+1)].\begin{bmatrix}\text{PE}_{(\text{pos}+k,\,2i)} \\[2pt] \text{PE}_{(\text{pos}+k,\,2i+1)}\end{bmatrix} = \begin{bmatrix}\cos(\omega_i k) & \sin(\omega_i k) \\[2pt] -\sin(\omega_i k) & \cos(\omega_i k)\end{bmatrix} \begin{bmatrix}\text{PE}_{(\text{pos},\,2i)} \\[2pt] \text{PE}_{(\text{pos},\,2i+1)}\end{bmatrix}.

Look at what is not in that matrix: pos\text{pos}. The starting position has stayed whole inside the vector on the right, and the expansion has left it there. Since each pair is transformed without touching the others, stacking the dmodel/2d_{\text{model}}/2 matrices, each 2×22 \times 2, along the diagonal gives a single matrix for the whole vector:

PEpos+k=Mk PEpos,Mk∈Rdmodel×dmodel.\text{PE}_{\text{pos}+k} = \mathbf{M}_k\,\text{PE}_{\text{pos}}, \qquad \mathbf{M}_k \in \mathbb{R}^{d_{\text{model}} \times d_{\text{model}}}.

That is the property, and it is worth reading carefully what it says: there is one matrix for each distance kk, and that matrix holds for every position in the sentence. Moving forward three positions is applying M3\mathbf{M}_3, whether you start from the first word or from the last. Each block is also a rotation (its two columns are perpendicular and of length 11), so Mk\mathbf{M}_k stretches and shrinks nothing: every row of PE\text{PE} has the same length.

What a score can see of all this

Mk\mathbf{M}_k is a property of the encoding, and the attention layer doesn't look at matrices: it looks at dot products. It is worth working one out and seeing what is left. With cos⁡(A−B)=cos⁡Acos⁡B+sin⁡Asin⁡B\cos(A - B) = \cos A \cos B + \sin A \sin B applied pair by pair:

PEpos⊤PEpos+k=∑i[sin⁡(ωipos)sin⁡(ωi(pos+k))+cos⁡(ωipos)cos⁡(ωi(pos+k))]=∑i=0dmodel/2−1cos⁡(ωik).\text{PE}_{\text{pos}}^{\top}\text{PE}_{\text{pos}+k} = \sum_{i} \left[\sin(\omega_i \text{pos})\sin\left(\omega_i(\text{pos}+k)\right) + \cos(\omega_i \text{pos})\cos\left(\omega_i(\text{pos}+k)\right)\right] = \sum_{i=0}^{d_{\text{model}}/2 - 1} \cos(\omega_i k).

pos\text{pos} has disappeared again. Two positions kk apart score the same number against each other at the start of the sentence and in the middle, and that number depends only on the distance. With k=0k = 0 each term is 11 and the sum gives dmodel/2d_{\text{model}}/2, which is the maximum: no position scores as highly against another as against itself.

The explorable below brings the two properties together. The map is PE\text{PE} for 2424 positions and 3232 coordinates: each row is a position, each column a coordinate, and the colour gives the value (green positive, blue negative, dark near zero). Read from left to right it is the ladder: the first columns, the fast hands, change colour every few rows, and the last ones are a smooth band because in 2424 positions they barely move. The three sliders choose a position (the row with a solid border), a coordinate (the outlined column, whose speed and value the panel gives) and a distance kk (the row with a dashed border, kk positions further down). The last line of the panel is that dot product, computed from your position and from two others: move the position with kk fixed and check that the three numbers agree and don't change.

The columns on the left change every few positions and those on the right are almost flat: it is the same function at ever slower speeds. The number at the bottom changes only when you change k.

And now the concession, because this is less than it looks. The layer doesn't compute PEpos⊤PEpos+k\text{PE}_{\text{pos}}^{\top}\text{PE}_{\text{pos}+k}: it computes q⊤k\mathbf{q}^{\top}\mathbf{k} with both projected from ewt+PEt\mathbf{e}_{w_t} + \text{PE}_t, so expanding the product gives four terms and only one of them is purely positional. What the sinusoidal form guarantees is that this term exists and depends only on the distance; a head that wants to learn to look for the determiner two positions back (the in the yellow house, seen from house) has the material to build it, because the signal for two positions back is the same throughout the sentence. Whether it builds it is for training to decide, not this lesson.

That concession is the weakness RoPE (rotary position embedding) corrects, the encoding Su and colleagues proposed in 2021 and that most large language models use today. The idea comes straight out of Mk\mathbf{M}_k: instead of adding the position to the input, where it mixes with the meaning before the projections, it is applied as a rotation after them. The query at position mm is rotated, pair by pair and with the same frequencies ωi\omega_i, through an angle ωim\omega_i m, and the key at position nn through an angle ωin\omega_i n. Rotating both vectors by the same amount doesn't change their dot product, so when they are compared only the difference counts, ωi(n−m)\omega_i(n - m): the whole score, and not one of its four terms, depends on the positions only through the distance between them.

The ladder in NumPy

The first cell builds PE\text{PE} with two slices and not a single loop, and then prints the wavelength of a few pairs.

import numpy as np

T, d_model = 24, 32
i = np.arange(d_model // 2) # one pair of coordinates for each i
omega = 1.0 / (10000 ** (2 * i / d_model))
pos = np.arange(T)[:, None] # (T, 1) against (d_model/2,)

PE = np.zeros((T, d_model))
PE[:, 0::2] = np.sin(pos * omega) # even coordinates: the sine
PE[:, 1::2] = np.cos(pos * omega) # odd ones: the cosine of that same angle

print("PE", PE.shape, " values between", round(PE.min(), 3), "and", round(PE.max(), 3))
print("row 0 :", np.round(PE[0, :8], 3))
print("row 1 :", np.round(PE[1, :8], 3))
print("row 12:", np.round(PE[12, :8], 3))

print("\n pair omega wavelength")
for j in (0, 1, 2, 8, 15):
print(f"{j:6d} {omega[j]:.6f} {2 * np.pi / omega[j]:14.1f}")

norm = np.linalg.norm(PE, axis=1)
print("\nevery row has the same length:",
bool(np.allclose(norm, np.sqrt(d_model / 2))), "->", round(float(norm[0]), 3))
numpy

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

Row 00 comes out as (0,1,0,1,… )(0, 1, 0, 1, \dots), which is what it has to be: at position 00 every angle is 00 and every hand points at twelve. The first three rows of the table are the ladder: pair 00 comes back every 6.36.3 positions, pair 11 every 11.211.2, pair 22 every 19.919.9 (each 1.781.78 times the one before), and pair 1515, the last for this dmodeld_{\text{model}}, every 35 332.935\,332.9, which over 2424 positions is a straight line. The last line is the observation from the end of the previous section, checked: every row has length 44, which is 32/2\sqrt{32/2}.

The second cell checks the two properties, which is where the content of the lesson lies.

import numpy as np

T, d_model, k = 24, 32, 3
i = np.arange(d_model // 2)
omega = 1.0 / (10000 ** (2 * i / d_model))
pos = np.arange(T + k)[:, None]
PE = np.zeros((T + k, d_model))
PE[:, 0::2] = np.sin(pos * omega)
PE[:, 1::2] = np.cos(pos * omega)

c, s = np.cos(k * omega), np.sin(k * omega) # the four numbers of each block
M = np.zeros((d_model, d_model))
M[0::2, 0::2] = np.diag(c)
M[0::2, 1::2] = np.diag(s)
M[1::2, 0::2] = np.diag(-s)
M[1::2, 1::2] = np.diag(c)

shifted = PE[:T] @ M.T # M times a column == the row times M transposed
print("a single M moves all", T, "rows at once; maximum error",
f"{np.abs(shifted - PE[k:T + k]).max():.2e}")

print("\nPE_pos . PE_pos+k, from four different positions:")
print(" ", np.round([float(PE[p] @ PE[p + k]) for p in (0, 5, 11, 19)], 6))
print(" sum of cosines:", round(float(np.cos(k * omega).sum()), 6))

print("\nand how it changes with the distance:")
for kk in (0, 1, 2, 3, 8, 20):
print(f" k = {kk:2d} -> {np.cos(kk * omega).sum():7.3f}")
numpy

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

The first line is Mk\mathbf{M}_k applied to all twenty-four positions at once, and the maximum error stays of the order of 10−1510^{-15}: the same matrix, every row. The second is the other property (four starting positions and four times 12.27239812.272398, which is exactly the sum of cosines), and the table at the end says how that quantity behaves as the two positions move apart: 1616 against itself, 15.31415.314 one step away, 12.27212.272 at three, and after that it falls slowly and not monotonically, because it is a sum of cosines and not a distance.

Test your intuition

Five questions: why the position number won't do, what Mk\mathbf{M}_k depends on, how a position scores against itself, what breaks when the cosines go, and what adding instead of concatenating guarantees.

What does writing the position number (00, 11, 22, …) into one coordinate of xt\mathbf{x}_t break?

The matrix Mk\mathbf{M}_k satisfies PEpos+k=MkPEpos\text{PE}_{\text{pos}+k} = \mathbf{M}_k\text{PE}_{\text{pos}}. What does it depend on?

With dmodel=512d_{\text{model}} = 512, what is PEpos⊤PEpos\text{PE}_{\text{pos}}^{\top}\text{PE}_{\text{pos}}?

A margin of ±0 is accepted.

You keep only the sines: one coordinate per pair, without its cosine. Mark what is still true.

Select every correct option. This is graded all-or-nothing: there is no partial credit.

Adding the encoding to the embedding, instead of concatenating it, guarantees that the model can separate meaning and position again.

Write the lesson's two pieces.

positional_encoding(T, d_model) returns PE\text{PE} of shape (T,dmodel)(T, d_{\text{model}}), with row pos\text{pos} carrying sin⁡(pos⋅ωi)\sin(\text{pos} \cdot \omega_i) in the even coordinates and cos⁡(pos⋅ωi)\cos(\text{pos} \cdot \omega_i) in the odd ones, where ωi=1/10 0002i/dmodel\omega_i = 1/10\,000^{2i/d_{\text{model}}} and pair ii takes up coordinates 2i2i and 2i+12i+1.

shift(k, d_model) returns Mk\mathbf{M}_k of shape (dmodel,dmodel)(d_{\text{model}}, d_{\text{model}}): zeros except for one 2×22 \times 2 block per pair, [cos⁡(ωik)sin⁡(ωik)−sin⁡(ωik)cos⁡(ωik)]\begin{bmatrix}\cos(\omega_i k) & \sin(\omega_i k) \\ -\sin(\omega_i k) & \cos(\omega_i k)\end{bmatrix}, placed in rows and columns 2i2i and 2i+12i+1.

The two have to fit together: Mk\mathbf{M}_k applied to row pos\text{pos} gives row pos+k\text{pos}+k, across the whole sentence. Assume dmodeld_{\text{model}} is even.

The first run downloads the Python interpreter (~15 MB); after that it stays in the browser cache. This challenge is much easier to solve on a physical keyboard: on a phone, read it and come back later.


With this the input is complete: each row of X\mathbf{X} carries what the token says and where it was, and the attention layer of the last four lessons can now be computed in full on top of it. What remains is to stack it, which is what turns a layer into a model. And there something turns up that this lesson leaves pending without saying so: the position is added once, at the very bottom, and it has to arrive alive at the last layer.

What the paper draws around the attention (a connection that skips the whole layer, a normalisation and a position-wise perceptron) looks like plumbing around the important part, and it isn't. It is what decides whether a signal put in at the bottom is still there at the top, and Block 3 has already measured why, by following a gradient along a chain of products and watching it vanish. That is the next lesson, on the full block with residual connections and layer norm.

Was this helpful?
Further reading3 sources · 2 papers, 1 article

Where this lesson comes from, and where to go next. None of it is needed to carry on with the course.

  • Attention Is All You Need
    paperVaswani, Shazeer, Parmar and others, 2017arXiv:1706.03762EN

    Its §3.5 defines the sines and cosines and states, without proof, that shifting by k positions is a linear function of PE_pos. That proof, the matrix M_k, is the centre of this lesson; the paper only says it exists.

  • Transformer Architecture: The Positional Encoding
    articleAmirhossein Kazemnejad, 2019kazemnejad.comEN

    Does the working the paper skips: it builds the rotation M_k pair by pair and checks that it does not depend on the position, your own derivation. It goes a little further, towards the relative distance between positions.

  • RoFormer: Enhanced Transformer with Rotary Position Embedding
    paperSu, Lu, Pan and others, 2021arXiv:2104.09864EN

    Introduces RoPE, this lesson's rotation applied to queries and keys instead of added to the input. Its equation 6 is the four-term expansion that, here, keeps position in only one term; section 3 resolves it.