The neural notebook
← All chapters

IV-36 / Part VIII · Positional Information

Rotary Position Embeddings (RoPE)

Hand-calculate query/key pair rotations, prove norm preservation and the n-minus-m relative-position identity, and inspect actual saved residuals.

Review the ideas this chapter uses

Two words can occur near each other or far apart. Attention’s query/key comparison is a place to introduce that positional relationship. Instead of adding a position vector to the token input, rotary position embeddings turn pairs of query/key features through position-dependent angles. We will calculate the turns, then prove which relationship survives when both positions shift together.

Learning objective: Rotate paired query/key feature coordinates by positional angles.

Review IV-35 — Learned and Sinusoidal Position Embeddings for paired frequencies and IV-25 — Self-Attention: Complete Numerical Trace for scaled query/key dot products. Book II’s II.4 — Dot product, angle, and orthogonality explains the dot product, II.11 — Transpose and orthogonality explains orthogonality, and VIII.4 — Catastrophic cancellation explains cancellation. Book III’s III-39 — Reproducibility and Numerical Reliability helps distinguish a mathematical identity from numerical verification. The vectors here are hand-set, not fitted to text.

Inspect three rotation routes

Compute it yourself

Rotary Position Embeddings (RoPE)

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
D
4
base
10000
m
1
n
3
q0
1
q1
2
q2
0
q3
1
k0
3
k1
-1
k2
2
k3
0
dot5.988932484619295
relativeDot5.988932484619296
score2.9944662423096475
difference-8.881784197001252e-16
Original query Q
Original key K

dot 5.988932484619295. relativeDot 5.988932484619296. score 2.9944662423096475. difference -8.881784197001252e-16. Validate adjacent pairs and choose query/key positions. All 12 stored scalars are validated, including q2,q3,k2,k3 at D=2. Positions are integer indices; their frequency-scaled angles are radians. This standard mechanism rotates Q and K, not V.. D 4. pairs 2. base 10000. m 1. n 3

Validate adjacent pairs and choose query/key positions

pairs=D/2; D must be even; query position=m; key position=n

All 12 stored scalars are validated, including q2,q3,k2,k3 at D=2. Positions are integer indices; their frequency-scaled angles are radians. This standard mechanism rotates Q and K, not V.

Inputs

D
4
base
10000
m
1
n
3
q0
1
q1
2
q2
0
q3
1
k0
3
k1
-1
k2
2
k3
0

Outputs

D
4
pairs
2
base
10000
m
1
n
3

Rotate pairs, compare two dot-product routes, and inspect squared norms

Inspecting pair 0. These selectors change the view only. The live graded question uses a fixed coordinate and the current starting inputs.

The selected trace operation is setup; its matching saved table row is marked current. Calculation step above exposes its equation, explanation and all inputs and outputs.

All validated setup fields and declared dimensions
setup; saved values shown without display rounding
Saved operationInput DInput baseInput mInput nInput q0Input q1Input q2Input q3Input k0Input k1Input k2Input k3Result DResult pairsResult baseResult mResult n
setup4100001312013-120421000013

Q and K are query and key feature vectors, with D active coordinates. Adjacent features (0,1) and, at D=4, (2,3) form pairs. Each pair turns by an angle: its position index times its frequency. Angles are radians. This lesson rotates Q at m and K at n; the standard mechanism shown here leaves value vectors unrotated.

Saved q_rotate_0 starts with (1, 2), frequency 1, and angle 1. Its four products are 0.5403023058681398, 1.682941969615793, 0.8414709848078965, 1.0806046117362795. Subtraction gives -1.1426396637476532; addition gives 1.922075596544176. These are the actual stored rotated coordinates.

Q

Feature=4 · float64 · display precision 8. Original active query coordinates; inactive stored coordinates remain validated.

Q; saved values shown without display rounding
FeatureCoordinate 0
01
12
20
31

K

Feature=4 · float64 · display precision 8. Original active key coordinates.

K; saved values shown without display rounding
FeatureCoordinate 0
03
1-1
22
30

Frequencies

Pair=2 · float64 · display precision 8. base**(-2*pair/D); pair 0 is 1 for both D=2 and D=4.

Frequencies; saved values shown without display rounding
Adjacent pairFrequency 0
01
10.01

Angles

Route=3 × Pair=2 · float64 · display precision 8. Route rows in order: Q at m, K at n, relative K at n-m. Angles are radians.

Angles; saved values shown without display rounding
RoutePair 0Pair 1
Q at m10.01
K at n30.03
Relative K at n−m20.02

All query rotations, then all key rotations, then all relative-key rotations

For original pair (x,y), c=cos(angle), s=sin(angle), the four products are x×c, y×s, x×s, y×c. Subtract the first two for coordinate 0; add the last two for coordinate 1. The relative route rotates the original K by the signed position n−m, which can be negative.

query pair rotations; saved values shown without display rounding
Saved operationInput pairInput positionInput baseInput DInput xInput yInput exponentResult frequencyResult angleResult cosineResult sineResult product0Result product1Result product2Result product3Result value0Result value1
q_rotate_001100004120110.54030230586813980.84147098480789650.54030230586813981.6829419696157930.84147098480789651.0806046117362795-1.14263966374765321.922075596544176
q_rotate_11110000401-0.50.010.010.99995000041666530.00999983333416666400.00999983333416666400.9999500004166653-0.0099998333341666640.9999500004166653
key pair rotations; saved values shown without display rounding
Saved operationInput pairInput positionInput baseInput DInput xInput yInput exponentResult frequencyResult angleResult cosineResult sineResult product0Result product1Result product2Result product3Result value0Result value1
k_rotate_0031000043-1013-0.98999249660044540.1411200080598672-2.9699774898013365-0.14112000805986720.42336002417960160.9899924966004454-2.8288574817414691.413352520780047
k_rotate_11310000420-0.50.010.030.99955003374898750.029995500202495661.99910006749797500.0599910004049913201.9991000674979750.05999100040499132
relative key pair rotations; saved values shown without display rounding
Saved operationInput pairInput positionInput baseInput DInput xInput yInput exponentResult frequencyResult angleResult cosineResult sineResult product0Result product1Result product2Result product3Result value0Result value1
relative_rotate_0021000043-1012-0.41614683654714240.9092974268256817-1.2484405096414273-0.90929742682568172.7278922804770450.4161468365471424-0.339143082815745573.1440391170241875
relative_rotate_11210000420-0.50.010.020.99980000666657780.019998666693333081.999600013333155500.0399973333866661601.99960001333315550.03999733338666616

RotatedQ

Feature=4 · float64 · display precision 8. Adjacent query pairs rotated at position m.

