Skip to content

6.2 Trigonometry, rotations, complex numbers, and Euler's formula

A bigram model sees one previous byte, so the order of a text matters to it only through adjacent pairs. The models that come later read whole contexts with attention, and attention on its own is blind to order. It scores every pair of positions with a dot product of two vectors, and shuffling the tokens shuffles the scores without changing any of them: “the dog bit the man” and “the man bit the dog” would get the same representation. AI Engineering adds position back in two ways, and both are rotations. The 2017 Transformer’s sinusoidal encoding writes sin⁡\sin and cos⁡\cos of position-dependent angles into the input. RoPE, the scheme in Llama and SmolLM2, rotates each pair of coordinates of every query and key by an angle proportional to its position.

Concepts from other sections (8)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

This section builds rotations from the unit circle up, proves the relative-angle property RoPE depends on, and shows how Euler’s formula turns the same rotation into a single complex multiplication. It then implements rotate_pairs, the function RoPE calls. The same cos⁡\cos and sin⁡\sin reappear in Random variables and the normal, where Box-Muller turns uniform random numbers into normal ones. You need the exponentials and the laws of exponents from Exponents, logarithms, and units of information, and the code uses numpy strided slicing and broadcasting as described in Python and numpy from Programming and Algorithms.

The finished code is course/solutions/python/tinyllm/num/rotation.py, which provides rotation_matrix, rotate_pairs, as_complex, and as_real; its interface is fixed by the contract course/contracts/py/tinyllm/num/rotation.pyi.

Learning objectives

  • Define cos⁡\cos and sin⁡\sin from the unit circle and derive the rotation matrix R(θ)R(\theta) from where it sends the basis vectors.
  • Show that rotations preserve lengths and dot products and compose by adding angles, and derive the angle-addition formulas from that.
  • Prove that the dot product of two rotated vectors depends only on the difference of their angles, and explain why RoPE therefore encodes relative position.
  • Use Euler’s formula eiθ=cos⁡θ+isin⁡θe^{i\theta} = \cos\theta + i\sin\theta to perform the same rotation as one complex multiplication.
  • Implement rotate_pairs with the interleaved layout, without modifying its input, and explain the layout bug that crashes nothing.

The symbols used throughout are collected here first:

SymbolMeaningType / shape
θ,a,b\theta, a, bangles in radiansfloat
π\pihalf the circumference of a circle of radius 1, 3.14159…3.14159\ldotsmath.pi
cos⁡θ,sin⁡θ\cos\theta, \sin\thetathe coordinates of the point at angle θ\theta on the unit circlefloat
u,vu, vvectors in the plane, u=(u0,u1)u = (u_0, u_1)float[2]
⟨u,v⟩\langle u, v\rangledot product u0v0+u1v1u_0 v_0 + u_1 v_1float
∥u∥\lVert u\rVertlength u02+u12\sqrt{u_0^2 + u_1^2}float
R(θ)R(\theta)the 2×22 \times 2 rotation matrix by θ\thetafloat[2, 2]
iithe imaginary unit, i2=−1i^2 = -11j
z=x+iyz = x + iya complex number with real part xx and imaginary part yycomplex
zˉ\bar zthe conjugate x−iyx - iycomplex
∣z∣\lvert z\rvertthe modulus x2+y2\sqrt{x^2 + y^2}float
kkthe number of pairs in a vector of length 2k2kint
m,nm, ntoken positionsint
ω\omegaan angular frequency: radians per positionfloat

Walk along the circle of radius 1 centred at the origin, starting at (1,0)(1, 0) and going counterclockwise. The radian measure of an angle is the distance walked. A full turn is the whole circumference, 2π2\pi; a half turn is π\pi; a right angle is π/2\pi/2. Degrees convert by 180°=π180° = \pi, so 60°=π/360° = \pi/3. Every function in this section, and numpy’s np.cos and np.sin, takes radians. Negative angles walk clockwise, and adding 2π2\pi lands on the same point, so the trigonometric functions repeat with period 2π2\pi.

