Rotary Position Embeddings (RoPE) encode position by rotating each 2D sub-pair of a query/key vector by an angle that grows with position. During training, a whole sequence's rotations are usually applied at once. At inference time, decoding one token at a time, a new token arrives at exactly ONE absolute position (the current cache length) — only that single query/key vector needs to be rotated, not a whole sequence. Implement rotary embeddings applied at a single (or batched) position, the setting that actually matters for autoregressive decoding.
Implement apply_rope(x, position, base=10000.0):
theta_i = base^(-2i/d) for i = 0..d/2-1
x'_2i = x_2i * cos(m*theta_i) - x_2i+1 * sin(m*theta_i)
x'_2i+1 = x_2i * sin(m*theta_i) + x_2i+1 * cos(m*theta_i)
d (vector length) must be even.theta_i = base^(-2i/d) for i in 0..d/2-1.(x[2i], x[2i+1]) by angle position * theta_i.(seq_len, d) with a matching list/array of positions, and also a single 1D vector with a scalar position.theta_i only depends on the pair index i and d, not on position — compute the theta vector once, then multiply by position m to get the per-pair angle. x[0::2] and x[1::2] give you the two halves of every pair without a Python loop.
Click "Run Tests" to test your implementation