Rotate a vector by its position (RoPE)
Rotary position embeddings (RoPE) tell attention where each token sits by rotating its query and key vectors. Pairs of numbers are treated as points on a plane and turned by an angle that depends on the position.
Write apply_rope(x, pos, base=10000.0) where x is a 1D array of even length d and pos is an integer position.
For each pair index i from 0 to d/2 - 1:
- theta_i = base ** (-2 * i / d)
- angle = pos * theta_i
- take the pair (x[2i], x[2i+1]) and rotate it: new_even = x[2i]*cos(angle) - x[2i+1]*sin(angle), new_odd = x[2i]*sin(angle) + x[2i+1]*cos(angle)
Return the rotated array. Position 0 leaves x unchanged, and rotation never changes the vector's length.
def apply_rope(x, pos, base=10000.0)Understand the idea
RoPE tells attention where a token sits by rotating its query and key vectors. Picture each pair of numbers as a clock hand: position decides how far the hand turns. Each pair i has its own speed theta_i = base^(-2i/d), so early pairs spin fast and later pairs spin slowly. The angle for a pair is pos * theta_i. Worked example: d = 2, so there is one pair with theta_0 = 1. Take x = [1, 0] at pos = 1, so angle = 1 radian, cos = 0.540, sin = 0.841. New even = 1*0.540 - 0*0.841 = 0.540, new odd = 1*0.841 + 0*0.540 = 0.841. The length is still 1. For d = 4, the second pair has theta_1 = 10000^(-0.5) = 0.01, so it turns 100 times slower. Rule: for pair (a, b) and angle t, output (a cos t - b sin t, a sin t + b cos t). Position 0 means no change. Llama and most modern LLMs use RoPE.
Similar problems
Part of the advanced LLM architecture track.