The point reached at angle θ\theta has coordinates (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta); that is the definition of cosine and sine. Because the point is at distance 1 from the origin, Pythagoras gives

cos⁡2θ+sin⁡2θ=1.\cos^2\theta + \sin^2\theta = 1 .

Reflecting across the horizontal axis gives cos⁡(−θ)=cos⁡θ\cos(-\theta) = \cos\theta and sin⁡(−θ)=−sin⁡θ\sin(-\theta) = -\sin\theta. A few values come from familiar triangles and are worth knowing by heart:

θ\theta0π/6\pi/6π/4\pi/4π/3\pi/3π/2\pi/2π\pi
cos⁡θ\cos\theta13/2\sqrt3/22/2\sqrt2/21/21/20−1-1
sin⁡θ\sin\theta01/21/22/2\sqrt2/23/2\sqrt3/210

Rotating the plane by θ\theta about the origin is linear: rotating a sum is the sum of the rotations, and rotating c uc\,u is cc times the rotation of uu. So it is enough to know where the two basis vectors go. (1,0)(1, 0) goes to (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) by definition, and (0,1)(0, 1), a quarter turn further, goes to (cos⁡(θ+π/2),sin⁡(θ+π/2))=(−sin⁡θ,cos⁡θ)(\cos(\theta + \pi/2), \sin(\theta + \pi/2)) = (-\sin\theta, \cos\theta). Those images are the columns of the matrix:

R(θ)=(cos⁡θ−sin⁡θsin⁡θcos⁡θ),R(θ)(xy)=(xcos⁡θ−ysin⁡θxsin⁡θ+ycos⁡θ).R(\theta) = \begin{pmatrix}\cos\theta & -\sin\theta \\ \sin\theta & \cos\theta\end{pmatrix}, \qquad R(\theta)\begin{pmatrix}x\\y\end{pmatrix} = \begin{pmatrix}x\cos\theta - y\sin\theta\\ x\sin\theta + y\cos\theta\end{pmatrix}.

A rotation keeps lengths. Expanding, (xcos⁡θ−ysin⁡θ)2+(xsin⁡θ+ycos⁡θ)2=(x2+y2)(cos⁡2θ+sin⁡2θ)=x2+y2(x\cos\theta - y\sin\theta)^2 + (x\sin\theta + y\cos\theta)^2 = (x^2 + y^2)(\cos^2\theta + \sin^2\theta) = x^2 + y^2, because the cross terms ∓2xycos⁡θsin⁡θ\mp 2xy\cos\theta\sin\theta cancel. It also keeps dot products, ⟨Ru,Rv⟩=⟨u,v⟩\langle R u, R v\rangle = \langle u, v\rangle. In matrix terms, R(θ)⊤R(θ)=IR(\theta)^\top R(\theta) = I, and R(θ)⊤=R(−θ)R(\theta)^\top = R(-\theta) undoes the rotation.

Rotating by bb and then by aa is a rotation by a+ba + b, so R(a)R(b)=R(a+b)R(a)R(b) = R(a + b). Multiplying the two matrices out and comparing the first column with that of R(a+b)R(a + b) gives the angle-addition formulas:

cos⁡(a+b)=cos⁡acos⁡b−sin⁡asin⁡b,sin⁡(a+b)=sin⁡acos⁡b+cos⁡asin⁡b.\cos(a + b) = \cos a\cos b - \sin a\sin b, \qquad \sin(a + b) = \sin a\cos b + \cos a\sin b .

With b=−ab = -a, R(a)R(−a)=R(0)=IR(a)R(-a) = R(0) = I. This one law, that angles add, is what everything else in the section rests on.

Rotate uu by α\alpha and vv by β\beta, then take the dot product. Using ⟨Ru,w⟩=⟨u,R⊤w⟩\langle R u, w\rangle = \langle u, R^\top w\rangle and the composition law,

