Position by Rotation

TransformersMedium+20 XP+20

Position by Rotation

Chapter 4 gave a transformer its sense of order by adding a position vector to each token's vector. Many recent decoder models do it differently. They leave the token vectors alone and instead rotate each query and key vector, inside attention, by angles that depend on its position. This is called rotary position embedding.

Take a vector x\mathbf{x}x of even length ddd at position ppp. Group its slots into adjacent pairs: (x0,x1),(x2,x3),…(x_0, x_1), (x_2, x_3), \dots(x0​,x1​),(x2​,x3​),… Pair iii, for i=0,1,…,d/2−1i = 0, 1, \dots, d/2 - 1i=0,1,…,d/2−1, is turned anticlockwise by the angle (in radians)

θi=p⋅base−2i/d\theta_i = p \cdot \text{base}^{-2i/d}θi​=p⋅base−2i/d

which means

x2i′=x2icos⁡θi−x2i+1sin⁡θi,x2i+1′=x2isin⁡θi+x2i+1cos⁡θix'_{2i} = x_{2i}\cos\theta_i - x_{2i+1}\sin\theta_i, \qquad x'_{2i+1} = x_{2i}\sin\theta_i + x_{2i+1}\cos\theta_ix2i′​=x2i​cosθi​−x2i+1​sinθi​,x2i+1′​=x2i​sinθi​+x2i+1​cosθi​

Pair 000 turns by a full radian for every step in position, and each later pair turns more slowly. These are the waves of different lengths from the positional encoding lesson, used as rotation speeds. A vector at position 000 is not turned at all.

Task: write rotate_positions(vectors, start, base). The list vectors holds query (or key) vectors for consecutive tokens, all of the same even length, and vectors[k] sits at position start + k. Return the rotated vectors, with every number rounded to 4 decimal places.

start matters during generation: if the model has already processed 500 tokens and now computes the vector for one new token, that token sits at position 500, not at 0.

Why rotate? A rotation never changes a vector's length, and once the query at position mmm and the key at position nnn have both been rotated, their dot product depends only on the gap m−nm - nm−n. The attention score sees how far apart two tokens are, not where in the text they happen to sit.

Examples

vectors = [[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]
start = 0
base = 10000.0
returns [[1.0, 0.0], [0.5403, 0.8415], [-0.4161, 0.9093]]
vectors = [[2.0, 1.0, 1.0, -1.0], [0.5, 0.0, 3.0, 2.0]]
start = 1
base = 100.0
returns [[0.2391, 2.2232, 1.0948, -0.8952], [-0.2081, 0.4546, 2.5429, 2.5561]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run