Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON rope

Rotary position embeddings: turn position into geometry

Rotate coordinate pairs, derive relative-position scores, and test cache and context-length assumptions.

Preparation: Queries and keys; vectors; angles and dot products.

Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.

Section 01 / 07

Why the same words need different positions

College path. Rotate coordinate pairs, derive relative-position scores, and test cache and context-length assumptions. Preparation: Queries and keys; vectors; angles and dot products. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.

A list of token meanings does not by itself tell a model which token came first. Changing word order can change a sentence: the dog followed the child is different from the child followed the dog. An attention mechanism compares queries and keys, so position can influence those comparisons. Rotary position embeddings, usually called RoPE, rotate pairs of coordinates in queries and keys according to token position. They do not physically rearrange the tokens or rotate a picture of the sentence. The rotation is a precise numerical transformation inside attention.

For a fixed content query q and key k, define position-dependent versions using rotation matrices R_m and R_n. The score becomes the dot product of R_m q and R_n k. Content still matters: a position rule alone cannot determine the score of arbitrary token representations. Causal masking remains separate; position encoding does not prevent a token from reading the future.

Worked example. Imagine two arrows representing a question and a candidate match. Position changes their directions before the dot product measures alignment. An arrow can turn without becoming longer. If both arrows turn by the same angle, their alignment stays the same. That shared-turn observation starts our understanding of relative position.

position-aware score = (R_m q)ᵀ(R_n k)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does rotary position information remove the need for a causal mask?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. Rotation changes scores. A causal mask specifies which positions may be read. Autoregressive generation needs the intended mask as well as consistent position information.

Section 02 / 07

Rotate one pair without changing its length

Begin with a two-number vector rather than a large model. A rotation through angle a maps the pair x, y to x cosine a minus y sine a, followed by x sine a plus y cosine a. Think of these as new horizontal and vertical coordinates of the same arrow. At ninety degrees, the vector one, zero becomes zero, one. At zero degrees it stays unchanged. The angle convention must be consistent between queries and keys. Our Workbench shows degrees for readability and converts them to radians for calculation.

The matrix R(a) has rows [cos(a), -sin(a)] and [sin(a), cos(a)]. It is orthogonal: its transpose times itself is the identity. Consequently, squared Euclidean norm is preserved in exact arithmetic. Small discrepancies can arise from floating-point trigonometric calculations. A general learned projection does not have this norm-preserving property.

Worked example. Rotate [1,0] by ninety degrees. Its coordinates become approximately [0,1], and its squared length remains one. Rotate [0,1] by ninety degrees and obtain [-1,0]. Tiny values sometimes displayed instead of exact zero are rounding effects, not new geometric dimensions.

R(a)[x,y] = [x cos(a) − y sin(a), x sin(a) + y cos(a)]

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. If rotation changes [1,0] into [0,1], did the vector lose information?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. The coordinates changed together through an invertible transformation. Applying the opposite rotation recovers the original pair, up to numerical rounding.

Section 03 / 07

Derive the relative-position identity

Rotate a query by its position and a key by its own position, using the same angular step. Their dot product depends on relative rotation. Moving both positions forward by the same amount leaves this calculation unchanged when the underlying content vectors stay fixed. This is a property of the rotation operation, not a promise that an entire language model ignores absolute context. Changing the text around a token can change its hidden representation, even if the relative position between two selected tokens stays the same.

With one frequency theta, R(m theta) transpose times R(n theta) equals R((n-m) theta). Thus the rotated dot product equals q transpose R((n-m) theta) k. The sign follows our stated column-vector convention. Test with nonidentical vectors so cosine symmetry does not accidentally hide a sign error.

Worked example. Use query [1,0] and key [0,1]. Put the query at position two, key at position one, and use thirty degrees per position. The query rotates sixty degrees and key thirty degrees. Their dot product is one half. Shift both positions forward by five: individual directions change, but the dot product remains one half.

(R(mθ)q)ᵀR(nθ)k = qᵀR((n−m)θ)k

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why must content vectors stay fixed when testing a common position shift?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

The identity concerns the position transformation applied to specified vectors. If the vectors also change, content differences can change the score even though the positional algebra remains correct.

Section 04 / 07

Use several angular speeds across a head

A real attention head has many coordinates. Rotary embeddings split an even number into pairs and rotate different pairs at different angular speeds. A fast pair changes direction substantially over nearby positions; a slow pair changes gradually. The full dot product adds these contributions. A single rotating pair repeats periodically and cannot uniquely label every possible distance. Several frequencies provide richer structure, but do not guarantee perfect distance recognition or reliable retrieval at any length. The model must learn to use these patterns with content.