⟨R(α)u, R(β)v⟩=⟨u, R(−α)R(β)v⟩=⟨u, R(β−α)v⟩.\langle R(\alpha)u,\ R(\beta)v\rangle = \langle u,\ R(-\alpha)R(\beta)v\rangle = \langle u,\ R(\beta - \alpha)v\rangle .

The result depends on α\alpha and β\beta only through β−α\beta - \alpha. RoPE sets α=mω\alpha = m\omega for a query at position mm and β=nω\beta = n\omega for a key at position nn, so the attention score ⟨R(mω)q,R(nω)k⟩\langle R(m\omega)q, R(n\omega)k\rangle depends only on n−mn - m, the distance between the tokens. Shifting a sentence along the context changes nothing.

A single frequency ω\omega would make positions 2π/ω2\pi/\omega apart indistinguishable, so RoPE splits a 2k2k-dimensional query into kk pairs and rotates pair ii by mωim\omega_i, using a ladder of frequencies ωi\omega_i that the next section builds. rotate_pairs(x, theta) is exactly that operation, with theta[..., i] the angle of pair ii. Pair ii is (x2i,x2i+1)(x_{2i}, x_{2i+1}), the interleaved layout of the RoFormer paper and Meta’s Llama code. Hugging Face’s Llama pairs xix_i with xi+kx_{i+k} instead, the “half” layout of rotate_half; the RoPE section of AI Engineering implements both and converts between them.

There is a second, more compact way to say all of this. A complex number z=x+iyz = x + iy is a point (x,y)(x, y) of the plane with a multiplication: expand as polynomials in ii and replace i2i^2 by −1-1.

(x+iy)(c+is)=(xc−ys)+i(xs+yc).(x + iy)(c + is) = (xc - ys) + i(xs + yc) .

Compare this with the rotation formula: with c=cos⁡θc = \cos\theta and s=sin⁡θs = \sin\theta, the right-hand side is exactly R(θ)(x,y)R(\theta)(x, y). Multiplying by cos⁡θ+isin⁡θ\cos\theta + i\sin\theta rotates by θ\theta. The modulus ∣z∣=x2+y2\lvert z\rvert = \sqrt{x^2 + y^2} is the length, and zzˉ=∣z∣2z\bar z = \lvert z\rvert^2.

Euler’s formula names that rotating number:

eiθ=cos⁡θ+isin⁡θ.e^{i\theta} = \cos\theta + i\sin\theta .

Why an exponential? Because it obeys the law of exponents: eiaeib=ei(a+b)e^{ia}e^{ib} = e^{i(a + b)} is the composition rule, now in one line. Taylor series proves the formula by comparing the series of exe^x, cos⁡x\cos x, and sin⁡x\sin x. Several consequences are used in the problem set: eiπ=−1e^{i\pi} = -1, eiπ/2=ie^{i\pi/2} = i, (eiθ)n=einθ(e^{i\theta})^n = e^{in\theta} (De Moivre’s formula), cos⁡θ=(eiθ+e−iθ)/2\cos\theta = (e^{i\theta} + e^{-i\theta})/2, and Re⁡(eia eib‾)=cos⁡(a−b)\operatorname{Re}(e^{ia}\,\overline{e^{ib}}) = \cos(a - b), which is the relative-angle property in complex form.

The code mirrors this view. as_complex reads a real vector of length 2k2k as kk complex numbers zi=x2i+i x2i+1z_i = x_{2i} + i\,x_{2i+1}, the numpy analogue of torch.view_as_complex, and as_real reads them back. With them, rotate_pairs(x, t) equals as_real(as_complex(x) * np.exp(1j * t)).

Take two pairs and two angles. x=[3,4,1,0]x = [3, 4, 1, 0] has pairs (3,4)(3, 4) and (1,0)(1, 0). Rotate pair 0 by the angle t0t_0 with cos⁡t0=3/5\cos t_0 = 3/5 and sin⁡t0=4/5\sin t_0 = 4/5 (so t0=atan2⁡(4,3)≈0.9273t_0 = \operatorname{atan2}(4, 3) \approx 0.9273 radians, about 53.13°53.13°), and pair 1 by π/2\pi/2. The rotation formula gives:

