v9.1.1
Menu

Rotary Position Embedding

hardFREEEmbeddings & Positional EncodingLLM 1: Foundations

Implement Rotary Position Embedding (RoPE).

RoPE rotates pairs of embedding dimensions by position-dependent angles. For a vector x of dimension D at position pos:

  • Split x into pairs: (x[0], x[1]), (x[2], x[3]), ...
  • For pair i, compute angle θ_i = pos / 10000^(2i/D)
  • Apply rotation: x'[2i] = x[2i] * cos(θ_i) - x[2i+1] * sin(θ_i) x'[2i+1] = x[2i] * sin(θ_i) + x[2i+1] * cos(θ_i)

Input: rope(pos, D, x)

  • pos: position index (integer)
  • D: dimension (even)
  • x: NumPy array of shape (D,), the vector

Output: the rotated vector as a NumPy array of shape (D,). The tests print each value rounded to 4 decimal places.

Example

Input
1 4
1.0 0.0 1.0 0.0
Output
0.5403 0.8415 1.0000 0.0100
Reasoning
  • Inputs: pos =1= 1 is the token's position, D =4= 4 is the embedding size, and x =(1,0,1,0)= (1, 0, 1, 0) is the vector. That gives two pairs: (x0,x1)=(1,0)(x_0, x_1) = (1, 0) and (x2,x3)=(1,0)(x_2, x_3) = (1, 0).
  • Angles: pair ii turns by θi=pos/100002i/D\theta_i = \text{pos} / 10000^{2i/D}. Pair 0: θ0=1/100000=1\theta_0 = 1 / 10000^{0} = 1 rad. Pair 1: θ1=1/100002/4=1/100=0.01\theta_1 = 1 / 10000^{2/4} = 1/100 = 0.01 rad.
  • Rotate pair 0 by 1 rad: x0′=1⋅cos⁡1−0⋅sin⁡1≈0.5403x'_0 = 1\cdot\cos 1 - 0\cdot\sin 1 \approx 0.5403 and x1′=1⋅sin⁡1+0⋅cos⁡1≈0.8415x'_1 = 1\cdot\sin 1 + 0\cdot\cos 1 \approx 0.8415.
  • Rotate pair 1 by 0.01 rad: x2′=cos⁡0.01≈0.99995x'_2 = \cos 0.01 \approx 0.99995, which rounds to 1.00001.0000, and x3′=sin⁡0.01≈0.0100x'_3 = \sin 0.01 \approx 0.0100.
  • Output: (0.5403, 0.8415, 1.0000, 0.0100)(0.5403,\ 0.8415,\ 1.0000,\ 0.0100). Rotation keeps each pair's length at 1.
  • Notice the frequency ladder: early pairs spin fast with position and later pairs barely move. At pos=0\text{pos} = 0 every angle is 0, so the vector comes back unchanged.

Constraints

  • 0 <= pos <= 100, 2 <= D <= 16 (D is even)
  • Use base 10000 for frequency
  • Round to 4 decimal places

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.