RotatedQ; saved values shown without display rounding
FeatureCoordinate 0
0-1.1426396637476532
11.922075596544176
2-0.009999833334166664
30.9999500004166653

RotatedK

Feature=4 · float64 · display precision 8. Adjacent key pairs rotated at position n.

RotatedK; saved values shown without display rounding
FeatureCoordinate 0
0-2.828857481741469
11.413352520780047
21.999100067497975
30.05999100040499132

RelativeK

Feature=4 · float64 · display precision 8. Original key rotated at the signed relative position n-m.

RelativeK; saved values shown without display rounding
FeatureCoordinate 0
0-0.33914308281574557
13.1440391170241875
21.9996000133331555
30.03999733338666616

Two independent saved dot-product routes

Each pair contributes q0×k0+q1×k1. Both routes start their running sum at zero and visit pairs in increasing order. The first uses RotatedQ and RotatedK; the second uses original Q and RelativeK.

rotated dot products; saved values shown without display rounding
Saved operationInput pairInput q0Input q1Input k0Input k1Input previousResult product0Result product1Result pairDotResult running
dot_00-1.14263966374765321.922075596544176-2.8288574817414691.41335252078004703.23236476172710542.71657038950552385.9489351512326295.948935151232629
dot_11-0.0099998333341666640.99995000041666531.9991000674979750.059991000404991325.948935151232629-0.019990667493301080.059988000879967240.039997333386666155.988932484619295
relative dot products; saved values shown without display rounding
Saved operationInput pairInput q0Input q1Input k0Input k1Input previousResult product0Result product1Result pairDotResult running
relative_dot_0012-0.339143082815745573.14403911702418750-0.339143082815745576.2880782340483755.948935151232635.94893515123263
relative_dot_11011.99960001333315550.039997333386666165.9489351512326300.039997333386666160.039997333386666165.988932484619296

The first stored dot is 5.988932484619295; the relative route is 5.988932484619296. The actual residual first−relative is -8.881784197001252e-16. Their scores are 2.9944662423096475 and 2.994466242309648 after dividing by sqrt(D), with D=4.

Norm preservation: actual squares and sums

A squared norm is the sum of squared coordinates; it measures squared vector length. Each pair's before/after sums are saved below. The totals start at zero and add these pair sums in increasing order. This checks length, not whether individual coordinates stay unchanged.

pair squared norms; saved values shown without display rounding
Saved operationInput pairInput q0Input q1Input k0Input k1Input qR0Input qR1Input kR0Input kR1Result qBeforeSquaredResult qAfterSquaredResult kBeforeSquaredResult kAfterSquared
norm_00123-1-1.14263966374765321.922075596544176-2.8288574817414691.413352520780047551010
norm_110120-0.0099998333341666640.99995000041666531.9991000674979750.059991000404991321144

norm_0: Q before=(1)²+(2)²=5; Q after=(-1.1426396637476532)²+(1.922075596544176)²=5. K before=(3)²+(-1)²=10; K after=(-2.828857481741469)²+(1.413352520780047)²=10.

norm_1: Q before=(0)²+(1)²=1; Q after=(-0.009999833334166664)²+(0.9999500004166653)²=1. K before=(2)²+(0)²=4; K after=(1.999100067497975)²+(0.05999100040499132)²=4.

total squared norm evidence; saved values shown without display rounding
VectorBefore squared normAfter squared normActual after−before
Q660
K14140
final scaling and identity/norm residuals; saved values shown without display rounding
Saved operationInput dotInput relativeDotInput DInput qBeforeSquaredInput qAfterSquaredInput kBeforeSquaredInput kAfterSquaredResult scoreResult relativeScoreResult differenceResult normQErrorResult normKError
summary5.9889324846192955.98893248461929646614142.99446624230964752.994466242309648-8.881784197001252e-1600

In real arithmetic, dot(R_m q,R_n k)=dot(q,R_(n−m) k), and each rotation preserves squared norm. The saved binary64 residuals are computed, never overwritten with zero. Equal positions give the original dot in real arithmetic; a common valid shift of both positions preserves the real dot. Greater distance need not lower a score because sine and cosine oscillate.

Pair 0 has frequency base^0=1 for both D=2 and D=4: matched first-pair inputs and positions give the same first-pair rotations. D=4 adds the second pair and scales the full dot by 2 rather than sqrt(2), so full scores may differ. Frequencies of higher pairs generally depend on D. D=3 is unavailable because it leaves an unpaired coordinate; base=1 is valid and repeats frequencies.

Every number above comes from a saved tensor or operation record. The full-precision inspector also lists all scalar aliases, named axes, dtypes, provenance and detached row-major storage. Changing an input creates a new trace and resets the graded answers.

Inspect tensor shapes and full precision

All computed outputs