pair(x,y)(x, y)cos⁡,sin⁡\cos, \sinxcos⁡−ysin⁡x\cos - y\sinxsin⁡+ycos⁡x\sin + y\cos
0(3,4)(3, 4)0.6,0.80.6, 0.81.8−3.2=−1.41.8 - 3.2 = -1.42.4+2.4=4.82.4 + 2.4 = 4.8
1(1,0)(1, 0)0,10, 10−0=00 - 0 = 01+0=11 + 0 = 1

So rotate_pairs([3, 4, 1, 0], [t0, pi/2]) is [−1.4,4.8,0,1][-1.4, 4.8, 0, 1]. numpy gives 6×10−176 \times 10^{-17} instead of the exact 0, because cos⁡(π/2)\cos(\pi/2) in floating point is not exactly 0. As a length check, 1.96+23.04=5=9+16\sqrt{1.96 + 23.04} = 5 = \sqrt{9 + 16}.

The same computation with complex numbers: as_complex([3, 4, 1, 0]) is [3+4i, 1+0i][3 + 4i,\ 1 + 0i], and

(3+4i)(0.6+0.8i)=1.8+2.4i+2.4i+3.2 i2=−1.4+4.8i,(1+0i)⋅i=i,(3 + 4i)(0.6 + 0.8i) = 1.8 + 2.4i + 2.4i + 3.2\,i^2 = -1.4 + 4.8i, \qquad (1 + 0i)\cdot i = i ,

so as_real returns [−1.4,4.8,0,1][-1.4, 4.8, 0, 1].

Finally, composition. Multiply R(π/2)R(π/3)=(0−110)(1/2−3/23/21/2)=(−3/2−1/21/2−3/2)R(\pi/2)R(\pi/3) = \begin{pmatrix}0 & -1\\ 1 & 0\end{pmatrix}\begin{pmatrix}1/2 & -\sqrt3/2\\ \sqrt3/2 & 1/2\end{pmatrix} = \begin{pmatrix}-\sqrt3/2 & -1/2\\ 1/2 & -\sqrt3/2\end{pmatrix}. Its first column, (cos⁡,sin⁡)=(−3/2,1/2)(\cos, \sin) = (-\sqrt3/2, 1/2), is the point at 5π/6=π/2+π/35\pi/6 = \pi/2 + \pi/3, as the composition law promises.

Four functions cover both views of a rotation:

python/tinyllm/num/rotation.py
def rotation_matrix(theta: float) -> NDArray: ... # [[cos, -sin], [sin, cos]], float64
def rotate_pairs(x: ArrayLike, theta: ArrayLike) -> NDArray: ... # pair i of the last axis by theta[..., i]
def as_complex(x: ArrayLike) -> NDArray: ... # [..., 2k] -> complex [..., k]
def as_real(z: ArrayLike) -> NDArray: ... # complex [..., k] -> [..., 2k]

theta broadcasts to x.shape[:-1] + (k,). A [k] theta rotates every row alike, and a [T, k] theta gives each position its own angles, which is what RoPE passes. The result is a new array; float32 input stays float32, and everything else comes back float64. An odd last axis, or a theta that does not broadcast, raises ValueError.