A common schedule is theta_i = base raised to minus 2i divided by d, for i from zero to d/2 minus one. Here d is the rotary dimension, possibly only part of a head. Interleaved-pair and split-half implementations require compatible weights and conventions. Our single-pair controls illustrate an identity, not an entire frequency schedule.

Worked example. For rotary dimension four and base ten thousand, the two frequencies are one and one hundredth of a radian per position. At position one hundred, their angles are one hundred radians and one radian. These are separate from the thirty-degree teaching settings in our Workbench fixture.

θ_i = base^(−2i/d), i = 0,…,d/2−1

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does a larger rotation angle always mean a lower attention score?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. Sine and cosine oscillate, and content vectors affect the dot product. One pair’s score is not generally a monotonic measure of distance.

Section 05 / 07

Keep positions consistent with the KV cache

During generation, old keys are commonly cached after the intended position transformation. New queries and keys must use positions consistent with that state. Resetting position numbers halfway through a continuation can change relative phases and attention scores. A cache is not simply a bag of reusable numbers: it belongs to a particular prefix, model and position policy. Padding, packed examples, sliding windows and resumed conversations make position bookkeeping especially important. A successful cache read does not prove the entries have the intended meaning.

Compare a full causal forward pass with incremental cached decoding under identical position IDs, masks, precision and model state. Implementations may store transformed or alternative representations; follow their contract rather than assuming every cache contains the same K form. A changed rotation-scaling policy can invalidate reuse even when token strings match.

Worked example. Keep the key at position one in our thirty-degree example. Query position two gives score one half for the specified orthogonal content vectors. Incorrectly resetting the query to zero gives minus one half. A common shift of both would preserve the score; shifting only the new query does not.

Cache reuse requires compatible prefix, model, positions and rotation policy

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Can identical token text alone prove two rotary-attention caches are interchangeable?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. Model state, prefix context, positions, masks and rotation policy must also agree. The same text can correspond to different computed cache values.

Section 06 / 07

Longer context needs more than larger indices

Calculating a rotation at a large position is different from having a model trained to use that position well. Beyond its training range, it can encounter unfamiliar phase relationships or fail to retrieve relevant information. Position interpolation compresses a longer range into a smaller position range. Other extensions adjust frequencies or related scaling. These methods change the model’s operating conditions and need evaluation. Increasing a context-length setting does not by itself establish that every token remains useful. Check both distant evidence and nearby distinctions.

Simple interpolation changes position p to p divided by a scale factor s. This also reduces local phase differences, potentially trading positional resolution against long-range compatibility. Methods such as YaRN use more structured adjustments; our uniform scaling slider does not reproduce them. Report adaptation training and evaluation conditions when comparing extensions.

Worked example. At a thirty-degree step and a gap of one, our score is one half. Dividing positions by two changes the effective gap angle to fifteen degrees and the score to about 0.258819. This demonstrates a changed calculation, not improved language understanding or a validated doubling of context capacity.

Uniform teaching interpolation: angle(p) = p θ / s

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. If a setting allows twice as many tokens, what still needs testing?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Retrieval, reasoning, short-context behavior, cache consistency and resource cost need evaluation. Successful allocation or a completed forward pass is only an execution check.

Section 07 / 07

Separate geometry tests from language quality

Start with small checks whose answers you can explain. Rotate a vector and verify its length. Apply the opposite rotation and recover it. Compare the direct rotated score with the relative-angle expression. Shift both positions together while holding content fixed. Then test an implementation with full versus cached decoding. Finally evaluate useful tasks at several lengths and evidence locations. Save your prediction and Workbench result in Field Notes, and label which level of evidence you obtained. A correct identity is valuable without proving every larger claim.

Include multiple frequency pairs, unsupported rotary dimensions, padding and packed-sequence boundaries in implementation tests. Set tolerances appropriate to precision and operation order. Pairwise algebraic invariance is distinct from global translation invariance of a network with boundaries, masks and content-dependent hidden states.

Worked example. Begin at query position two, key position one, thirty degrees per step and scale one. Shift both by five; the score stays one half. Set scale two; it becomes about 0.258819. Compare direct and relative-route values, and explain why one change preserves the score while the other changes it.

Geometry tests → implementation tests → task evaluation

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. What does agreement between the Workbench routes establish, and leave open?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

It verifies the rotation identity for the displayed vectors and controls. It does not establish long-context quality, complete cache correctness or any hardware speed claim.

Final checkpoint. For the stated rotation convention, which relative angle is correct? Option 1: (n minus m) times theta. Option 2: (n plus m) times theta. Option 3: m times n times theta.

Pause and choose an answer before continuing.

Reveal worked solution

Option 1 is correct. R(m theta) transpose R(n theta) equals R((n minus m) theta).

Continue the learning path

Sources and scope

Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.