dot
5.988932484619295
relativeDot
5.988932484619296
score
2.9944662423096475
difference
-8.881784197001252e-16
relativeScore
2.994466242309648
normQError
0
normKError
0
D
4
m
1
n
3
base
10000
setup_D
4
setup_pairs
2
setup_base
10000
setup_m
1
setup_n
3
q_rotate_0_frequency
1
q_rotate_0_angle
1
q_rotate_0_cosine
0.5403023058681398
q_rotate_0_sine
0.8414709848078965
q_rotate_0_product0
0.5403023058681398
q_rotate_0_product1
1.682941969615793
q_rotate_0_product2
0.8414709848078965
q_rotate_0_product3
1.0806046117362795
q_rotate_0_value0
-1.1426396637476532
q_rotate_0_value1
1.922075596544176
q_rotate_1_frequency
0.01
q_rotate_1_angle
0.01
q_rotate_1_cosine
0.9999500004166653
q_rotate_1_sine
0.009999833334166664
q_rotate_1_product0
0
q_rotate_1_product1
0.009999833334166664
q_rotate_1_product2
0
q_rotate_1_product3
0.9999500004166653
q_rotate_1_value0
-0.009999833334166664
q_rotate_1_value1
0.9999500004166653
k_rotate_0_frequency
1
k_rotate_0_angle
3
k_rotate_0_cosine
-0.9899924966004454
k_rotate_0_sine
0.1411200080598672
k_rotate_0_product0
-2.9699774898013365
k_rotate_0_product1
-0.1411200080598672
k_rotate_0_product2
0.4233600241796016
k_rotate_0_product3
0.9899924966004454
k_rotate_0_value0
-2.828857481741469
k_rotate_0_value1
1.413352520780047
k_rotate_1_frequency
0.01
k_rotate_1_angle
0.03
k_rotate_1_cosine
0.9995500337489875
k_rotate_1_sine
0.02999550020249566
k_rotate_1_product0
1.999100067497975
k_rotate_1_product1
0
k_rotate_1_product2
0.05999100040499132
k_rotate_1_product3
0
k_rotate_1_value0
1.999100067497975
k_rotate_1_value1
0.05999100040499132
relative_rotate_0_frequency
1
relative_rotate_0_angle
2
relative_rotate_0_cosine
-0.4161468365471424
relative_rotate_0_sine
0.9092974268256817
relative_rotate_0_product0
-1.2484405096414273
relative_rotate_0_product1
-0.9092974268256817
relative_rotate_0_product2
2.727892280477045
relative_rotate_0_product3
0.4161468365471424
relative_rotate_0_value0
-0.33914308281574557
relative_rotate_0_value1
3.1440391170241875
relative_rotate_1_frequency
0.01
relative_rotate_1_angle
0.02
relative_rotate_1_cosine
0.9998000066665778
relative_rotate_1_sine
0.01999866669333308
relative_rotate_1_product0
1.9996000133331555
relative_rotate_1_product1
0
relative_rotate_1_product2
0.03999733338666616
relative_rotate_1_product3
0
relative_rotate_1_value0
1.9996000133331555
relative_rotate_1_value1
0.03999733338666616
dot_0_product0
3.2323647617271054
dot_0_product1
2.7165703895055238
dot_0_pairDot
5.948935151232629
dot_0_running
5.948935151232629
dot_1_product0
-0.01999066749330108
dot_1_product1
0.05998800087996724
dot_1_pairDot
0.03999733338666615
dot_1_running
5.988932484619295
relative_dot_0_product0
-0.33914308281574557
relative_dot_0_product1
6.288078234048375
relative_dot_0_pairDot
5.94893515123263
relative_dot_0_running
5.94893515123263
relative_dot_1_product0
0
relative_dot_1_product1
0.03999733338666616
relative_dot_1_pairDot
0.03999733338666616
relative_dot_1_running
5.988932484619296
norm_0_qBeforeSquared
5
norm_0_qAfterSquared
5
norm_0_kBeforeSquared
10
norm_0_kAfterSquared
10
norm_1_qBeforeSquared
1
norm_1_qAfterSquared
1
norm_1_kBeforeSquared
4
norm_1_kAfterSquared
4
summary_score
2.9944662423096475
summary_relativeScore
2.994466242309648
summary_difference
-8.881784197001252e-16
summary_normQError
0
summary_normKError
0

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

Q

Feature=4 · float64 · display precision 8 · Original active query coordinates; inactive stored coordinates remain validated.

Storage indexValue
01
12
20
31

K

Feature=4 · float64 · display precision 8 · Original active key coordinates.

Storage indexValue
03
1-1
22
30

RotatedQ

Feature=4 · float64 · display precision 8 · Adjacent query pairs rotated at position m.

Storage indexValue
0-1.1426396637476532
11.922075596544176
2-0.009999833334166664
30.9999500004166653

RotatedK

Feature=4 · float64 · display precision 8 · Adjacent key pairs rotated at position n.

Storage indexValue
0-2.828857481741469
11.413352520780047
21.999100067497975
30.05999100040499132

RelativeK

Feature=4 · float64 · display precision 8 · Original key rotated at the signed relative position n-m.

Storage indexValue
0-0.33914308281574557
13.1440391170241875
21.9996000133331555
30.03999733338666616

Frequencies

Pair=2 · float64 · display precision 8 · base**(-2*pair/D); pair 0 is 1 for both D=2 and D=4.

Storage indexValue
01
10.01

Angles

Route=3 × Pair=2 · float64 · display precision 8 · Route rows in order: Q at m, K at n, relative K at n-m. Angles are radians.

Storage indexValue
01
10.01
23
30.03
42
50.02

Start with D=4, base=10000, query position m=1 and key position n=3. Q=(1,2,0,1) and K=(3,−1,2,0). Edit any coordinate, index or base to create a new calculation. All 12 fields are checked, including the second pair when D=2. Choosing D=3 intentionally shows the incomplete-pair error, with no partial numerical output.

The reset pair frequencies are 1 and 1/100. Q uses angles 1 and 0.01 radians; K uses 3 and 0.03; the relative route uses 2 and 0.02. For any pair (x,y), multiply to get x×cos(angle), y×sin(angle), x×sin(angle), y×cos(angle). The new first coordinate subtracts the first two products; the new second coordinate adds the last two. The saved rotation records show these four products and two results for every route.

To understand the relative identity, write q=(a,b), k=(c,d), and delta=(n−m)×frequency for one pair. Expanding the rotation gives (ac+bd)cos(delta)+(bc−ad)sin(delta). At reset, pair 0 has ac+bd=1 and bc−ad=7; pair 1 has ac+bd=0 and bc−ad=2. The full real dot is cos(2)+7sin(2)+2sin(0.02), and the scaled score is that expression divided by 2. This is a symbolic derivation of the reset example, not a serialized observation or a substitute for the actual two dot-product traces.

Squared norm means the sum of squared feature coordinates. At reset the original Q total is (1²+2²)+(0²+1²)=6, and K's is (3²+(−1)²)+(2²+0²)=14. Rotations preserve those totals in real arithmetic because cosine²+sine²=1 and the cross terms cancel. The tables retain the actual before/after totals and their computed residuals; they do not replace small floating-point errors with exact zero.

Try n<m to inspect a negative relative angle, or m=n to compare with the original real dot. A common valid shift preserves the real relative dot, while changing individual coordinates. Pair 0 has frequency 1 for either supported width; D=4 adds a second pair and changes the score divisor. RoPE supplies a relative-position structure, not a guarantee that similarity decreases with distance, that every coordinate stays fixed, or that a trained model generalizes to unseen lengths.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. Which operation is the standard RoPE mechanism shown here?
2. For m=1 and n=3, what signed relative position rotates the original K in dot(R_m q,R_n k)=dot(q,R_(n−m) k)?
3. Using the current starting inputs, saved q_rotate_0 has product0=0.5403023058681398 and product1=1.682941969615793. What value and operation produce RotatedQ[0]?
4. Hold Q,K,D,base fixed and add the same integer shift to m and n, keeping both positions in 0..8. What does the real dot-product identity predict?
5. Hold q0,q1,k0,k1,base,m,n fixed and switch from D=2 to D=4. Which statement is correct?

Reset supplies four query features, four key features, query position m=1 and key position n=3. Inspect Q rotated at m, K rotated at n, and a separate K rotation at the relative position n−m. The lab computes the dot product using the first two routes and independently computes the query’s dot product with the third. Compare the saved operands, not just a rounded equality label.

Try m=n, then reset. Next shift both positions by the same amount while keeping them within 0..8. The real relative dot should retain its value; saved binary64 residuals need not be zero. Edit an individual q or k coordinate to see real recomputation. D=2 activates only the first pair; D=4 activates both pairs. Reset before following all the products below. Open Original query Q and Original key K to edit feature coordinates. Adjacent pair to inspect changes the view only. Calculation step exposes a saved rotation, dot, norm or summary record and marks its full-table row; it does not rerun a new approximation.