Seven observations from the theory fix the implementation.

  1. A rotation is fixed by where the basis vectors go. e0↦(cos⁡θ,sin⁡θ)e_0 \mapsto (\cos\theta, \sin\theta) and e1↦(−sin⁡θ,cos⁡θ)e_1 \mapsto (-\sin\theta, \cos\theta) are the columns of R(θ)R(\theta); that is all rotation_matrix has to write.
  2. Rotating many pairs is the same formula applied elementwise. With the pairs’ coordinates in two arrays, even and odd, the rotation is x′=xcos⁡−ysin⁡x' = x\cos - y\sin, y′=xsin⁡+ycos⁡y' = x\sin + y\cos, computed for every pair at once by broadcasting. No 2×22 \times 2 matrix product per pair is needed.
  3. The layout is part of the specification. Pair ii is (x2i,x2i+1)(x_{2i}, x_{2i+1}), which in numpy is the strided views x[..., 0::2] and x[..., 1::2].
  4. Both outputs must read the old values. The formula for y′y' uses the original xx; computing x′x' into the input first would corrupt it. Writing into a fresh output array makes this automatic and also leaves the caller’s x untouched.
  5. Angles are per pair and may be per position. theta must broadcast to x.shape[:-1] + (k,); checking that up front turns a confusing numpy error into a clear ValueError.
  6. Precision follows the caller. Compute in float64 for accuracy, then return float32 if the input was float32, as RoPE needs for activations.
  7. The complex view is the same data reinterpreted. as_complex builds x2i+i x2i+1x_{2i} + i\,x_{2i+1} and as_real writes real and imaginary parts back to the even and odd slots. The dtype pairs float32 with complex64 and float64 with complex128, so the round trip is exact.
def rotation_matrix(theta: float) -> NDArray:
c, s = math.cos(theta), math.sin(theta)
# Columns are where the basis vectors land: e0 -> (c, s), e1 -> (-s, c).
return np.array([[c, -s], [s, c]], dtype=np.float64)

The minus sign sits in the first row, second column. That is what makes the rotation counterclockwise for positive θ\theta; writing the transpose instead rotates clockwise. math.cos takes radians, like np.cos.

def rotate_pairs(x: ArrayLike, theta: ArrayLike) -> NDArray:
a = np.asarray(x)
# float32 stays float32; every other input is computed and returned in float64.
out_dtype = np.float32 if a.dtype == np.float32 else np.float64
if a.ndim == 0 or a.shape[-1] % 2 != 0:
raise ValueError(
f"the last axis must have even length (pairs), got shape {a.shape}"
)
k = a.shape[-1] // 2
t = np.asarray(theta, dtype=np.float64)
# One angle per pair, for every leading index: [k] or [T, k] both broadcast.
try:
t = np.broadcast_to(t, a.shape[:-1] + (k,))
except ValueError:
raise ValueError(
f"theta of shape {t.shape} does not broadcast to {a.shape[:-1] + (k,)}"
) from None
a64 = a.astype(np.float64) # a copy: the caller's x is never touched
even, odd = a64[..., 0::2], a64[..., 1::2] # interleaved pairs (x[2i], x[2i+1])
c, s = np.cos(t), np.sin(t)
out = np.empty(a.shape, dtype=np.float64) # a new array: x is never modified
# Both outputs read the OLD even and odd values.
out[..., 0::2] = even * c - odd * s
out[..., 1::2] = even * s + odd * c
return out.astype(out_dtype)

Trace the hand example through it. even = [3, 1], odd = [4, 0], c = [0.6, 6e-17], and s = [0.8, 1], so out[0::2] = [1.8 - 3.2, 6e-17 - 0] = [-1.4, 6e-17] and out[1::2] = [2.4 + 2.4, 1 + 0] = [4.8, 1], interleaved back to [−1.4,4.8,6×10−17,1][-1.4, 4.8, 6 \times 10^{-17}, 1]. The from None hides numpy’s internal broadcast error, so the message the caller sees names both shapes. The 0-d check comes before a.shape[-1], which would otherwise raise an IndexError.

