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 and 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.
- bigram model: a language model that predicts the next token from the current token alone, stored as a table. Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle in AI Engineering
- Box-Muller: the transform , that turns two uniforms into two independent standard normals. Read more: 13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
- positional encoding: a vector depending only on position, added to the token embedding so attention can see order. Read more: 11.4 Positional encodings: sinusoidal, learned in AI Engineering
- RoPE layout: the rule for which two entries of a head form a rotated pair: half or interleaved . Read more: 22.8 Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax in AI Engineering
- frequency ladder: the geometric sequence of angular speeds, from 1 down to about . Read more: 11.4 Positional encodings: sinusoidal, learned in AI Engineering
- Half layout: pair is ; used by Hugging Face Llama-family checkpoints. Read more: 13.3 Rotary Position Embeddings in AI Engineering
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 and 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 and from the unit circle and derive the rotation matrix 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 to perform the same rotation as one complex multiplication.
- Implement
rotate_pairswith the interleaved layout, without modifying its input, and explain the layout bug that crashes nothing.
Angles in radians
Section titled “Angles in radians”The symbols used throughout are collected here first:
| Symbol | Meaning | Type / shape |
|---|---|---|
| angles in radians | float | |
| half the circumference of a circle of radius 1, | math.pi | |
| the coordinates of the point at angle on the unit circle | float | |
| vectors in the plane, | float[2] | |
| dot product | float | |
| length | float | |
| the rotation matrix by | float[2, 2] | |
| the imaginary unit, | 1j | |
| a complex number with real part and imaginary part | complex | |
| the conjugate | complex | |
| the modulus | float | |
| the number of pairs in a vector of length | int | |
| token positions | int | |
| an angular frequency: radians per position | float |
Walk along the circle of radius 1 centred at the origin, starting at and going counterclockwise. The radian measure of an angle is the distance walked. A full turn is the whole circumference, ; a half turn is ; a right angle is . Degrees convert by , so . Every function in this section, and numpy’s np.cos and np.sin, takes radians. Negative angles walk clockwise, and adding lands on the same point, so the trigonometric functions repeat with period .
The unit circle
Section titled “The unit circle”The point reached at angle has coordinates ; that is the definition of cosine and sine. Because the point is at distance 1 from the origin, Pythagoras gives
Reflecting across the horizontal axis gives and . A few values come from familiar triangles and are worth knowing by heart:
| 0 | ||||||
|---|---|---|---|---|---|---|
| 1 | 0 | |||||
| 0 | 1 | 0 |
Rotations of the plane
Section titled “Rotations of the plane”Rotating the plane by about the origin is linear: rotating a sum is the sum of the rotations, and rotating is times the rotation of . So it is enough to know where the two basis vectors go. goes to by definition, and , a quarter turn further, goes to . Those images are the columns of the matrix:
A rotation keeps lengths. Expanding, , because the cross terms cancel. It also keeps dot products, . In matrix terms, , and undoes the rotation.
Composition: angles add
Section titled “Composition: angles add”Rotating by and then by is a rotation by , so . Multiplying the two matrices out and comparing the first column with that of gives the angle-addition formulas:
With , . This one law, that angles add, is what everything else in the section rests on.
Why RoPE rotates pairs
Section titled “Why RoPE rotates pairs”Rotate by and by , then take the dot product. Using and the composition law,
The result depends on and only through . RoPE sets for a query at position and for a key at position , so the attention score depends only on , the distance between the tokens. Shifting a sentence along the context changes nothing.
A single frequency would make positions apart indistinguishable, so RoPE splits a -dimensional query into pairs and rotates pair by , using a ladder of frequencies that the next section builds. rotate_pairs(x, theta) is exactly that operation, with theta[..., i] the angle of pair . Pair is , the interleaved layout of the RoFormer paper and Meta’s Llama code. Hugging Face’s Llama pairs with instead, the “half” layout of rotate_half; the RoPE section of AI Engineering implements both and converts between them.
Complex numbers and Euler’s formula
Section titled “Complex numbers and Euler’s formula”There is a second, more compact way to say all of this. A complex number is a point of the plane with a multiplication: expand as polynomials in and replace by .
Compare this with the rotation formula: with and , the right-hand side is exactly . Multiplying by rotates by . The modulus is the length, and .
Euler’s formula names that rotating number:
Why an exponential? Because it obeys the law of exponents: is the composition rule, now in one line. Taylor series proves the formula by comparing the series of , , and . Several consequences are used in the problem set: , , (De Moivre’s formula), , and , which is the relative-angle property in complex form.
The code mirrors this view. as_complex reads a real vector of length as complex numbers , 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)).
Working it by hand
Section titled “Working it by hand”Take two pairs and two angles. has pairs and . Rotate pair 0 by the angle with and (so radians, about ), and pair 1 by . The rotation formula gives:
| pair | ||||
|---|---|---|---|---|
| 0 | ||||
| 1 |
So rotate_pairs([3, 4, 1, 0], [t0, pi/2]) is . numpy gives instead of the exact 0, because in floating point is not exactly 0. As a length check, .
The same computation with complex numbers: as_complex([3, 4, 1, 0]) is , and
so as_real returns .
Finally, composition. Multiply . Its first column, , is the point at , as the composition law promises.
Designing the interface
Section titled “Designing the interface”Four functions cover both views of a rotation:
def rotation_matrix(theta: float) -> NDArray: ... # [[cos, -sin], [sin, cos]], float64def 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.
Building it step by step
Section titled “Building it step by step”Seven observations from the theory fix the implementation.
- A rotation is fixed by where the basis vectors go. and are the columns of ; that is all
rotation_matrixhas to write. - Rotating many pairs is the same formula applied elementwise. With the pairs’ coordinates in two arrays,
evenandodd, the rotation is , , computed for every pair at once by broadcasting. No matrix product per pair is needed. - The layout is part of the specification. Pair is , which in numpy is the strided views
x[..., 0::2]andx[..., 1::2]. - Both outputs must read the old values. The formula for uses the original ; computing into the input first would corrupt it. Writing into a fresh output array makes this automatic and also leaves the caller’s
xuntouched. - Angles are per pair and may be per position.
thetamust broadcast tox.shape[:-1] + (k,); checking that up front turns a confusing numpy error into a clearValueError. - Precision follows the caller. Compute in float64 for accuracy, then return float32 if the input was float32, as RoPE needs for activations.
- The complex view is the same data reinterpreted.
as_complexbuilds andas_realwrites 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.
The rotation matrix
Section titled “The rotation matrix”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 ; writing the transpose instead rotates clockwise. math.cos takes radians, like np.cos.
Rotating pairs
Section titled “Rotating pairs”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 . 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.
The complex views
Section titled “The complex views”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.
Why this design
Section titled “Why this design”rotate_pairs costs for a vector of coordinates (one and one per pair, four multiplies and two adds) and extra memory for the float64 copy and the output. It uses elementwise formulas rather than a stack of matrices: np.einsum with per pair would build a 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 and in float64 keeps those values accurate, and only the final result is rounded to float32.
What can go wrong
Section titled “What can go wrong”A correct implementation must pass the following checks, each tied to something that depends on it:
| Case | Kind of check | What must hold | Why it matters downstream |
|---|---|---|---|
| the hand example | unit | becomes | everyone agrees on direction and layout |
| the hand example in complex form | unit | through as_complex and as_real | the complex view of the same example |
rotation_matrix hand values | unit | , , | the columns are the images of the basis vectors |
rotate_pairs agrees with rotation_matrix | differential | each pair equals times the pair | the two functions agree |
| length is preserved | property | every pair keeps its length | RoPE never rescales queries or keys |
| angles add | property | , and rotating twice adds the angles | the law behind relative positions |
| a negative angle undoes | property | rotating by returns the input | |
| the dot product sees only the relative angle | property | is unchanged when and shift together | the RoPE property is built on it |
| Euler’s formula is the rotation | differential | as_complex(rotate_pairs(x, t)) == as_complex(x) * exp(1j t) | Euler’s formula, checked on random data |
| the layout is interleaved | boundary | pairs are , not halves | the layout bug that crashes nothing |
as_real round-trips | property | as_real(as_complex(x)) == x exactly, float32 stays complex64 | lossless views |
| agreement with torch | golden | three cases against torch.view_as_complex(x) * torch.polar(1, theta), one in float32 | the exact op Meta’s Llama code runs |
| theta broadcasts | unit | a [k] theta applies to every row of a batch | the shapes the positional encodings pass |
| dtype follows the input | boundary | float32 in, float32 out; integers promoted to float64 | RoPE keeps activations in float32 |
| the input is not modified | boundary | x is unchanged after the call | keys are reused for every query |
| odd or bad shapes rejected | boundary | odd lengths, bad theta, and 0-d input raise ValueError | no silently dropped coordinate |
The pitfalls behind these checks are all quiet ones; most produce plausible output. The worst is the layout.
Warning: Pairing halves, , instead of neighbours 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::2and1::2inrotate_pairs,as_complex, andas_real.
Putting the sign on the wrong term rotates by : lengths and relative positions still look right, but every value is wrong. The solution writes , and checks it against the hand example. Writing 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 in radians is ; 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, with the new , changes lengths so nothing matches; both outputs read the old even and odd.
Where this leads
Section titled “Where this leads”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: is a fixed rotation of . In this book, Box-Muller in Random variables and the normal computes to turn two uniforms into a normal, and the next section builds the frequency ladder that RoPE feeds into the angles.
Further reading
Section titled “Further reading”- 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_embinllama/model.py(meta-llama/llama), the interleaved layout in production: it precomputes once (freqs_cis) and multiplies complex views. - Hugging Face
apply_rotary_pos_embwithrotate_halfintransformers/models/llama/modeling_llama.py, the half layout: it cachescosandsinper position and permutes the weights instead of the activations. - vLLM
RotaryEmbeddinginvllm/model_executor/layers/rotary_embedding.py: a fused CUDA kernel over queries and keys, whereis_neox_styleselects the layout. - llama.cpp
ggml_rope_extinggml/src/ggml-cpu/ops.cpp: both layouts on the CPU (GGML_ROPE_TYPE_NEOX) and the context-extension scaling.
Key terms
Section titled “Key terms”- Radian: the measure of an angle as the distance walked along the unit circle; a full turn is .
- Unit circle: the circle of radius 1 about the origin; the point at angle is .
- Rotation matrix: , whose columns are the images of the basis vectors.
- Angle addition: , equivalently the formulas for and .
- Complex number: a point of the plane with the multiplication defined by .
- Euler’s formula: ; multiplying by it rotates by .
- Interleaved layout: pairing coordinates as , as in RoFormer and Meta’s Llama code, in contrast to the half layout .
Summary
Section titled “Summary”- A point on the unit circle at angle (in radians) is , so .
- Rotating the plane by is the matrix . It keeps every length, and angles add: .
- 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 as , Euler’s formula makes the same rotation one multiplication.
- Pairs are interleaved, . Pairing with instead is a different model with the same shapes.
Review questions
Section titled “Review questions”- Why does
rotate_pairswrite into a newoutarray instead of updatingevenandodd?Answer
The second formula, $x\sin + y\cos$, needs the original $x$. Updatingevenfirst 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. - What goes wrong if the slices are
x[..., :k]andx[..., k:]instead of0::2and1::2?Answer
Nothing 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. - Why is the hand example’s third output and not 0?
Answer
$\pi/2$ is not exactly representable in float64, sonp.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. - Why does
as_complexchoose complex64 for float32 input?Answer
complex64 stores two float32 values, so every float32 coordinate is represented exactly andas_real(as_complex(x))returns the identical float32 array. complex128 would also be exact but would change the dtype the caller gets back. - Using only the relative-angle identity, explain why shifting both and 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. - Derive from .
Answer
The 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.