IV-35 / Part VIII · Positional Information
Learned and Sinusoidal Position Embeddings
Calculate all coordinates of learned and two-frequency sinusoidal position vectors, add them to token features, and expose out-of-range limits.
Review the ideas this chapter uses
A token’s content and its location answer different questions. A word feature vector describes the item; a position vector supplies information about where that item occurs. One simple design adds these vectors coordinate by coordinate. We will calculate the position vector in two ways, keeping every intermediate visible rather than treating “positional encoding” as a mysterious extra layer.
Learning objective: Compute additive position vectors and compare parameterized and fixed schemes.
Begin with IV-34 — Why Position Matters to Attention for why slot information changes attention. Review IV-16 — Token IDs and Embedding Lookup Tables for vector lookup and Book II’s I.3 — Vectors: components, magnitude, and direction for vector components. Book III’s III-05 — Parameters, Hyperparameters, Loss and Optimization distinguishes parameters from hyperparameters, and III-04 — Training, Validation, Testing and Generalization distinguishes fitting examples from generalization. Neither scheme is trained by this lab.
Compare the two actual calculations
Learned and Sinusoidal Position Embeddings
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
- 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
Token feature rows X
Learned position table (also validated in sinusoidal mode)
y00 1. y01 1. y02 0. y03 1. Validate all inputs and choose an additive position scheme. Both the table and sinusoidal inputs are validated even when inactive. Learned positions are restricted to 0..3; sinusoidal positions may use 0..8. No parameters are trained here.. T 3. D 4. kind 1. tableRows 4. base 10000
Validate all inputs and choose an additive position scheme
T=3; D=4; tableRows=4; kind=0 learned, kind=1 sinusoidal
Both the table and sinusoidal inputs are validated even when inactive. Learned positions are restricted to 0..3; sinusoidal positions may use 0..8. No parameters are trained here.
Inputs
- 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
Outputs
- T
- 3
- D
- 4
- kind
- 1
- tableRows
- 4
- base
- 10000
Build a position vector, then add it to the token
Inspecting token 0, feature 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
| Saved operation | Input kind | Input base | Input p0 | Input p1 | Input p2 | Input x00 | Input x01 | Input x02 | Input x03 | Input x10 | Input x11 | Input x12 | Input x13 | Input x20 | Input x21 | Input x22 | Input x23 | Input l00 | Input l01 | Input l02 | Input l03 | Input l10 | Input l11 | Input l12 | Input l13 | Input l20 | Input l21 | Input l22 | Input l23 | Input l30 | Input l31 | Input l32 | Input l33 | Result T | Result D | Result kind | Result tableRows | Result base |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| setup | 1 | 10000 | 0 | 1 | 2 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 3 | 4 | 1 | 4 | 10000 |
A position index selects where a token sits; a position vector supplies one numerical coordinate per token feature. X and PE both have shape [T,D]=[3,4]. The output Y keeps that shape because it adds matching coordinates, rather than appending features or multiplying token IDs.
Saved add_0_0: token coordinate 1 plus position-vector coordinate 0 gives Y[0,0]=. Token 0's position index is 0; the addition record's field named position is the vector coordinate, not that index.
X
T=3 × D=4 · float64 · display precision 8. Editable token feature rows before positional addition.
| Token | Feature 0 | Feature 1 | Feature 2 | Feature 3 |
|---|---|---|---|---|
| 0 | 1 | 0 | 0 | 0 |
| 1 | 0 | 1 | 0 | 0 |
| 2 | 0 | 0 | 1 | 0 |
Positions
T=3 · int32 · display precision 8. Integer position index per token, independent of the token vector.
| Token | Position index 0 |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
LearnedTable
Position=4 × D=4 · float64 · display precision 8. Four editable parameter rows indexed 0..3; stored even in sinusoidal mode. No training is performed.
| Position index | Feature 0 | Feature 1 | Feature 2 | Feature 3 |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 1 | 1 | 0 | 0 | 0 |
| 2 | 0 | 1 | 0 | 0 |
| 3 | 0 | 0 | 1 | 0 |
Every sine/cosine pair
For pair r, frequency=base^(−2r/4), angle=position×frequency in radians, and features 2r,2r+1 receive sin(angle),cos(angle). Read exponent, frequency, angle, sine and cosine in these six saved records. At base=10000 the frequencies are 1 and 1/100. The displayed table remains editable and validated but is not used by this scheme.
| Saved operation | Input t | Input pair | Input position | Input base | Input exponent | Result frequency | Result angle | Result sine | Result cosine |
|---|---|---|---|---|---|---|---|---|---|
| sinusoid_0_0 | 0 | 0 | 0 | 10000 | 0 | 1 | 0 | 0 | 1 |
| sinusoid_0_1 | 0 | 1 | 0 | 10000 | -0.5 | 0.01 | 0 | 0 | 1 |
| sinusoid_1_0 | 1 | 0 | 1 | 10000 | 0 | 1 | 1 | 0.8414709848078965 | 0.5403023058681398 |
| sinusoid_1_1 | 1 | 1 | 1 | 10000 | -0.5 | 0.01 | 0.01 | 0.009999833334166664 | 0.9999500004166653 |
| sinusoid_2_0 | 2 | 0 | 2 | 10000 | 0 | 1 | 2 | 0.9092974268256817 | -0.4161468365471424 |
| sinusoid_2_1 | 2 | 1 | 2 | 10000 | -0.5 | 0.01 | 0.02 | 0.01999866669333308 | 0.9998000066665778 |
PE
T=3 × D=4 · float64 · display precision 8. Actual gathered or sinusoidal position vectors, in token and feature order.
| Token | Feature 0 | Feature 1 | Feature 2 | Feature 3 |
|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 1 |
| 1 | 0.8414709848078965 | 0.5403023058681398 | 0.009999833334166664 | 0.9999500004166653 |
| 2 | 0.9092974268256817 | -0.4161468365471424 | 0.01999866669333308 | 0.9998000066665778 |
All twelve token-plus-position additions
| Saved operation | Input t | Input d | Input token | Input position | Result value |
|---|---|---|---|---|---|
| add_0_0 | 0 | 0 | 1 | 0 | 1 |
| add_0_1 | 0 | 1 | 0 | 1 | 1 |
| add_0_2 | 0 | 2 | 0 | 0 | 0 |
| add_0_3 | 0 | 3 | 0 | 1 | 1 |
| add_1_0 | 1 | 0 | 0 | 0.8414709848078965 | 0.8414709848078965 |
| add_1_1 | 1 | 1 | 1 | 0.5403023058681398 | 1.5403023058681398 |
| add_1_2 | 1 | 2 | 0 | 0.009999833334166664 | 0.009999833334166664 |
| add_1_3 | 1 | 3 | 0 | 0.9999500004166653 | 0.9999500004166653 |
| add_2_0 | 2 | 0 | 0 | 0.9092974268256817 | 0.9092974268256817 |
| add_2_1 | 2 | 1 | 0 | -0.4161468365471424 | -0.4161468365471424 |
| add_2_2 | 2 | 2 | 1 | 0.01999866669333308 | 1.0199986666933332 |
| add_2_3 | 2 | 3 | 0 | 0.9998000066665778 | 0.9998000066665778 |
Y
T=3 × D=4 · float64 · display precision 8. Coordinatewise X+PE, with all 12 additions saved in the trace.
| Token | Feature 0 | Feature 1 | Feature 2 | Feature 3 |
|---|---|---|---|---|
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0.8414709848078965 | 1.5403023058681398 | 0.009999833334166664 | 0.9999500004166653 |
| 2 | 0.9092974268256817 | -0.4161468365471424 | 1.0199986666933332 | 0.9998000066665778 |
Try index 4: sinusoidal coordinates are defined, while learned mode reports UNSUPPORTED_SIZE because its only rows are 0..3. It never clamps or wraps the index. At base=1 both frequencies are 1, so the two pairs repeat. A formula being defined at an unseen position does not prove that a trained model generalizes there; periodic coordinates are not a universal uniqueness guarantee.
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
- y00
- 1
- y01
- 1
- y02
- 0
- y03
- 1
- y10
- 0.8414709848078965
- y11
- 1.5403023058681398
- y12
- 0.009999833334166664
- y13
- 0.9999500004166653
- y20
- 0.9092974268256817
- y21
- -0.4161468365471424
- y22
- 1.0199986666933332
- y23
- 0.9998000066665778
- T
- 3
- D
- 4
- kind
- 1
- base
- 10000
- pe00
- 0
- pe01
- 1
- pe02
- 0
- pe03
- 1
- pe10
- 0.8414709848078965
- pe11
- 0.5403023058681398
- pe12
- 0.009999833334166664
- pe13
- 0.9999500004166653
- pe20
- 0.9092974268256817
- pe21
- -0.4161468365471424
- pe22
- 0.01999866669333308
- pe23
- 0.9998000066665778
- setup_T
- 3
- setup_D
- 4
- setup_kind
- 1
- setup_tableRows
- 4
- setup_base
- 10000
- sinusoid_0_0_frequency
- 1
- sinusoid_0_0_angle
- 0
- sinusoid_0_0_sine
- 0
- sinusoid_0_0_cosine
- 1
- sinusoid_0_1_frequency
- 0.01
- sinusoid_0_1_angle
- 0
- sinusoid_0_1_sine
- 0
- sinusoid_0_1_cosine
- 1
- sinusoid_1_0_frequency
- 1
- sinusoid_1_0_angle
- 1
- sinusoid_1_0_sine
- 0.8414709848078965
- sinusoid_1_0_cosine
- 0.5403023058681398
- sinusoid_1_1_frequency
- 0.01
- sinusoid_1_1_angle
- 0.01
- sinusoid_1_1_sine
- 0.009999833334166664
- sinusoid_1_1_cosine
- 0.9999500004166653
- sinusoid_2_0_frequency
- 1
- sinusoid_2_0_angle
- 2
- sinusoid_2_0_sine
- 0.9092974268256817
- sinusoid_2_0_cosine
- -0.4161468365471424
- sinusoid_2_1_frequency
- 0.01
- sinusoid_2_1_angle
- 0.02
- sinusoid_2_1_sine
- 0.01999866669333308
- sinusoid_2_1_cosine
- 0.9998000066665778
- add_0_0_value
- 1
- add_0_1_value
- 1
- add_0_2_value
- 0
- add_0_3_value
- 1
- add_1_0_value
- 0.8414709848078965
- add_1_1_value
- 1.5403023058681398
- add_1_2_value
- 0.009999833334166664
- add_1_3_value
- 0.9999500004166653
- add_2_0_value
- 0.9092974268256817
- add_2_1_value
- -0.4161468365471424
- add_2_2_value
- 1.0199986666933332
- add_2_3_value
- 0.9998000066665778
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
X
T=3 × D=4 · float64 · display precision 8 · Editable token feature rows before positional addition.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | 1 |
| 11 | 0 |
LearnedTable
Position=4 × D=4 · float64 · display precision 8 · Four editable parameter rows indexed 0..3; stored even in sinusoidal mode. No training is performed.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 1 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 0 |
| 14 | 1 |
| 15 | 0 |
Positions
T=3 · int32 · display precision 8 · Integer position index per token, independent of the token vector.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
PE
T=3 × D=4 · float64 · display precision 8 · Actual gathered or sinusoidal position vectors, in token and feature order.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0.8414709848078965 |
| 5 | 0.5403023058681398 |
| 6 | 0.009999833334166664 |
| 7 | 0.9999500004166653 |
| 8 | 0.9092974268256817 |
| 9 | -0.4161468365471424 |
| 10 | 0.01999866669333308 |
| 11 | 0.9998000066665778 |
Y
T=3 × D=4 · float64 · display precision 8 · Coordinatewise X+PE, with all 12 additions saved in the trace.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0.8414709848078965 |
| 5 | 1.5403023058681398 |
| 6 | 0.009999833334166664 |
| 7 | 0.9999500004166653 |
| 8 | 0.9092974268256817 |
| 9 | -0.4161468365471424 |
| 10 | 1.0199986666933332 |
| 11 | 0.9998000066665778 |
Start with sinusoidal mode, base=10000 and position indices 0,1,2. The token rows are (1,0,0,0),(0,1,0,0),(0,0,1,0). Edit an index to change a position vector; edit an X coordinate to change the token content. The four-row learned table remains editable in its own group and is validated even while inactive. All 33 named inputs are checked before the selected scheme's position limits.
At reset, the two frequencies are 1 and 1/100. Thus PE0=(0,1,0,1), PE1=(sin(1),cos(1),sin(0.01),cos(0.01)), and PE2=(sin(2),cos(2),sin(0.02),cos(0.02)). The output rows are Y0=(1,1,0,1), Y1=(sin(1),1+cos(1),sin(0.01),cos(0.01)), and Y2=(sin(2),cos(2),1+sin(0.02),cos(0.02)). These are real formulas for the reset example, with angles in radians. Each actual sine/cosine pair and every addition is saved separately in the live trace.
Switch to learned mode at indices 0,1,2. The reset table rows are (0,0,0,0),(1,0,0,0),(0,1,0,0),(0,0,1,0). Gathering rows 0,1,2 gives output rows (1,0,0,0),(1,1,0,0),(0,1,1,0). You can change any table coordinate directly; the word learned means these coordinates could be parameters of a trained model, while this lab keeps training separate.
Try p0=4 in both modes and observe the explicit learned-table boundary. Try base=1 in sinusoidal mode and observe that both pairs use the same frequency. Finite position vectors do not guarantee unique codes for all possible positions, and a defined formula does not establish useful long-context behavior. The next lesson keeps the query/key vector width fixed while rotating feature pairs instead of adding a position vector.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Reset chooses sinusoidal positions 0,1,2, base 10000 and the token rows used below. Inspect the saved frequency, angle, sine and cosine before looking at Y, the sum. Switch to the learned scheme to gather rows from the editable four-row table. Change a table coordinate and compare PE with Y at the affected position. A table edit has no effect on sinusoidal PE, although all stored inputs still need to be valid.
Try position 4 under the sinusoidal scheme, then under the learned scheme. The first has a defined formula within this lab’s range. The second is unavailable because no table row 4 exists. Reset before following the worked default. The distinction is a real boundary, not an instruction to silently wrap to row zero. Open Token feature rows X and Learned position table (also validated in sinusoidal mode) for numeric edits. The token/feature inspection selectors change the displayed coordinate only; Calculation step exposes a saved operation, including its actual operands.
Vocabulary, axes and the addition
An embedding is a vector assigned to an index. A learned position embedding looks up a row whose numbers are model parameters. “Learned” describes how such a table can be fitted during training; here its entries are hand-set controls. A sinusoidal embedding instead uses the sine and cosine functions of position-dependent angles. These functions oscillate: sine starts at zero, cosine at one, and both repeat after an angle of 2π radians. Radians are angle units; a full turn is 2π, not 360 in these formulas.
A tensor is an array with named axes. Here T=3 counts token slots and D=4 counts features per slot. X, PE and Y each have shape [3,4], axes T,D. X contains token features, PE the position features and Y their sum. Positions has shape [3], integer axis T; p_t is the position number assigned to token slot t. These numbers are editable independently: two slots can share the same position number even though they remain different rows. Lowercase t and d name zero-based slot and feature indices.
LearnedTable has shape [4,4], axes Position,D: four table rows, each containing four features. The number of rows is a capacity, not the feature width’s definition; both happen to be four here. Row lookup returns a four-component vector, making the sum legal:
There is no feature multiplication, normalization or token-ID addition in this operation. A token ID is an integer used to select token content elsewhere; it is not the feature vector X used here. Addition preserves [3,4], so the result can feed a subsequent attention projection. This chapter calculates only that input preparation, not a new attention output or a next-token probability.
Two frequencies, six pairs, twelve position coordinates
A frequency ω specifies the angle increase per unit of position. A pair r groups adjacent features (2r,2r+1), so D=4 contains pairs r=0 and r=1. Let b denote the positive base control. The formula is
The exponent e_r is calculated before the power, the power before the angle multiplication, and the angle before sine/cosine. Feature zero is a sine coordinate; feature one is its cosine partner. Features two and three use a different frequency, rather than different functions at the same default angle.
At b=10000, pair zero has exponent −2·0/4=0 and frequency 10000⁰=1. Pair one has exponent −2·1/4=−1/2 and frequency 10000⁻¹ᐟ²=1/√10000=1/100. We write angles such as 1/100 symbolically; the machine representation of 0.01 is rounded binary64, not the exact rational 1/100.
| Slot t, position p | Pair r, coordinates | Exponent | Frequency | Angle p·ω | Sine coordinate | Cosine coordinate |
|---|---|---|---|---|---|---|
| 0,0 | 0, (0,1) | 0 | 1 | 0·1=0 | sin 0=0 | cos 0=1 |
| 0,0 | 1, (2,3) | −1/2 | 1/100 | 0·(1/100)=0 | sin 0=0 | cos 0=1 |
| 1,1 | 0, (0,1) | 0 | 1 | 1·1=1 | sin 1 | cos 1 |
| 1,1 | 1, (2,3) | −1/2 | 1/100 | 1·(1/100)=1/100 | sin(1/100) | cos(1/100) |
| 2,2 | 0, (0,1) | 0 | 1 | 2·1=2 | sin 2 | cos 2 |
| 2,2 | 1, (2,3) | −1/2 | 1/100 | 2·(1/100)=1/50 | sin(1/50) | cos(1/50) |
These are exact real expressions for all twelve PE entries. They are not copied measurements from a run. The default token rows are X₀=(1,0,0,0), X₁=(0,1,0,0) and X₂=(0,0,1,0). Here are all twelve additions, including the zeros:
| Slot | Feature 0 | Feature 1 | Feature 2 | Feature 3 |
|---|---|---|---|---|
| 0 | 1+0=1 | 0+1=1 | 0+0=0 | 0+1=1 |
| 1 | 0+sin 1=sin 1 | 1+cos 1 | 0+sin(1/100)=sin(1/100) | 0+cos(1/100)=cos(1/100) |
| 2 | 0+sin 2=sin 2 | 0+cos 2=cos 2 | 1+sin(1/50) | 0+cos(1/50)=cos(1/50) |
Thus position zero does not mean an all-zero sinusoidal vector: both cosine coordinates are one. It changes the first token row from (1,0,0,0) to (1,1,0,1). Keeping the cosine partners is essential to this convention.
The same inputs with a learned table
Switching schemes changes the source of PE, not the addition rule. At reset the four table rows are
For every feature d, the rule is PE[t,d]=L[p_t,d]. Dense row-major storage puts this entry at flat offset 4p_t+d. At positions 0,1,2, the twelve offsets are (0,1,2,3), (4,5,6,7) and (8,9,10,11); they select L₀,L₁,L₂. Row 3 remains stored and editable, even when no current token selects it.
| Slot, selected table row | PE from four gathered entries | Four explicit additions → Y |
|---|---|---|
| 0, row 0 | (0,0,0,0) | (1+0,0+0,0+0,0+0)=(1,0,0,0) |
| 1, row 1 | (1,0,0,0) | (0+1,1+0,0+0,0+0)=(1,1,0,0) |
| 2, row 2 | (0,1,0,0) | (0+0,0+1,1+0,0+0)=(0,1,1,0) |
For an edit example, change l10, row 1 feature 0, from 1 to 2. With default positions, PE[1,0] changes from 1 to 2 and Y[1,0] from 0+1 to 0+2. Other features and other selected rows stay as they were. If two tokens both select position 1, both use that edited parameter. Reusing a table row does not merge token rows or their content features.
If p₁=4, the attempted offsets would start at 16, beyond a sixteen-entry table. The supported learned indices are exactly 0..3; the whole result becomes UNSUPPORTED_SIZE with no PE/Y or partial trace accepted as a successful calculation. The implementation does not clamp 4 to 3, wrap it to 0, invent a row or extrapolate learned parameters. A finite integer can therefore pass the general position-input check yet be unsupported for the selected scheme.
Why pair sine with cosine, and what this does not prove
For a single frequency, angle θ=pω and an offset Δ give
So shifting position transforms the pair through a linear combination whose coefficients depend on Δ, not on the starting position p. Sine alone would omit the partner needed by these two identities. This is a mathematical reason for paired features; it is not a claim that adding them forces a trained network to extract any particular relation.
A second frequency supplies variation on another angular scale. At base 1, both frequencies equal 1: PE becomes (sin p,cos p,sin p,cos p). This is valid input with repeated information, not a numerical error. Multiple frequencies do not constitute a universal proof that every possible position has a unique encoding; trigonometric functions are periodic, and finite-precision storage adds its own limits. This bounded lab does not perform a collision study.
The sinusoidal formula is defined for position 4 even though this learned table stops at 3. That statement concerns the formula’s domain, not a model’s performance beyond training length. A subsequent model may use unfamiliar signals poorly. “Can calculate PE” and “generalizes correctly” are different claims. Learned rows can be fitted flexibly, but this hand-set table has not learned anything. Consult Book III’s generalization prerequisite before interpreting either demonstration as evidence of accuracy.
Read the actual maintained implementation
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-35 — Learned and Sinusoidal Position Embeddings.
X[T=3,D=4] stores token features. The learned table [Position=4,D=4]
is a set of editable parameters; this program performs no training. kind=0
looks up rows 0..3 and rejects larger positions without clamping or wrapping.
kind=1 uses PE[t,2r]=sin(p_t*base**(-2r/4)) and the corresponding cosine
at 2r+1. Either scheme computes Y[t,d]=X[t,d]+PE[t,d], not token-ID addition.
Hand sinusoidal default: frequencies (1,1/100), PE rows (0,1,0,1),
(sin(1),cos(1),sin(.01),cos(.01)), (sin(2),cos(2),sin(.02),cos(.02)).
Thus Y rows are (1,1,0,1), (sin(1),1+cos(1),sin(.01),cos(.01)),
(sin(2),cos(2),1+sin(.02),cos(.02)). Learned defaults instead give
(1,0,0,0),(1,1,0,0),(0,1,1,0). These are hand-derived expressions.
Base=1 is valid but gives identical pair frequencies. Being defined beyond a
training length does not prove model generalization or universal uniqueness.
Keep position_reference.py beside this file. Imports use file-relative paths;
source only, never imported or executed during the resource hold.
"""
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_IV35 = MappingProxyType(dict(_helper.ENCODING_DEFAULTS))
@_helper.guarded
def derive_iv35(state):
"""Save every positional lookup or trigonometric pair, then every addition."""
s = _helper.position_state(state, 35)
trace = _helper.position_trace()
trace.add("setup", "Validate both position schemes and every stored parameter",
"Y[t,d]=X[t,d]+PE[t,d]; learned table has four rows; sinusoidal D=4",
"Even inactive table entries and base are checked before selecting a scheme; no learning occurs.",
s, dict(T=3, D=4, kind=s["kind"], tableRows=4, base=s["base"]))
X, table = np.empty((3, 4), dtype=np.float64), np.empty((4, 4), dtype=np.float64)
positions = np.array([s[f"p{t}"] for t in range(3)], dtype=np.int32)
for t in range(3):
for d in range(4):
X[t, d] = s[f"x{t}{d}"]
for p in range(4):
for d in range(4):
table[p, d] = s[f"l{p}{d}"]
PE, Y = np.empty((3, 4), dtype=np.float64), np.empty((3, 4), dtype=np.float64)
if s["kind"] == 1:
for t in range(3):
position = int(positions[t])
for pair in range(2):
exponent = -2 * pair / 4
frequency = _helper.finite(s["base"] ** exponent, "sinusoidal frequency")
angle = _helper.finite(position * frequency, "sinusoidal angle")
sine = _helper.finite(math.sin(angle), "sinusoidal sine")
cosine = _helper.finite(math.cos(angle), "sinusoidal cosine")
PE[t, 2 * pair], PE[t, 2 * pair + 1] = sine, cosine
trace.add(f"sinusoid_{t}_{pair}", f"Position {position}, pair {pair}, token slot {t}",
"frequency=base**exponent; angle=position*frequency; sine=sin(angle); cosine=cos(angle)",
"Adjacent coordinates share one angle in radians: sine first, cosine second.",
dict(t=t, pair=pair, position=position, base=s["base"], exponent=exponent),
dict(frequency=frequency, angle=angle, sine=sine, cosine=cosine))
else:
for t in range(3):
position = int(positions[t])
for d in range(4):
offset = position * 4 + d
source = float(table[position, d])
PE[t, d] = source
trace.add(f"lookup_{t}_{d}", f"Learned table row {position}, feature {d}",
"offset=position*D+d; value=LearnedTable[position,d]",
"Copy a real stored parameter; there is no interpolation or extrapolation.",
dict(t=t, d=d, position=position, offset=offset, source=source), dict(value=source))
# All positional coordinates are computed before any token addition.
for t in range(3):
for d in range(4):
token, position = float(X[t, d]), float(PE[t, d])
value = _helper.finite(token + position, "token plus position")
Y[t, d] = value
trace.add(f"add_{t}_{d}", f"Add token and positional feature [{t},{d}]",
"value=token+position",
"Here position is the actual PE feature value, not the integer position index.",
dict(t=t, d=d, token=token, position=position), dict(value=value))
summary = {f"y{t}{d}": float(Y[t, d]) for t in range(3) for d in range(4)}
summary.update(T=3, D=4, kind=s["kind"], base=s["base"])
summary.update({f"pe{t}{d}": float(PE[t, d]) for t in range(3) for d in range(4)})
tensors = [
_helper.tensor("X", [3, 4], ["T", "D"], X, "Original token feature rows before positional addition."),
_helper.tensor("LearnedTable", [4, 4], ["Position", "D"], table, "Four editable learned parameter rows; no training in this program."),
_helper.tensor("Positions", [3], ["T"], positions, "Explicit integer position index for each token slot.", "int32"),
_helper.tensor("PE", [3, 4], ["T", "D"], PE, "Actual positional features from the selected scheme."),
_helper.tensor("Y", [3, 4], ["T", "D"], Y, "Coordinate-wise X+PE, with all twelve additions recorded."),
]
return trace.result(summary, tensors)
if __name__ == "__main__":
_helper.run(derive_iv35, DEFAULT_IV35)
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=(",", ":")))
The iv35.py wrapper requests validation of the entire 33-field state, stores setup, computes the selected PE, then performs the additions. position_reference.py owns validation, trace and tensor boundaries, and the protected-source loader. NumPy supplies shaped arrays; scalar operation order determines saved values. In sinusoidal mode there are six sinusoid_t_r records before twelve add_t_d records, for 19 records including setup. Each pair saves frequency, angle, sine and cosine. In learned mode twelve lookup_t_d records save the table source/offset before the same twelve additions, for 25 records. add_0_0 always means token zero, feature zero; its operands distinguish a token value from a position value even though both are scalars.
All five tensors remain explicit: X, LearnedTable, Positions, PE and Y. Positions uses int32 storage; the other arrays use float64, also called binary64. Precision eight is tensor metadata; the full saved-value tables use String(value) without display rounding, and addition consumes the saved numbers. The displayed real expressions are separate from the saved approximations of powers, angles, sine/cosine and sums.
The base must be finite in [1,10000]; positions are integers 0..8; token and table coordinates are finite in [−4,4]. Scheme kind is an integer choice, 0 learned or 1 sinusoidal. Every stored field validates before scheme-specific checks, including an unused table in sinusoidal mode and the base in learned mode. Missing/extra fields and nonfinite inputs do not quietly produce partial outputs. Repeated or nonascending positions are allowed: the lab calculates the explicit positions you supplied.
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.
These are the lab’s actual five questions, in order. Its feedback gives the reasoning, while the live addition uses the current saved result.
additive-position: Identify the operation and shape. PE supplies one position coordinate per token feature. X[3,4]+PE[3,4] gives Y[3,4]. Concatenating would instead change the width, and adding position IDs is not the defined vector addition.sinusoidal-frequency: Calculate pair one’s frequency. For D=4 and base=10000, exponent −2·1/4=−1/2 gives 1/√10000=1/100. It is neither 1/10000 nor 100. Multiply by the position index next; the frequency itself is the angle only at position one.live-addition: Add the current saved coordinates.add_0_0always asks for Y[0,0]. Its token operand plus its position-vector operand gives the saved value. At reset sinusoidal PE[0,0]=sin 0=0, so the real answer is 1+0=1. After an edit, use that record’s actual operands. Its field named position is already a PE feature, not p0. Changing the inspected token or feature does not relocate this question.shared-table-row: Edit one shared parameter. Choose learned mode with p0=p2=1, then edit only l10. Tokens 0 and 2 both gather table row 1 feature 0, so Y[0,0] and Y[2,0] can change. Y[1,0] also can change if p1=1. Other features and other table rows do not depend on l10. Sharing a row does not mean it can be used only once.learned-boundary: Set p0=4. With every other field valid, learned mode is unavailable because it has only rows 0..3. Sinusoidal mode is defined at this supported index, with no promise of model generalization. Neither mode silently wraps to learned row zero or invents a parameter row.
Recap and bridge
Both schemes supply four features per token and add them to X. Learned PE gathers an existing parameter row; sinusoidal PE calculates two sine/cosine pairs at frequencies 1 and 1/100 at reset. Sinusoidal position zero contains cosine ones. A missing learned row is unavailable, and a defined sinusoidal vector proves no extrapolation accuracy. IV-36 — Rotary Position Embeddings (RoPE) next places position into query/key pair rotations and derives exactly why their dot product can depend on relative position.