def as_complex(x: ArrayLike) -> NDArray:
a = np.asarray(x)
if a.ndim == 0 or a.shape[-1] % 2 != 0:
raise ValueError(
f"the last axis must have even length (pairs), got shape {a.shape}"
)
# complex64 is two float32s: the float32 round trip stays bit-exact.
ctype = np.complex64 if a.dtype == np.float32 else np.complex128
a = a.astype(np.float64)
z = a[..., 0::2] + 1j * a[..., 1::2] # z_i = x_{2i} + i x_{2i+1}
return z.astype(ctype)
def as_real(z: ArrayLike) -> NDArray:
c = np.asarray(z)
if c.ndim == 0:
raise ValueError("as_real needs at least one axis")
rtype = np.float32 if c.dtype == np.complex64 else np.float64
c = c.astype(np.complex128)
out = np.empty(c.shape[:-1] + (2 * c.shape[-1],), dtype=np.float64)
out[..., 0::2] = c.real # back to the even slots
out[..., 1::2] = c.imag # and the odd slots
return out.astype(rtype)

These are the numpy counterparts of torch.view_as_complex and torch.view_as_real. They copy rather than reinterpret memory (numpy could view a contiguous float array as complex), which costs a pass over the data but works for any input, including non-contiguous slices and integer arrays. With them, rotate_pairs(x, t) equals as_real(as_complex(x) * np.exp(1j * t)), which is how the solution is checked against the torch formulation.

The full solution is rotation.py.

rotate_pairs costs O(n)O(n) for a vector of n=2kn = 2k coordinates (one cos⁡\cos and one sin⁡\sin per pair, four multiplies and two adds) and O(n)O(n) extra memory for the float64 copy and the output. It uses elementwise formulas rather than a stack of 2×22 \times 2 matrices: np.einsum with R(θi)R(\theta_i) per pair would build a […,k,2,2][\ldots, k, 2, 2] array and do twice the multiplications for the same result. It uses real arithmetic rather than complex multiplication; the two are exact restatements of each other, but the real form keeps float32 inputs in a real dtype and avoids two conversions, while the complex form stays available for comparison. It copies and returns rather than rotating in place, because an in-place rotation would save memory but corrupt keys that RoPE reuses for every query. And it computes in float64 internally because RoPE’s angles reach thousands of radians at long positions; computing cos⁡\cos and sin⁡\sin in float64 keeps those values accurate, and only the final result is rounded to float32.

A correct implementation must pass the following checks, each tied to something that depends on it:

CaseKind of checkWhat must holdWhy it matters downstream
the hand exampleunit[3,4,1,0][3, 4, 1, 0] becomes [−1.4,4.8,0,1][-1.4, 4.8, 0, 1]everyone agrees on direction and layout
the hand example in complex formunit(3+4i)(0.6+0.8i)=−1.4+4.8i(3 + 4i)(0.6 + 0.8i) = -1.4 + 4.8i through as_complex and as_realthe complex view of the same example
rotation_matrix hand valuesunitR(π/2)R(\pi/2), R(t0)R(t_0), R(0)=IR(0) = Ithe columns are the images of the basis vectors
rotate_pairs agrees with rotation_matrixdifferentialeach pair equals R(θi)R(\theta_i) times the pairthe two functions agree
length is preservedpropertyevery pair keeps its lengthRoPE never rescales queries or keys
angles addpropertyR(a)R(b)=R(a+b)R(a)R(b) = R(a + b), and rotating twice adds the anglesthe law behind relative positions
a negative angle undoespropertyrotating by −θ-\theta returns the inputR(θ)⊤=R(−θ)R(\theta)^\top = R(-\theta)
the dot product sees only the relative angleproperty⟨R(mω)q,R(nω)k⟩\langle R(m\omega)q, R(n\omega)k\rangle is unchanged when mm and nn shift togetherthe RoPE property is built on it
Euler’s formula is the rotationdifferentialas_complex(rotate_pairs(x, t)) == as_complex(x) * exp(1j t)Euler’s formula, checked on random data
the layout is interleavedboundarypairs are (x2i,x2i+1)(x_{2i}, x_{2i+1}), not halvesthe layout bug that crashes nothing
as_real round-tripspropertyas_real(as_complex(x)) == x exactly, float32 stays complex64lossless views
agreement with torchgoldenthree cases against torch.view_as_complex(x) * torch.polar(1, theta), one in float32the exact op Meta’s Llama code runs
theta broadcastsunita [k] theta applies to every row of a batchthe shapes the positional encodings pass
dtype follows the inputboundaryfloat32 in, float32 out; integers promoted to float64RoPE keeps activations in float32
the input is not modifiedboundaryx is unchanged after the callkeys are reused for every query
odd or bad shapes rejectedboundaryodd lengths, bad theta, and 0-d input raise ValueErrorno silently dropped coordinate