Vocabulary and shapes before the rotation

A query q and key k are feature vectors whose dot product supplies an attention score before softmax. A dot product multiplies matching coordinates and adds the products. D counts their feature width. In this isolated lab, Q and K each have shape [D], axis Feature, for one query/key comparison. There is no batch, token or head axis in these stored vectors; m and n supply the two position indices. In a full attention head this operation is applied separately to its query/key rows.

A pair r consists of adjacent features (2r,2r+1). For D=4, r=0 uses coordinates 0,1 and r=1 uses 2,3. This adjacent-pair convention is fixed for the lesson. A rotation changes the pair’s direction in a two-coordinate plane. Its norm, or length, is √(x²+y²); squared norm is x²+y². Norm preservation does not mean that individual coordinates remain unchanged.

RoPE abbreviates rotary position embeddings. Here it rotates Q and K, not the value vector V subsequently mixed by attention. It introduces neither an additive PE tensor nor a softmax probability distribution in this lab. RotatedQ, RotatedK and RelativeK all have shape [D], axis Feature. Frequencies has shape [D/2], axis Pair. Angles has shape [3,D/2], axes Route,Pair; route order is Q, K, relative K. These seven tensors contain the actual saved vectors and angles.

Let b be the base. For pair r, first calculate

er=−2r/D,ωr=ber,θ=pωr.e_r=-2r/D,\qquad \omega_r=b^{e_r},\qquad \theta=p\omega_r.

Here p is the position used by the route, ω is the angle change per position, and θ is the resulting angle in radians. Sine and cosine receive radians, not degrees. Write c=cos θ and s=sin θ. The rotation is

Rθ(x,y)=(xc−ys,  xs+yc).R_\theta(x,y)=(x c-y s,\;x s+y c).

The minus sign belongs to the first coordinate and the plus sign to the second. As a matrix acting on a two-entry column it is