The pitfalls behind these checks are all quiet ones; most produce plausible output. The worst is the layout.

Warning: Pairing halves, (xi,xi+k)(x_i, x_{i+k}), instead of neighbours (x2i,x2i+1)(x_{2i}, x_{2i+1}) crashes nothing and preserves every length, but the outputs differ from the original model. With Hugging Face weights this is the classic RoPE layout bug. The solution uses the strided slices 0::2 and 1::2 in rotate_pairs, as_complex, and as_real.

Putting the sign on the wrong sin⁡\sin term rotates by −θ-\theta: lengths and relative positions still look right, but every value is wrong. The solution writes x′=xcos⁡−ysin⁡x' = x\cos - y\sin, y′=xsin⁡+ycos⁡y' = x\sin + y\cos and checks it against the hand example. Writing R(θ)R(\theta) transposed is the matrix version of the same mistake: rotation_matrix rotates clockwise while rotate_pairs may still be right, so the two disagree; the columns must be the images of the basis vectors, [[c, -s], [s, c]]. Angles in degrees give meaningless rotations, since cos⁡(90)\cos(90) in radians is −0.448-0.448; numpy and math take radians and no conversion is applied.

Two mistakes concern state. Rotating in place makes the first call right and corrupts x, so the second use of the same keys is rotated twice; the computation runs on a float64 copy into a fresh out. And computing the second output from the already-rotated first, y=x′sin⁡+ycos⁡y = x'\sin + y\cos with the new xx, changes lengths so nothing matches; both outputs read the old even and odd.