Rθ=(cos⁡θ−sin⁡θsin⁡θcos⁡θ).R_\theta=\begin{pmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{pmatrix}.

Our stored vector is a list of features; this column notation specifies exactly the same two scalar formulas and does not silently reverse the signs. Each saved rotation computes four products x·c, y·s, x·s, y·c in that order, then subtracts the first two and adds the last two. Rotating coordinates separately by unrelated angles would not be this operation.

The complete default rotations

Defaults are D=4, b=10000, q=(1,2,0,1), k=(3,−1,2,0), m=1, n=3. Pair zero has exponent 0, frequency 1; pair one has exponent −1/2, frequency 1/100. Denote Cₐ=cos(a) and Sₐ=sin(a). Decimal subscripts .01, .02 and .03 below stand for the real angles 1/100, 2/100 and 3/100. They are symbolic expressions, not observed serialized results.

The three angle rows are (1,1/100), (3,3/100), (2,2/100). The last uses n−m=3−1=2. All Q pairs are computed first, then all K pairs, then all relative K pairs. This table gives every product and coordinate in that order:

Record, pair input, angleproduct0 x·cproduct1 y·sproduct2 x·sproduct3 y·cvalue0=p0−p1value1=p2+p3
q_rotate_0, (1,2), 11C₁=C₁2S₁1S₁=S₁2C₁C₁−2S₁S₁+2C₁
q_rotate_1, (0,1), .010C_.01=01S_.01=S_.010S_.01=01C_.01=C_.01−S_.01C_.01
k_rotate_0, (3,−1), 33C₃−S₃3S₃−C₃3C₃+S₃3S₃−C₃
k_rotate_1, (2,0), .032C_.030S_.03=02S_.030C_.03=02C_.032S_.03
relative_rotate_0, (3,−1), 23C₂−S₂3S₂−C₂3C₂+S₂3S₂−C₂
relative_rotate_1, (2,0), .022C_.020S_.02=02S_.020C_.02=02C_.022S_.02

In the table’s last two headings p0..p3 abbreviate the four products, not position indices. For example k_rotate_0 first subtracts product1=−S₃, so value0 is 3C₃−(−S₃)=3C₃+S₃. This is an easy place to lose a sign.

Both dot products, pair by pair

The direct route multiplies the saved rotated Q and K coordinates. Within a pair, it adds product0+product1 to form pairDot; it then adds that pairDot to the previous running total, initially zero. It does not flatten the two pairs into a differently grouped reduction.

Recordproduct0product1pairDotRunning total
dot_0(C₁−2S₁)(3C₃+S₃)(S₁+2C₁)(3S₃−C₃)A = product0+product10+A=A
dot_1(−S_.01)(2C_.03)C_.01(2S_.03)B = product0+product1A+B
relative_dot_01(3C₂+S₂)2(3S₂−C₂)(3C₂+S₂)+(6S₂−2C₂)=C₂+7S₂0+(C₂+7S₂)
relative_dot_10(2C_.02)=01(2S_.02)=2S_.020+2S_.02(C₂+7S₂)+2S_.02

To see why direct A simplifies to the same first-pair result, expand its two products before collecting terms:

A=3C1C3+C1S3−6S1C3−2S1S3+3S1S3−S1C3+6C1S3−2C1C3.A=3C_1C_3+C_1S_3-6S_1C_3-2S_1S_3 +3S_1S_3-S_1C_3+6C_1S_3-2C_1C_3.

The C₁C₃ coefficient is 3−2=1; S₁S₃ is −2+3=1; C₁S₃ is 1+6=7; S₁C₃ is −6−1=−7. Therefore

A=(C1C3+S1S3)+7(C1S3−S1C3)=cos⁡(3−1)+7sin⁡(3−1)=C2+7S2.A=(C_1C_3+S_1S_3)+7(C_1S_3-S_1C_3) =\cos(3-1)+7\sin(3-1)=C_2+7S_2.

Likewise B=−2S_.01C_.03+2C_.01S_.03=2sin(.03−.01)=2S_.02. The complete real default dot product and scaled score are

dot=cos⁡2+7sin⁡2+2sin⁡(1/50),score=dot/4=dot/2.\mathrm{dot}=\cos2+7\sin2+2\sin(1/50),\qquad \mathrm{score}=\mathrm{dot}/\sqrt4=\mathrm{dot}/2.

The relative path reaches that expression by different operations. Floating-point dot and relativeDot are stored separately; difference subtracts the latter from the former. The code does not insert this symbolic expression as their answer and does not force their difference to zero. relativeScore divides the actual relativeDot by the same √D.

Prove the n-minus-m identity, including the sign

For one pair, write q=(a,b), k=(c,d), and α=mω, β=nω. In this proof paragraph b is a query coordinate; the base control does not appear in the expanded products. Applying the rotation formula twice and expanding the dot gives

(ac+bd)(cos⁡αcos⁡β+sin⁡αsin⁡β)+(bc−ad)(cos⁡αsin⁡β−sin⁡αcos⁡β).(ac+bd)(\cos\alpha\cos\beta+\sin\alpha\sin\beta) +(bc-ad)(\cos\alpha\sin\beta-\sin\alpha\cos\beta).

The angle-difference identities turn the two parentheses into cos(β−α) and sin(β−α). With δ=(n−m)ω the result is

(ac+bd)cos⁡δ+(bc−ad)sin⁡δ.(ac+bd)\cos\delta+(bc-ad)\sin\delta.

Now rotate only k by δ and take its dot with the original q:

q⋅Rδk=a(ccos⁡δ−dsin⁡δ)+b(csin⁡δ+dcos⁡δ)=(ac+bd)cos⁡δ+(bc−ad)sin⁡δ.q\cdot R_\delta k =a(c\cos\delta-d\sin\delta)+b(c\sin\delta+d\cos\delta) =(ac+bd)\cos\delta+(bc-ad)\sin\delta.

Thus dot(R_m q,R_n k)=dot(q,R_(n−m)k), with each route using its pair frequency. The notation R_m means the block of pair rotations at position m, not a single common angle for all features. Summing the proven identity over all pairs proves the full vector identity.

A matrix check reaches the same conclusion: R_αᵀ=R_−α and R_−αR_β=R_(β−α). The transpose reverses the query rotation, which is why the relative sign is n−m. Using m−n while keeping q on the left and rotating k would flip the sine term and generally change the result. The default first pair has ac+bd=1·3+2·(−1)=3−2=1 and bc−ad=2·3−1·(−1)=6+1=7. The second has ac+bd=0·2+1·0=0 and bc−ad=1·2−0·0=2. These coefficients independently explain the default formula.

If m=n, δ=0, so cos δ=1 and sin δ=0: the dot becomes the original q·k. At reset vectors this is (1·3+2·(−1))+(0·2+1·0)=1+0=1, hence real score 1/2 for D=4. If both positions shift by h, (n+h)−(m+h)=n−m, so the real dot is unchanged. The two absolute rotation routes still use different angles and can accumulate different floating-point errors.

Raw positions must be nonnegative supported integers, but the derived relative position may be negative. For m=3,n=1 it is −2, a valid reverse turn; reapplying the raw 0..8 input rule to n−m would incorrectly reject it. This identity holds for fixed q,k. It does not claim that a whole contextual model’s q,k stay unchanged when its input moves.

Prove norm preservation and inspect its evidence

For one pair, square both output coordinates and add:

(xc−ys)2+(xs+yc)2=x2c2−2xycs+y2s2+x2s2+2xysc+y2c2.(xc-ys)^2+(xs+yc)^2 =x^2c^2-2xycs+y^2s^2+x^2s^2+2xysc+y^2c^2.

The mixed terms cancel. Grouping the rest gives x²(c²+s²)+y²(s²+c²)=x²+y² because c²+s²=1. Adding across pairs preserves the whole squared norm. The proof preserves length, not dot products between vectors rotated by different angles.

Every default norm has explicit before/after evidence:

Vector, pairBefore: two squares and sumAfter: two squares and sumReal simplification
Q,01·1+2·2=1+4=5(C₁−2S₁)²+(S₁+2C₁)²5(C₁²+S₁²)=5
Q,10·0+1·1=0+1=1(−S_.01)²+C_.01²S_.01²+C_.01²=1
K,03·3+(−1)(−1)=9+1=10(3C₃+S₃)²+(3S₃−C₃)²10(C₃²+S₃²)=10
K,12·2+0·0=4+0=4(2C_.03)²+(2S_.03)²4(C_.03²+S_.03²)=4

The norm loop calculates two actual squares then their sum for each pair and vector, saving norm_0 and norm_1. It accumulates totals in pair order: Q has real total (0+5)+1=6; K has (0+10)+4=14. The summary saves normQError=actual Q-after total minus Q-before total, and analogously normKError. These residuals are evidence to inspect, not values overwritten by the proof. Finite precision can leave a small difference even with a correct formula. Near cancellation, a tiny absolute residual alone does not establish a strong relative-accuracy claim.

Widths, boundaries and counterexamples

For both supported widths D=2 and D=4, pair zero has exponent −2·0/D=0 and frequency b⁰=1. At matched first-pair inputs and positions its rotations use the same operations. D=4 adds pair one and divides the full score by 2; D=2 divides by √2. Matching first-pair rotations therefore does not imply matching full scores. Higher-pair frequencies generally depend on D, but the first pair does not change here.

D must be even so every active feature has a partner. The raw integer D=3 is inside the numeric interval 2..4 yet causes SHAPE_MISMATCH; it is not silently padded or truncated. Both positions are integers 0..8, the base is finite in [1,10000], and every q/k coordinate is finite in [−4,4]. Coordinates q2,q3,k2,k3 still validate when D=2 makes them inactive. Known invalid input returns an unavailable whole result with no successful partial vectors or trace.

At base 1 both active frequencies equal 1. That is a supported repetition of angular scales. A zero pair remains zero after rotation; a nonzero pair can change both coordinates while preserving its norm. Norm preservation is not a guarantee that attention scores grow with distance. For example a single q=k=(1,0) pair contributes cos(n−m), which decreases from separation zero to one radian and oscillates as separation grows. There is no general monotonic proximity rule built into this identity. Nor does norm preservation by itself prove model accuracy or long-context generalization.

Follow the maintained Python in arithmetic order

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-36 — Rotary Position Embeddings (RoPE).

Adjacent pairs of Q and K rotate in radians: R_theta(x,y)=(x*c-y*s,
x*s+y*c), with c=cos(theta), s=sin(theta), omega=base**(-2*pair/D).
Q rotates at m; K at n. A separate path rotates K at n-m, including negative
relative positions, and checks dot(R_m Q,R_n K)=dot(Q,R_(n-m) K).
The standard Q/K mechanism here does not rotate a value vector.

For one pair the real relative dot is (q0*k0+q1*k1)*cos(delta)
+(q1*k0-q0*k1)*sin(delta). The default gives
cos(2)+7*sin(2)+2*sin(.02), with scaled score equal to this expression /2.
Rotations preserve real norms; coordinate values change and binary64 norm/dot
errors are measured, never overwritten with zero. A common position shift
preserves the real relative dot, not necessarily its rounded representation.
For supported D=2 and D=4, pair0 frequency is always base**0=1, so its
rotations agree for matched vectors/positions. D=4 adds a second pair and
uses score divisor 2, whereas D=2 uses sqrt(2). Higher-pair frequencies
in general depend on D. Dot products need not increase with distance.

Keep position_reference.py beside this file. Imports use file-relative paths.
This is authored executable source; execution and validation remain deferred.
"""
import importlib.util
import math
from pathlib import Path
from types import MappingProxyType
import numpy as np

_helper_spec = importlib.util.spec_from_file_location(
    "_p08_position_reference", Path(__file__).resolve().with_name("position_reference.py"))
_helper = importlib.util.module_from_spec(_helper_spec)
_helper_spec.loader.exec_module(_helper)

DEFAULT_IV36 = MappingProxyType(dict(_helper.ROPE_DEFAULTS))


@_helper.guarded
def derive_iv36(state):
    """Save three rotation routes, both dot products, and actual norm evidence."""
    s = _helper.position_state(state, 36)
    D, pairs, base, m, n = s["D"], s["D"] // 2, s["base"], s["m"], s["n"]
    trace = _helper.position_trace()
    trace.add("setup", "Validate the complete RoPE state before selecting active pairs",
              "omega_r=base**(-2*r/D); dot(R_m q,R_n k)=dot(q,R_(n-m) k)",
              "D is even; inactive q/k scalars are validated too. Relative position n-m may be negative.",
              s, dict(D=D, pairs=pairs, base=base, m=m, n=n))
    Q = np.array([s[f"q{d}"] for d in range(D)], dtype=np.float64)
    K = np.array([s[f"k{d}"] for d in range(D)], dtype=np.float64)
    rotated_q, rotated_k, relative_k = (np.empty(D, dtype=np.float64) for _ in range(3))
    frequencies = np.empty(pairs, dtype=np.float64)
    angles = np.empty((3, pairs), dtype=np.float64)
    # Complete the Q route, then K, then relative K. Never interleave routes.
    routes = (("q", Q, rotated_q, m), ("k", K, rotated_k, n), ("relative", K, relative_k, n - m))
    for route, (name, source, target, position) in enumerate(routes):
        for pair in range(pairs):
            x, y = float(source[2 * pair]), float(source[2 * pair + 1])
            exponent = -2 * pair / D
            frequency = _helper.finite(base ** exponent, "RoPE frequency")
            angle = _helper.finite(position * frequency, "RoPE angle")
            cosine = _helper.finite(math.cos(angle), "RoPE cosine")
            sine = _helper.finite(math.sin(angle), "RoPE sine")
            product0 = _helper.finite(x * cosine, "rotation x*cos")
            product1 = _helper.finite(y * sine, "rotation y*sin")
            product2 = _helper.finite(x * sine, "rotation x*sin")
            product3 = _helper.finite(y * cosine, "rotation y*cos")
            value0 = _helper.finite(product0 - product1, "rotated first coordinate")
            value1 = _helper.finite(product2 + product3, "rotated second coordinate")
            target[2 * pair], target[2 * pair + 1] = value0, value1
            frequencies[pair], angles[route, pair] = frequency, angle
            trace.add(f"{name}_rotate_{pair}", f"{name.capitalize()} route, adjacent pair {pair}",
                      "frequency=base**exponent; angle=position*frequency; c=cos(angle); s=sin(angle); product0=x*c; product1=y*s; product2=x*s; product3=y*c; value0=product0-product1; value1=product2+product3",
                      "Four separate scalar products precede the subtraction and addition; angles are in radians.",
                      dict(pair=pair, position=position, base=base, D=D, x=x, y=y, exponent=exponent),
                      dict(frequency=frequency, angle=angle, cosine=cosine, sine=sine,
                           product0=product0, product1=product1, product2=product2, product3=product3,
                           value0=value0, value1=value1))
    dots = []
    for name, query, key in (("dot", rotated_q, rotated_k), ("relative_dot", Q, relative_k)):
        running = 0.0
        for pair in range(pairs):
            q0, q1 = float(query[2 * pair]), float(query[2 * pair + 1])
            k0, k1 = float(key[2 * pair]), float(key[2 * pair + 1])
            previous = running
            product0 = _helper.finite(q0 * k0, "dot product0")
            product1 = _helper.finite(q1 * k1, "dot product1")
            pair_dot = _helper.finite(product0 + product1, "pair dot")
            running = _helper.finite(previous + pair_dot, "dot running sum")
            trace.add(f"{name}_{pair}", f"{name.replace('_', ' ').capitalize()}, pair {pair}",
                      "product0=q0*k0; product1=q1*k1; pairDot=product0+product1; running=previous+pairDot",
                      "Pair sums are accumulated in ascending pair order, starting from zero.",
                      dict(pair=pair, q0=q0, q1=q1, k0=k0, k1=k1, previous=previous),
                      dict(product0=product0, product1=product1, pairDot=pair_dot, running=running))
        dots.append(running)
    q_before = q_after = k_before = k_after = 0.0
    for pair in range(pairs):
        q0, q1 = float(Q[2 * pair]), float(Q[2 * pair + 1])
        k0, k1 = float(K[2 * pair]), float(K[2 * pair + 1])
        qr0, qr1 = float(rotated_q[2 * pair]), float(rotated_q[2 * pair + 1])
        kr0, kr1 = float(rotated_k[2 * pair]), float(rotated_k[2 * pair + 1])
        # Each norm uses two separate squares, then their sum; no NumPy norm.
        qb = _helper.finite(_helper.finite(q0 * q0, "q0 squared") + _helper.finite(q1 * q1, "q1 squared"), "Q pair squared norm")
        qa = _helper.finite(_helper.finite(qr0 * qr0, "qR0 squared") + _helper.finite(qr1 * qr1, "qR1 squared"), "rotated Q pair squared norm")
        kb = _helper.finite(_helper.finite(k0 * k0, "k0 squared") + _helper.finite(k1 * k1, "k1 squared"), "K pair squared norm")
        ka = _helper.finite(_helper.finite(kr0 * kr0, "kR0 squared") + _helper.finite(kr1 * kr1, "kR1 squared"), "rotated K pair squared norm")
        trace.add(f"norm_{pair}", f"Squared norm evidence for pair {pair}",
                  "qBeforeSquared=q0*q0+q1*q1; qAfterSquared=qR0*qR0+qR1*qR1; kBeforeSquared=k0*k0+k1*k1; kAfterSquared=kR0*kR0+kR1*kR1",
                  "Real rotations preserve squared norms; these saved values retain their actual rounding.",
                  dict(pair=pair, q0=q0, q1=q1, k0=k0, k1=k1, qR0=qr0, qR1=qr1, kR0=kr0, kR1=kr1),
                  dict(qBeforeSquared=qb, qAfterSquared=qa, kBeforeSquared=kb, kAfterSquared=ka))
        q_before = _helper.finite(q_before + qb, "total Q squared norm")
        q_after = _helper.finite(q_after + qa, "total rotated Q squared norm")
        k_before = _helper.finite(k_before + kb, "total K squared norm")
        k_after = _helper.finite(k_after + ka, "total rotated K squared norm")
    dot, relative_dot = dots
    divisor = _helper.finite(math.sqrt(D), "score divisor")
    score = _helper.finite(dot / divisor, "RoPE score")
    relative_score = _helper.finite(relative_dot / divisor, "relative score")
    difference = _helper.finite(dot - relative_dot, "relative dot difference")
    norm_q_error = _helper.finite(q_after - q_before, "Q squared norm error")
    norm_k_error = _helper.finite(k_after - k_before, "K squared norm error")
    trace.add("summary", "Compare the actual dot products and squared norms",
              "score=dot/sqrt(D); relativeScore=relativeDot/sqrt(D); difference=dot-relativeDot; normQError=qAfterSquared-qBeforeSquared; normKError=kAfterSquared-kBeforeSquared",
              "The real identities do not justify forcing a binary64 residual to zero.",
              dict(dot=dot, relativeDot=relative_dot, D=D, qBeforeSquared=q_before, qAfterSquared=q_after,
                   kBeforeSquared=k_before, kAfterSquared=k_after),
              dict(score=score, relativeScore=relative_score, difference=difference,
                   normQError=norm_q_error, normKError=norm_k_error))
    summary = dict(dot=dot, relativeDot=relative_dot, score=score, difference=difference,
                   relativeScore=relative_score, normQError=norm_q_error, normKError=norm_k_error,
                   D=D, m=m, n=n, base=base)
    tensors = [
        _helper.tensor("Q", [D], ["Feature"], Q, "Active original query features in adjacent-pair order."),
        _helper.tensor("K", [D], ["Feature"], K, "Active original key features in adjacent-pair order."),
        _helper.tensor("RotatedQ", [D], ["Feature"], rotated_q, "Actual adjacent-pair rotation of Q at position m."),
        _helper.tensor("RotatedK", [D], ["Feature"], rotated_k, "Actual adjacent-pair rotation of K at position n."),
        _helper.tensor("RelativeK", [D], ["Feature"], relative_k, "Separate actual rotation of K at relative position n-m."),
        _helper.tensor("Frequencies", [pairs], ["Pair"], frequencies, "base**(-2*pair/D); first pair frequency is 1 for both supported widths."),
        _helper.tensor("Angles", [3, pairs], ["Route", "Pair"], angles, "Routes in order: Q at m, K at n, relative K at n-m; radians."),
    ]
    return trace.result(summary, tensors)


if __name__ == "__main__":
    _helper.run(derive_iv36, DEFAULT_IV36)
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Part VIII common boundaries: shaped NumPy storage and ordered scalar records.

The three lesson wrappers contain the calculations. This helper validates every
stored input (even an inactive one), detaches saved records, and loads the actual
protected IV-25 source by its file location. No attention algorithm is copied.
Python floats perform the arithmetic; NumPy gives arrays their explicit axes.
This is executable educational source, authored without importing or running it.
"""
import argparse
from functools import lru_cache, wraps
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    """Accept real numeric scalars, never a bool, string, NaN or infinity."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


PERMUTATION_DEFAULTS = MappingProxyType(dict(
    permutation=4, signal=0,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    wq00=1, wq01=0, wq10=0, wq11=1,
    wk00=1, wk01=0, wk10=0, wk11=1,
    wv00=1, wv01=0, wv10=0, wv11=1,
))
ENCODING_DEFAULTS = MappingProxyType(dict(
    kind=1, base=10000, p0=0, p1=1, p2=2,
    x00=1, x01=0, x02=0, x03=0,
    x10=0, x11=1, x12=0, x13=0,
    x20=0, x21=0, x22=1, x23=0,
    l00=0, l01=0, l02=0, l03=0,
    l10=1, l11=0, l12=0, l13=0,
    l20=0, l21=1, l22=0, l23=0,
    l30=0, l31=0, l32=1, l33=0,
))
ROPE_DEFAULTS = MappingProxyType(dict(
    D=4, base=10000, m=1, n=3,
    q0=1, q1=2, q2=0, q3=1, k0=3, k1=-1, k2=2, k3=0,
))
PERMUTATIONS = ((0, 1, 2), (0, 2, 1), (1, 0, 2),
                (1, 2, 0), (2, 0, 1), (2, 1, 0))


def position_state(state, chapter):
    """Raw validation precedes learned-table and even-width semantic checks."""
    if type(chapter) is not int or chapter not in (34, 35, 36):
        raise NumericalFault("INVALID_INPUT", "Use position chapter 34, 35 or 36.")
    defaults = {34: PERMUTATION_DEFAULTS, 35: ENCODING_DEFAULTS, 36: ROPE_DEFAULTS}[chapter]
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    integer_bounds = (dict(permutation=(0, 5), signal=(0, 1)) if chapter == 34 else
                      dict(kind=(0, 1), p0=(0, 8), p1=(0, 8), p2=(0, 8)) if chapter == 35 else
                      dict(D=(2, 4), m=(0, 8), n=(0, 8)))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        bounds = (1, 10000) if key == "base" else (-2, 2) if chapter == 34 else (-4, 4)
        low, high = integer_bounds.get(key, bounds)
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    if chapter == 35 and result["kind"] == 0 and any(result[f"p{t}"] > 3 for t in range(3)):
        raise NumericalFault("UNSUPPORTED_SIZE", "The learned table supports positions 0..3 only; no extrapolation, clamping or wrapping.")
    if chapter == 36 and result["D"] % 2:
        raise NumericalFault("SHAPE_MISMATCH", "RoPE requires an even feature width (D=2 or D=4).")
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return dict(status="unavailable", code=error.code, reason=str(error))
        except (OverflowError, FloatingPointError) as error:
            return dict(status="unavailable", code="NONFINITE", reason=str(error))
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class PositionTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        inputs, values = numbers(inputs), numbers(values)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})

    def result(self, summary, tensors):
        # Python dict insertion order keeps aliases before the flattened trace.
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def position_trace():
    return PositionTrace()


def tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    """Require actual shaped storage; serialize a detached, dense named tensor."""
    if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if dtype not in ("float64", "int32", "bool"):
        raise NumericalFault("INVALID_INPUT", f"{identifier}: unsupported dtype.")
    array = np.asarray(values)
    if array.shape != tuple(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    flat = []
    for index, value in enumerate(array.reshape(-1)):
        if dtype == "bool":
            if not isinstance(value, (bool, np.bool_)):
                raise NumericalFault("INVALID_INPUT", f"{identifier}[{index}] must be boolean.")
            flat.append(bool(value))
        else:
            value = finite(value, f"{identifier}[{index}]")
            if dtype == "int32":
                if not value.is_integer() or not -2147483648 <= value <= 2147483647:
                    raise NumericalFault("INVALID_INPUT", f"{identifier}[{index}] must be int32.")
                value = int(value)
            flat.append(value)
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype=dtype,
                values=flat, provenance=provenance, precision=8)


def _load_source(identifier, path):
    spec = importlib.util.spec_from_file_location(identifier, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load canonical Python source at {path}.")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


@lru_cache(maxsize=1)
def _protected_iv25():
    """Load only this Book's p05 sources; restore temporary legacy import names."""
    root = Path(__file__).resolve().parent.parent / "p05"
    attention = _load_source("_p08_p05_attention", root / "attention_reference.py")
    # value_reference and iv25 use legacy sibling imports. Bind BOTH names to
    # these exact file-loaded modules, then restore any caller's existing names.
    names = ("attention_reference", "value_reference")
    missing = object()
    previous = {name: sys.modules.get(name, missing) for name in names}
    try:
        sys.modules["attention_reference"] = attention
        values = _load_source("_p08_p05_values", root / "value_reference.py")
        sys.modules["value_reference"] = values
        return _load_source("_p08_p05_iv25", root / "iv25.py")
    finally:
        for name in names:
            if previous[name] is missing:
                sys.modules.pop(name, None)
            else:
                sys.modules[name] = previous[name]


def protected_attention(s, X):
    """Compose the valid 33-field child state and call unchanged derive_iv25."""
    canonical = _protected_iv25()
    child = dict(canonical.ATTENTION_DEFAULTS)
    child.update(B=1, T=3, Dk=2, Dv=2, mode=0, valid0=1, valid1=1, valid2=1, shift=0)
    for t in range(3):
        for d in range(2):
            child[f"x0{t}{d}"] = float(X[0, t, d])
    for prefix in ("wq", "wk", "wv"):
        for d in range(2):
            for f in range(2):
                child[f"{prefix}{d}{f}"] = s[f"{prefix}{d}{f}"]
    result = canonical.derive_iv25(child)
    if result["status"] == "unavailable":
        # The adapter keeps the child's known fault, never any partial tensors.
        raise NumericalFault(result["code"], result["reason"])
    return result


def append_attention(trace, child, prefix, label):
    """Retain every child step, INCLUDING setup, and clone tensor metadata."""
    for step in child["steps"]:
        trace.add(f"{prefix}_{step['id']}", f"{label}: {step['label']}",
                  step["equation"], step["explanation"], step["inputs"], step["outputs"])
    tensors = [dict(id=f"{label}{record['id']}", shape=list(record["shape"]),
                    axes=list(record["axes"]), dtype=record["dtype"], values=list(record["values"]),
                    provenance=record["provenance"], precision=record["precision"])
               for record in child["tensors"]]
    aliases = {f"{prefix}_{key}": value for key, value in child["outputs"].items()}
    return dict(tensors=tensors, aliases=aliases)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; JSON replaces the full state; '-' reads stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    def _members(pairs):
        value = {}
        for key, member in pairs:
            if key in value:
                raise ParseFault("Duplicate JSON object members are not allowed.")
            value[key] = member
        return value

    def _constant(token):
        raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")

    def _integer(token):
        if token == "-0":
            return -0.0
        try:
            return _JSON_INT(token)
        except ValueError as fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members,
                               parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

iv36.py owns the rotations, both dot loops, norm loop and final summary. position_reference.py owns raw validation, trace/tensor boundaries and supporting source loading. NumPy supplies shaped storage; explicit scalar products determine the arithmetic.

After setup, follow all q_rotate_r, all k_rotate_r, all relative_rotate_r, all dot_r, all relative_dot_r, all norm_r, then summary. The result has 14 records for D=4 and 8 for D=2. Each dot record retains previous, the two products, pairDot and running; summary retains the totals used for the differences and score divisions. The equations, tensors and exercise answers consume those saved values. Float64 means binary64 finite-precision arithmetic. Precision 8 is tensor metadata; full saved tables use String(value) without display rounding. Real algebraic identities above are not assertions of bitwise equality between differently ordered computations.

Five graded questions

For the live question, choose the value and operation together. Two options can contain the same number in a special state while proposing different calculations; the saved operation determines the correct method.

The lab’s five questions follow the actual mechanisms and saved operands below. Use its corrective feedback to find a missing sign or premise before trying again.

  1. rotary-pairs: Name the rotated objects. RoPE here rotates adjacent pairs of query/key features by position-dependent angles. It does not add a position index to V, rotate each scalar without a partner, or preserve each individual coordinate. The standard Q/K mechanism shown leaves V unrotated.
  2. relative-sign: Calculate n−m. At m=1,n=3, the signed relative position is 3−1=2. Pair zero therefore has relative angle 2 radians; at reset pair one has 2/100 radians. Moving the query rotation through the dot product takes its transpose, giving n−m rather than m−n or m+n.
  3. live-rotation: Subtract the current saved products. q_rotate_0 always asks for RotatedQ[0], pair zero’s first coordinate. Compute product0−product1, where the two saved products are x·cos(angle) and y·sin(angle). At reset the real expression is C₁−2S₁. Use actual saved operands after edits; the second coordinate instead adds product2+product3. Selecting pair one in the view does not change this fixed question.
  4. common-position-shift: Shift both positions together. Hold Q,K,D,base fixed and add the same integer h to m,n, keeping both inside 0..8. The difference (n+h)−(m+h)=n−m is unchanged, so the real dot stays the same. Individual rotated coordinates can change, and their saved rounding residuals may differ. Larger absolute position numbers do not force a larger dot.
  5. width-counterexample: Change D=2 to D=4. With first-pair inputs, base and positions matched, pair zero’s frequency is 1 and its rotations agree in both widths. D=4 adds the second pair and divides the full dot by 2 instead of √2, so the full scores need not agree. Higher-pair frequencies generally depend on width; the first pair does not change here. D=3 remains unsupported, and inactive coordinates still validate at D=2.

Recap and bridge

RoPE rotates adjacent Q/K pairs through position times frequency, with first-coordinate subtraction and second-coordinate addition. A shared angle preserves norms; two different positional angles give a dot expressible through relative position n−m. Pair zero agrees between D=2 and D=4, while the extra pair and score divisor can change the full score. Saved floating-point residuals remain computed quantities. Next, Part IX begins with IV-37 — From Unicode Text to Token IDs: how actual Unicode text becomes the token IDs whose feature vectors eventually enter these operations.