The direct consumer is RoPE in AI Engineering, which calls rotate_pairs(q, positions[:, None] * inv_freq) for queries and keys, in both layouts. The sinusoidal encoding relies on the same property: PE(p+j)\mathrm{PE}(p + j) is a fixed rotation of PE(p)\mathrm{PE}(p). In this book, Box-Muller in Random variables and the normal computes −2ln⁡(1−u1) cos⁡(2πu2)\sqrt{-2\ln(1 - u_1)}\,\cos(2\pi u_2) to turn two uniforms into a normal, and the next section builds the frequency ladder ωi\omega_i that RoPE feeds into the angles.

  • OpenStax, Precalculus 2e (free), chapters 5 to 7 on trigonometric functions and identities, and section 8.5 on the polar form of complex numbers.
  • 3Blue1Brown, “Euler’s formula with introductory group theory” (video).
  • Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding” (2021), section 3.2.
  • Meta’s Llama reference apply_rotary_emb in llama/model.py (meta-llama/llama), the interleaved layout in production: it precomputes eimωie^{im\omega_i} once (freqs_cis) and multiplies complex views.
  • Hugging Face apply_rotary_pos_emb with rotate_half in transformers/models/llama/modeling_llama.py, the half layout: it caches cos and sin per position and permutes the weights instead of the activations.
  • vLLM RotaryEmbedding in vllm/model_executor/layers/rotary_embedding.py: a fused CUDA kernel over queries and keys, where is_neox_style selects the layout.
  • llama.cpp ggml_rope_ext in ggml/src/ggml-cpu/ops.cpp: both layouts on the CPU (GGML_ROPE_TYPE_NEOX) and the context-extension scaling.
  • Radian: the measure of an angle as the distance walked along the unit circle; a full turn is 2π2\pi.
  • Unit circle: the circle of radius 1 about the origin; the point at angle θ\theta is (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta).
  • Rotation matrix: R(θ)=(cos⁡θ−sin⁡θsin⁡θcos⁡θ)R(\theta) = \begin{pmatrix}\cos\theta & -\sin\theta \\ \sin\theta & \cos\theta\end{pmatrix}, whose columns are the images of the basis vectors.
  • Angle addition: R(a)R(b)=R(a+b)R(a)R(b) = R(a + b), equivalently the formulas for cos⁡(a+b)\cos(a + b) and sin⁡(a+b)\sin(a + b).
  • Complex number: a point x+iyx + iy of the plane with the multiplication defined by i2=−1i^2 = -1.
  • Euler’s formula: eiθ=cos⁡θ+isin⁡θe^{i\theta} = \cos\theta + i\sin\theta; multiplying by it rotates by θ\theta.
  • Interleaved layout: pairing coordinates as (x2i,x2i+1)(x_{2i}, x_{2i+1}), as in RoFormer and Meta’s Llama code, in contrast to the half layout (xi,xi+k)(x_i, x_{i+k}).
  • A point on the unit circle at angle θ\theta (in radians) is (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta), so cos⁡2θ+sin⁡2θ=1\cos^2\theta + \sin^2\theta = 1.
  • Rotating the plane by θ\theta is the matrix R(θ)R(\theta). It keeps every length, and angles add: R(a)R(b)=R(a+b)R(a)R(b) = R(a + b).
  • Because angles add, the dot product of two rotated vectors depends only on the difference of their angles. RoPE turns token positions into angles and gets attention scores that depend only on relative position.
  • Reading (x,y)(x, y) as x+iyx + iy, Euler’s formula eiθ=cos⁡θ+isin⁡θe^{i\theta} = \cos\theta + i\sin\theta makes the same rotation one multiplication.
  • Pairs are interleaved, (x2i,x2i+1)(x_{2i}, x_{2i+1}). Pairing xix_i with xi+kx_{i+k} instead is a different model with the same shapes.
  1. Why does rotate_pairs write into a new out array instead of updating even and odd?
    AnswerThe second formula, $x\sin + y\cos$, needs the original $x$. Updating even first would feed the rotated value into it and change lengths. A separate output also guarantees the caller's array is not modified, which matters because keys are reused for every query.
  2. What goes wrong if the slices are x[..., :k] and x[..., k:] instead of 0::2 and 1::2?
    AnswerNothing crashes and every length is preserved, but each "pair" is now $(x_i, x_{i+k})$, the half layout. Outputs no longer match a model trained with interleaved RoPE: the classic silent layout bug.
  3. Why is the hand example’s third output 6×10−176 \times 10^{-17} and not 0?
    Answer$\pi/2$ is not exactly representable in float64, so np.cos(np.pi/2) is the cosine of a number slightly off $\pi/2$, about $6 \times 10^{-17}$. Multiplied by the pair's $x = 1$, it appears in the output; comparisons must use a tolerance.
  4. Why does as_complex choose complex64 for float32 input?
    Answercomplex64 stores two float32 values, so every float32 coordinate is represented exactly and as_real(as_complex(x)) returns the identical float32 array. complex128 would also be exact but would change the dtype the caller gets back.
  5. Using only the relative-angle identity, explain why shifting both mm and nn by the same amount leaves the RoPE score unchanged.
    Answer$\langle R(m\omega)q, R(n\omega)k\rangle = \langle q, R((n - m)\omega)k\rangle$, which depends on $m$ and $n$ only through $n - m$. Adding the same shift to both leaves $n - m$, and so the score, the same.
  6. Derive cos⁡(a+b)\cos(a + b) from R(a)R(b)=R(a+b)R(a)R(b) = R(a + b).
    AnswerThe top-left entry of $R(a)R(b)$ is the first row of $R(a)$, $(\cos a, -\sin a)$, dotted with the first column of $R(b)$, $(\cos b, \sin b)$: $\cos a\cos b - \sin a\sin b$. The top-left entry of $R(a + b)$ is $\cos(a + b)$, so they are equal.