IV-60 / Part XV · Modern LLM Architectures
Encoder, Decoder and Cross-Attention Variants
Follow every projection, score, mask and weighted value in three small attention sublayers, including two query rows reading three separate memory rows.
Review the ideas this chapter uses
Imagine two rows describing a partial answer and three rows describing a source passage. Each answer row needs a mixture of information from the passage. Must the two streams have the same length? Must passage position 2 be hidden from answer position 0? We can answer both questions by following the numbers.
Learning objective: Contrast bidirectional encoders, causal decoders and cross-attention.
This lesson compares one attention sublayer in three settings. A sublayer is one stage inside a larger network. All features and weights here are hand-set and untrained. We do not construct a complete encoder or decoder: there is no normalization, feed-forward network, residual addition, output projection, loss, training, generation or cache in this calculation. The two streams below are already feature rows; there is no hidden tokenizer or encoder producing them.
Encoder, Decoder and Cross-Attention Variants
Compare one hand-set attention sublayer in three modes. Start in cross-attention: two query rows ask for a mixture of three memory value rows. Change the mode to compare encoder memory self-attention and causal decoder query self-attention. Open a source group to edit its coordinates, a gain group to change projections, or key validity to exclude keys. The graph, tables, trace and questions share one saved calculation.
All ten source coordinates accept finite numbers in [-4,4]; q/k/v gains accept [-1,1], including -0. Mode and the three key bits use native menus. Every field remains editable and validated in every mode, including inactive query fields in encoder and inactive memory/key2 in decoder. Key bits refer to the current K/V source. Padding retains query rows; an empty allowed row is unavailable.
An empty, unfinished, nonfinite or out-of-range draft withholds all computed views, evidence and questions. Fix every draft or choose Reset example, which restores the default cross case. Editing, reset and trace selection clear graded answers. Opening a disclosure preserves them.
Query source: two rows; inactive in encoder, still validated
Memory source: three rows; inactive in decoder, still validated
Projection gains: WQ, WK and WV
Key validity: memory in encoder/cross, query in decoder; key2 inactive in decoder
Exact starting inputs for this saved calculation
mode 2. queryOrigin 0. keyValueOrigin 1. Tq 2. Capture both sources after complete mask preflight. All seventeen finite raw fields and their domains, then the ASCII prefix and every allowed row, are checked before this first frame. One attention sublayer is compared; padding excludes keys only and never removes a query.
Capture both sources after complete mask preflight
Q=Xq*WQ; K=Xkv*WK; V=Xkv*WV; S=Q*K^T/sqrt(2); P=allowedSoftmax(S); O=P*V
All seventeen finite raw fields and their domains, then the ASCII prefix and every allowed row, are checked before this first frame. One attention sublayer is compared; padding excludes keys only and never removes a query.
Saved inputs
- mode
- 2
- query00
- 1
- query01
- 0
- query10
- 0
- query11
- 1
- memory00
- 1
- memory01
- 0
- memory10
- 0
- memory11
- 1
- memory20
- 1
- memory21
- 1
- q
- 1
- k
- 1
- v
- 1
- key0
- 1
- key1
- 1
- key2
- 1
Saved outputs
- mode
- 2
- query00
- 1
- query01
- 0
- query10
- 0
- query11
- 1
- memory00
- 1
- memory01
- 0
- memory10
- 0
- memory11
- 1
- memory20
- 1
- memory21
- 1
- q
- 1
- k
- 1
- v
- 1
- key0
- 1
- key1
- 1
- key2
- 1
- B
- 1
- H
- 1
- Tq
- 2
- Tk
- 3
- D
- 2
- Dk
- 2
- Dv
- 2
- queryOrigin
- 0
- keyValueOrigin
- 1
- rawInputCount
- 17
Selected saved step variant_setup. Capture both sources after complete mask preflight. Equation: Q=Xq*WQ; K=Xkv*WK; V=Xkv*WV; S=Q*K^T/sqrt(2); P=allowedSoftmax(S); O=P*V. All seventeen finite raw fields and their domains, then the ASCII prefix and every allowed row, are checked before this first frame. One attention sublayer is compared; padding excludes keys only and never removes a query. Saved inputs: mode=2; query00=1; query01=0; query10=0; query11=1; memory00=1; memory01=0; memory10=0; memory11=1; memory20=1; memory21=1; q=1; k=1; v=1; key0=1; key1=1; key2=1. Saved outputs: mode=2; query00=1; query01=0; query10=0; query11=1; memory00=1; memory01=0; memory10=0; memory11=1; memory20=1; memory21=1; q=1; k=1; v=1; key0=1; key1=1; key2=1; B=1; H=1; Tq=2; Tk=3; D=2; Dk=2; Dv=2; queryOrigin=0; keyValueOrigin=1; rawInputCount=17.
Cross-attention: follow the sources
Q (query projection) uses query; K (key projection) and V (value projection) use memory. Tq=2 counts retained query rows; Tk=3 counts key/value rows. B=1 is one batch and H=1 is one head. D=Dk=Dv=2 counts source, query/key and value features. Output has Tq rows, each with two value features.
Both source streams and all three key bits are active. A memory key j>i remains eligible when its key bit is valid; no causal rule is applied across streams. Inactive fields: none. All remain editable and validated.
One hand-set attention sublayer with B=H=1 and D=Dk=Dv=2. No complete encoder/decoder block, output projection, residual, normalization, FFN, loss, training, generation or cache is computed.
Eleven stages from this saved root
- Raw query rows
variant_Query· B=1 × QueryPosition=2 × D=2 · [1,2,2]
1, 0, 0, 1 - Raw memory rows
variant_Memory· B=1 × MemoryPosition=3 × D=2 · [1,3,2]
1, 0, 0, 1, 1, 1 - Selected Q source
variant_QuerySource· B=1 × Tq=2 × D=2 · [1,2,2]
1, 0, 0, 1 - Selected K/V source
variant_KeyValueSource· B=1 × Tk=3 × D=2 · [1,3,2]
1, 0, 0, 1, 1, 1 - Q projection
variant_Q· B=1 × H=1 × Tq=2 × Dk=2 · [1,1,2,2]
1, 0, 1, 1 - K projection
variant_K· B=1 × H=1 × Tk=3 × Dk=2 · [1,1,3,2]
1, 0, 0, 1, 1, 1 - V projection
variant_V· B=1 × H=1 × Tk=3 × Dv=2 · [1,1,3,2]
1, 1, 0, 1, 1, 2 - Every finite score
variant_Scores· B=1 × H=1 × Tq=2 × Tk=3 · [1,1,2,3]
0.7071067811865475, 0, 0.7071067811865475, 0.7071067811865475, 0.7071067811865475, 1.414213562373095 - Allowed key mask
variant_Allowed· B=1 × H=1 × Tq=2 × Tk=3 · [1,1,2,3]
true, true, true, true, true, true - Stable attention probabilities
variant_Probabilities· B=1 × H=1 × Tq=2 × Tk=3 · [1,1,2,3]
0.4011120926797859, 0.1977758146404282, 0.4011120926797859, 0.2482550782577231, 0.2482550782577231, 0.5034898434845538 - Weighted-value output
variant_Output· B=1 × H=1 × Tq=2 × Dv=2 · [1,1,2,2]
0.8022241853595719, 1.401112092679786, 0.7517449217422769, 1.5034898434845538
| Raw source | Row | Saved features | Current projection roles |
|---|---|---|---|
| Query | 0 | [1, 0] | Q |
| Query | 1 | [0, 1] | Q |
| Memory | 0 | [1, 0] | K/V |
| Memory | 1 | [0, 1] | K/V |
| Memory | 2 | [1, 1] | K/V |
Q, K and V: the actual two-product projections
Each row-feature weight matrix maps a two-feature source row to two projected features. WQ=[[q,+0],[q,q]], WK=[[k,+0],[+0,k]], WV=[[v,v],[+0,v]]. Gain entries copy their saved word, including -0; structural zeros are literal +0. Each output uses product0+product1 directly, with no initial +0 or bias. Expand complete storage below to inspect all three weight matrices and source offsets.
| Projection | Origin | Row | Feature | Raw source offsets | Source row | Product 0 | Product 1 | Direct sum |
|---|---|---|---|---|---|---|---|---|
| Q | query | 0 | 0 | 1, 2 | [1, 0] | 1 | 0 | 1 |
| Q | query | 0 | 1 | 1, 2 | [1, 0] | 0 | 0 | 0 |
| Q | query | 1 | 0 | 3, 4 | [0, 1] | 0 | 1 | 1 |
| Q | query | 1 | 1 | 3, 4 | [0, 1] | 0 | 1 | 1 |
| K | memory | 0 | 0 | 5, 6 | [1, 0] | 1 | 0 | 1 |
| K | memory | 0 | 1 | 5, 6 | [1, 0] | 0 | 0 | 0 |
| K | memory | 1 | 0 | 7, 8 | [0, 1] | 0 | 0 | 0 |
| K | memory | 1 | 1 | 7, 8 | [0, 1] | 0 | 1 | 1 |
| K | memory | 2 | 0 | 9, 10 | [1, 1] | 1 | 0 | 1 |
| K | memory | 2 | 1 | 9, 10 | [1, 1] | 0 | 1 | 1 |
| V | memory | 0 | 0 | 5, 6 | [1, 0] | 1 | 0 | 1 |
| V | memory | 0 | 1 | 5, 6 | [1, 0] | 1 | 0 | 1 |
| V | memory | 1 | 0 | 7, 8 | [0, 1] | 0 | 0 | 0 |
| V | memory | 1 | 1 | 7, 8 | [0, 1] | 0 | 1 | 1 |
| V | memory | 2 | 0 | 9, 10 | [1, 1] | 1 | 0 | 1 |
| V | memory | 2 | 1 | 9, 10 | [1, 1] | 1 | 1 | 2 |
Every score, its eligibility and stable probability
For query i and key j, the two Q/K products are added directly, then divided by the single saved sqrt(2) divisor. Every finite score is computed, including forbidden positions. The Boolean mask decides eligibility for softmax. Each row uses its saved allowed-only maximum, actual exponential terms and Tk-ordered denominator starting at +0. Forbidden terms and probabilities are +0; forbidden shifts and exponential calls do not exist.
| Query i | Key j | Score offset | Product 0 | Product 1 | Dot | Divisor | Score | Allowed | Row max | Saved shift | Exp term | Denominator | P[i,j] |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 1 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 | true | 0.7071067811865475 | 0 | 1 | 2.49306869139524 | 0.4011120926797859 |
| 0 | 1 | 1 | 0 | 0 | 0 | 1.4142135623730951 | 0 | true | 0.7071067811865475 | -0.7071067811865475 | 0.49306869139523984 | 2.49306869139524 | 0.1977758146404282 |
| 0 | 2 | 2 | 1 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 | true | 0.7071067811865475 | 0 | 1 | 2.49306869139524 | 0.4011120926797859 |
| 1 | 0 | 3 | 1 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 | true | 1.414213562373095 | -0.7071067811865475 | 0.49306869139523984 | 1.9861373827904796 | 0.2482550782577231 |
| 1 | 1 | 4 | 0 | 1 | 1 | 1.4142135623730951 | 0.7071067811865475 | true | 1.414213562373095 | -0.7071067811865475 | 0.49306869139523984 | 1.9861373827904796 | 0.2482550782577231 |
| 1 | 2 | 5 | 1 | 1 | 2 | 1.4142135623730951 | 1.414213562373095 | true | 1.414213562373095 | 0 | 1 | 1.9861373827904796 | 0.5034898434845538 |
key0/key1/key2 are key-position validity for the selected K/V source. Encoder/cross allow each valid memory key for every query. Decoder intersects query-key validity with j<=i; key2 is inactive. Padding never deletes query rows. An empty row faults before any frame, projection or native call.
The unchanged platform stableSoftmax computes allowed-only Math.max with +0 tie preference, actual allowed exp terms, forbidden literal +0 terms, a Tk-ordered denominator starting +0 and every term/denominator probability. Forbidden finite scores remain saved; forbidden shifts and native occurrences are absent.
Every weighted value and running sum
P[i,j] multiplies V[j,d] for each value feature d. Each feature accumulator starts at +0 and visits every key in ascending order, including forbidden keys with P=+0. A negative value can produce a saved -0 product. The last saved partial sum becomes output[i,d]; the view copies these words without calculating a new mixture.
| Query i | Key j | Feature d | Storage offset | P[i,j] | V[j,d] | Previous sum | Product | Updated partial |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0.4011120926797859 | 1 | 0 | 0.4011120926797859 | 0.4011120926797859 |
| 0 | 0 | 1 | 1 | 0.4011120926797859 | 1 | 0 | 0.4011120926797859 | 0.4011120926797859 |
| 0 | 1 | 0 | 2 | 0.1977758146404282 | 0 | 0.4011120926797859 | 0 | 0.4011120926797859 |
| 0 | 1 | 1 | 3 | 0.1977758146404282 | 1 | 0.4011120926797859 | 0.1977758146404282 | 0.5988879073202141 |
| 0 | 2 | 0 | 4 | 0.4011120926797859 | 1 | 0.4011120926797859 | 0.4011120926797859 | 0.8022241853595719 |
| 0 | 2 | 1 | 5 | 0.4011120926797859 | 2 | 0.5988879073202141 | 0.8022241853595719 | 1.401112092679786 |
| 1 | 0 | 0 | 6 | 0.2482550782577231 | 1 | 0 | 0.2482550782577231 | 0.2482550782577231 |
| 1 | 0 | 1 | 7 | 0.2482550782577231 | 1 | 0 | 0.2482550782577231 | 0.2482550782577231 |
| 1 | 1 | 0 | 8 | 0.2482550782577231 | 0 | 0.2482550782577231 | 0 | 0.2482550782577231 |
| 1 | 1 | 1 | 9 | 0.2482550782577231 | 1 | 0.2482550782577231 | 0.2482550782577231 | 0.4965101565154462 |
| 1 | 2 | 0 | 10 | 0.5034898434845538 | 1 | 0.2482550782577231 | 0.5034898434845538 | 0.7517449217422769 |
| 1 | 2 | 1 | 11 | 0.5034898434845538 | 2 | 0.4965101565154462 | 1.0069796869691077 | 1.5034898434845538 |
| Query i | Q source row | P row over Tk keys | Saved output [feature 0, feature 1] |
|---|---|---|---|
| 0 | query 0 | [0.4011120926797859, 0.1977758146404282, 0.4011120926797859] | [0.8022241853595719, 1.401112092679786] |
| 1 | query 1 | [0.2482550782577231, 0.2482550782577231, 0.5034898434845538] | [0.7517449217422769, 1.5034898434845538] |
All 32 saved tensors: every cell, source marker, offset and native copy
Tables group the last named axis into columns and flatten preceding axes into outer rows. Every cell retains its zero-based flat index. Shapes, axes, dtype, declared precision and provenance come from each saved record. Values are round-trip decimal words with -0 explicit and Boolean true/false; declared precision does not round these tables.
variant_Raw
RawField=17 · shape [17] · float64 · declared display precision 8 · 17 stored cells
Captured raw17 in texts.rawFields order. mode/key0/key1/key2 are VALUE; thirteen source/gain fields are binary64 WORD, including -0.
| Outer row (zero-based) | mode | query00 | query01 | query10 | query11 | memory00 | memory01 | memory10 | memory11 | memory20 | memory21 | q | k | v | key0 | key1 | key2 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
variant_Query
B=1 × QueryPosition=2 × D=2 · shape [1,2,2] · float64 · declared display precision 8 · 4 stored cells
Unchanged raw query00,query01,query10,query11 words, including when inactive in encoder mode.
| Outer row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
variant_Memory
B=1 × MemoryPosition=3 × D=2 · shape [1,3,2] · float64 · declared display precision 8 · 6 stored cells
Unchanged raw memory00,memory01,memory10,memory11,memory20,memory21 words, including when inactive in decoder mode.
| Outer row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
variant_KeyValidity
KeySlot=3 · shape [3] · int32 · declared display precision 0 · 3 stored cells
Captured positional key bits for the selected K/V origin; key2 is validated but inactive in decoder mode. VALUE.
| Outer row (zero-based) | KeySlot 0 | KeySlot 1 | KeySlot 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
variant_SourceOrigins
SourceRole=2 · shape [2] · int32 · declared display precision 0 · 2 stored cells
Q-source then K/V-source codes: query=0,memory=1. VALUE; equal numbers do not merge origins.
| Outer row (zero-based) | Q | K/V |
|---|---|---|
| 0 | 0 | 1 |
variant_QuerySource
B=1 × Tq=2 × D=2 · shape [1,2,2] · float64 · declared display precision 8 · 4 stored cells
Q source WORD copies: memory in encoder mode, query in decoder/cross modes.
| Outer row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
variant_KeyValueSource
B=1 × Tk=3 × D=2 · shape [1,3,2] · float64 · declared display precision 8 · 6 stored cells
K/V source WORD copies: query in decoder mode, memory in encoder/cross modes.
| Outer row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
variant_QuerySourceOffsets
Tq=2 × D=2 · shape [2,2] · int32 · declared display precision 0 · 4 stored cells
Raw17 VALUE offsets for each Q-source coordinate, in row-major order.
| Outer row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 1 | 2 |
| 1 | 3 | 4 |
variant_KeyValueSourceOffsets
Tk=3 × D=2 · shape [3,2] · int32 · declared display precision 0 · 6 stored cells
Raw17 VALUE offsets for each K/V-source coordinate, in row-major order.
| Outer row (zero-based) | D 0 | D 1 |
|---|---|---|
| 0 | 5 | 6 |
| 1 | 7 | 8 |
| 2 | 9 | 10 |
variant_WQ
D=2 × Dk=2 · shape [2,2] · float64 · declared display precision 8 · 4 stored cells
Row-feature WQ=[[q,+0],[q,q]]: gain slots copy q WORD; structural zero is literal +0.
| Outer row (zero-based) | Dk 0 | Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 1 | 1 |
variant_WK
D=2 × Dk=2 · shape [2,2] · float64 · declared display precision 8 · 4 stored cells
Row-feature WK=[[k,+0],[+0,k]]: gain slots copy k WORD; structural zeros are literal +0.
| Outer row (zero-based) | Dk 0 | Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
variant_WV
D=2 × Dv=2 · shape [2,2] · float64 · declared display precision 8 · 4 stored cells
Row-feature WV=[[v,v],[+0,v]]: gain slots copy v WORD; structural zero is literal +0.
| Outer row (zero-based) | Dv 0 | Dv 1 |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 0 | 1 |
variant_QProducts
Tq=2 × Dk=2 × InputFeature=2 · shape [2,2,2] · float64 · declared display precision 8 · 8 stored cells
Actual Q projection product0,product1 for each query row/output feature; direct sum without an initial +0.
| Outer row (zero-based) | product0 | product1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 2 | 0 | 1 |
| 3 | 0 | 1 |
variant_KProducts
Tk=3 × Dk=2 × InputFeature=2 · shape [3,2,2] · float64 · declared display precision 8 · 12 stored cells
Actual K projection product0,product1 for each key row/output feature; direct sum without an initial +0.
| Outer row (zero-based) | product0 | product1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 0 | 1 |
| 4 | 1 | 0 |
| 5 | 0 | 1 |
variant_VProducts
Tk=3 × Dv=2 × InputFeature=2 · shape [3,2,2] · float64 · declared display precision 8 · 12 stored cells
Actual V projection product0,product1 for each key row/output feature; direct sum without an initial +0.
| Outer row (zero-based) | product0 | product1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 1 | 0 |
| 2 | 0 | 0 |
| 3 | 0 | 1 |
| 4 | 1 | 0 |
| 5 | 1 | 1 |
variant_Q
B=1 × H=1 × Tq=2 × Dk=2 · shape [1,1,2,2] · float64 · declared display precision 8 · 4 stored cells
Actual Q direct sums from the declared Q origin; singleton batch/head axes require no permutation.
| Outer row (zero-based) | Dk 0 | Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 1 | 1 |
variant_K
B=1 × H=1 × Tk=3 × Dk=2 · shape [1,1,3,2] · float64 · declared display precision 8 · 6 stored cells
Actual K direct sums from the declared K/V origin; source row j uses offset 2*j+d.
| Outer row (zero-based) | Dk 0 | Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
variant_V
B=1 × H=1 × Tk=3 × Dv=2 · shape [1,1,3,2] · float64 · declared display precision 8 · 6 stored cells
Actual V direct sums from the declared K/V origin; every row remains computed under padding.
| Outer row (zero-based) | Dv 0 | Dv 1 |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 2 | 1 | 2 |
variant_Divisor
Scalar=1 · shape [1] · float64 · declared display precision 8 · 1 stored cells
Actual single sqrt(2) output WORD, copied into every score division and the native ledger.
| Outer row (zero-based) | Scalar 0 |
|---|---|
| 0 | 1.4142135623730951 |
variant_ScoreProducts
Tq=2 × Tk=3 × Dk=2 · shape [2,3,2] · float64 · declared display precision 8 · 12 stored cells
Actual score product0,product1 for every query/key pair, including forbidden pairs.
| Outer row (zero-based) | product0 | product1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 2 | 1 | 0 |
| 3 | 1 | 0 |
| 4 | 0 | 1 |
| 5 | 1 | 1 |
variant_Dots
B=1 × H=1 × Tq=2 × Tk=3 · shape [1,1,2,3] · float64 · declared display precision 8 · 6 stored cells
Direct product0+product1 WORD at offset i*Tk+j, without an initial +0.
| Outer row (zero-based) | Tk 0 | Tk 1 | Tk 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 1 | 1 | 2 |
variant_Scores
B=1 × H=1 × Tq=2 × Tk=3 · shape [1,1,2,3] · float64 · declared display precision 8 · 6 stored cells
Actual dot/divisor WORD for every query/key pair, including forbidden pairs; no shift or -Infinity sentinel.
| Outer row (zero-based) | Tk 0 | Tk 1 | Tk 2 |
|---|---|---|---|
| 0 | 0.7071067811865475 | 0 | 0.7071067811865475 |
| 1 | 0.7071067811865475 | 0.7071067811865475 | 1.414213562373095 |
variant_Allowed
B=1 × H=1 × Tq=2 × Tk=3 · shape [1,1,2,3] · bool · declared display precision 0 · 6 stored cells
Boolean key eligibility: key[j] AND (mode!=decoder OR j<=i). Keys only; query rows are retained.
| Outer row (zero-based) | Tk 0 | Tk 1 | Tk 2 |
|---|---|---|---|
| 0 | true | true | true |
| 1 | true | true | true |
variant_Maxima
B=1 × H=1 × Tq=2 · shape [1,1,2] · float64 · declared display precision 8 · 2 stored cells
Actual platform Math.max of allowed scores, including +0 preference on mixed-zero ties.
| Outer row (zero-based) | Tq 0 | Tq 1 |
|---|---|---|
| 0 | 0.7071067811865475 | 1.414213562373095 |
variant_Terms
B=1 × H=1 × Tq=2 × Tk=3 · shape [1,1,2,3] · float64 · declared display precision 8 · 6 stored cells
Actual platform exp outputs at allowed positions; forbidden positions are literal +0 with no exp call.
| Outer row (zero-based) | Tk 0 | Tk 1 | Tk 2 |
|---|---|---|---|
| 0 | 1 | 0.49306869139523984 | 1 |
| 1 | 0.49306869139523984 | 0.49306869139523984 | 1 |
variant_Denominators
B=1 × H=1 × Tq=2 · shape [1,1,2] · float64 · declared display precision 8 · 2 stored cells
Actual platform Tk-ordered term sums from literal +0, copied without reassociation.
| Outer row (zero-based) | Tq 0 | Tq 1 |
|---|---|---|
| 0 | 2.49306869139524 | 1.9861373827904796 |
variant_Probabilities
B=1 × H=1 × Tq=2 × Tk=3 · shape [1,1,2,3] · float64 · declared display precision 8 · 6 stored cells
Actual platform term/denominator at every position; forbidden probabilities are +0.
| Outer row (zero-based) | Tk 0 | Tk 1 | Tk 2 |
|---|---|---|---|
| 0 | 0.4011120926797859 | 0.1977758146404282 | 0.4011120926797859 |
| 1 | 0.2482550782577231 | 0.2482550782577231 | 0.5034898434845538 |
variant_WeightedProducts
Tq=2 × Tk=3 × Dv=2 · shape [2,3,2] · float64 · declared display precision 8 · 12 stored cells
Every actual P[i,j]*V[j,d] WORD at (i*Tk+j)*2+d; masked products can be -0.
| Outer row (zero-based) | Dv 0 | Dv 1 |
|---|---|---|
| 0 | 0.4011120926797859 | 0.4011120926797859 |
| 1 | 0 | 0.1977758146404282 |
| 2 | 0.4011120926797859 | 0.8022241853595719 |
| 3 | 0.2482550782577231 | 0.2482550782577231 |
| 4 | 0 | 0.2482550782577231 |
| 5 | 0.5034898434845538 | 1.0069796869691077 |
variant_WeightedPartials
Tq=2 × Tk=3 × Dv=2 · shape [2,3,2] · float64 · declared display precision 8 · 12 stored cells
Actual updated sum after every product, with independent +0-initialized feature accumulators; traversal i,j,d.
| Outer row (zero-based) | Dv 0 | Dv 1 |
|---|---|---|
| 0 | 0.4011120926797859 | 0.4011120926797859 |
| 1 | 0.4011120926797859 | 0.5988879073202141 |
| 2 | 0.8022241853595719 | 1.401112092679786 |
| 3 | 0.2482550782577231 | 0.2482550782577231 |
| 4 | 0.2482550782577231 | 0.4965101565154462 |
| 5 | 0.7517449217422769 | 1.5034898434845538 |
variant_Output
B=1 × H=1 × Tq=2 × Dv=2 · shape [1,1,2,2] · float64 · declared display precision 8 · 4 stored cells
Final saved +0-initialized, ascending-key weighted sums; no output projection, bias, residual or normalization.
| Outer row (zero-based) | Dv 0 | Dv 1 |
|---|---|---|
| 0 | 0.8022241853595719 | 1.401112092679786 |
| 1 | 0.7517449217422769 | 1.5034898434845538 |
variant_NativeArguments
Native=7 × NativeField=2 · shape [7,2] · float64 · declared display precision 8 · 14 stored cells
Ordered actual native input,output WORD copies. Exp inputs functionally reconstruct the identical subtraction; exp outputs are actual platform terms. No extra native call in serialization.
| Outer row (zero-based) | input | output |
|---|---|---|
| 0 | 2 | 1.4142135623730951 |
| 1 | 0 | 1 |
| 2 | -0.7071067811865475 | 0.49306869139523984 |
| 3 | 0 | 1 |
| 4 | -0.7071067811865475 | 0.49306869139523984 |
| 5 | -0.7071067811865475 | 0.49306869139523984 |
| 6 | 0 | 1 |
variant_NativeKinds
Native=7 · shape [7] · int32 · declared display precision 0 · 7 stored cells
VALUE native kind codes in occurrence order: sqrt=0,exp=1; bind texts.nativeIds and texts.nativeKinds.
| Outer row (zero-based) | Native 0 | Native 1 | Native 2 | Native 3 | Native 4 | Native 5 | Native 6 |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
Ordered native-leaf ledger
| Occurrence | Exact ID | Kind | Saved argument | Saved native output |
|---|---|---|---|---|
| 0 | variant_sqrt | sqrt | 2 | 1.4142135623730951 |
| 1 | variant_exp_0_0 | exp | 0 | 1 |
| 2 | variant_exp_0_1 | exp | -0.7071067811865475 | 0.49306869139523984 |
| 3 | variant_exp_0_2 | exp | 0 | 1 |
| 4 | variant_exp_1_0 | exp | -0.7071067811865475 | 0.49306869139523984 |
| 5 | variant_exp_1_1 | exp | -0.7071067811865475 | 0.49306869139523984 |
| 6 | variant_exp_1_2 | exp | 0 | 1 |
Occurrence order is one sqrt(2), then exp for allowed i,j pairs in row/key order. Each exp input repeats the same subtraction of the immutable score and actual maximum used by stableSoftmax: a functional witness, not physical call interception. Each exp output copies the actual term; serialization performs no extra exp.
Complete saved operation text fallback: all 39 frames in trace order
variant_setup: Capture both sources after complete mask preflight
Q=Xq*WQ; K=Xkv*WK; V=Xkv*WV; S=Q*K^T/sqrt(2); P=allowedSoftmax(S); O=P*V
All seventeen finite raw fields and their domains, then the ASCII prefix and every allowed row, are checked before this first frame. One attention sublayer is compared; padding excludes keys only and never removes a query.
Saved inputs
- mode
- 2
- query00
- 1
- query01
- 0
- query10
- 0
- query11
- 1
- memory00
- 1
- memory01
- 0
- memory10
- 0
- memory11
- 1
- memory20
- 1
- memory21
- 1
- q
- 1
- k
- 1
- v
- 1
- key0
- 1
- key1
- 1
- key2
- 1
Saved outputs
- mode
- 2
- query00
- 1
- query01
- 0
- query10
- 0
- query11
- 1
- memory00
- 1
- memory01
- 0
- memory10
- 0
- memory11
- 1
- memory20
- 1
- memory21
- 1
- q
- 1
- k
- 1
- v
- 1
- key0
- 1
- key1
- 1
- key2
- 1
- B
- 1
- H
- 1
- Tq
- 2
- Tk
- 3
- D
- 2
- Dk
- 2
- Dv
- 2
- queryOrigin
- 0
- keyValueOrigin
- 1
- rawInputCount
- 17
variant_project_Q_0_0: Q row 0, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 0
- d
- 0
- origin
- 0
- sourceOffset0
- 0
- sourceOffset1
- 1
- rawOffset0
- 1
- rawOffset1
- 2
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 1
Saved outputs
- product0
- 1
- product1
- 0
- value
- 1
variant_project_Q_0_1: Q row 0, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 0
- d
- 1
- origin
- 0
- sourceOffset0
- 0
- sourceOffset1
- 1
- rawOffset0
- 1
- rawOffset1
- 2
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 1
- x0
- 1
- x1
- 0
- w0
- 0
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 0
- value
- 0
variant_project_Q_1_0: Q row 1, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 1
- d
- 0
- origin
- 0
- sourceOffset0
- 2
- sourceOffset1
- 3
- rawOffset0
- 3
- rawOffset1
- 4
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 2
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 1
- value
- 1
variant_project_Q_1_1: Q row 1, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 1
- d
- 1
- origin
- 0
- sourceOffset0
- 2
- sourceOffset1
- 3
- rawOffset0
- 3
- rawOffset1
- 4
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 3
- x0
- 0
- x1
- 1
- w0
- 0
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 1
- value
- 1
variant_project_K_0_0: K row 0, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 0
- d
- 0
- origin
- 1
- sourceOffset0
- 0
- sourceOffset1
- 1
- rawOffset0
- 5
- rawOffset1
- 6
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 0
Saved outputs
- product0
- 1
- product1
- 0
- value
- 1
variant_project_K_0_1: K row 0, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 0
- d
- 1
- origin
- 1
- sourceOffset0
- 0
- sourceOffset1
- 1
- rawOffset0
- 5
- rawOffset1
- 6
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 1
- x0
- 1
- x1
- 0
- w0
- 0
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 0
- value
- 0
variant_project_K_1_0: K row 1, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 1
- d
- 0
- origin
- 1
- sourceOffset0
- 2
- sourceOffset1
- 3
- rawOffset0
- 7
- rawOffset1
- 8
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 2
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 0
Saved outputs
- product0
- 0
- product1
- 0
- value
- 0
variant_project_K_1_1: K row 1, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 1
- d
- 1
- origin
- 1
- sourceOffset0
- 2
- sourceOffset1
- 3
- rawOffset0
- 7
- rawOffset1
- 8
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 3
- x0
- 0
- x1
- 1
- w0
- 0
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 1
- value
- 1
variant_project_K_2_0: K row 2, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 2
- d
- 0
- origin
- 1
- sourceOffset0
- 4
- sourceOffset1
- 5
- rawOffset0
- 9
- rawOffset1
- 10
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 4
- x0
- 1
- x1
- 1
- w0
- 1
- w1
- 0
Saved outputs
- product0
- 1
- product1
- 0
- value
- 1
variant_project_K_2_1: K row 2, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 2
- d
- 1
- origin
- 1
- sourceOffset0
- 4
- sourceOffset1
- 5
- rawOffset0
- 9
- rawOffset1
- 10
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 5
- x0
- 1
- x1
- 1
- w0
- 0
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 1
- value
- 1
variant_project_V_0_0: V row 0, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 0
- d
- 0
- origin
- 1
- sourceOffset0
- 0
- sourceOffset1
- 1
- rawOffset0
- 5
- rawOffset1
- 6
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 0
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 0
Saved outputs
- product0
- 1
- product1
- 0
- value
- 1
variant_project_V_0_1: V row 0, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 0
- d
- 1
- origin
- 1
- sourceOffset0
- 0
- sourceOffset1
- 1
- rawOffset0
- 5
- rawOffset1
- 6
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 1
- x0
- 1
- x1
- 0
- w0
- 1
- w1
- 1
Saved outputs
- product0
- 1
- product1
- 0
- value
- 1
variant_project_V_1_0: V row 1, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 1
- d
- 0
- origin
- 1
- sourceOffset0
- 2
- sourceOffset1
- 3
- rawOffset0
- 7
- rawOffset1
- 8
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 2
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 0
Saved outputs
- product0
- 0
- product1
- 0
- value
- 0
variant_project_V_1_1: V row 1, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 1
- d
- 1
- origin
- 1
- sourceOffset0
- 2
- sourceOffset1
- 3
- rawOffset0
- 7
- rawOffset1
- 8
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 3
- x0
- 0
- x1
- 1
- w0
- 1
- w1
- 1
Saved outputs
- product0
- 0
- product1
- 1
- value
- 1
variant_project_V_2_0: V row 2, feature 0: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 2
- d
- 0
- origin
- 1
- sourceOffset0
- 4
- sourceOffset1
- 5
- rawOffset0
- 9
- rawOffset1
- 10
- weightOffset0
- 0
- weightOffset1
- 2
- outputOffset
- 4
- x0
- 1
- x1
- 1
- w0
- 1
- w1
- 0
Saved outputs
- product0
- 1
- product1
- 0
- value
- 1
variant_project_V_2_1: V row 2, feature 1: two products then their direct sum
product0=x0*w0; product1=x1*w1; value=product0+product1
Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.
Saved inputs
- i
- 2
- d
- 1
- origin
- 1
- sourceOffset0
- 4
- sourceOffset1
- 5
- rawOffset0
- 9
- rawOffset1
- 10
- weightOffset0
- 1
- weightOffset1
- 3
- outputOffset
- 5
- x0
- 1
- x1
- 1
- w0
- 1
- w1
- 1
Saved outputs
- product0
- 1
- product1
- 1
- value
- 2
variant_scale: Compute the single key-width divisor
divisor=sqrt(Dk)
One actual sqrt(2) is reused by every score division, including forbidden score cells.
Saved inputs
- Dk
- 2
Saved outputs
- divisor
- 1.4142135623730951
variant_score_0_0: Query 0, key 0: compute the finite score even when forbidden
product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor
Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.
Saved inputs
- i
- 0
- j
- 0
- queryOffset0
- 0
- queryOffset1
- 1
- keyOffset0
- 0
- keyOffset1
- 1
- q0
- 1
- q1
- 0
- k0
- 1
- k1
- 0
- divisor
- 1.4142135623730951
- allowed
- 1
Saved outputs
- product0
- 1
- product1
- 0
- dot
- 1
- score
- 0.7071067811865475
variant_score_0_1: Query 0, key 1: compute the finite score even when forbidden
product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor
Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.
Saved inputs
- i
- 0
- j
- 1
- queryOffset0
- 0
- queryOffset1
- 1
- keyOffset0
- 2
- keyOffset1
- 3
- q0
- 1
- q1
- 0
- k0
- 0
- k1
- 1
- divisor
- 1.4142135623730951
- allowed
- 1
Saved outputs
- product0
- 0
- product1
- 0
- dot
- 0
- score
- 0
variant_score_0_2: Query 0, key 2: compute the finite score even when forbidden
product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor
Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.
Saved inputs
- i
- 0
- j
- 2
- queryOffset0
- 0
- queryOffset1
- 1
- keyOffset0
- 4
- keyOffset1
- 5
- q0
- 1
- q1
- 0
- k0
- 1
- k1
- 1
- divisor
- 1.4142135623730951
- allowed
- 1
Saved outputs
- product0
- 1
- product1
- 0
- dot
- 1
- score
- 0.7071067811865475
variant_score_1_0: Query 1, key 0: compute the finite score even when forbidden
product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor
Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.
Saved inputs
- i
- 1
- j
- 0
- queryOffset0
- 2
- queryOffset1
- 3
- keyOffset0
- 0
- keyOffset1
- 1
- q0
- 1
- q1
- 1
- k0
- 1
- k1
- 0
- divisor
- 1.4142135623730951
- allowed
- 1
Saved outputs
- product0
- 1
- product1
- 0
- dot
- 1
- score
- 0.7071067811865475
variant_score_1_1: Query 1, key 1: compute the finite score even when forbidden
product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor
Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.
Saved inputs
- i
- 1
- j
- 1
- queryOffset0
- 2
- queryOffset1
- 3
- keyOffset0
- 2
- keyOffset1
- 3
- q0
- 1
- q1
- 1
- k0
- 0
- k1
- 1
- divisor
- 1.4142135623730951
- allowed
- 1
Saved outputs
- product0
- 0
- product1
- 1
- dot
- 1
- score
- 0.7071067811865475
variant_score_1_2: Query 1, key 2: compute the finite score even when forbidden
product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor
Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.
Saved inputs
- i
- 1
- j
- 2
- queryOffset0
- 2
- queryOffset1
- 3
- keyOffset0
- 4
- keyOffset1
- 5
- q0
- 1
- q1
- 1
- k0
- 1
- k1
- 1
- divisor
- 1.4142135623730951
- allowed
- 1
Saved outputs
- product0
- 1
- product1
- 1
- dot
- 2
- score
- 1.414213562373095
variant_row_0: Query 0: allowed-only stable softmax in key order
max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=fold(+0,terms); probability[j]=term[j]/denominator
The unchanged platform primitive prefers +0 on a mixed signed-zero maximum tie, exponentiates only allowed keys, adds all Tk terms from +0 and divides every term. Allowed shifted witnesses repeat its identical immutable subtraction; no extra exp is evaluated and forbidden shifts are absent.
Saved inputs
- i
- 0
- Tk
- 3
- score0
- 0.7071067811865475
- allowed0
- 1
- score1
- 0
- allowed1
- 1
- score2
- 0.7071067811865475
- allowed2
- 1
Saved outputs
- max
- 0.7071067811865475
- shifted0
- 0
- term0
- 1
- shifted1
- -0.7071067811865475
- term1
- 0.49306869139523984
- shifted2
- 0
- term2
- 1
- denominator
- 2.49306869139524
- probability0
- 0.4011120926797859
- probability1
- 0.1977758146404282
- probability2
- 0.4011120926797859
variant_row_1: Query 1: allowed-only stable softmax in key order
max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=fold(+0,terms); probability[j]=term[j]/denominator
The unchanged platform primitive prefers +0 on a mixed signed-zero maximum tie, exponentiates only allowed keys, adds all Tk terms from +0 and divides every term. Allowed shifted witnesses repeat its identical immutable subtraction; no extra exp is evaluated and forbidden shifts are absent.
Saved inputs
- i
- 1
- Tk
- 3
- score0
- 0.7071067811865475
- allowed0
- 1
- score1
- 0.7071067811865475
- allowed1
- 1
- score2
- 1.414213562373095
- allowed2
- 1
Saved outputs
- max
- 1.414213562373095
- shifted0
- -0.7071067811865475
- term0
- 0.49306869139523984
- shifted1
- -0.7071067811865475
- term1
- 0.49306869139523984
- shifted2
- 0
- term2
- 1
- denominator
- 1.9861373827904796
- probability0
- 0.2482550782577231
- probability1
- 0.2482550782577231
- probability2
- 0.5034898434845538
variant_weighted_0_0_0: Query 0, key 0, value feature 0: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 0
- j
- 0
- d
- 0
- probabilityOffset
- 0
- valueOffset
- 0
- storageOffset
- 0
- outputOffset
- 0
- allowed
- 1
- probability
- 0.4011120926797859
- value
- 1
- previous
- 0
Saved outputs
- product
- 0.4011120926797859
- sum
- 0.4011120926797859
variant_weighted_0_0_1: Query 0, key 0, value feature 1: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 0
- j
- 0
- d
- 1
- probabilityOffset
- 0
- valueOffset
- 1
- storageOffset
- 1
- outputOffset
- 1
- allowed
- 1
- probability
- 0.4011120926797859
- value
- 1
- previous
- 0
Saved outputs
- product
- 0.4011120926797859
- sum
- 0.4011120926797859
variant_weighted_0_1_0: Query 0, key 1, value feature 0: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 0
- j
- 1
- d
- 0
- probabilityOffset
- 1
- valueOffset
- 2
- storageOffset
- 2
- outputOffset
- 0
- allowed
- 1
- probability
- 0.1977758146404282
- value
- 0
- previous
- 0.4011120926797859
Saved outputs
- product
- 0
- sum
- 0.4011120926797859
variant_weighted_0_1_1: Query 0, key 1, value feature 1: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 0
- j
- 1
- d
- 1
- probabilityOffset
- 1
- valueOffset
- 3
- storageOffset
- 3
- outputOffset
- 1
- allowed
- 1
- probability
- 0.1977758146404282
- value
- 1
- previous
- 0.4011120926797859
Saved outputs
- product
- 0.1977758146404282
- sum
- 0.5988879073202141
variant_weighted_0_2_0: Query 0, key 2, value feature 0: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 0
- j
- 2
- d
- 0
- probabilityOffset
- 2
- valueOffset
- 4
- storageOffset
- 4
- outputOffset
- 0
- allowed
- 1
- probability
- 0.4011120926797859
- value
- 1
- previous
- 0.4011120926797859
Saved outputs
- product
- 0.4011120926797859
- sum
- 0.8022241853595719
variant_weighted_0_2_1: Query 0, key 2, value feature 1: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 0
- j
- 2
- d
- 1
- probabilityOffset
- 2
- valueOffset
- 5
- storageOffset
- 5
- outputOffset
- 1
- allowed
- 1
- probability
- 0.4011120926797859
- value
- 2
- previous
- 0.5988879073202141
Saved outputs
- product
- 0.8022241853595719
- sum
- 1.401112092679786
variant_weighted_1_0_0: Query 1, key 0, value feature 0: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 1
- j
- 0
- d
- 0
- probabilityOffset
- 3
- valueOffset
- 0
- storageOffset
- 6
- outputOffset
- 2
- allowed
- 1
- probability
- 0.2482550782577231
- value
- 1
- previous
- 0
Saved outputs
- product
- 0.2482550782577231
- sum
- 0.2482550782577231
variant_weighted_1_0_1: Query 1, key 0, value feature 1: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 1
- j
- 0
- d
- 1
- probabilityOffset
- 3
- valueOffset
- 1
- storageOffset
- 7
- outputOffset
- 3
- allowed
- 1
- probability
- 0.2482550782577231
- value
- 1
- previous
- 0
Saved outputs
- product
- 0.2482550782577231
- sum
- 0.2482550782577231
variant_weighted_1_1_0: Query 1, key 1, value feature 0: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 1
- j
- 1
- d
- 0
- probabilityOffset
- 4
- valueOffset
- 2
- storageOffset
- 8
- outputOffset
- 2
- allowed
- 1
- probability
- 0.2482550782577231
- value
- 0
- previous
- 0.2482550782577231
Saved outputs
- product
- 0
- sum
- 0.2482550782577231
variant_weighted_1_1_1: Query 1, key 1, value feature 1: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 1
- j
- 1
- d
- 1
- probabilityOffset
- 4
- valueOffset
- 3
- storageOffset
- 9
- outputOffset
- 3
- allowed
- 1
- probability
- 0.2482550782577231
- value
- 1
- previous
- 0.2482550782577231
Saved outputs
- product
- 0.2482550782577231
- sum
- 0.4965101565154462
variant_weighted_1_2_0: Query 1, key 2, value feature 0: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 1
- j
- 2
- d
- 0
- probabilityOffset
- 5
- valueOffset
- 4
- storageOffset
- 10
- outputOffset
- 2
- allowed
- 1
- probability
- 0.5034898434845538
- value
- 1
- previous
- 0.2482550782577231
Saved outputs
- product
- 0.5034898434845538
- sum
- 0.7517449217422769
variant_weighted_1_2_1: Query 1, key 2, value feature 1: product then running sum
product=probability*value; sum=previous+product
Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.
Saved inputs
- i
- 1
- j
- 2
- d
- 1
- probabilityOffset
- 5
- valueOffset
- 5
- storageOffset
- 11
- outputOffset
- 3
- allowed
- 1
- probability
- 0.5034898434845538
- value
- 2
- previous
- 0.4965101565154462
Saved outputs
- product
- 1.0069796869691077
- sum
- 1.5034898434845538
finish: Read the saved attention output for every query
output[i,d]=saved weighted sum after the last key; output length=Tq
Copy each actual output word and source-graph count after the complete sublayer. Source origin codes are query=0,memory=1. Counts describe this declared computation, not hardware timing, a full architecture or learned capability.
Saved inputs
- mode
- 2
- Tq
- 2
- Tk
- 3
Saved outputs
- mode
- 2
- queryOrigin
- 0
- keyValueOrigin
- 1
- Tq
- 2
- Tk
- 3
- allowedPairs
- 6
- outputRows
- 2
- outputFeatures
- 2
- sqrtCalls
- 1
- expCalls
- 6
- nativeElementaryCalls
- 7
- frames
- 39
- tensorCount
- 32
- output00
- 0.8022241853595719
- output01
- 1.401112092679786
- output10
- 0.7517449217422769
- output11
- 1.5034898434845538
Saved primary counts and complete numerical policies
| Output key | Saved value |
|---|---|
| mode | 2 |
| queryOrigin | 0 |
| keyValueOrigin | 1 |
| Tq | 2 |
| Tk | 3 |
| allowedPairs | 6 |
| outputRows | 2 |
| outputFeatures | 2 |
| sqrtCalls | 1 |
| expCalls | 6 |
| nativeElementaryCalls | 7 |
| frames | 39 |
| tensorCount | 32 |
Encoder Q/K/V use all three memory rows. Decoder Q/K/V use both query rows. Cross Q uses both query rows and K/V use all three memory rows. Numeric equality never changes source identity; all inactive raw fields remain editable, captured and validated.
Compute all Q, then K, then V in row/feature order with two products and one direct sum. Compute one sqrt(2), all scores in i,j order, all softmax rows in i order, then every weighted product and partial sum in i,j,d order. Score division has no added +0. Output accumulators start +0 separately for each feature.
Thirteen raw source/gain fields, their source and weight copies, every arithmetic result and native argument/output use binary64 WORD including -0. mode, key bits, dimensions, origins, offsets, counts and native kind codes use VALUE; mask tensors use Boolean VALUE. Gain slots copy words directly and structural weight zeros are literal +0. Forbidden terms/probabilities are +0; weighted products retain their computed signs.
All storage is row-major. Active source/output offset is 2*row+d, score offset is i*Tk+j, projection product offset is (row*2+d)*2+inputFeature and weighted product/partial offset is (i*Tk+j)*2+d. Raw offsets identify the separate raw17 origins. All tensors have at most four axes.
No wrapper frame precedes raw/prefix/all-row mask preflight. The first helper setup frame carries all raw17 fields. The unchanged decoderTrace factory captures finite operands once, checks nonempty unique IDs before operands and the 512 cap after operands, then saves detached frozen six-field frames. Every frame output appears as frameId_key in root outputs, without recomputing arithmetic.
mode, origins, dimensions, allowed-pair/native/frame/tensor counts and output sizes are VALUE. output00,output01 and later row coordinates are unchanged output WORD copies. All frame-output aliases retain their source VALUE or WORD role. Origin codes are query=0,memory=1; native kind codes are sqrt=0,exp=1.
SOURCE IMPLEMENTATION ONLY. All tests, independent executable authority, canonical parity, typecheck, build, browser, accessibility and offline checks are UNRUN under the human FluxGeo hold. Public inventory adoption and validation belong to the owner; this record is not runtime acceptance.
All 32 tensors above, every native occurrence and every saved frame read this same complete root. The house inspector below also retains all scalar outputs and aliases, all text metadata, and complete tensor storage. The selected trace step changes the explanation; it does not change this whole-root evidence or the current question's answer.
Inspect all stored values, text metadata and tensor storage
Every scalar output, including flattened operation outputs
Exact text evidence from the same record
These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.
variant_Raw
RawField=17 · float64 · precision 8 · Captured raw17 in texts.rawFields order. mode/key0/key1/key2 are VALUE; thirteen source/gain fields are binary64 WORD, including -0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
| 6 | 0 |
| 7 | 0 |
| 8 | 1 |
| 9 | 1 |
| 10 | 1 |
| 11 | 1 |
| 12 | 1 |
| 13 | 1 |
| 14 | 1 |
| 15 | 1 |
| 16 | 1 |
variant_Query
B=1 × QueryPosition=2 × D=2 · float64 · precision 8 · Unchanged raw query00,query01,query10,query11 words, including when inactive in encoder mode.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
variant_Memory
B=1 × MemoryPosition=3 × D=2 · float64 · precision 8 · Unchanged raw memory00,memory01,memory10,memory11,memory20,memory21 words, including when inactive in decoder mode.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
variant_KeyValidity
KeySlot=3 · int32 · precision 0 · Captured positional key bits for the selected K/V origin; key2 is validated but inactive in decoder mode. VALUE.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
variant_SourceOrigins
SourceRole=2 · int32 · precision 0 · Q-source then K/V-source codes: query=0,memory=1. VALUE; equal numbers do not merge origins.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
variant_QuerySource
B=1 × Tq=2 × D=2 · float64 · precision 8 · Q source WORD copies: memory in encoder mode, query in decoder/cross modes.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
variant_KeyValueSource
B=1 × Tk=3 × D=2 · float64 · precision 8 · K/V source WORD copies: query in decoder mode, memory in encoder/cross modes.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
variant_QuerySourceOffsets
Tq=2 × D=2 · int32 · precision 0 · Raw17 VALUE offsets for each Q-source coordinate, in row-major order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
variant_KeyValueSourceOffsets
Tk=3 × D=2 · int32 · precision 0 · Raw17 VALUE offsets for each K/V-source coordinate, in row-major order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 5 |
| 1 | 6 |
| 2 | 7 |
| 3 | 8 |
| 4 | 9 |
| 5 | 10 |
variant_WQ
D=2 × Dk=2 · float64 · precision 8 · Row-feature WQ=[[q,+0],[q,q]]: gain slots copy q WORD; structural zero is literal +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
variant_WK
D=2 × Dk=2 · float64 · precision 8 · Row-feature WK=[[k,+0],[+0,k]]: gain slots copy k WORD; structural zeros are literal +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
variant_WV
D=2 × Dv=2 · float64 · precision 8 · Row-feature WV=[[v,v],[+0,v]]: gain slots copy v WORD; structural zero is literal +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
variant_QProducts
Tq=2 × Dk=2 × InputFeature=2 · float64 · precision 8 · Actual Q projection product0,product1 for each query row/output feature; direct sum without an initial +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
variant_KProducts
Tk=3 × Dk=2 × InputFeature=2 · float64 · precision 8 · Actual K projection product0,product1 for each key row/output feature; direct sum without an initial +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 1 |
| 8 | 1 |
| 9 | 0 |
| 10 | 0 |
| 11 | 1 |
variant_VProducts
Tk=3 × Dv=2 × InputFeature=2 · float64 · precision 8 · Actual V projection product0,product1 for each key row/output feature; direct sum without an initial +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 1 |
| 8 | 1 |
| 9 | 0 |
| 10 | 1 |
| 11 | 1 |
variant_Q
B=1 × H=1 × Tq=2 × Dk=2 · float64 · precision 8 · Actual Q direct sums from the declared Q origin; singleton batch/head axes require no permutation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
variant_K
B=1 × H=1 × Tk=3 × Dk=2 · float64 · precision 8 · Actual K direct sums from the declared K/V origin; source row j uses offset 2*j+d.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
variant_V
B=1 × H=1 × Tk=3 × Dv=2 · float64 · precision 8 · Actual V direct sums from the declared K/V origin; every row remains computed under padding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
variant_Divisor
Scalar=1 · float64 · precision 8 · Actual single sqrt(2) output WORD, copied into every score division and the native ledger.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.4142135623730951 |
variant_ScoreProducts
Tq=2 × Tk=3 × Dk=2 · float64 · precision 8 · Actual score product0,product1 for every query/key pair, including forbidden pairs.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 0 |
| 9 | 1 |
| 10 | 1 |
| 11 | 1 |
variant_Dots
B=1 × H=1 × Tq=2 × Tk=3 · float64 · precision 8 · Direct product0+product1 WORD at offset i*Tk+j, without an initial +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
variant_Scores
B=1 × H=1 × Tq=2 × Tk=3 · float64 · precision 8 · Actual dot/divisor WORD for every query/key pair, including forbidden pairs; no shift or -Infinity sentinel.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.7071067811865475 |
| 1 | 0 |
| 2 | 0.7071067811865475 |
| 3 | 0.7071067811865475 |
| 4 | 0.7071067811865475 |
| 5 | 1.414213562373095 |
variant_Allowed
B=1 × H=1 × Tq=2 × Tk=3 · bool · precision 0 · Boolean key eligibility: key[j] AND (mode!=decoder OR j<=i). Keys only; query rows are retained.
| Zero-based storage index | Stored value |
|---|---|
| 0 | true |
| 1 | true |
| 2 | true |
| 3 | true |
| 4 | true |
| 5 | true |
variant_Maxima
B=1 × H=1 × Tq=2 · float64 · precision 8 · Actual platform Math.max of allowed scores, including +0 preference on mixed-zero ties.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.7071067811865475 |
| 1 | 1.414213562373095 |
variant_Terms
B=1 × H=1 × Tq=2 × Tk=3 · float64 · precision 8 · Actual platform exp outputs at allowed positions; forbidden positions are literal +0 with no exp call.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.49306869139523984 |
| 2 | 1 |
| 3 | 0.49306869139523984 |
| 4 | 0.49306869139523984 |
| 5 | 1 |
variant_Denominators
B=1 × H=1 × Tq=2 · float64 · precision 8 · Actual platform Tk-ordered term sums from literal +0, copied without reassociation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.49306869139524 |
| 1 | 1.9861373827904796 |
variant_Probabilities
B=1 × H=1 × Tq=2 × Tk=3 · float64 · precision 8 · Actual platform term/denominator at every position; forbidden probabilities are +0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4011120926797859 |
| 1 | 0.1977758146404282 |
| 2 | 0.4011120926797859 |
| 3 | 0.2482550782577231 |
| 4 | 0.2482550782577231 |
| 5 | 0.5034898434845538 |
variant_WeightedProducts
Tq=2 × Tk=3 × Dv=2 · float64 · precision 8 · Every actual P[i,j]*V[j,d] WORD at (i*Tk+j)*2+d; masked products can be -0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4011120926797859 |
| 1 | 0.4011120926797859 |
| 2 | 0 |
| 3 | 0.1977758146404282 |
| 4 | 0.4011120926797859 |
| 5 | 0.8022241853595719 |
| 6 | 0.2482550782577231 |
| 7 | 0.2482550782577231 |
| 8 | 0 |
| 9 | 0.2482550782577231 |
| 10 | 0.5034898434845538 |
| 11 | 1.0069796869691077 |
variant_WeightedPartials
Tq=2 × Tk=3 × Dv=2 · float64 · precision 8 · Actual updated sum after every product, with independent +0-initialized feature accumulators; traversal i,j,d.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4011120926797859 |
| 1 | 0.4011120926797859 |
| 2 | 0.4011120926797859 |
| 3 | 0.5988879073202141 |
| 4 | 0.8022241853595719 |
| 5 | 1.401112092679786 |
| 6 | 0.2482550782577231 |
| 7 | 0.2482550782577231 |
| 8 | 0.2482550782577231 |
| 9 | 0.4965101565154462 |
| 10 | 0.7517449217422769 |
| 11 | 1.5034898434845538 |
variant_Output
B=1 × H=1 × Tq=2 × Dv=2 · float64 · precision 8 · Final saved +0-initialized, ascending-key weighted sums; no output projection, bias, residual or normalization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8022241853595719 |
| 1 | 1.401112092679786 |
| 2 | 0.7517449217422769 |
| 3 | 1.5034898434845538 |
variant_NativeArguments
Native=7 × NativeField=2 · float64 · precision 8 · Ordered actual native input,output WORD copies. Exp inputs functionally reconstruct the identical subtraction; exp outputs are actual platform terms. No extra native call in serialization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
| 1 | 1.4142135623730951 |
| 2 | 0 |
| 3 | 1 |
| 4 | -0.7071067811865475 |
| 5 | 0.49306869139523984 |
| 6 | 0 |
| 7 | 1 |
| 8 | -0.7071067811865475 |
| 9 | 0.49306869139523984 |
| 10 | -0.7071067811865475 |
| 11 | 0.49306869139523984 |
| 12 | 0 |
| 13 | 1 |
variant_NativeKinds
Native=7 · int32 · precision 0 · VALUE native kind codes in occurrence order: sqrt=0,exp=1; bind texts.nativeIds and texts.nativeKinds.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
Check your understanding
Use the inputs stated in each question. Live questions use the current calculation. Each option pairs a value or conclusion with its mechanism. Editing a raw input, resetting or selecting a trace step clears graded answers; local inspection selectors preserve them.
Exactly five corrective questions use stated default worksheets or the current WHOLE saved root. Focus a table region to scroll with the keyboard; menus, number inputs, trace controls, disclosures and reset use native keyboard controls. This toy computes one attention sublayer with hand-set weights; it performs no training, generation or complete encoder/decoder block.
Try a route, then follow its saved calculation
Start with the default 2 — cross: query Q, memory K/V. Open the memory source group and change memory20 from 1 to 2. The query projection stays fixed while the third key and value change. Compare output row 0 before and after the edit: that memory row is eligible even though its index is larger than the query’s. Choose Reset example before comparing the default worksheets below. Reset restores all seventeen defaults, the first trace step and unanswered questions.
There are seventeen controls. The mode menu offers 0 — encoder: memory Q/K/V, bidirectional, 1 — decoder: query Q/K/V, causal, and 2 — cross: query Q, memory K/V. Four query-coordinate inputs, six memory-coordinate inputs and three gain inputs accept finite numbers within the bounds listed later. The final three menus offer 0 — key excluded and 1 — key valid. Open their disclosure groups to edit them. Query inputs remain editable and validated in encoder mode; memory inputs and key2 remain editable and validated in decoder mode. Their saved values persist when you change mode. Key menus always describe the current K/V source.
An empty, unfinished, nonfinite or out-of-range numeric draft retains the text you are editing and keeps the last valid numeric state internally. It withholds the graph, trace, inspector and all five questions, so an older output is not presented as the answer to the invalid draft. Correct every draft or reset. A complete numeric state can also be mathematically unavailable: decoder mode with key0=0 has an empty first allowed row, regardless of key1 or key2. The error explains why no probability distribution exists. Unknown programming or runtime errors propagate; they are not relabeled as a known input failure.
Use Previous step, Calculation step and Next step to select an immutable saved frame. The selected equation, explanation and operands describe that frame; the eleven-stage graph and all projection, score, weighted-product and output tables still describe the whole current calculation. Expand All saved tensors for every cell, flat storage index, named axis, shape, dtype, declared display precision and source explanation. The ordered native-leaf ledger shows every saved square-root/exponential argument and result, including separate occurrences with equal arguments. Expand Complete saved operation text fallback for every frame, and the house inspector for all scalar aliases, all text metadata and a second full tensor representation. Numbers there retain stored precision and show −0 explicitly; display formatting does not feed the computation.
The five questions are inside this single lab. The first four state fixed default worksheets: origins, unequal shapes, decoder products and a memory edit. Their premises remain fixed when you edit the lab. The fifth begins Current WHOLE saved root and includes all raw inputs, source names, dimensions, allowed rows, probabilities and outputs. Answer from that saved evidence: encoder uses memory throughout, decoder uses query throughout with causality, and cross uses query Q with memory K/V. Moving the trace cursor does not change its correct answer. Editing, resetting or seeking clears graded answers; opening a disclosure preserves them. Each selection gives corrective feedback.
Use Tab to reach native menus, numeric inputs, trace buttons, reset, disclosures and radio answers; use each control’s native keyboard actions. Focus a scrollable table region to inspect its wider columns with the keyboard. The selected frame also supplies a polite announcement of its exact equation and operands. These describe the authored interface; keyboard, screen-reader, rendering and offline behavior remain unvalidated under the current execution hold.
Review IV-59 — Decoder-Only Transformer Anatomy for a complete disclosed decoder-only toy and IV-25 — Self-Attention: Complete Numerical Trace for the score–mask–softmax–value sequence. Book II’s II.9 — Matrix × vector, II.10 — Matrix × matrix as composition and II.11 — Transpose and orthogonality explain matrix products and transposes; VII.6 — Logits and softmax and VII.7 — Numerical stability: log-sum-exp and stable softmax explain softmax and its stable evaluation. Book III’s III-16 — Multiclass Classification and Softmax Regression connects scores to probabilities, while III-41 — Composition and Learned Representations explains composing feature transformations.
First choose where the rows come from
Call the two-row query stream R and the three-row memory stream M. “Memory” means the supplied source features, not a cache or learned memory bank. Their default values are:
R = [[1,0], M = [[1,0],
[0,1]] [0,1],
[1,1]]
A query Q is a projected row used to request information. A key K is a projected row used for comparison with a query. A value V is the projected information that receives the resulting weight. These are numerical roles, not claims about understanding. Self-attention takes all three from one stream. Cross-attention takes queries from one stream and keys and values from another.
| Mode | Q source | K and V source | Query rows Tq | Key rows Tk | Eligible key j for query i |
|---|---|---|---|---|---|
| 0: encoder self-attention | M | M | 3 | 3 | Any valid key |
| 1: decoder causal self-attention | R | R | 2 | 2 | A valid key with j no greater than i |
| 2: cross-attention, the default | R | M | 2 | 3 | Any valid memory key |
Bidirectional means the encoder query may use keys on either side of its own position. Causal means the decoder query may use its own and earlier positions, preventing information from later decoder positions entering that output. This local rule assumes aligned positions and no cache offset. The cross-attention indices refer to different streams: memory key 2 is not a future answer query. Adding a rule that requires j no greater than i in cross mode would change the intended calculation.
Padding marks keys that are ineligible. The three bits key0, key1, key2 refer to positions in the currently selected K/V stream. They refer to M in encoder/cross mode and R in decoder mode. Decoder has only two keys, so its retained key2 is inactive. Padding does not delete query rows. In particular, an encoder row excluded as a key still supplies a query that can read other keys. This is this lesson’s explicit key-only convention; a larger architecture may separately specify what to do with padded query outputs.
Shapes tell us which products are legal
A tensor is an array with named axes; its shape lists the axis lengths. B=1 means one sequence in a batch, H=1 means one attention head, and a head is one set of query/key comparisons and value mixtures. D=2 is the source feature width, Dk=2 the comparison width, and Dv=2 the value width. Their equal sizes do not make their meanings interchangeable.
Index i selects a query, j a key, and d an output feature, starting at zero. Tq counts queries and Tk counts keys. A superscript transpose exchanges matrix axes: K transposed has one column per key, so a query can form one dot product with every key. A dot product multiplies corresponding features and adds the products. P will denote the attention probabilities and O the output; M remains the source memory, not a mask.
| Quantity | Full shape | Cross-mode shape |
|---|---|---|
| Query source; K/V source | [B,Tq,D]; [B,Tk,D] | [1,2,2]; [1,3,2] |
| Q | [B,H,Tq,Dk] | [1,1,2,2] |
| K; V | [B,H,Tk,Dk]; [B,H,Tk,Dv] | [1,1,3,2] each |
| Scores S; Boolean allowed mask; P | [B,H,Tq,Tk] | [1,1,2,3] each |
| O | [B,H,Tq,Dv] | [1,1,2,2] |
| Weighted products and running sums | [Tq,Tk,Dv], singleton axes omitted | [2,3,2] |
The hand tables suppress B and H. Cross Q is then 2 by 2, K transposed is 2 by 3, and their product is 2 by 3. P of size 2 by 3 multiplies V of size 3 by 2, producing O of size 2 by 2. The output has one row per query, not per key. No third query is invented to make the attention square.
Book II starts from column vectors. Here a feature row multiplies a row-feature weight matrix, which is the transpose of the corresponding column-form weight matrix. We make that change of convention explicitly; it is not a silent transpose of these displayed weights.
Project every source row, including the zero products
The three gains q, k and v control these row-feature matrices:
WQ = [[q,+0], WK = [[k,+0], WV = [[v,v],
[q, q]] [+0,k]] [+0,v]]
A gain is a scalar setting the indicated entries; there are no projection biases. Entries marked q, k or v copy that gain, including the sign of zero. A structural +0 is a literal positive zero, not a gain multiplied by zero. Defaults q=k=v=1 give:
WQ = [[1,0], WK = [[1,0], WV = [[1,1],
[1,1]] [0,1]] [0,1]]
For each output coordinate we compute the first product, the second product, then their direct sum. For example, M2=(1,1) gives Q=(1·1+1·1, 1·0+1·1)=(2,1). Its V is (1·1+1·0, 1·1+1·1)=(1,2). Queries and values need not be identical even for one source row.
| Source row | Q feature 0 | Q feature 1 | K feature 0 | K feature 1 | V feature 0 | V feature 1 |
|---|---|---|---|---|---|---|
| R0=(1,0) | 1·1+0·1=1 | 1·0+0·1=0 | 1·1+0·0=1 | 1·0+0·1=0 | 1·1+0·0=1 | 1·1+0·1=1 |
| R1=(0,1) | 0·1+1·1=1 | 0·0+1·1=1 | 0·1+1·0=0 | 0·0+1·1=1 | 0·1+1·0=0 | 0·1+1·1=1 |
| M0=(1,0) | 1·1+0·1=1 | 1·0+0·1=0 | 1·1+0·0=1 | 1·0+0·1=0 | 1·1+0·0=1 | 1·1+0·1=1 |
| M1=(0,1) | 0·1+1·1=1 | 0·0+1·1=1 | 0·1+1·0=0 | 0·0+1·1=1 | 0·1+1·0=0 | 0·1+1·1=1 |
| M2=(1,1) | 1·1+1·1=2 | 1·0+1·1=1 | 1·1+1·0=1 | 1·0+1·1=1 | 1·1+1·0=1 | 1·1+1·1=2 |
This table explains each possible route; a selected mode projects only its active sources. All active Q rows are projected first, then all K rows, then all V rows, in ascending row and feature order. The equal first two R/M rows are still separate source records. Changing M2 later will expose the difference.
The nonsymmetric matrices matter: transposing WQ would send (1,0) to (1,1), rather than (1,0). Transposing WV would send it to (1,0), rather than (1,1). The identity WK would conceal this mistake, so checking keys alone is insufficient.
From comparisons to a mixture
For every query/key pair the unscaled dot is Q feature 0 times K feature 0 plus Q feature 1 times K feature 1. Divide that direct sum by a single square root of Dk=2 to obtain score S. Scaling keeps dot-product magnitudes from growing unchecked with comparison width; it does not turn them into probabilities.
Softmax turns the allowed scores in one row into nonnegative weights summing to one in real arithmetic. Let m be that row’s largest allowed score. Subtract m before taking each allowed exponential. The exponential exp(x) means e raised to x, with e the base of natural logarithms. Since subtracting m multiplies every allowed exponential by the same positive factor, it leaves the real probabilities unchanged and keeps the arguments nonpositive.
Forbidden slots contribute literal +0 without an exponential or numerical shifted argument. Add all Tk terms from +0 in ascending key order to get denominator Z, then divide each term by Z. Finally multiply every probability by the corresponding V coordinate, including masked slots, and add those products from +0, again in ascending key order. Scores are computed for all cells of a valid state, including forbidden cells; masking controls eligibility for normalization.
The following worksheets are symbolic real arithmetic, not recorded floating-point results. Define s=1/√2, r=exp(−s) and t=exp(−2s). Thus t=r² over the reals. For readable denominators define:
A = ((+0+1)+r)+1 = 2+r
B = ((+0+r)+r)+1 = 1+2r
C = ((+0+r)+t)+1 = 1+r+t
Here A, B and C name real sums, distinct from the batch-axis symbol B in the shape table. The right-hand simplifications help us understand the answer; they do not prescribe a reordered machine calculation. No rounded display number is fed back into these formulas.
Cross-attention: two queries read three memory rows
With default mode 2 and all keys valid, Q comes from R, while K and V come from M:
Q = [[1,0], K = [[1,0], V = [[1,1],
[1,1]] [0,1], [0,1],
[1,1]] [1,2]]
| i,j | First product + second product = dot | Score after division by √2 |
|---|---|---|
| 0,0 | 1·1+0·0=1 | s |
| 0,1 | 1·0+0·1=0 | 0 |
| 0,2 | 1·1+0·1=1 | s |
| 1,0 | 1·1+1·0=1 | s |
| 1,1 | 1·0+1·1=1 | s |
| 1,2 | 1·1+1·1=2 | 2s |
Thus S has rows (s,0,s) and (s,s,2s). Every cell is allowed.
| Query | Maximum m | Shifts in key order | Exponential terms | Ordered denominator | P in key order |
|---|---|---|---|---|---|
| R0 | s | (0,−s,0) | (1,r,1) | ((+0+1)+r)+1=A | (1/A,r/A,1/A) |
| R1 | 2s | (−s,−s,0) | (r,r,1) | ((+0+r)+r)+1=B | (r/B,r/B,1/B) |
Row R0 gives equal weights to memory keys 0 and 2 because their scores tie. That does not give equal outputs from those keys: their values are (1,1) and (1,2). Carry the actual values into every product:
| Query | Key 0 products (d=0,d=1) | Key 1 products | Key 2 products | O feature 0 | O feature 1 |
|---|---|---|---|---|---|
| R0 | ((1/A)·1,(1/A)·1)=(1/A,1/A) | ((r/A)·0,(r/A)·1)=(0,r/A) | ((1/A)·1,(1/A)·2)=(1/A,2/A) | ((+0+1/A)+0)+1/A=2/A | ((+0+1/A)+r/A)+2/A=(3+r)/A |
| R1 | ((r/B)·1,(r/B)·1)=(r/B,r/B) | ((r/B)·0,(r/B)·1)=(0,r/B) | ((1/B)·1,(1/B)·2)=(1/B,2/B) | ((+0+r/B)+0)+1/B=(1+r)/B | ((+0+r/B)+r/B)+2/B=(2+2r)/B |
The complete real output is:
O_cross = [[2/(2+r), (3+r)/(2+r)],
[(1+r)/(1+2r), (2+2r)/(1+2r)]]
There are two output rows. In particular P[0,2]=1/(2+r) is positive although key index 2 exceeds query index 0. Source position 2 is available context, not a future decoder position.
Encoder self-attention: three queries read the same three-row stream
Mode 0 uses M for Q, K and V. K and V are exactly the memory matrices above; Q has an additional third row:
Q = [[1,0], K = [[1,0], V = [[1,1],
[1,1], [0,1], [0,1],
[2,1]] [1,1]] [1,2]]
| i,j | First product + second product = dot | Score |
|---|---|---|
| 0,0 | 1·1+0·0=1 | s |
| 0,1 | 1·0+0·1=0 | 0 |
| 0,2 | 1·1+0·1=1 | s |
| 1,0 | 1·1+1·0=1 | s |
| 1,1 | 1·0+1·1=1 | s |
| 1,2 | 1·1+1·1=2 | 2s |
| 2,0 | 2·1+1·0=2 | 2s |
| 2,1 | 2·0+1·1=1 | s |
| 2,2 | 2·1+1·1=3 | 3s |
S has rows (s,0,s), (s,s,2s) and (2s,s,3s). All nine cells are allowed. The third row particularly rewards key 2, but no hard selection discards the others.
| Query | Maximum | Shifts | Exponential terms | Ordered denominator | P |
|---|---|---|---|---|---|
| M0 | s | (0,−s,0) | (1,r,1) | ((+0+1)+r)+1=A | (1/A,r/A,1/A) |
| M1 | 2s | (−s,−s,0) | (r,r,1) | ((+0+r)+r)+1=B | (r/B,r/B,1/B) |
| M2 | 3s | (−s,−2s,0) | (r,t,1) | ((+0+r)+t)+1=C | (r/C,t/C,1/C) |
| Query | Key 0 products | Key 1 products | Key 2 products | O feature 0 | O feature 1 |
|---|---|---|---|---|---|
| M0 | ((1/A)·1,(1/A)·1)=(1/A,1/A) | ((r/A)·0,(r/A)·1)=(0,r/A) | ((1/A)·1,(1/A)·2)=(1/A,2/A) | ((+0+1/A)+0)+1/A=2/A | ((+0+1/A)+r/A)+2/A=(3+r)/A |
| M1 | ((r/B)·1,(r/B)·1)=(r/B,r/B) | ((r/B)·0,(r/B)·1)=(0,r/B) | ((1/B)·1,(1/B)·2)=(1/B,2/B) | ((+0+r/B)+0)+1/B=(1+r)/B | ((+0+r/B)+r/B)+2/B=(2+2r)/B |
| M2 | ((r/C)·1,(r/C)·1)=(r/C,r/C) | ((t/C)·0,(t/C)·1)=(0,t/C) | ((1/C)·1,(1/C)·2)=(1/C,2/C) | ((+0+r/C)+0)+1/C=(1+r)/C | ((+0+r/C)+t/C)+2/C=(2+r+t)/C |
The complete real output is:
O_encoder = [[2/(2+r), (3+r)/(2+r)],
[(1+r)/(1+2r), (2+2r)/(1+2r)],
[(1+r)/(1+r+t), (2+r+t)/(1+r+t)]]
The first two output rows happen to equal the cross-mode outputs at these defaults. Their query origins differ: M0/M1 here, R0/R1 there. Equal numbers in one example do not prove equivalent source routing.
Decoder self-attention: two queries, with a causal restriction
Mode 1 uses R for all three projections:
Q = [[1,0], K = [[1,0], V = [[1,1],
[1,1]] [0,1]] [0,1]]
| i,j | First product + second product = dot | Score | Allowed with default key bits |
|---|---|---|---|
| 0,0 | 1·1+0·0=1 | s | Yes |
| 0,1 | 1·0+0·1=0 | 0 | No: later decoder position |
| 1,0 | 1·1+1·0=1 | s | Yes |
| 1,1 | 1·0+1·1=1 | s | Yes |
| Query | Allowed maximum | Shifts | Terms | Ordered denominator | P |
|---|---|---|---|---|---|
| R0 | s | (0,not evaluated) | (1,masked +0) | (+0+1)+0=1 | (1,0) |
| R1 | s | (0,0) | (1,1) | (+0+1)+1=2 | (1/2,1/2) |
The forbidden score S[0,1]=0 still exists as finite evidence. Its zero probability comes from the mask, not from a claim that exp(0) is zero. Only the allowed shift in row 0 is exponentiated.
| Query | Key 0 products | Key 1 products | O feature 0 | O feature 1 |
|---|---|---|---|---|
| R0 | (1·1,1·1)=(1,1) | (0·0,0·1)=(0,0) | (+0+1)+0=1 | (+0+1)+0=1 |
| R1 | ((1/2)·1,(1/2)·1)=(1/2,1/2) | ((1/2)·0,(1/2)·1)=(0,1/2) | (+0+1/2)+0=1/2 | (+0+1/2)+1/2=1 |
O_decoder = [[1,1],
[1/2,1]]
Row 1 is an average of values, not of queries or source rows. Row 0 uses only its own key/value. Changing only the later R1 cannot alter decoder output row 0, provided the complete input remains valid.
Padding and edits that distinguish the mechanisms
With key bits (1,0,1), cross row 0 has terms (1,0,1), denominator 2 and P=(1/2,0,1/2). Its products are (1/2,1/2), (0,0), (1/2,1), giving O=(1,3/2). Cross row 1 instead has terms (r,0,1), denominator 1+r and O=(1,(r+2)/(1+r)). Encoder keeps all three queries; its third output has that same latter real expression. Decoder sees only its first two key bits (1,0): both query rows output (1,1). Its key2 never creates another key.
With only key 2 valid, every encoder/cross query reads V_M2=(1,2), so every output is (1,2). Decoder has no eligible first key and is unavailable. With bits (0,1,1), decoder query 0 is also empty, even though query 1 could read key 1. Cross query 0 remains defined: its terms are (0,r,1), P=(0,r/(1+r),1/(1+r)), and output is (1/(1+r),(r+2)/(1+r)).
An empty allowed set has no probability distribution. The entire request reports FULLY_MASKED_ROW: “This query has no allowed keys; no probability distribution exists.” It does not manufacture uniform weights, return a valid zero output, remove the query or unmask a key. The complete allowed matrix is preflighted before projections, any trace additions or any square-root/exponential call. A pre-existing trusted collector remains unchanged on this failure.
With all other defaults unchanged and all keys valid, setting q=0 or, separately, k=0 makes all real scores zero. Valid encoder/cross rows then have terms (1,1,1), denominator 3 and weights (1/3,1/3,1/3). The value mixture is ((1+0+1)/3,(1+1+2)/3)=(2/3,4/3). Causal decoder row 0 still has weights (1,0), and row 1 has (1/2,1/2). Tied scores give equal weight only among allowed keys. A zero gain cannot repair an empty allowed set.
Setting v=0 leaves Q, K and the probabilities unchanged; it makes values and outputs zero over the reals. Changing what is mixed is different from changing the comparison. Machine zero signs still follow the actual products and additions.
For a source-origin counterexample, change only M2 from (1,1) to (2,1). Cross Q stays fixed; K2 becomes (2,1) and V2 becomes (2,3). Cross row 0 scores become (s,0,2s), with shifts (−s,−2s,0), terms (r,t,1) and denominator C. Products are (r/C,r/C), (0,t/C), (2/C,3/C); their ordered sums give ((r+2)/C,(r+t+3)/C). Cross row 1 has scores (s,s,3s), terms (t,t,1) and denominator F=((+0+t)+t)+1=1+2t. Its products (t/F,t/F), (0,t/F), (2/F,3/F) give ((t+2)/F,(2t+3)/F). Decoder’s active arithmetic stays unchanged because M is inactive. Encoder’s third query changes to (3,1), because it uses M for Q as well.
Conversely, changing only R1 to (1,1) leaves cross output row 0 unchanged and changes cross Q1 to (2,1). Its new row-1 scores are (2s,s,3s), so its new real output is ((1+r)/C,(2+r+t)/C). Encoder is unchanged because R is inactive. Decoder output row 0 remains (1,1), while row 1 now uses Q=(2,1), K rows (1,0),(1,1), and V rows (1,1),(1,2). Scores (2s,3s) give terms (r,1), denominator 1+r and output (1,(r+2)/(1+r)). These edits distinguish source identity, causality and equal default numbers.
Input limits include inactive fields
The complete raw record has exactly these seventeen finite numeric fields, in this order. A source coordinate is one of the ten entries in R or M. Bounds include their endpoints.
| Position | Field | Default | Domain |
|---|---|---|---|
| 1 | mode | 2 | Integer 0, 1 or 2 |
| 2 | query00 | 1 | [−4,4] |
| 3 | query01 | 0 | [−4,4] |
| 4 | query10 | 0 | [−4,4] |
| 5 | query11 | 1 | [−4,4] |
| 6 | memory00 | 1 | [−4,4] |
| 7 | memory01 | 0 | [−4,4] |
| 8 | memory10 | 0 | [−4,4] |
| 9 | memory11 | 1 | [−4,4] |
| 10 | memory20 | 1 | [−4,4] |
| 11 | memory21 | 1 | [−4,4] |
| 12 | q | 1 | [−1,1] |
| 13 | k | 1 | [−1,1] |
| 14 | v | 1 | [−1,1] |
| 15 | key0 | 1 | Integer 0 or 1 |
| 16 | key1 | 1 | Integer 0 or 1 |
| 17 | key2 | 1 | Integer 0 or 1 |
Mode chooses a route; it does not erase other values. Encoder leaves all four query-source fields inactive. Decoder leaves all six memory fields and key2 inactive. All remain retained and validated. An inactive NaN, infinity or out-of-range value still invalidates the request. Changing an inactive but valid source can leave numerical outputs unchanged while changing the saved input evidence; that is not equality of the whole record.
The pure model boundary first requires a plain or null-prototype object and checks all seventeen own data descriptors, with no missing, extra, symbol, inherited or getter-based substitutes. It then captures values once and checks all seventeen for finite numbers before testing any domain. Strings and booleans are not numeric inputs. Only after domains does the trace-name prefix undergo its ASCII rule: an initial letter followed by letters, digits or underscores. Only then comes the full allowed-matrix preflight. For example, an invalid inactive value takes precedence over an empty-mask failure; an invalid prefix also precedes that mask failure. There is no coercion, clamping or silent default merge at this boundary.
The editable interface has a separate draft boundary: it converts numeric text and checks each control’s finite value and domain in control order before submitting a complete numeric state. Its first draft error therefore need not match the pure model’s all-finite-before-any-domain precedence. Both paths validate inactive fields. The Python reference accepts exact ordinary or house-frozen dictionaries, rejects booleans as numbers, and checks huge finite integers against domains before converting source/gain values to binary64.
This corresponds to four discrete choices—mode and three key bits—and thirteen continuous numeric settings—ten source coordinates and three gains. Numerical −0 counts as zero for a mode or bit. In source coordinates and gains, its floating-point sign is retained.
Why symbolic equality is not machine-word equality
Binary64 is the floating-point number format used here. A word is its complete stored bit pattern, including a zero’s sign. Round to nearest, ties to even chooses the nearest representable result of an elementary operation, using an even final bit at an exact tie. The VIII.1 — Floating-point representation and VIII.2 — Rounding and representation error lessons develop these ideas.
For a row (−0,−0) and q=1, the two products for Q feature 0 are both −0. Their direct sum is −0. Inserting an initialized accumulator would compute (+0+−0)+−0, which gives +0 instead. Therefore projection and score contractions use two products and one direct addition, with no initial zero or bias. Denominator and weighted-output reductions deliberately start at +0; they are different operations.
The stable softmax maximum keeps the existing Math.max preference for +0 when signed-zero scores tie. Its forbidden terms are literal +0; every term is divided by the denominator. Masked products need not be +0: with M1=(0,−1), v=1 and key bits (1,0,1), V1 feature 1 is −1. Its forbidden probability +0 times −1 produces −0. That product is retained even when a later initialized sum erases its sign.
Every valid evaluation follows this order: all Q projections, all K projections, all V projections; one sqrt(2); every score in query-then-key order; every softmax row; then weighted products and running sums in query-then-key-then-feature order. Each output feature has its own +0 accumulator. Flat source/output storage uses offset 2*i+d; score storage uses i*Tk+j; weighted products and partial sums use (i*Tk+j)*2+d. Flattening changes storage, not these named axes or source identities.
The real identities t=r², 2s=2/√2 and the simplified output fractions do not authorize squaring one machine exponential, multiplying by a rounded reciprocal, or dividing a combined numerator instead of forming each probability/value product. The actual second exponential uses its actual rounded score-minus-maximum argument. All finite intermediates remain required even if masking later excludes a cell.
What an independent comparison can establish
A native leaf is an actual square-root or exponential result supplied by the runtime’s math library. A successful default graph calls one square root and one exponential per allowed cell: ten native occurrences in encoder mode, four in causal decoder mode, seven in cross mode. These are counts derived from the specified graph, not measured executions. Equal arguments still belong to distinct occurrences. Zero gains do not bypass the graph.
The independent policy admits each actual leaf only within four ordered positive binary64 word steps of an independently isolated reference, with positive finite output and exp(±0) exactly +1. The reference domains are sqrt input [1/4,4096] and exponential input [−256,0]. Source/gain bounds imply absolute Q feature bounds (8,4), K bounds (4,4), and dot magnitude at most 48. An admitted sqrt(2) is greater than 1, so scores stay in [−48,48] and allowed score-minus-maximum arguments in [−96,0]. This fits the existing reference domains; it does not establish any installed runtime’s compliance.
After native admission, independent replay must check every elementary rounded operation and every saved copy using that backend’s own actual leaves. It cannot infer exact cross-backend words merely from an error budget. An exponential argument reconstructed from the same immutable score and maximum is a functional witness of the subtraction; it does not physically intercept a math-library call. The saved exponential output must be the actual normalization term, with no fresh exponential during serialization and no invented forbidden shift.
These are forward calculations. There is no differentiated V3 claim. Hand derivation, source inspection, independent mathematical replay, Python/TypeScript parity and browser evidence are separate kinds of evidence.
Read the complete Python calculation
The following panels import three complete repository files, in dependency order. Keep all three in the same folder: decoder_reference.py supplies shared support, variants_reference.py supplies this lesson’s new scalar calculation and saved records, and iv60.py supplies the entry point. This is a three-project-file dependency closure; NumPy is an external dependency. The loaders resolve their neighboring files relative to their own file locations, rather than searching the current working directory.
1. Shared support: decoder_reference.py
This complete file includes historical IV59 model definitions. IV60 uses only its generic numerical-fault identity, exact record capture, immutable copies, prefix validation, trace collector and indexed NumPy storage. It does not call those old decoder, block, attention, head or task-check functions. Showing the full support file makes the actual dependency visible; its old tasks are not new IV60 evidence. For this lesson NumPy only stores already-computed scalars through indexed writes; it performs no attention contraction or hidden matrix multiplication.
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.
"""Independent IV59 scalar FIRST, with owner-adopted public bindings.
All execution and checks are UNRUN. Saved scalar captures drive serialization.
NumPy is used only for explicitly indexed result storage, never contractions.
"""
import math
import re
from types import MappingProxyType
import numpy as np
class NumericalFault(Exception):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
self.reason = reason
class _FrozenDict(dict):
def _readonly(self, *args, **kwargs):
raise TypeError("Frozen trace record.")
__setitem__ = __delitem__ = clear = pop = popitem = setdefault = update = __ior__ = _readonly
class _FrozenList(list):
def _readonly(self, *args, **kwargs):
raise TypeError("Frozen trace array.")
__setitem__ = __delitem__ = append = clear = extend = insert = pop = remove = reverse = sort = __iadd__ = __imul__ = _readonly
def _freeze(value):
if type(value) in (dict, _FrozenDict):
return _FrozenDict({key: _freeze(child) for key, child in value.items()})
if type(value) in (list, tuple, _FrozenList):
return _FrozenList(_freeze(child) for child in value)
if value is None or type(value) in (str, bool, int, float):
if type(value) is float and not math.isfinite(value):
raise TypeError("Trace values must be finite, plain JSON data.")
return value
raise TypeError("Copy typed arrays to plain arrays before tracing.")
DEFAULT_IV59 = _freeze(dict(
token0=97, token1=97, positionScale=0.5,
q1=1.0, k1=1.0, v1=1.0, o1=0.5, f1=0.5,
q2=1.0, k2=0.5, v2=1.0, o2=0.25, f2=0.25,
biasA=0.0, biasB=0.0, biasEOS=0.0))
_FIELDS = tuple(DEFAULT_IV59)
_GAIN_FIELDS = ("q", "k", "v", "o", "f")
_IDS = (97, 98, 512)
def _finite(value, name):
if not math.isfinite(value):
raise NumericalFault("NONFINITE", name + " must be finite.")
return value
def _capture_record(value, fields, label):
# Exact built-ins exclude custom reflection/getitem/accessor side effects.
if type(value) not in (dict, _FrozenDict):
raise NumericalFault("INVALID_INPUT", label + " must be a plain object.")
keys = tuple(value)
if len(keys) != len(fields) or any(type(key) is not str for key in keys) or set(keys) != set(fields):
raise NumericalFault("INVALID_INPUT", label + " must have exactly " + ", ".join(fields) + " as own fields.")
captured = {key: value[key] for key in fields}
for key in fields:
item = captured[key]
if type(item) not in (int, float) or (type(item) is float and not math.isfinite(item)):
raise NumericalFault("NONFINITE", label + "." + key + " must be an actual finite number.")
return captured
def decoder_state(value):
"""Capture raw16 once; check every number before any domain or conversion."""
captured = _capture_record(value, _FIELDS, "state")
for key in _FIELDS:
item = captured[key]
if key in ("token0", "token1"):
if item not in _IDS or (type(item) is float and not item.is_integer()):
raise NumericalFault("INVALID_INPUT", key + " must be an integer token ID in {97,98,512}.")
else:
lower, upper = ((0, 1) if key == "positionScale" else
(-2, 2) if key.startswith("bias") else (-1, 1))
if not lower <= item <= upper:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {lower} and {upper}.")
return _freeze({key: int(captured[key]) if key in ("token0", "token1") else float(captured[key])
for key in _FIELDS})
def _block_inputs(features, gains, prefix):
if type(features) not in (list, _FrozenList):
raise NumericalFault("INVALID_INPUT", "features must be an ordinary dense array.")
if len(features) not in (2, 4, 6):
raise NumericalFault("INVALID_INPUT", "features must contain 2, 4 or 6 words for B=1,T=1..3,D=2.")
captured = list(features)
for i, item in enumerate(captured):
if type(item) not in (int, float) or (type(item) is float and not math.isfinite(item)):
raise NumericalFault("NONFINITE", f"features[{i}] must be an actual finite number.")
for i, item in enumerate(captured):
if not -16 <= item <= 16:
raise NumericalFault("INVALID_INPUT", f"features[{i}] must be between -16 and 16.")
captured_gains = _capture_record(gains, _GAIN_FIELDS, "gains")
for key in _GAIN_FIELDS:
if not -1 <= captured_gains[key] <= 1:
raise NumericalFault("INVALID_INPUT", f"gains.{key} must be between -1 and 1.")
_prefix(prefix)
return [float(item) for item in captured], {key: float(captured_gains[key]) for key in _GAIN_FIELDS}
def _prefix(prefix):
if type(prefix) is not str or re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", prefix) is None:
raise NumericalFault("INVALID_INPUT", "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores.")
class _MechanismTrace:
"""Private captures; labels and schema are NOT the public adopted inventory."""
def __init__(self):
self.steps = []
self.native = []
self._ids = set()
def add(self, identifier, inputs, outputs):
if type(identifier) is not str or not identifier or identifier in self._ids:
raise NumericalFault("INVALID_INPUT", "Trace IDs must be nonempty and unique.")
before, after = dict(inputs), dict(outputs)
for record in (before, after):
for key, value in record.items():
if type(key) is not str or type(value) not in (int, float):
raise NumericalFault("INVALID_INPUT", "Capture scalar data only.")
_finite(value, identifier + "/" + key)
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
self._ids.add(identifier)
self.steps.append((identifier, MappingProxyType(before), MappingProxyType(after)))
def leaf(self, identifier, kind, argument):
_finite(argument, identifier + " argument")
lower, upper = (0.25, 4096.0) if kind == "sqrt" else (-256.0, 0.0)
if not lower <= argument <= upper:
raise NumericalFault("INVALID_INPUT", "Native argument outside authored scope.")
if any(record["id"] == identifier for record in self.native):
raise NumericalFault("INVALID_INPUT", "Native capture ID must be unique.")
output = _finite(math.sqrt(argument) if kind == "sqrt" else math.exp(argument), identifier)
if output <= 0:
raise NumericalFault("NONFINITE", "Native result must be positive.")
self.native.append(MappingProxyType(dict(id=identifier, kind=kind, input=argument, output=output)))
return output
def decoder_trace():
"""Create the adopted collector, with no implicit self-check."""
return _PublicTrace()
def _norm(features, trace, prefix):
result = []
for t in range(len(features) // 2):
x0, x1 = features[2 * t:2 * t + 2]
total = _finite(x0 + x1, "feature sum")
mean = _finite(total / 2.0, "feature mean")
centered0, centered1 = _finite(x0 - mean, "centered0"), _finite(x1 - mean, "centered1")
square0, square1 = _finite(centered0 * centered0, "square0"), _finite(centered1 * centered1, "square1")
square_sum = _finite(square0 + square1, "square sum")
variance = _finite(square_sum / 2.0, "population variance")
argument = _finite(variance + 0.25, "variance plus epsilon")
denominator = trace.leaf(f"{prefix}_{t}_sqrt", "sqrt", argument)
trace.add(f"{prefix}_{t}_statistics", dict(x0=x0, x1=x1, epsilon=0.25),
dict(sum=total, mean=mean, centered0=centered0, centered1=centered1,
square0=square0, square1=square1, squareSum=square_sum,
variance=variance, variancePlusEpsilon=argument, denominator=denominator))
for d, source in enumerate((centered0, centered1)):
normalized = _finite(source / denominator, "normalized")
scaled = _finite(1.0 * normalized, "gamma times normalized")
value = _finite(scaled + 0.0, "plus beta")
result.append(value)
trace.add(f"{prefix}_{t}_feature_{d}", dict(source=source, denominator=denominator, gamma=1.0, beta=0.0),
dict(normalized=normalized, scaled=scaled, value=value))
return result
def _two_products(features, weights, trace, prefix, bias=None, cols=2):
result = []
for t in range(len(features) // 2):
x0, x1 = features[2 * t:2 * t + 2]
for d in range(cols):
w0, w1 = weights[d], weights[cols + d]
product0, product1 = _finite(x0 * w0, "product0"), _finite(x1 * w1, "product1")
total = _finite(product0 + product1, "two product sum")
outputs = dict(product0=product0, product1=product1, sum=total)
inputs = dict(x0=x0, x1=x1, w0=w0, w1=w1)
value = total
if bias is not None:
inputs["bias"] = bias[d]
value = _finite(total + bias[d], "bias last")
outputs["value"] = value
trace.add(f"{prefix}_{t}_{d}", inputs, outputs)
result.append(value)
return result
def _softmax(logits, allowed, trace, prefix, positive_zero=True):
candidates = [value for value, keep in zip(logits, allowed) if keep]
maximum = candidates[0]
for value in candidates[1:]:
# Match Math.max's +0 preference; the shifted native argument keeps sign.
if value > maximum or (positive_zero and value == 0.0 and maximum == 0.0 and math.copysign(1.0, value) > 0.0):
maximum = value
terms = []
shifted = {}
denominator = 0.0
running = []
for j, (value, keep) in enumerate(zip(logits, allowed)):
term = 0.0
if keep:
argument = _finite(value - maximum, "allowed shifted logit")
shifted[f"shifted{j}"] = argument
term = trace.leaf(f"{prefix}_exp_{j}", "exp", argument)
terms.append(term)
for term in terms:
denominator = _finite(denominator + term, "softmax ordered denominator")
running.append(denominator)
probabilities = [_finite(term / denominator, "probability") for term in terms]
inputs = {f"logit{j}": value for j, value in enumerate(logits)}
inputs.update({f"allowed{j}": int(keep) for j, keep in enumerate(allowed)})
outputs = dict(max=maximum, denominator=denominator, **shifted)
outputs.update({f"term{j}": term for j, term in enumerate(terms)})
outputs.update({f"p{j}": probability for j, probability in enumerate(probabilities)})
outputs.update({f"running{j}": value for j, value in enumerate(running)})
trace.add(prefix, inputs, outputs)
return probabilities
def _accumulate_rows(features, width, weights, cols, trace, prefix, bias=None):
result = []
for t in range(len(features) // width):
for d in range(cols):
running = 0.0
inputs, outputs = {}, {}
for k in range(width):
value, weight = features[t * width + k], weights[k * cols + d]
inputs[f"x{k}"], inputs[f"w{k}"] = value, weight
product = _finite(value * weight, "ordered product")
running = _finite(running + product, "ordered running sum")
outputs[f"product{k}"], outputs[f"running{k}"] = product, running
value = running
if bias is not None:
inputs["bias"] = bias[d]
value = _finite(running + bias[d], "output bias last")
outputs["value"] = value
trace.add(f"{prefix}_{t}_{d}", inputs, outputs)
result.append(value)
return result
def _residual(left, right, trace, prefix):
result = []
for i in range(len(left)):
value = _finite(left[i] + right[i], "residual")
trace.add(f"{prefix}_{i}", dict(left=left[i], right=right[i]), dict(value=value))
result.append(value)
return result
def _storage(values, rows, cols):
"""No numerical NumPy operation: store already computed Python scalars."""
stored = np.empty((1, rows, cols), dtype=np.float64)
for t in range(rows):
for d in range(cols):
stored[0, t, d] = values[t * cols + d]
return stored
def _decoder_block_mechanics(features, gains, trace, prefix):
"""Original independent scalar graph; public metadata is a copy projection."""
count = len(features) // 2
norm1 = _norm(features, trace, prefix + "_ln1")
matrices = {key: [gains[key], 0.0, 0.0, gains[key]] for key in ("q", "k", "v", "o")}
q = _two_products(norm1, matrices["q"], trace, prefix + "_Q")
k = _two_products(norm1, matrices["k"], trace, prefix + "_K")
v = _two_products(norm1, matrices["v"], trace, prefix + "_V")
# H=1 split is still an actual copy with an explicit coordinate capture.
heads = []
for label, source in (("Q", q), ("K", k), ("V", v)):
copied = []
for i, value in enumerate(source):
copied.append(value)
trace.add(f"{prefix}_{label}_split_{i}", dict(source=value), dict(value=value))
heads.append(copied)
q, k, v = heads
divisor = trace.leaf(prefix + "_attention_sqrt", "sqrt", 2.0)
raw, scores, logits, allowed = [], [], [], []
for i in range(count):
for j in range(count):
product0 = _finite(q[2 * i] * k[2 * j], "score product0")
product1 = _finite(q[2 * i + 1] * k[2 * j + 1], "score product1")
dot = _finite(product0 + product1, "raw score")
score = _finite(dot / divisor, "scaled score")
raw.append(dot)
scores.append(score)
trace.add(f"{prefix}_score_{i}_{j}", dict(q0=q[2*i], q1=q[2*i+1], k0=k[2*j], k1=k[2*j+1], divisor=divisor),
dict(product0=product0, product1=product1, raw=dot, score=score))
probabilities = []
for i in range(count):
row, mask = [], []
for j in range(count):
row.append(_finite(scores[i * count + j] + 0.0, "score plus zero common shift"))
mask.append(j <= i)
logits.extend(row)
allowed.extend(mask)
probabilities.extend(_softmax(row, mask, trace, f"{prefix}_attention_row_{i}"))
mixed = []
for i in range(count):
for d in range(2):
running = 0.0
inputs, outputs = {}, {}
for j in range(count):
probability, value = probabilities[i * count + j], v[2 * j + d]
inputs[f"p{j}"], inputs[f"v{j}"] = probability, value
product = _finite(probability * value, "including forbidden zero product")
running = _finite(running + product, "attention running sum")
outputs[f"product{j}"], outputs[f"running{j}"] = product, running
outputs["value"] = running
trace.add(f"{prefix}_mix_{i}_{d}", inputs, outputs)
mixed.append(running)
joined = []
for i, value in enumerate(mixed):
joined.append(value)
trace.add(f"{prefix}_join_{i}", dict(source=value), dict(value=value))
attention = _accumulate_rows(joined, 2, matrices["o"], 2, trace, prefix + "_WO")
residual1 = _residual(features, attention, trace, prefix + "_residual1")
norm2 = _norm(residual1, trace, prefix + "_ln2")
w1, w2 = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0], [gains["f"], 0.0, 0.0, gains["f"], 0.0, 0.0]
preactivation = _two_products(norm2, w1, trace, prefix + "_ffn_hidden", [0.0, 0.0, 0.0], 3)
hidden = []
for i, value in enumerate(preactivation):
activation = value if value > 0.0 else 0.0
hidden.append(activation)
trace.add(f"{prefix}_relu_{i}", dict(preactivation=value), dict(activation=activation))
ffn = _accumulate_rows(hidden, 3, w2, 2, trace, prefix + "_ffn_output", [0.0, 0.0])
output = _residual(residual1, ffn, trace, prefix + "_residual2")
return dict(input=list(features), norm1=norm1, matrices=matrices, Q=q, K=k, V=v,
raw=raw, scores=scores, logits=logits, allowed=allowed, probabilities=probabilities,
mixed=mixed, joined=joined, attention=attention, residual1=residual1,
norm2=norm2, W1=w1, W2=w2, b1=[0.0]*3, b2=[0.0]*2,
preactivation=preactivation, hidden=hidden, ffn=ffn, output=output,
storage=_storage(output, count, 2))
def _evaluate_decoder_mechanics(state, trace, prefix):
features, embedding, positions = [], [], []
table = {97: (1.0, 0.0), 98: (0.0, 1.0), 512: (0.0, 0.0)}
for t in range(2):
token = state[f"token{t}"]
for d in range(2):
looked_up = table[token][d]
position = state["positionScale"] if (t, d) == (1, 1) else 0.0
value = _finite(looked_up + position, "embedding plus position")
embedding.append(looked_up)
positions.append(position)
features.append(value)
trace.add(f"{prefix}_position_{t}_{d}", dict(token=token, embedding=looked_up, position=position), dict(value=value))
block1 = _decoder_block_mechanics(features, {key: state[key + "1"] for key in _GAIN_FIELDS}, trace, prefix + "_block1")
block2 = _decoder_block_mechanics(block1["output"], {key: state[key + "2"] for key in _GAIN_FIELDS}, trace, prefix + "_block2")
readout = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]
bias = [state["biasA"], state["biasB"], state["biasEOS"]]
logits = _two_products(block2["output"], readout, trace, prefix + "_readout", bias, 3)
probabilities, winners = [], []
for t in range(2):
row = logits[3*t:3*t+3]
distribution = _softmax(row, [True, True, True], trace, f"{prefix}_class_row_{t}", positive_zero=False)
probabilities.extend(distribution)
best = 0
for index in range(1, 3):
if row[index] > row[best]:
best = index
winner = dict(index=best, token=_IDS[best], probability=distribution[best])
winners.append(winner)
trace.add(f"{prefix}_winner_{t}", {f"logit{j}": row[j] for j in range(3)}, winner)
return dict(embedding=embedding, positions=positions, features=features, block1=block1, block2=block2,
U=readout, bias=bias, logits=logits, probabilities=probabilities,
winners=winners, next=winners[-1].copy(), storage=_storage(logits, 2, 3))
def check_mechanism():
"""Explicit bounded FIRST checks only; these do NOT admit public records."""
if not __debug__:
raise RuntimeError("Explicit mechanism self-check refuses optimized Python (-O).")
import struct
def words(values):
return [struct.pack(">d", value) for value in values]
default = decoder_state(dict(DEFAULT_IV59))
trace = _MechanismTrace()
result = _evaluate_decoder_mechanics(default, trace, "default")
assert result["features"] == [1.0, 0.0, 1.0, 0.5]
assert words(result["block2"]["input"]) == words(result["block1"]["output"])
assert words(result["block1"]["storage"][0].flat) == words(result["block1"]["output"])
assert result["block1"]["input"] != result["block2"]["input"]
assert [winner["token"] for winner in result["winners"]] == [97, 97]
assert result["next"] == result["winners"][-1] and result["next"] is not result["winners"][-1]
assert result["block1"]["W1"] == [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]
assert result["block1"]["W2"] == [0.5, 0.0, 0.0, 0.5, 0.0, 0.0]
assert result["block2"]["W2"] == [0.25, 0.0, 0.0, 0.25, 0.0, 0.0]
for block in (result["block1"], result["block2"]):
assert block["allowed"] == [True, False, True, True]
assert words(block["probabilities"][:2]) == words([1.0, 0.0])
assert len(block["raw"]) == 4 and len(block["preactivation"]) == 6
assert words(block["preactivation"][2::3]) == words([0.0, 0.0])
assert words(block["hidden"][2::3]) == words([0.0, 0.0])
frames = {identifier: (inputs, outputs) for identifier, inputs, outputs in trace.steps}
first = frames["default_block1_ln1_0_statistics"][1]
assert first["sum"] == 1.0 and first["mean"] == 0.5
assert first["centered0"] == 0.5 and first["centered1"] == -0.5
assert first["variancePlusEpsilon"] == 0.5
second = frames["default_block1_ln1_1_statistics"][1]
assert second["sum"] == 1.5 and second["mean"] == 0.75
assert second["centered0"] == 0.25 and second["centered1"] == -0.25
assert second["variancePlusEpsilon"] == 0.3125
assert frames["default_block1_mix_0_0"][1]["product1"] == 0.0
native_ids = [leaf["id"] for leaf in trace.native]
assert len(set(native_ids)) == len(native_ids)
for leaf in trace.native:
if leaf["kind"] == "sqrt":
assert 0.25 <= leaf["input"] <= 4096.0
expected = math.sqrt(leaf["input"])
else:
assert -256.0 <= leaf["input"] <= 0.0
expected = math.exp(leaf["input"])
assert words([leaf["output"]]) == words([expected])
for layer in (1, 2):
leaf = next(item for item in trace.native if item["id"] == f"default_block{layer}_attention_sqrt")
for i in range(2):
for j in range(2):
copied = frames[f"default_block{layer}_score_{i}_{j}"][0]["divisor"]
assert words([copied]) == words([leaf["output"]])
zero = dict(default, o1=0.0, f1=0.0, o2=0.0, f2=0.0)
zero_trace = _MechanismTrace()
identity = _evaluate_decoder_mechanics(zero, zero_trace, "zero")
for key in ("block1", "block2"):
assert words(identity[key]["output"]) == words([1.0, 0.0, 1.0, 0.5])
assert len(identity[key]["hidden"]) == 6
assert words(identity["logits"]) == words([1.0, 0.0, 0.0, 1.0, 0.5, 0.0])
for t, arguments in enumerate(((0.0, -1.0, -1.0), (0.0, -0.5, -1.0))):
terms = [math.exp(argument) for argument in arguments]
denominator = ((0.0 + terms[0]) + terms[1]) + terms[2]
expected = [term / denominator for term in terms]
assert words(identity["probabilities"][3*t:3*t+3]) == words(expected)
assert len(zero_trace.native) == len(trace.native)
assert len(zero_trace.steps) == len(trace.steps)
# A changed future token cannot change any first-row result in either block.
future_trace = _MechanismTrace()
future = _evaluate_decoder_mechanics(dict(default, token1=98), future_trace, "future")
assert words(future["logits"][:3]) == words(result["logits"][:3])
assert words(future["block2"]["output"][:2]) == words(result["block2"]["output"][:2])
tied = _evaluate_decoder_mechanics(dict(zero, token0=512, token1=512, positionScale=0.0), _MechanismTrace(), "tie")
assert words(tied["logits"]) == words([0.0] * 6)
assert [winner["index"] for winner in tied["winners"]] == [0, 0]
assert [winner["token"] for winner in tied["winners"]] == [97, 97]
for length in (2, 4, 6):
features = [16.0, -16.0] * (length // 2)
gains = dict(q=-1.0, k=1.0, v=-1.0, o=0.0, f=0.0)
captured, checked_gains = _block_inputs(features, gains, "bounded")
block = _decoder_block_mechanics(captured, checked_gains, _MechanismTrace(), "bounded")
assert words(block["output"]) == words(features)
assert len(block["hidden"]) == (length // 2) * 3
captured, gains = _block_inputs([-0.0, 0.0], dict(q=-0.0, k=1, v=1, o=0, f=0), "signed")
assert words([captured[0], gains["q"]]) == words([-0.0, -0.0])
detached = _MechanismTrace()
before, after = dict(x=-0.0), dict(y=1.0)
detached.add("capture", before, after)
before["x"], after["y"] = 8.0, 9.0
assert words([detached.steps[0][1]["x"]]) == words([-0.0])
assert detached.steps[0][2]["y"] == 1.0
signed_trace = _MechanismTrace()
_softmax([-0.0, 0.0, -1.0], [True, True, True], signed_trace, "signed_max")
assert words([signed_trace.steps[0][2]["max"]]) == words([0.0])
assert words([signed_trace.native[0]["input"]]) == words([-0.0])
assert words([signed_trace.native[1]["input"]]) == words([0.0])
# Public binding projects the independent FIRST captures; it never recomputes floats.
def _numeric(value, label):
if type(value) is int:
# Compare before conversion: huge Python integers must not raise OverflowError.
if not -1.7976931348623157e308 <= value <= 1.7976931348623157e308:
raise NumericalFault("NONFINITE", label + " must be an actual finite number.")
return value if -9007199254740991 <= value <= 9007199254740991 else float(value)
if type(value) is not float or not math.isfinite(value):
raise NumericalFault("NONFINITE", label + " must be an actual finite number.")
return value
def _trace_entries(value):
"""Capture trusted items once, then use JavaScript's canonical-index order."""
if type(value) in (list, str):
entries = [(str(index), item) for index, item in enumerate(value)]
elif type(value) in (int, float, bool):
entries = []
else:
entries = list(value.items()) # Preserve trusted observers and their exception identity.
indices, rest = [], []
for key, item in entries:
if type(key) is not str:
raise TypeError("Trusted trace operand keys must be strings.")
index = (bool(key) and len(key) <= 10 and all(c in "0123456789" for c in key)
and (key == "0" or key[0] != "0") and int(key) < 4294967295)
(indices if index else rest).append((key, item))
return sorted(indices, key=lambda pair: int(pair[0])) + rest
class _PublicTrace:
"""Frozen observer container, mutable collector, immutable saved frames."""
__slots__ = ("outputs", "steps", "_ids")
def __init__(self):
object.__setattr__(self, "outputs", {})
object.__setattr__(self, "steps", [])
object.__setattr__(self, "_ids", set())
def __setattr__(self, name, value):
raise TypeError("Frozen trace observer.")
def __delattr__(self, name):
raise TypeError("Frozen trace observer.")
def add(self, identifier, label, equation, explanation, inputs, outputs):
if type(identifier) is not str or not identifier or identifier in self._ids:
raise NumericalFault("INVALID_INPUT", "Trace IDs must be nonempty and unique.")
before = {key: _numeric(value, identifier + ".inputs." + key) for key, value in _trace_entries(inputs)}
after = {key: _numeric(value, identifier + ".outputs." + key) for key, value in _trace_entries(outputs)}
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
frame = _freeze(dict(id=identifier, label=label, equation=equation, explanation=explanation,
inputs=before, outputs=after))
self.steps.append(frame)
self._ids.add(identifier)
for key, value in after.items():
alias = identifier + "_" + key
# The actual ordinary JS object ignores numeric assignments to its inherited setter.
if alias != "__proto__":
self.outputs[alias] = value
_STAT_FIELDS = ("sum", "mean", "centered0", "centered1", "square0", "square1", "squareSum",
"variance", "variancePlusEpsilon", "denominator")
def _tensor(identifier, shape, axes, values, provenance, dtype="float64"):
return dict(id=identifier, shape=list(shape), axes=list(axes), dtype=dtype, values=list(values),
provenance=provenance, precision=0 if dtype == "int32" else 8)
def _native_tensors(prefix, natives):
return [
_tensor(prefix + "_NativeArguments", [len(natives), 2], ["Native", "NativeField"],
[value for leaf in natives for value in (leaf["input"], leaf["output"])],
"Ordered actual native input,output words; IDs and kinds are recorded in texts.nativeIds and texts.nativeKinds. No native evaluation occurs while serializing."),
_tensor(prefix + "_NativeKinds", [len(natives)], ["Native"],
[0 if leaf["kind"] == "sqrt" else 1 for leaf in natives],
"Native kind codes in native occurrence order: sqrt=0, exp=1.", "int32"),
]
def _native_texts(natives):
return dict(nativeIds=[leaf["id"] for leaf in natives], nativeKinds=[leaf["kind"] for leaf in natives],
nativeFields=["input", "output"])
def _norm_binding(mechanism, captures, trace, prefix, stage):
T = len(mechanism["input"]) // 2
private = prefix + ("_ln1" if stage == 1 else "_ln2")
public = prefix + f"_n{stage}"
statistics, centered, normalized = [], [], []
for t in range(T):
before, after = captures[f"{private}_{t}_statistics"]
trace.add(f"{public}_0_{t}_statistics", f"0_{t}: feature-only mean and population variance",
"sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon)",
"Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed.",
dict(before), dict(after))
statistics.extend(after[key] for key in _STAT_FIELDS)
centered.extend((after["centered0"], after["centered1"]))
for d in range(2):
before, after = captures[f"{private}_{t}_feature_{d}"]
trace.add(f"{public}_0_{t}_feature_{d}", f"0_{t}: affine feature {d}",
"normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta",
"The source is the saved centered feature. Gamma and beta may change output mean and variance.",
dict(d=d, **before), dict(after))
normalized.append(after["normalized"])
shape, axes = [1, T, 2], ["B", "T", "D"]
return [
_tensor(public + "_Gamma", [2], ["D"], [1.0, 1.0], "Shared literal feature scales [1,1]."),
_tensor(public + "_Beta", [2], ["D"], [0.0, 0.0], "Shared literal feature offsets [+0,+0]."),
_tensor(public + "_Statistics", [1, T, 10], ["B", "T", "NormStatistic"], statistics,
"Actual sum,mean,centered0,centered1,square0,square1,squareSum,variance,variancePlusEpsilon,denominator in token order."),
_tensor(public + "_Centered", shape, axes, centered, "Actual saved input feature minus feature mean, before division."),
_tensor(public + "_Normalized", shape, axes, normalized, "Actual centered/denominator words before gamma multiplication and beta addition."),
_tensor(public + "_Output", shape, axes, mechanism[f"norm{stage}"], "Actual per-position feature LayerNorm affine output; gamma=[1,1], beta=[0,0], epsilon=1/4."),
]
def _block_natives(captured, prefix, T):
names = {f"{prefix}_ln1_{t}_sqrt": f"{prefix}_n1_0_{t}_sqrt" for t in range(T)}
names[prefix + "_attention_sqrt"] = prefix + "_attn_sqrt"
for i in range(T):
for j in range(i + 1):
names[f"{prefix}_attention_row_{i}_exp_{j}"] = f"{prefix}_attn_exp_0_0_{i}_{j}"
names.update({f"{prefix}_ln2_{t}_sqrt": f"{prefix}_n2_0_{t}_sqrt" for t in range(T)})
return [dict(id=names[leaf["id"]], kind=leaf["kind"], input=leaf["input"], output=leaf["output"])
for leaf in captured]
def _residual_binding(mechanism, captures, trace, prefix, stage, left_id, right_id):
T = len(mechanism["input"]) // 2
identifier = prefix + ("_R1" if stage == 1 else "_Output")
for t in range(T):
for d in range(2):
before, after = captures[f"{prefix}_residual{stage}_{2*t+d}"]
trace.add(f"{prefix}_r{stage}_0_{t}_{d}", f"{identifier}[0,{t},{d}]: skip plus branch", "value=skip+branch",
"The unchanged same-shape primitive performs this actual feature addition. Both residuals are always on; no broadcasting or zero-gain bypass occurs.",
dict(b=0, t=t, d=d, skip=before["left"], branch=before["right"]), dict(after))
return _tensor(identifier, [1, T, 2], ["B", "T", "D"],
mechanism["residual1" if stage == 1 else "output"],
f"Exact named-shape addition of {left_id} and {right_id}; no broadcasting.")
def _bind_block(features, gains, mechanism, captured, trace, prefix):
T = len(features) // 2
captures = {identifier: (before, after) for identifier, before, after in captured.steps}
natives = _block_natives(captured.native, prefix, T)
tensors = [
_tensor(prefix + "_Features", [1, T, 2], ["B", "T", "D"], features,
"Actual captured per-position block features; repeated token IDs do not merge positions."),
_tensor(prefix + "_Gains", [5], ["Gain"], [gains[key] for key in _GAIN_FIELDS],
"Actual q,k,v,o,f gain words; diagonal slots copy these words and off-diagonal slots are literal +0."),
]
tensors.extend(_norm_binding(mechanism, captures, trace, prefix, 1))
a = prefix + "_attn"
setup = dict(B=1, T=T, H=1, Dk=2, Dv=2)
for name in ("x000", "x001", "x010", "x011", "x020", "x021", "x100", "x101", "x110", "x111", "x120", "x121"):
setup[name] = 0.0
for kind in ("q", "k", "v"):
for name in ("000", "001", "010", "011", "100", "101", "110", "111"):
setup["w" + kind + name] = gains[kind] if name in ("000", "101") else 0.0
setup.update(mode=1, valid0=1, valid1=1, valid2=1, shift=0.0)
for name in ("000", "001", "010", "011", "100", "101", "110", "111"):
setup["wo" + name] = gains["o"] if name in ("000", "011") else 0.0
for t in range(T):
for d in range(2):
setup[f"x0{t}{d}"] = mechanism["norm1"][2*t+d]
trace.add(a + "_setup", "Validate every scalar slot, then select active dimensions",
"D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv]",
"All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights.",
setup, dict(B=1, T=T, D=2, H=1, Dk=2, Dv=2))
for kind in ("Q", "K", "V"):
for t in range(T):
for f in range(2):
before, after = captures[f"{prefix}_{kind}_{t}_{f}"]
trace.add(f"{a}_project_{kind}_0_{t}_0_{f}", f"{kind}[0,{t},head 0,feature {f}]: both input contributions",
"product0=x0*w0; product1=x1*w1; value=product0+product1",
"One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.",
dict(b=0, t=t, h=0, f=f, **before),
dict(product0=after["product0"], product1=after["product1"], value=after["value"]))
for kind in ("Q", "K", "V"):
trace.add(f"{a}_reshape_{kind}", f"{kind}: reshape the packed feature axis",
"[B,T,H*F] → [B,T,H,F]; feature=h*F+f",
"Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped.",
dict(B=1, T=T, H=1, F=2, features=2, elements=2*T), dict(elements=2*T))
for t in range(T):
for f in range(2):
before, after = captures[f"{prefix}_{kind}_split_{2*t+f}"]
trace.add(f"{a}_permute_{kind}_0_0_{t}_{f}", f"{kind}: copy [0,{t},0,{f}] to [0,0,{t},{f}]",
"axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]",
"Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.",
dict(b=0, h=0, t=t, f=f, feature=f, sourceOffset=2*t+f, destinationOffset=2*t+f, sourceValue=before["source"]), dict(after))
for i in range(T):
for j in range(T):
before, after = captures[f"{prefix}_score_{i}_{j}"]
trace.add(f"{a}_score_0_0_{i}_{j}", f"Batch 0, head 0: query {i} against key {j}",
"product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
"Matching features are multiplied inside this batch and head only. Dk, not H or T or Dv, supplies the scaling width. Signed scores are not probabilities.",
dict(b=0, h=0, i=i, j=j, Dk=2, divisor=before["divisor"], q0=before["q0"], k0=before["k0"], q1=before["q1"], k1=before["k1"]), dict(after))
for i in range(T):
before, after = captures[f"{prefix}_attention_row_{i}"]
inputs = dict(b=0, h=0, i=i, mode=1, shift=0.0)
inputs.update({f"score{j}": mechanism["scores"][i*T+j] for j in range(T)})
inputs.update({f"allowed{j}": before[f"allowed{j}"] for j in range(T)})
outputs = dict(max=after["max"], denominator=after["denominator"])
outputs.update({f"shifted{j}": after[f"shifted{j}"] for j in range(i+1)})
outputs.update({f"term{j}": after[f"term{j}"] for j in range(T)})
outputs.update({f"p{j}": after[f"p{j}"] for j in range(T)})
trace.add(f"{a}_row_0_0_{i}", f"Batch 0, head 0, query {i}: key-axis stable softmax",
"logit_j=score_j+shift; max=max(allowed logits); term_j=allowed_j?exp(logit_j-max):0; denominator=sum_j term_j; p_j=term_j/denominator",
"Each head has its own probabilities. Key validity is shared across batches and heads; queries remain. Forbidden terms are exactly zero, without an infinity sentinel or invented shifted value. Allowed terms can underflow; a large common shift can change low bits.", inputs, outputs)
for i in range(T):
for f in range(2):
before, after = captures[f"{prefix}_mix_{i}_{f}"]
outputs = {f"product{j}": after[f"product{j}"] for j in range(T)}
outputs.update({f"running{j}": after[f"running{j}"] for j in range(T)})
outputs["value"] = after["value"]
trace.add(f"{a}_head_mix_0_0_{i}_{f}", f"OHeads[0,0,{i},{f}]: this head’s weighted values",
"product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
"Use the real probability row and values in the same head and batch. Compute each product, then immediately accumulate in ascending key order, including actual zero times V for forbidden keys. No averaging across heads or extra division.",
dict(b=0, h=0, i=i, f=f, **before), outputs)
for t in range(T):
for f in range(2):
before, after = captures[f"{prefix}_join_{2*t+f}"]
trace.add(f"{a}_concat_0_{t}_0_{f}", f"Join head 0, feature {f} into C[0,{t},{f}]", "C[b,t,h*Dv+f]=OHeads[b,h,t,f]",
"Copy one actual head output unchanged. Concatenate in head order then within-head feature order; never average heads or mix batches.",
dict(b=0, t=t, h=0, f=f, concatFeature=f, sourceOffset=2*t+f, destinationOffset=2*t+f, sourceValue=before["source"]), dict(after))
for t in range(T):
for d in range(2):
before, after = captures[f"{prefix}_WO_{t}_{d}"]
inputs = dict(b=0, t=t, d=d, c0=before["x0"], w0=before["w0"], c1=before["x1"], w1=before["w1"])
outputs = {key: after[key] for key in ("product0", "product1", "running0", "running1", "value")}
trace.add(f"{a}_output_0_{t}_{d}", f"Y[0,{t},{d}]: explicit output projection",
"product_c=C_c*WO[c,d]; running starts at 0; running_c=previous+product_c; Y=last running sum",
"WO rows preserve named head/feature identity when Dv changes. Every joined feature contributes one recorded product and running sum. Y may be signed; no output softmax, bias, residual, dropout or normalization is added.", inputs, outputs)
tensors.extend(_attention_tensors(mechanism, a, T))
tensors.append(_residual_binding(mechanism, captures, trace, prefix, 1, prefix + "_Features", a + "_Y"))
tensors.extend(_norm_binding(mechanism, captures, trace, prefix, 2))
tensors.extend(_ffn_binding(mechanism, captures, trace, prefix, T))
output = _residual_binding(mechanism, captures, trace, prefix, 2, prefix + "_R1", prefix + "_ffn_F")
tensors.extend([output, *_native_tensors(prefix, natives)])
texts = dict(**_native_texts(natives), gainFields=list(_GAIN_FIELDS), normStatisticFields=list(_STAT_FIELDS),
featurePolicy="One batch, one to three positions, two features per position. Block output keeps B,T,D axes and feeds the next block directly; it is never a token lookup.",
kernelPolicy="Unchanged p07 featureNorm, p06 projectHeads/attendHeads/joinHeads, p07 feedForward and sameShapeAdd perform all scalar arithmetic. All inactive attention state slots are explicit +0 except validity=1; active dimensions are B1,H1,Dk2,Dv2,mode1,shift+0. Every matrix coordinate and all three FFN hidden coordinates are computed at every gain.",
nativePolicy="Occurrence order is LN1 sqrt by token, one sqrt(Dk), allowed attention exp by query/key, then LN2 sqrt by token. LN arguments/outputs and attention divisor/terms copy actual primitive records. Old stableSoftmax trace shifted values repeat the same subtraction of immutable logit and max operands as its exp arguments: functional reconstruction, not a physical instruction trace. Masked cells have no exp occurrence. No native math occurs in serialization.",
zeroPolicy="Feature words, gain words, arithmetic results and every copy retain binary64 WORD, including allowed -0. Diagonal weights copy gains; every off-diagonal or inactive weight is literal +0. Dimensions, indices, mask decisions and native kind codes use VALUE.",
limitsPolicy="Forward-only authored toy. No differentiated loss, training, optimizer, dropout, sampling, KV cache, physical timing or production-model claim. Public input features are bounded [-16,16], gains [-1,1]; epsilon=1/4, gamma=[1,1], beta=[0,0], width-three ReLU FFN.")
return _freeze(dict(features=features, gains=gains, output=output, natives=natives, tensors=tensors, texts=texts))
def _attention_tensors(m, prefix, T):
shape, axes = [1, T, 2], ["B", "T", "D"]
result = [_tensor(prefix + "_X", shape, axes, m["norm1"], "Active token rows; D=2 input features always retained.")]
for kind, feature, provenance in (
("Q", "QueryFeature", "Query columns packed by h*Dk+f from wq{d}{h}{f}."),
("K", "KeyFeature", "Key columns packed by h*Dk+f from wk{d}{h}{f}."),
("V", "ValueFeature", "Value columns packed by h*Dv+f from wv{d}{h}{f}.")):
result.append(_tensor(prefix + "_W" + kind, [2, 2], ["D", feature], m["matrices"][kind.lower()], provenance))
for kind, feature, provenance in (
("Q", "QueryFeature", "XWQ; each packed coordinate has two products and one sum."),
("K", "KeyFeature", "XWK; each packed coordinate has two products and one sum."),
("V", "ValueFeature", "XWV; values are projected separately from queries and keys.")):
result.append(_tensor(prefix + "_" + kind + "Concat", shape, ["B", "T", feature], m[kind], provenance))
for kind in ("Q", "K", "V"):
width = "Dv" if kind == "V" else "Dk"
result.extend([
_tensor(prefix + "_" + kind + "Split", [1, T, 1, 2], ["B", "T", "H", width], m[kind],
kind + "Concat reshaped without changing flat order; feature=h*F+f."),
_tensor(prefix + "_" + kind + "Heads", [1, 1, T, 2], ["B", "H", "T", width], m[kind],
kind + "Split permuted by axes [0,2,1,3]; every copied source/destination offset is traced."),
])
shape, axes = [1, 1, T, T], ["B", "H", "Query", "Key"]
for key, provenance, dtype in (
("raw", "Separate QHeads KHeads transpose products within every batch and head.", "float64"),
("scores", "raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.", "float64"),
("allowed", "Causal and/or valid-key mask; shared validity across B and H; every query retained.", "bool"),
("logits", "Finite score+shift, including forbidden cells; mask applied separately.", "float64"),
("probabilities", "Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.", "float64")):
result.append(_tensor(prefix + "_" + key, shape, axes, m[key], provenance, dtype))
result.extend([
_tensor(prefix + "_OHeads", [1, 1, T, 2], ["B", "H", "Query", "Dv"], m["mixed"], "Actual per-head P times VHeads; every product and running sum is traced."),
_tensor(prefix + "_C", [1, T, 2], ["B", "T", "JoinedValue"], m["joined"], "OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged."),
_tensor(prefix + "_WO", [2, 2], ["JoinedValue", "D"], m["matrices"]["o"], "wo{h}{f}{d} packed in h,f,d order, preserving parameter identity."),
_tensor(prefix + "_Y", [1, T, 2], ["B", "T", "D"], m["attention"], "Y=C WO, summing products in ascending joined-feature order from zero; no normalization."),
])
return result
def _ffn_binding(m, captures, trace, prefix, T):
f = prefix + "_ffn"
for t in range(T):
for hidden in range(3):
before, after = captures[f"{prefix}_ffn_hidden_{t}_{hidden}"]
trace.add(f"{f}_hidden_0_{t}_{hidden}", f"Hidden affine [0,{t},{hidden}]",
"product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
"The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs.",
dict(b=0, t=t, m=hidden, **before),
dict(product0=after["product0"], product1=after["product1"], sum=after["sum"], preactivation=after["value"]))
for t in range(T):
for hidden in range(3):
before, after = captures[f"{prefix}_relu_{3*t+hidden}"]
trace.add(f"{f}_relu_0_{t}_{hidden}", f"ReLU [0,{t},{hidden}]", "activation=max(0,preactivation)",
"ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.",
dict(b=0, t=t, m=hidden, **before), dict(after))
for t in range(T):
for d in range(2):
before, after = captures[f"{prefix}_ffn_output_{t}_{d}"]
inputs = dict(b=0, t=t, d=d)
for hidden in range(3):
inputs[f"h{hidden}"] = before[f"x{hidden}"]
inputs[f"w{hidden}"] = before[f"w{hidden}"]
inputs["bias"] = before["bias"]
outputs = {f"product{hidden}": after[f"product{hidden}"] for hidden in range(3)}
outputs.update({f"running{hidden}": after[f"running{hidden}"] for hidden in range(3)})
outputs.update(sum=after["running2"], value=after["value"])
trace.add(f"{f}_output_0_{t}_{d}", f"FFN output [0,{t},{d}]",
"product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
"Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN.", inputs, outputs)
return [
_tensor(f + "_W1", [2, 3], ["D", "HiddenFeature"], m["W1"], "Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features."),
_tensor(f + "_b1", [3], ["HiddenFeature"], m["b1"], "Shared hidden bias, added after the two products."),
_tensor(f + "_Z", [1, T, 3], ["B", "T", "HiddenFeature"], m["preactivation"], "Hidden preactivations X W1+b1; no batch or token mixing."),
_tensor(f + "_Hidden", [1, T, 3], ["B", "T", "HiddenFeature"], m["hidden"], "ReLU(Z)=max(0,Z), before the second affine layer."),
_tensor(f + "_W2", [3, 2], ["HiddenFeature", "D"], m["W2"], "Shared hidden-to-output weights, f2{m}{d}."),
_tensor(f + "_b2", [2], ["D"], m["b2"], "Shared output bias, added after all three running sums."),
_tensor(f + "_F", [1, T, 2], ["B", "T", "D"], m["ffn"], "ReLU(X W1+b1) W2+b2, independently per token with shared parameters."),
]
def decoder_block(features, gains, trace, prefix):
"""Adopted helper, scalar FIRST plus complete metadata/copy projection."""
features, gains = _block_inputs(features, gains, prefix)
captured = _MechanismTrace()
mechanism = _decoder_block_mechanics(features, gains, captured, prefix)
return _bind_block(features, gains, mechanism, captured, trace, prefix)
def _head_binding(mechanism, captures, captured_natives, trace, prefix):
logits, probabilities = mechanism["logits"], mechanism["probabilities"]
maxima, shifted, terms, denominators, readout = [], [], [], [], []
for t in range(2):
for c in range(3):
before, after = captures[f"{prefix}_readout_{t}_{c}"]
trace.add(f"{prefix}_readout_{t}_{c}", f"Readout at position {t}, class {c}",
"product0=x0*u0; product1=x1*u1; sum=product0+product1; logit=sum+bias",
"Both final block features contribute through actual products for every class, including zero weights. Add that class bias last. U is hand-set, not trained.",
dict(t=t, c=c, x0=before["x0"], x1=before["x1"], u0=before["w0"], u1=before["w1"], bias=before["bias"]),
dict(product0=after["product0"], product1=after["product1"], sum=after["sum"], logit=after["value"]))
readout.extend((after["product0"], after["product1"], after["sum"], after["value"]))
for t in range(2):
before, after = captures[f"{prefix}_class_row_{t}"]
maximum = after["max"]
maxima.append(maximum)
trace.add(f"{prefix}_classMax_{t}", f"Stable class maximum at position {t}",
"max=logit0; scan class1,class2; replace only on strict greater",
"The maximum is selected from the actual saved logits. Class order is a,b,EOS with ascending IDs 97,98,512.",
{f"logit{c}": logits[3*t+c] for c in range(3)}, dict(max=maximum))
for c in range(3):
argument, term = after[f"shifted{c}"], after[f"term{c}"]
shifted.append(argument)
terms.append(term)
trace.add(f"{prefix}_classExp_{t}_{c}", f"Stable class exponential at position {t}, class {c}",
"shifted=logit-max; term=exp(shifted)",
"Save the exact argument and output at this native exp call. The argument is nonpositive; there is no logarithm or hidden loss.",
dict(logit=logits[3*t+c], max=maximum), dict(shifted=argument, term=term))
for c in range(3):
previous = 0.0 if c == 0 else after[f"running{c-1}"]
trace.add(f"{prefix}_classSum_{t}_{c}", f"Ordered class denominator at position {t}, class {c}", "sum=previous+term",
"Start from literal +0 and immediately add terms in class order 0,1,2. Keep this actual running sum; do not simplify equal terms.",
dict(previous=previous, term=after[f"term{c}"]), dict(sum=after[f"running{c}"]))
denominators.append(after["denominator"])
for c in range(3):
trace.add(f"{prefix}_classProbability_{t}_{c}", f"Class probability at position {t}, class {c}", "probability=term/denominator",
"Divide the saved class term by the final saved ordered denominator. Display rounding is never an operand.",
dict(term=after[f"term{c}"], denominator=after["denominator"]), dict(probability=probabilities[3*t+c]))
winner = mechanism["winners"][t]
inputs = {f"logit{c}": logits[3*t+c] for c in range(3)}
inputs.update({f"probability{c}": probabilities[3*t+c] for c in range(3)})
trace.add(f"{prefix}_argmax_{t}", f"Greedy recommendation from position {t}",
"index=first maximum logit; tokenId=IDS[index]; probability=probabilities[index]",
"Strict-greater scanning retains the smallest actual token ID on an exact logit tie. This row recommends the next token after this observed prefix; it does not append it.",
inputs, dict(index=winner["index"], tokenId=winner["token"], probability=winner["probability"]))
natives = []
for leaf in captured_natives:
# Only readout leaves are supplied; each name is a direct occurrence copy.
suffix = leaf["id"].removeprefix(prefix + "_class_row_")
t, c = suffix.split("_exp_")
natives.append(dict(id=f"{prefix}_readout_exp_{t}_{c}", kind=leaf["kind"], input=leaf["input"], output=leaf["output"]))
return dict(readout=readout, maxima=maxima, shifted=shifted, terms=terms, denominators=denominators, natives=natives)
def evaluate_decoder(value, trace, prefix):
"""All actual scalar values are captured before metadata projection."""
state = decoder_state(value)
_prefix(prefix)
captured = _MechanismTrace()
mechanism = _evaluate_decoder_mechanics(state, captured, prefix)
captures = {identifier: (before, after) for identifier, before, after in captured.steps}
for t in range(2):
token_id = state[f"token{t}"]
row = _IDS.index(token_id)
for d in range(2):
before, after = captures[f"{prefix}_position_{t}_{d}"]
trace.add(f"{prefix}_embedding_{t}_{d}", f"Observed position {t}, feature {d}: lookup then add position", "feature=embedding+position",
"Look up this observed token ID in the authored E table and add the displayed absolute-position coordinate. An observed EOS has its explicit zero row; no token is generated or silently stopped.",
dict(t=t, d=d, tokenId=token_id, row=row, embedding=before["embedding"], position=before["position"]), dict(feature=after["value"]))
blocks = []
for layer in (1, 2):
block_prefix = prefix + f"_block{layer}"
block_capture = _MechanismTrace()
block_capture.steps = [frame for frame in captured.steps if frame[0].startswith(block_prefix + "_")]
block_capture.native = [leaf for leaf in captured.native if leaf["id"].startswith(block_prefix + "_")]
m = mechanism[f"block{layer}"]
gains = {key: state[key + str(layer)] for key in _GAIN_FIELDS}
blocks.append(_bind_block(m["input"], gains, m, block_capture, trace, block_prefix))
block1, block2 = blocks
head = _head_binding(mechanism, captures, [leaf for leaf in captured.native if leaf["id"].startswith(prefix + "_class_row_")], trace, prefix)
natives = [*block1["natives"], *block2["natives"], *head["natives"]]
indices = [winner["index"] for winner in mechanism["winners"]]
ids = [winner["token"] for winner in mechanism["winners"]]
selected = [winner["probability"] for winner in mechanism["winners"]]
tensors = _evaluation_tensors(state, mechanism, block1, block2, head, natives, prefix, indices, ids, selected)
texts = _evaluation_texts(natives)
return _freeze(dict(state=state, features=mechanism["features"], block1=block1, block2=block2,
logits=mechanism["logits"], probabilities=mechanism["probabilities"], argmaxIndices=indices,
argmaxIds=ids, selectedProbabilities=selected, nextTokenId=ids[1], nextTokenProbability=selected[1],
natives=natives, tensors=tensors, texts=texts))
def _evaluation_tensors(state, m, block1, block2, head, natives, p, indices, ids, selected):
return [
_tensor(p + "_Raw", [16], ["RawField"], [state[key] for key in _FIELDS], "Captured raw16 in declared field order; token0/token1 cells are integer VALUE, all other cells binary64 WORD."),
_tensor(p + "_TokenIds", [1, 2], ["B", "T"], [state["token0"], state["token1"]], "Both observed input token IDs; EOS is an ordinary explicit lookup row here.", "int32"),
_tensor(p + "_VocabularyIds", [3], ["Vocab"], _IDS, "Class order and strict-tie ID order: a=97,b=98,EOS=512.", "int32"),
_tensor(p + "_E", [3, 2], ["Vocab", "D"], [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], "Authored embedding rows [1,0],[0,1],[0,0] for a,b,EOS."),
_tensor(p + "_Positions", [1, 2, 2], ["B", "T", "D"], m["positions"], "Literal P0=[+0,+0], P1=[+0,positionScale]; disclosed absolute position addition."),
_tensor(p + "_Embeddings", [1, 2, 2], ["B", "T", "D"], m["embedding"], "Actual E lookup copies before position addition."),
_tensor(p + "_Features", [1, 2, 2], ["B", "T", "D"], m["features"], "Actual lookup plus position sums; first block input, retained on its residual skip."),
*block1["tensors"], *block2["tensors"],
_tensor(p + "_U", [2, 3], ["D", "Vocab"], m["U"], "Authored feature-last readout rows [1,0,0],[0,1,0]."),
_tensor(p + "_Bias", [3], ["Vocab"], m["bias"], "Actual biasA,biasB,biasEOS words, added after both feature products."),
_tensor(p + "_Readout", [1, 2, 3, 4], ["B", "T", "Vocab", "ReadoutField"], head["readout"], "Actual product0,product1,sum,logit per position and class."),
_tensor(p + "_Logits", [1, 2, 3], ["B", "T", "Vocab"], m["logits"], "Actual final readout logits before stable class softmax."),
_tensor(p + "_ClassMaxima", [1, 2], ["B", "T"], head["maxima"], "Actual selected maximum logit per observed position."),
_tensor(p + "_ClassShifted", [1, 2, 3], ["B", "T", "Vocab"], head["shifted"], "Actual direct exp arguments, each saved once as logit minus row maximum."),
_tensor(p + "_ClassTerms", [1, 2, 3], ["B", "T", "Vocab"], head["terms"], "Actual native exp outputs; no log native exists in this family."),
_tensor(p + "_ClassDenominators", [1, 2], ["B", "T"], head["denominators"], "Final ordered +0 then term0,term1,term2 running sums."),
_tensor(p + "_Probabilities", [1, 2, 3], ["B", "T", "Vocab"], m["probabilities"], "Actual term/final denominator probabilities at every observed position."),
_tensor(p + "_ArgmaxIndices", [1, 2], ["B", "T"], indices, "Smallest class index on exact actual-logit ties.", "int32"),
_tensor(p + "_ArgmaxIds", [1, 2], ["B", "T"], ids, "Actual selected token IDs in observed-position order.", "int32"),
_tensor(p + "_SelectedProbabilities", [1, 2], ["B", "T"], selected, "Unchanged copies of the actual selected class probabilities."),
*_native_tensors(p, natives),
]
def _evaluation_texts(natives):
return dict(**_native_texts(natives), rawFields=list(_FIELDS), vocabularyLabels=["a", "b", "EOS"],
gainFields=list(_GAIN_FIELDS), normStatisticFields=list(_STAT_FIELDS), readoutFields=["product0", "product1", "sum", "logit"],
inputPolicy="Exact own-data raw16 on a plain/null-prototype object: all descriptors, then all actual finite numbers, then domains in raw order, then ASCII prefix. Tokens are integer members {97,98,512}; positionScale [0,1]; ten gains [-1,1]; three biases [-2,2]. No coercion, clamping, partial defaults or skipped inactive computation.",
architecturePolicy="B1,T2,D2,H1,Dk2,Dv2. Look up both observed IDs, add absolute positions, compute two distinct pre-norm causal blocks on actual per-position features, then compute all three readout logits and class probabilities at both positions. Block2 consumes block1 output words, never token IDs or re-embedded values.",
headPolicy="U rows [1,0,0],[0,1,0]; each logit uses two products, sum, bias last. Stable class softmax saves exp arguments/outputs, ordered +0 term sum and divisions. Greedy strict-greater scan over ascending IDs keeps the smallest token ID on exact logit ties. Only the last observed row supplies nextTokenId and nextTokenProbability; no token is appended.",
nativePolicy="Both complete block-native ledgers precede output-head exp occurrences in token/class order. LN sqrt and attention sqrt(Dk) save actual outputs. Old attention shifted arguments repeat the identical immutable-operand subtraction used internally by stableSoftmax: functional word reconstruction, not a physical instruction trace. Output-head exp arguments are captured directly. No log, sin, cos or native call during serialization.",
numericPolicy="Separate finite binary64 scalar operations retain primitive order without contraction or reassociation. Every numeric operand/result/copy uses WORD including admitted -0, except explicit token IDs, indices, dimensions, mask decisions, kind codes and counts use VALUE. Display precision8 is presentation only. Root Raw token cells are VALUE and its other fourteen cells are WORD.",
nativeAdmissionPolicy="Declared future independent policy: positive finite sqrt outputs with argument [1/4,4096] and exp outputs with argument [-256,0], at most four ordered binary64 word steps from an independently isolated RN-even reference. Admit each complete TS/canonical record separately, then require exact scalar/copy words inside it. This is neither bit-exact libm parity nor validation evidence.",
limitsPolicy="Authored forward-only toy with hand-set embeddings, gains, norms, FFN and readout. Two blocks are neither two generated tokens nor two optimizer steps. An observed EOS is an input embedding; generated-EOS stopping is not implemented. No loss, gradient, training, sampling, cache, latency, production intelligence or physical-trace claim. Runtime validation remains deferred under the FluxGeo hold.",
provenance="Owner-chosen IV59 toy within the human full-book source authorization; these concrete model choices are not attributed to the human or the dossier. No external model or dataset.")
def _check_native_copies(natives, tensors, texts, frames, prefix):
if not __debug__:
raise RuntimeError("Explicit native-copy self-check refuses optimized Python (-O).")
import struct
def word(value):
return struct.pack(">d", value)
table = {record["id"]: record for record in tensors}
arguments = table[prefix + "_NativeArguments"]["values"]
kinds = table[prefix + "_NativeKinds"]["values"]
assert texts["nativeFields"] == ["input", "output"]
assert texts["nativeIds"] == [leaf["id"] for leaf in natives]
assert texts["nativeKinds"] == [leaf["kind"] for leaf in natives]
assert len(arguments) == 2 * len(natives) and len(kinds) == len(natives)
for n, leaf in enumerate(natives):
assert tuple(leaf) == ("id", "kind", "input", "output")
assert word(arguments[2*n]) == word(leaf["input"])
assert word(arguments[2*n+1]) == word(leaf["output"])
assert kinds[n] == (0 if leaf["kind"] == "sqrt" else 1)
identifier = leaf["id"]
if leaf["kind"] == "sqrt" and "_attn_sqrt" not in identifier:
statistics_id = identifier.removesuffix("_sqrt") + "_statistics"
frame = frames[statistics_id]
assert word(leaf["input"]) == word(frame["outputs"]["variancePlusEpsilon"])
assert word(leaf["output"]) == word(frame["outputs"]["denominator"])
norm_prefix, t = identifier.removesuffix("_sqrt").rsplit("_0_", 1)
row = table[norm_prefix + "_Statistics"]["values"][10*int(t):10*int(t)+10]
assert word(row[8]) == word(leaf["input"]) and word(row[9]) == word(leaf["output"])
for d in range(2):
copied = frames[f"{norm_prefix}_0_{t}_feature_{d}"]["inputs"]["denominator"]
assert word(copied) == word(leaf["output"])
elif leaf["kind"] == "sqrt":
attention = identifier.removesuffix("_sqrt")
assert leaf["input"] == 2.0
for key, frame in frames.items():
if key.startswith(attention + "_score_"):
assert word(frame["inputs"]["Dk"]) == word(leaf["input"])
assert word(frame["inputs"]["divisor"]) == word(leaf["output"])
elif "_readout_exp_" in identifier:
evaluation, coordinates = identifier.split("_readout_exp_")
t, c = (int(index) for index in coordinates.split("_"))
frame = frames[f"{evaluation}_classExp_{t}_{c}"]
assert word(frame["outputs"]["shifted"]) == word(leaf["input"])
assert word(frame["outputs"]["term"]) == word(leaf["output"])
assert word(table[evaluation + "_ClassShifted"]["values"][3*t+c]) == word(leaf["input"])
assert word(table[evaluation + "_ClassTerms"]["values"][3*t+c]) == word(leaf["output"])
assert word(frames[f"{evaluation}_classSum_{t}_{c}"]["inputs"]["term"]) == word(leaf["output"])
assert word(frames[f"{evaluation}_classProbability_{t}_{c}"]["inputs"]["term"]) == word(leaf["output"])
else:
attention, coordinates = identifier.split("_exp_0_0_")
i, j = (int(index) for index in coordinates.split("_"))
frame = frames[f"{attention}_row_0_0_{i}"]
assert frame["inputs"][f"allowed{j}"] == 1
assert word(frame["outputs"][f"shifted{j}"]) == word(leaf["input"])
assert word(frame["outputs"][f"term{j}"]) == word(leaf["output"])
def check_public():
"""Explicit complete helper/native/copy checks; not an independent oracle."""
if not __debug__:
raise RuntimeError("Explicit public-helper self-check refuses optimized Python (-O).")
import struct
def words(values):
return [struct.pack(">d", value) for value in values]
ordered = decoder_trace()
operands = {"2": -0.0, "1": 1.0, "01": 2.0, "4294967295": 3.0, "4294967294": 4.0}
ordered.add("order", "", "", "", operands, operands)
expected_keys = ["1", "2", "4294967294", "01", "4294967295"]
assert list(ordered.steps[0]["inputs"]) == list(ordered.steps[0]["outputs"]) == expected_keys
assert list(ordered.outputs) == ["order_" + key for key in expected_keys]
assert words([ordered.steps[0]["inputs"]["2"]]) == words([-0.0])
reused = decoder_trace()
reused.add("frozen", "", "", "", ordered.steps[0]["inputs"], ordered.steps[0]["outputs"])
assert list(reused.steps[0]["inputs"]) == expected_keys
assert words(reused.steps[0]["inputs"].values()) == words(ordered.steps[0]["inputs"].values())
proto = decoder_trace()
proto.add("__proto", "", "", "", {}, {"_": 1.0})
assert proto.outputs == {} and proto.steps[0]["outputs"] == {"_": 1.0}
proto.add("ordinary", "", "", "", {}, {"__proto__": 2.0})
assert proto.outputs == {"ordinary___proto__": 2.0}
large = decoder_trace()
large.add("large", "", "", "", {"x": 2**53 + 1, "y": 10**300}, {"z": -0.0})
assert words(large.steps[0]["inputs"].values()) == words([9007199254740992.0, 1e300])
for huge in (10**400, -(10**400)):
for side in ("inputs", "outputs"):
try:
large.add("bad", "", "", "", {"x": huge} if side == "inputs" else {}, {"x": huge} if side == "outputs" else {})
except NumericalFault as error:
assert error.code == "NONFINITE" and str(error) == "bad." + side + ".x must be an actual finite number."
else:
raise AssertionError("Huge trace integer must fail before conversion.")
assert len(large.steps) == 1
gains = dict(q=-0.0, k=0.5, v=-1.0, o=0.0, f=0.0)
for T, frame_count, alias_count, native_count in ((1, 42, 127, 4), (2, 82, 266, 8), (3, 124, 426, 13)):
features = [16.0, -16.0] * T
trace = decoder_trace()
block = decoder_block(features, gains, trace, "bounded")
assert tuple(block) == ("features", "gains", "output", "natives", "tensors", "texts")
assert len(trace.steps) == frame_count and len(trace.outputs) == alias_count
assert len(block["tensors"]) == 47 and len(block["natives"]) == native_count
assert len(block["texts"]) == 10 and tuple(block["gains"]) == _GAIN_FIELDS
assert block["output"]["id"] == "bounded_Output"
assert block["output"] == block["tensors"][44]
assert words(block["output"]["values"]) == words(features)
assert words(block["features"]) == words(features)
features[0] = 3.0
assert block["features"][0] == 16.0
table = {record["id"]: record for record in block["tensors"]}
frames = {frame["id"]: frame for frame in trace.steps}
assert len(table) == 47 and len(frames) == frame_count
assert tuple(block["texts"]) == ("nativeIds", "nativeKinds", "nativeFields", "gainFields", "normStatisticFields",
"featurePolicy", "kernelPolicy", "nativePolicy", "zeroPolicy", "limitsPolicy")
for record in block["tensors"]:
assert tuple(record) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
assert len(record["shape"]) == len(record["axes"])
assert record["precision"] == (0 if record["dtype"] == "int32" else 8)
mask = table["bounded_attn_allowed"]
assert mask["dtype"] == "bool" and mask["precision"] == 8
assert mask["values"] == [j <= i for i in range(T) for j in range(T)]
assert all(type(value) is bool for value in mask["values"])
assert words(table["bounded_attn_WQ"]["values"]) == words([-0.0, 0.0, 0.0, -0.0])
for stage in (1, 2):
p = f"bounded_n{stage}"
for t in range(T):
statistics = frames[f"{p}_0_{t}_statistics"]["outputs"]
assert words(table[p + "_Statistics"]["values"][10*t:10*t+10]) == words(statistics.values())
for d in range(2):
frame = frames[f"{p}_0_{t}_feature_{d}"]
assert words([frame["inputs"]["source"]]) == words([table[p + "_Centered"]["values"][2*t+d]])
assert words([frame["outputs"]["normalized"]]) == words([table[p + "_Normalized"]["values"][2*t+d]])
assert words([frame["outputs"]["value"]]) == words([table[p + "_Output"]["values"][2*t+d]])
for i in range(T):
row = frames[f"bounded_attn_row_0_0_{i}"]["outputs"]
for j in range(T):
probability = table["bounded_attn_probabilities"]["values"][i*T+j]
assert words([probability]) == words([row[f"p{j}"]])
if j > i:
assert f"shifted{j}" not in row
assert words([probability, row[f"term{j}"]]) == words([0.0, 0.0])
for d in range(2):
mixed = frames[f"bounded_attn_head_mix_0_0_{i}_{d}"]["outputs"]["value"]
assert words([mixed]) == words([table["bounded_attn_OHeads"]["values"][2*i+d]])
assert words([mixed]) == words([table["bounded_attn_C"]["values"][2*i+d]])
for suffix, source in (("r1", "R1"), ("r2", "Output")):
assert words([frames[f"bounded_{suffix}_0_{i}_{d}"]["outputs"]["value"]]) == words([table["bounded_" + source]["values"][2*i+d]])
for hidden in range(3):
index = 3*i+hidden
assert words([frames[f"bounded_ffn_hidden_0_{i}_{hidden}"]["outputs"]["preactivation"]]) == words([table["bounded_ffn_Z"]["values"][index]])
assert words([frames[f"bounded_ffn_relu_0_{i}_{hidden}"]["outputs"]["activation"]]) == words([table["bounded_ffn_Hidden"]["values"][index]])
for frame in trace.steps:
assert tuple(frame) == ("id", "label", "equation", "explanation", "inputs", "outputs")
for key, value in frame["outputs"].items():
assert words([value]) == words([trace.outputs[frame["id"] + "_" + key]])
_check_native_copies(block["natives"], block["tensors"], block["texts"], frames, "bounded")
try:
block["output"]["values"][0] = 0.0
except TypeError:
pass
else:
raise AssertionError("Saved tensor must be immutable.")
trace = decoder_trace()
evaluated = evaluate_decoder(DEFAULT_IV59, trace, "observed")
assert tuple(evaluated) == ("state", "features", "block1", "block2", "logits", "probabilities", "argmaxIndices", "argmaxIds",
"selectedProbabilities", "nextTokenId", "nextTokenProbability", "natives", "tensors", "texts")
assert len(trace.steps) == 196 and len(trace.outputs) == 592
assert len(evaluated["tensors"]) == 115 and len(evaluated["texts"]) == 16
assert sum(len(record["values"]) for record in evaluated["tensors"]) == 640
assert words(evaluated["block2"]["features"]) == words(evaluated["block1"]["output"]["values"])
assert evaluated["argmaxIds"] == [97, 97]
assert evaluated["nextTokenId"] == evaluated["argmaxIds"][1]
assert words([evaluated["nextTokenProbability"]]) == words([evaluated["selectedProbabilities"][1]])
frames = {frame["id"]: frame for frame in trace.steps}
_check_native_copies(evaluated["natives"], evaluated["tensors"], evaluated["texts"], frames, "observed")
assert [frame["id"] for frame in trace.steps if "_readout_" in frame["id"]] == [f"observed_readout_{t}_{c}" for t in range(2) for c in range(3)]
assert next(i for i, frame in enumerate(trace.steps) if "_classMax_" in frame["id"]) > next(i for i, frame in enumerate(trace.steps) if frame["id"] == "observed_readout_1_2")
# A fabricated logit row isolates strict-FIRST head max, even if unreachable by a particular preset.
for first, second in ((-0.0, 0.0), (0.0, -0.0)):
capture = _MechanismTrace()
_softmax([first, second, -1.0], [True]*3, capture, "head", positive_zero=False)
assert words([capture.steps[0][2]["max"]]) == words([first])
# Serialization must consume captures even when native evaluation is disabled.
source = [1.0, 0.0, 1.0, 0.5]
capture = _MechanismTrace()
mechanism = _decoder_block_mechanics(source, gains, capture, "serialized")
saved_sqrt, saved_exp = math.sqrt, math.exp
def forbidden(argument):
raise AssertionError("Native evaluation during serialization.")
try:
math.sqrt = math.exp = forbidden
projected = _bind_block(source, gains, mechanism, capture, decoder_trace(), "serialized")
assert len(projected["tensors"]) == 47
finally:
math.sqrt, math.exp = saved_sqrt, saved_exp
2. New scalar mechanism and saved records: variants_reference.py
Read variant_state and _preflight first: they capture all inputs, enforce their domains, validate the prefix and reject any empty allowed row before numerical work. In _scalar_first, qsource and kvsource select the origins, while tq and tk keep the two lengths separate. The projection loop records two products and their direct sum for each coordinate. _ScalarGraph.binary records each elementary operation, and _ScalarGraph.native captures the actual square-root or exponential occurrence. The score loop includes forbidden cells; the softmax loop omits only their shifts and exponentials. Separate feature accumulators then record every weighted product and updated sum in i,j,d order.
Next, evaluate_variant passes that single private capture to _bind_variant. The binding copies saved words into the public frames, tensors, texts and native ledger; it does not recompute floating-point results. derive_iv60 appends the final summary and scalar aliases. Its returned output coordinates match the saved variant_Output tensor. The labels and offsets in the lab come from those same declared record families.
Public observer callbacks (trace.add) occur after the complete private scalar and native capture, then in the declared frame order. Consequently an observer, duplicate-ID or collector-cap failure can occur after numerical work that the TypeScript path would not yet have performed. The reference compares saved functional results; it does not attest identical physical callback timing. Raw, domain, prefix and whole-mask failures still precede both private numerical work and observer callbacks. Likewise, the TypeScript exponential-input witness repeats the identical saved score-minus-maximum subtraction rather than physically intercepting the native call. Neither serialization path evaluates a new exponential to manufacture evidence.
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.
"""IV60 independent scalar FIRST with owner-adopted public bindings.
Private FIRST predates producer/oracle reads; bindings use signed owner adoption.
All execution/checks UNRUN. NumPy is used only by generic indexed storage.
"""
import importlib.util
import math
from pathlib import Path
import sys
def _load_support():
path = Path(__file__).resolve().with_name("decoder_reference.py")
name = "_book_iv_p15_decoder_reference"
if name in sys.modules:
module = sys.modules[name]
if Path(module.__file__).resolve() != path:
raise ImportError("IV60 support module identity collision.")
return module
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError("IV60 support loader unavailable.")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
try:
spec.loader.exec_module(module)
except BaseException:
if sys.modules.get(name) is module:
del sys.modules[name]
raise
return module
_support = _load_support()
NumericalFault = _support.NumericalFault
_freeze = _support._freeze
_capture_record = _support._capture_record
_prefix = _support._prefix
variant_trace = _support.decoder_trace
DEFAULT_IV60 = _freeze(dict(
mode=2, query00=1, query01=0, query10=0, query11=1,
memory00=1, memory01=0, memory10=0, memory11=1, memory20=1, memory21=1,
q=1, k=1, v=1, key0=1, key1=1, key2=1))
_FIELDS = tuple(DEFAULT_IV60)
_SOURCES = _FIELDS[1:11]
_GAINS = ("q", "k", "v")
_KEYS = ("key0", "key1", "key2")
_EMPTY_REASON = "This query has no allowed keys; no probability distribution exists."
def variant_state(value):
raw = _capture_record(value, _FIELDS, "state")
# Every finite slot was captured before even the first domain comparison.
for key in _FIELDS:
item = raw[key]
if key == "mode":
valid = item in (0, 1, 2)
reason = "mode must be an integer in {0,1,2}."
elif key in _KEYS:
valid = item in (0, 1)
reason = key + " must be an integer in {0,1}."
else:
bound = 4 if key in _SOURCES else 1
valid = -bound <= item <= bound
reason = f"{key} must be between {-bound} and {bound}."
if not valid:
raise NumericalFault("INVALID_INPUT", reason)
# Domain checks precede conversion, including arbitrarily large finite ints.
return _freeze({key: (int(raw[key]) if key == "mode" or key in _KEYS
else float(raw[key])) for key in _FIELDS})
def _preflight(state, prefix):
_prefix(prefix)
tq, tk = ((3, 3) if state["mode"] == 0 else
(2, 2) if state["mode"] == 1 else (2, 3))
allowed = [[state[_KEYS[j]] == 1 and (state["mode"] != 1 or j <= i)
for j in range(tk)] for i in range(tq)]
if any(not any(row) for row in allowed):
raise NumericalFault("FULLY_MASKED_ROW", _EMPTY_REASON)
return tq, tk, allowed
def _finite(value, label):
if not math.isfinite(value):
raise NumericalFault("NONFINITE", label + " must be finite.")
return value
class _ScalarGraph:
"""Private operation/native captures, not public frames or tensor metadata."""
def __init__(self):
self.operations = []
self.natives = []
def binary(self, identifier, kind, left, right):
if kind == "mul":
output = left * right
elif kind == "add":
output = left + right
elif kind == "sub":
output = left - right
elif kind == "div":
output = left / right
else:
raise ValueError("Unknown private scalar operation.")
_finite(output, identifier)
self.operations.append(dict(id=identifier, kind=kind, left=left, right=right, output=output))
return output
def native(self, identifier, kind, argument):
_finite(argument, identifier)
if kind == "sqrt":
if not 0.25 <= argument <= 4096.0:
raise NumericalFault("INVALID_INPUT", "sqrt argument outside authored scope.")
output = math.sqrt(argument)
elif kind == "exp":
if not -256.0 <= argument <= 0.0:
raise NumericalFault("INVALID_INPUT", "exp argument outside authored scope.")
output = math.exp(argument)
else:
raise ValueError("Unknown private native operation.")
_finite(output, identifier)
if output <= 0:
reason = ("attention divisor must be positive." if kind == "sqrt"
else "allowed softmax terms must be positive.")
raise NumericalFault("INVALID_INPUT", reason)
leaf = dict(id=identifier, kind=kind, input=argument, output=output)
self.natives.append(leaf)
self.operations.append(leaf)
return output
def _max_word(left, right):
# Math.max prefers +0 on a mixed-zero tie; Python max preserves the first.
if right > left or (right == left == 0.0 and math.copysign(1.0, right) > 0):
return right
return left
def _scalar_first(value, prefix):
state = variant_state(value)
tq, tk, allowed = _preflight(state, prefix)
graph = _ScalarGraph()
query = [state[key] for key in _FIELDS[1:5]]
memory = [state[key] for key in _FIELDS[5:11]]
qsource = memory if state["mode"] == 0 else query
kvsource = query if state["mode"] == 1 else memory
q, k, v = (state[key] for key in _GAINS)
weights = dict(Q=[q, 0.0, q, q], K=[k, 0.0, 0.0, k], V=[v, v, 0.0, v])
projected, projection_products = {}, {}
for name, source, rows in (("Q", qsource, tq), ("K", kvsource, tk), ("V", kvsource, tk)):
values, products = [], []
for i in range(rows):
for d in range(2):
label = prefix + "_" + name + "_" + str(i) + "_" + str(d)
p0 = graph.binary(label + "_p0", "mul", source[2*i], weights[name][d])
p1 = graph.binary(label + "_p1", "mul", source[2*i+1], weights[name][2+d])
products.extend((p0, p1))
values.append(graph.binary(label + "_sum", "add", p0, p1))
projected[name], projection_products[name] = values, products
divisor = graph.native(prefix + "_sqrt2", "sqrt", 2.0)
score_products, dots, scores = [], [], []
for i in range(tq):
for j in range(tk):
label = prefix + "_score_" + str(i) + "_" + str(j)
p0 = graph.binary(label + "_p0", "mul", projected["Q"][2*i], projected["K"][2*j])
p1 = graph.binary(label + "_p1", "mul", projected["Q"][2*i+1], projected["K"][2*j+1])
score_products.extend((p0, p1))
dot = graph.binary(label + "_sum", "add", p0, p1)
dots.append(dot)
scores.append(graph.binary(label + "_scale", "div", dot, divisor))
maxima, terms, denominators, probabilities, shifts = [], [], [], [], []
for i in range(tq):
maximum = -math.inf
for j in range(tk):
if allowed[i][j]:
maximum = _max_word(maximum, scores[i*tk+j])
maxima.append(_finite(maximum, "maximum"))
row_terms, row_shifts = [], {}
for j in range(tk):
label = prefix + "_softmax_" + str(i) + "_" + str(j)
if allowed[i][j]:
shifted = graph.binary(label + "_shift", "sub", scores[i*tk+j], maximum)
row_shifts[str(j)] = shifted
row_terms.append(graph.native(label + "_exp", "exp", shifted))
else:
row_terms.append(0.0)
denominator = 0.0
for j in range(tk):
denominator = graph.binary(prefix + "_denom_" + str(i) + "_" + str(j),
"add", denominator, row_terms[j])
if denominator <= 0:
raise NumericalFault("INVALID_INPUT", "softmax denominator must be positive.")
for j in range(tk):
probabilities.append(graph.binary(prefix + "_prob_" + str(i) + "_" + str(j),
"div", row_terms[j], denominator))
terms.extend(row_terms)
shifts.append(row_shifts)
denominators.append(denominator)
products, partials, output = [], [], []
for i in range(tq):
sums = [0.0, 0.0]
for j in range(tk):
for d in range(2):
label = prefix + "_weighted_" + str(i) + "_" + str(j) + "_" + str(d)
product = graph.binary(label + "_product", "mul", probabilities[i*tk+j], projected["V"][2*j+d])
sums[d] = graph.binary(label + "_sum", "add", sums[d], product)
products.append(product)
partials.append(sums[d])
output.extend(sums)
captured = _freeze(dict(
state=state, tq=tq, tk=tk, allowed=allowed,
q_origin="memory" if state["mode"] == 0 else "query",
kv_origin="query" if state["mode"] == 1 else "memory",
query=query, memory=memory, qsource=qsource, kvsource=kvsource,
weights=weights, projected=projected, projection_products=projection_products,
divisor=divisor, score_products=score_products, dots=dots, scores=scores,
maxima=maxima, shifts=shifts, terms=terms, denominators=denominators,
probabilities=probabilities, products=products, partials=partials, output=output,
operations=graph.operations, natives=graph.natives))
return captured, _support._storage(output, tq, 2)
def evaluate_variant(value, trace, prefix):
"""Capture privately first; public observer callbacks then copy saved words."""
mechanism, _ = _scalar_first(value, prefix)
return _bind_variant(mechanism, trace, prefix)
def _tensor(identifier, shape, axes, values, provenance, dtype="float64"):
return dict(id=identifier, shape=list(shape), axes=list(axes), dtype=dtype,
values=list(values), provenance=provenance, precision=8 if dtype == "float64" else 0)
def _bind_variant(m, trace, prefix):
"""Only indexing/copies and integer metadata; no float/native arithmetic."""
state, tq, tk = m["state"], m["tq"], m["tk"]
qo, ko = (1 if m["q_origin"] == "memory" else 0), (1 if m["kv_origin"] == "memory" else 0)
qs, ks = (1 if qo == 0 else 5), (1 if ko == 0 else 5)
allowed = [keep for row in m["allowed"] for keep in row]
trace.add(prefix + "_setup", "Capture both sources after complete mask preflight",
"Q=Xq*WQ; K=Xkv*WK; V=Xkv*WV; S=Q*K^T/sqrt(2); P=allowedSoftmax(S); O=P*V",
"All seventeen finite raw fields and their domains, then the ASCII prefix and every allowed row, are checked before this first frame. One attention sublayer is compared; padding excludes keys only and never removes a query.",
dict(state), dict(state, B=1, H=1, Tq=tq, Tk=tk, D=2, Dk=2, Dv=2,
queryOrigin=qo, keyValueOrigin=ko, rawInputCount=17))
for name, source, rows, origin, raw_start in (("Q", m["qsource"], tq, qo, qs),
("K", m["kvsource"], tk, ko, ks),
("V", m["kvsource"], tk, ko, ks)):
for i in range(rows):
for d in range(2):
offset = 2*i+d
trace.add(f"{prefix}_project_{name}_{i}_{d}",
f"{name} row {i}, feature {d}: two products then their direct sum",
"product0=x0*w0; product1=x1*w1; value=product0+product1",
"Source offsets address the selected origin; raw offsets address the complete raw17 record. Weight offsets address row-feature storage. There is no initial +0, bias, fused operation or zero-gain bypass.",
dict(i=i, d=d, origin=origin, sourceOffset0=2*i, sourceOffset1=2*i+1,
rawOffset0=raw_start+2*i, rawOffset1=raw_start+2*i+1,
weightOffset0=d, weightOffset1=2+d, outputOffset=offset,
x0=source[2*i], x1=source[2*i+1],
w0=m["weights"][name][d], w1=m["weights"][name][2+d]),
dict(product0=m["projection_products"][name][2*offset],
product1=m["projection_products"][name][2*offset+1],
value=m["projected"][name][offset]))
natives = [dict(id=prefix+"_sqrt", kind="sqrt", input=m["natives"][0]["input"],
output=m["natives"][0]["output"])]
trace.add(prefix+"_scale", "Compute the single key-width divisor", "divisor=sqrt(Dk)",
"One actual sqrt(2) is reused by every score division, including forbidden score cells.",
dict(Dk=2), dict(divisor=m["divisor"]))
for i in range(tq):
for j in range(tk):
offset = i*tk+j
trace.add(f"{prefix}_score_{i}_{j}",
f"Query {i}, key {j}: compute the finite score even when forbidden",
"product0=q0*k0; product1=q1*k1; dot=product0+product1; score=dot/divisor",
"Both key-width coordinates contribute in order. The Boolean eligibility decision controls softmax, not whether this score is calculated. Division has no added shift or +0 stage.",
dict(i=i, j=j, queryOffset0=2*i, queryOffset1=2*i+1, keyOffset0=2*j,
keyOffset1=2*j+1, q0=m["projected"]["Q"][2*i],
q1=m["projected"]["Q"][2*i+1], k0=m["projected"]["K"][2*j],
k1=m["projected"]["K"][2*j+1], divisor=m["divisor"], allowed=int(allowed[offset])),
dict(product0=m["score_products"][2*offset], product1=m["score_products"][2*offset+1],
dot=m["dots"][offset], score=m["scores"][offset]))
leaf_index = 1
for i in range(tq):
inputs, outputs = dict(i=i, Tk=tk), dict(max=m["maxima"][i])
for j in range(tk):
offset = i*tk+j
inputs[f"score{j}"], inputs[f"allowed{j}"] = m["scores"][offset], int(allowed[offset])
if allowed[offset]:
outputs[f"shifted{j}"] = m["shifts"][i][str(j)]
leaf = m["natives"][leaf_index]
natives.append(dict(id=f"{prefix}_exp_{i}_{j}", kind=leaf["kind"],
input=leaf["input"], output=leaf["output"]))
leaf_index += 1
outputs[f"term{j}"] = m["terms"][offset]
outputs["denominator"] = m["denominators"][i]
for j in range(tk):
outputs[f"probability{j}"] = m["probabilities"][i*tk+j]
trace.add(f"{prefix}_row_{i}", f"Query {i}: allowed-only stable softmax in key order",
"max=Math.max(allowed scores); term[j]=allowed[j]?exp(score[j]-max):+0; denominator=fold(+0,terms); probability[j]=term[j]/denominator",
"The unchanged platform primitive prefers +0 on a mixed signed-zero maximum tie, exponentiates only allowed keys, adds all Tk terms from +0 and divides every term. Allowed shifted witnesses repeat its identical immutable subtraction; no extra exp is evaluated and forbidden shifts are absent.",
inputs, outputs)
for i in range(tq):
for j in range(tk):
for d in range(2):
offset = (i*tk+j)*2+d
trace.add(f"{prefix}_weighted_{i}_{j}_{d}",
f"Query {i}, key {j}, value feature {d}: product then running sum",
"product=probability*value; sum=previous+product",
"Each output feature starts at literal +0 and visits every key in ascending order. A forbidden +0 probability still multiplies its actual value, so a negative value can produce a saved -0 product. No slot is skipped.",
dict(i=i, j=j, d=d, probabilityOffset=i*tk+j, valueOffset=2*j+d,
storageOffset=offset, outputOffset=2*i+d, allowed=int(allowed[i*tk+j]),
probability=m["probabilities"][i*tk+j], value=m["projected"]["V"][2*j+d],
previous=0.0 if j == 0 else m["partials"][offset-2]),
dict(product=m["products"][offset], sum=m["partials"][offset]))
score_shape, score_axes = [1, 1, tq, tk], ["B", "H", "Tq", "Tk"]
tensors = [
_tensor(prefix+"_Raw", [17], ["RawField"], [state[key] for key in _FIELDS], "Captured raw17 in texts.rawFields order. mode/key0/key1/key2 are VALUE; thirteen source/gain fields are binary64 WORD, including -0."),
_tensor(prefix+"_Query", [1, 2, 2], ["B", "QueryPosition", "D"], m["query"], "Unchanged raw query00,query01,query10,query11 words, including when inactive in encoder mode."),
_tensor(prefix+"_Memory", [1, 3, 2], ["B", "MemoryPosition", "D"], m["memory"], "Unchanged raw memory00,memory01,memory10,memory11,memory20,memory21 words, including when inactive in decoder mode."),
_tensor(prefix+"_KeyValidity", [3], ["KeySlot"], [state[key] for key in _KEYS], "Captured positional key bits for the selected K/V origin; key2 is validated but inactive in decoder mode. VALUE.", "int32"),
_tensor(prefix+"_SourceOrigins", [2], ["SourceRole"], [qo, ko], "Q-source then K/V-source codes: query=0,memory=1. VALUE; equal numbers do not merge origins.", "int32"),
_tensor(prefix+"_QuerySource", [1, tq, 2], ["B", "Tq", "D"], m["qsource"], "Q source WORD copies: memory in encoder mode, query in decoder/cross modes."),
_tensor(prefix+"_KeyValueSource", [1, tk, 2], ["B", "Tk", "D"], m["kvsource"], "K/V source WORD copies: query in decoder mode, memory in encoder/cross modes."),
_tensor(prefix+"_QuerySourceOffsets", [tq, 2], ["Tq", "D"], [qs+o for o in range(2*tq)], "Raw17 VALUE offsets for each Q-source coordinate, in row-major order.", "int32"),
_tensor(prefix+"_KeyValueSourceOffsets", [tk, 2], ["Tk", "D"], [ks+o for o in range(2*tk)], "Raw17 VALUE offsets for each K/V-source coordinate, in row-major order.", "int32"),
_tensor(prefix+"_WQ", [2, 2], ["D", "Dk"], m["weights"]["Q"], "Row-feature WQ=[[q,+0],[q,q]]: gain slots copy q WORD; structural zero is literal +0."),
_tensor(prefix+"_WK", [2, 2], ["D", "Dk"], m["weights"]["K"], "Row-feature WK=[[k,+0],[+0,k]]: gain slots copy k WORD; structural zeros are literal +0."),
_tensor(prefix+"_WV", [2, 2], ["D", "Dv"], m["weights"]["V"], "Row-feature WV=[[v,v],[+0,v]]: gain slots copy v WORD; structural zero is literal +0."),
_tensor(prefix+"_QProducts", [tq, 2, 2], ["Tq", "Dk", "InputFeature"], m["projection_products"]["Q"], "Actual Q projection product0,product1 for each query row/output feature; direct sum without an initial +0."),
_tensor(prefix+"_KProducts", [tk, 2, 2], ["Tk", "Dk", "InputFeature"], m["projection_products"]["K"], "Actual K projection product0,product1 for each key row/output feature; direct sum without an initial +0."),
_tensor(prefix+"_VProducts", [tk, 2, 2], ["Tk", "Dv", "InputFeature"], m["projection_products"]["V"], "Actual V projection product0,product1 for each key row/output feature; direct sum without an initial +0."),
_tensor(prefix+"_Q", [1, 1, tq, 2], ["B", "H", "Tq", "Dk"], m["projected"]["Q"], "Actual Q direct sums from the declared Q origin; singleton batch/head axes require no permutation."),
_tensor(prefix+"_K", [1, 1, tk, 2], ["B", "H", "Tk", "Dk"], m["projected"]["K"], "Actual K direct sums from the declared K/V origin; source row j uses offset 2*j+d."),
_tensor(prefix+"_V", [1, 1, tk, 2], ["B", "H", "Tk", "Dv"], m["projected"]["V"], "Actual V direct sums from the declared K/V origin; every row remains computed under padding."),
_tensor(prefix+"_Divisor", [1], ["Scalar"], [m["divisor"]], "Actual single sqrt(2) output WORD, copied into every score division and the native ledger."),
_tensor(prefix+"_ScoreProducts", [tq, tk, 2], ["Tq", "Tk", "Dk"], m["score_products"], "Actual score product0,product1 for every query/key pair, including forbidden pairs."),
_tensor(prefix+"_Dots", score_shape, score_axes, m["dots"], "Direct product0+product1 WORD at offset i*Tk+j, without an initial +0."),
_tensor(prefix+"_Scores", score_shape, score_axes, m["scores"], "Actual dot/divisor WORD for every query/key pair, including forbidden pairs; no shift or -Infinity sentinel."),
_tensor(prefix+"_Allowed", score_shape, score_axes, allowed, "Boolean key eligibility: key[j] AND (mode!=decoder OR j<=i). Keys only; query rows are retained.", "bool"),
_tensor(prefix+"_Maxima", [1, 1, tq], ["B", "H", "Tq"], m["maxima"], "Actual platform Math.max of allowed scores, including +0 preference on mixed-zero ties."),
_tensor(prefix+"_Terms", score_shape, score_axes, m["terms"], "Actual platform exp outputs at allowed positions; forbidden positions are literal +0 with no exp call."),
_tensor(prefix+"_Denominators", [1, 1, tq], ["B", "H", "Tq"], m["denominators"], "Actual platform Tk-ordered term sums from literal +0, copied without reassociation."),
_tensor(prefix+"_Probabilities", score_shape, score_axes, m["probabilities"], "Actual platform term/denominator at every position; forbidden probabilities are +0."),
_tensor(prefix+"_WeightedProducts", [tq, tk, 2], ["Tq", "Tk", "Dv"], m["products"], "Every actual P[i,j]*V[j,d] WORD at (i*Tk+j)*2+d; masked products can be -0."),
_tensor(prefix+"_WeightedPartials", [tq, tk, 2], ["Tq", "Tk", "Dv"], m["partials"], "Actual updated sum after every product, with independent +0-initialized feature accumulators; traversal i,j,d."),
_tensor(prefix+"_Output", [1, 1, tq, 2], ["B", "H", "Tq", "Dv"], m["output"], "Final saved +0-initialized, ascending-key weighted sums; no output projection, bias, residual or normalization."),
_tensor(prefix+"_NativeArguments", [len(natives), 2], ["Native", "NativeField"], [word for leaf in natives for word in (leaf["input"], leaf["output"])], "Ordered actual native input,output WORD copies. Exp inputs functionally reconstruct the identical subtraction; exp outputs are actual platform terms. No extra native call in serialization."),
_tensor(prefix+"_NativeKinds", [len(natives)], ["Native"], [0 if leaf["kind"] == "sqrt" else 1 for leaf in natives], "VALUE native kind codes in occurrence order: sqrt=0,exp=1; bind texts.nativeIds and texts.nativeKinds.", "int32"),
]
mode_names = ["Encoder self-attention", "Decoder causal self-attention", "Cross-attention"]
texts = dict(
rawFields=list(_FIELDS), modeNames=mode_names, modeName=mode_names[state["mode"]],
sourceNames=["query", "memory"], sourceRoles=["Q", "K/V"],
querySource=m["q_origin"], keyValueSource=m["kv_origin"],
inactiveFields=(list(_FIELDS[1:5]) if state["mode"] == 0 else list(_FIELDS[5:11])+["key2"] if state["mode"] == 1 else []),
nativeIds=[leaf["id"] for leaf in natives], nativeKinds=[leaf["kind"] for leaf in natives],
nativeFields=["input", "output"], projectionProductFields=["product0", "product1"], scoreProductFields=["product0", "product1"],
scopePolicy="One hand-set attention sublayer with B=H=1 and D=Dk=Dv=2. No complete encoder/decoder block, output projection, residual, normalization, FFN, loss, training, generation or cache is computed.",
sourcePolicy="Encoder Q/K/V use all three memory rows. Decoder Q/K/V use both query rows. Cross Q uses both query rows and K/V use all three memory rows. Numeric equality never changes source identity; all inactive raw fields remain editable, captured and validated.",
maskPolicy="key0/key1/key2 are key-position validity for the selected K/V source. Encoder/cross allow each valid memory key for every query. Decoder intersects query-key validity with j<=i; key2 is inactive. Padding never deletes query rows. An empty row faults before any frame, projection or native call.",
arithmeticPolicy="Compute all Q, then K, then V in row/feature order with two products and one direct sum. Compute one sqrt(2), all scores in i,j order, all softmax rows in i order, then every weighted product and partial sum in i,j,d order. Score division has no added +0. Output accumulators start +0 separately for each feature.",
softmaxPolicy="The unchanged platform stableSoftmax computes allowed-only Math.max with +0 tie preference, actual allowed exp terms, forbidden literal +0 terms, a Tk-ordered denominator starting +0 and every term/denominator probability. Forbidden finite scores remain saved; forbidden shifts and native occurrences are absent.",
nativePolicy="Occurrence order is one sqrt(2), then exp for allowed i,j pairs in row/key order. Each exp input repeats the same subtraction of the immutable score and actual maximum used by stableSoftmax: a functional witness, not physical call interception. Each exp output copies the actual term; serialization performs no extra exp.",
wordPolicy="Thirteen raw source/gain fields, their source and weight copies, every arithmetic result and native argument/output use binary64 WORD including -0. mode, key bits, dimensions, origins, offsets, counts and native kind codes use VALUE; mask tensors use Boolean VALUE. Gain slots copy words directly and structural weight zeros are literal +0. Forbidden terms/probabilities are +0; weighted products retain their computed signs.",
storagePolicy="All storage is row-major. Active source/output offset is 2*row+d, score offset is i*Tk+j, projection product offset is (row*2+d)*2+inputFeature and weighted product/partial offset is (i*Tk+j)*2+d. Raw offsets identify the separate raw17 origins. All tensors have at most four axes.",
inactivePolicy=("The four query controls are inactive numerically but still captured and validated. Padded memory rows remain Q rows." if state["mode"] == 0 else "The six memory controls and key2 are inactive numerically but still captured and validated. key0 must be valid because query row0 cannot use a future key." if state["mode"] == 1 else "Both source streams and all three key bits are active. A memory key j>i remains eligible when its key bit is valid; no causal rule is applied across streams."))
saved = _freeze(tensors)
# Freeze children separately so output aliases the actual saved tensor object.
return _support._FrozenDict(state=state, output=saved[29], natives=_freeze(natives),
tensors=saved, texts=_freeze(texts))
def derive_iv60(value):
try:
trace = variant_trace()
evaluated = evaluate_variant(value, trace, "variant")
state, output, natives, tensors = (evaluated[key] for key in ("state", "output", "natives", "tensors"))
setup = trace.steps[0]["outputs"]
tq, tk = setup["Tq"], setup["Tk"]
exp_calls = sum(leaf["kind"] == "exp" for leaf in natives)
summary = dict(mode=state["mode"], queryOrigin=setup["queryOrigin"], keyValueOrigin=setup["keyValueOrigin"],
Tq=tq, Tk=tk, allowedPairs=exp_calls, outputRows=output["shape"][2], outputFeatures=output["shape"][3],
sqrtCalls=sum(leaf["kind"] == "sqrt" for leaf in natives), expCalls=exp_calls,
nativeElementaryCalls=len(natives), frames=len(trace.steps)+1, tensorCount=len(tensors))
for i in range(tq):
for d in range(2):
summary[f"output{i}{d}"] = output["values"][2*i+d]
trace.add("finish", "Read the saved attention output for every query",
"output[i,d]=saved weighted sum after the last key; output length=Tq",
"Copy each actual output word and source-graph count after the complete sublayer. Source origin codes are query=0,memory=1. Counts describe this declared computation, not hardware timing, a full architecture or learned capability.",
dict(mode=state["mode"], Tq=tq, Tk=tk), summary)
texts = dict(evaluated["texts"],
graphStages=["Raw query rows", "Raw memory rows", "Selected Q source", "Selected K/V source", "Q projection", "K projection", "V projection", "Every finite score", "Allowed key mask", "Stable attention probabilities", "Weighted-value output"],
graphTensorIds=["variant_Query", "variant_Memory", "variant_QuerySource", "variant_KeyValueSource", "variant_Q", "variant_K", "variant_V", "variant_Scores", "variant_Allowed", "variant_Probabilities", "variant_Output"],
tracePolicy="No wrapper frame precedes raw/prefix/all-row mask preflight. The first helper setup frame carries all raw17 fields. The unchanged decoderTrace factory captures finite operands once, checks nonempty unique IDs before operands and the 512 cap after operands, then saves detached frozen six-field frames. Every frame output appears as frameId_key in root outputs, without recomputing arithmetic.",
summaryPolicy="mode, origins, dimensions, allowed-pair/native/frame/tensor counts and output sizes are VALUE. output00,output01 and later row coordinates are unchanged output WORD copies. All frame-output aliases retain their source VALUE or WORD role. Origin codes are query=0,memory=1; native kind codes are sqrt=0,exp=1.",
validationPolicy="SOURCE IMPLEMENTATION ONLY. All tests, independent executable authority, canonical parity, typecheck, build, browser, accessibility and offline checks are UNRUN under the human FluxGeo hold. Public inventory adoption and validation belong to the owner; this record is not runtime acceptance.")
outputs = dict(summary)
for step in trace.steps:
for key, word in step["outputs"].items():
alias = step["id"]+"_"+key
if alias in outputs:
raise RuntimeError("IV60 output aliases must be unique.")
outputs[alias] = word
return _freeze(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))
except NumericalFault as fault:
return _fault_record(fault)
def _fault_record(fault):
return _freeze(dict(status="unavailable", code=fault.code, reason=fault.reason))
def _require(condition, reason):
if not condition:
raise AssertionError(reason)
def _explicit_checks_only():
if not __debug__:
raise RuntimeError("Explicit IV60 checks refuse Python -O.")
def _expect_fault(code, callback, reason=None):
try:
callback()
except NumericalFault as fault:
_require(fault.code == code, "Wrong numerical fault precedence.")
if reason is not None:
_require(fault.reason == reason, "Wrong numerical fault reason.")
return
raise AssertionError("Expected numerical fault was not raised.")
def _word(value):
return float(value).hex()
def check_mechanism():
_explicit_checks_only()
for mode, tq, tk, leaf_count in ((0, 3, 3, 10), (1, 2, 2, 4), (2, 2, 3, 7)):
m, stored = _scalar_first(dict(DEFAULT_IV60, mode=mode), "Mechanism")
_require((m["tq"], m["tk"]) == (tq, tk), "Wrong rectangular axes.")
_require(len(m["natives"]) == leaf_count, "Missing or fabricated native occurrence.")
_require(len(m["scores"]) == tq*tk, "Forbidden score was skipped.")
_require(len(m["products"]) == tq*tk*2, "Weighted slot was skipped.")
_require(m["projected"]["Q"] == ([1.0, 0.0, 1.0, 1.0, 2.0, 1.0] if mode == 0
else [1.0, 0.0, 1.0, 1.0]), "Wrong Q orientation.")
for i in range(tq):
for d in range(2):
_require(_word(stored[0, i, d]) == _word(m["output"][2*i+d]), "Indexed storage changed a word.")
expected_native_ids = ["Mechanism_sqrt2"] + [
"Mechanism_softmax_" + str(i) + "_" + str(j) + "_exp"
for i in range(tq) for j in range(tk) if m["allowed"][i][j]]
_require([leaf["id"] for leaf in m["natives"]] == expected_native_ids, "Wrong native traversal.")
native_by_id = {leaf["id"]: leaf for leaf in m["natives"]}
for i in range(tq):
for j in range(tk):
offset = i*tk+j
if m["allowed"][i][j]:
leaf = native_by_id["Mechanism_softmax_" + str(i) + "_" + str(j) + "_exp"]
_require(_word(leaf["input"]) == _word(m["shifts"][i][str(j)]), "Exp input copy mismatch.")
_require(_word(leaf["output"]) == _word(m["terms"][offset]), "Exp output copy mismatch.")
else:
_require(str(j) not in m["shifts"][i], "Fabricated forbidden shift.")
_require(_word(m["terms"][offset]) == _word(0.0), "Forbidden term is not +0.")
_require(_word(m["probabilities"][offset]) == _word(0.0), "Forbidden probability is not +0.")
# Direct contractions have two products then one addition, never +0 folds.
ops = m["operations"]
cursor = 0
for name, rows in (("Q", tq), ("K", tk), ("V", tk)):
for i in range(rows):
for d in range(2):
label = "Mechanism_" + name + "_" + str(i) + "_" + str(d)
_require([op["id"] for op in ops[cursor:cursor+3]] ==
[label+"_p0", label+"_p1", label+"_sum"], "Projection order changed.")
cursor += 3
_require(ops[cursor]["id"] == "Mechanism_sqrt2", "sqrt traversal changed.")
cursor += 1
for i in range(tq):
for j in range(tk):
label = "Mechanism_score_" + str(i) + "_" + str(j)
_require([op["id"] for op in ops[cursor:cursor+4]] ==
[label+"_p0", label+"_p1", label+"_sum", label+"_scale"], "Score order changed.")
cursor += 4
weighted_ids = []
for i in range(tq):
for j in range(tk):
for d in range(2):
label = "Mechanism_weighted_"+str(i)+"_"+str(j)+"_"+str(d)
weighted_ids.extend((label+"_product", label+"_sum"))
_require([op["id"] for op in ops[-len(weighted_ids):]] == weighted_ids, "Weighted i,j,d order changed.")
decoder, _ = _scalar_first(dict(DEFAULT_IV60, mode=1), "DecoderAnchor")
_require(decoder["output"] == [1.0, 1.0, 0.5, 1.0], "Manual decoder anchor failed.")
padded, _ = _scalar_first(dict(DEFAULT_IV60, key1=0), "PaddingAnchor")
_require(padded["probabilities"][:3] == [0.5, 0.0, 0.5], "Manual padding weights failed.")
_require(padded["output"][:2] == [1.0, 1.5], "Manual padding output failed.")
for mode in (0, 2):
only_last, _ = _scalar_first(dict(DEFAULT_IV60, mode=mode, key0=0, key1=0), "OnlyLast")
_require(only_last["output"] == [1.0, 2.0]*only_last["tq"], "Single memory key anchor failed.")
negative, _ = _scalar_first(dict(DEFAULT_IV60, query00=-0.0, query01=-0.0, q=1), "DirectZero")
_require(_word(negative["projected"]["Q"][0]) == _word(-0.0), "Inserted initial +0 in projection.")
negative, _ = _scalar_first(dict(DEFAULT_IV60, q=-0.0, k=-0.0, v=-0.0), "GainZero")
for name, gain_slots, zero_slots in (("Q", (0, 2, 3), (1,)), ("K", (0, 3), (1, 2)),
("V", (0, 1, 3), (2,))):
_require(all(_word(negative["weights"][name][i]) == _word(-0.0) for i in gain_slots), "Gain word erased.")
_require(all(_word(negative["weights"][name][i]) == _word(0.0) for i in zero_slots), "Structural zero inherited gain sign.")
_require(_word(_max_word(-0.0, 0.0)) == _word(0.0), "Math.max mixed-zero tie failed.")
_require(_word(_max_word(0.0, -0.0)) == _word(0.0), "Math.max reverse mixed-zero tie failed.")
_require(_word(_max_word(-0.0, -0.0)) == _word(-0.0), "Math.max negative-zero tie failed.")
signed, _ = _scalar_first(dict(DEFAULT_IV60, memory11=-1, key1=0), "MaskedNegative")
_require(_word(signed["products"][3]) == _word(-0.0), "Forbidden weighted product sign erased.")
for mode in (1, 2):
before, _ = _scalar_first(dict(DEFAULT_IV60, mode=mode), "Origin")
after, _ = _scalar_first(dict(DEFAULT_IV60, mode=mode, query10=1), "Origin")
_require(before["output"][:2] == after["output"][:2], "Later query affected earlier output.")
before, _ = _scalar_first(DEFAULT_IV60, "MemoryOrigin")
after, _ = _scalar_first(dict(DEFAULT_IV60, memory20=2), "MemoryOrigin")
_require(before["projected"]["Q"] == after["projected"]["Q"], "Memory edit changed cross Q.")
_require(before["output"][:2] != after["output"][:2], "Cross memory j>i was incorrectly causal.")
def check_boundaries():
_explicit_checks_only()
class Hostile(dict):
def __getitem__(self, key):
raise AssertionError("Untrusted descriptor was invoked.")
_expect_fault("INVALID_INPUT", lambda: variant_state(Hostile(DEFAULT_IV60)))
_expect_fault("INVALID_INPUT", lambda: variant_state(dict(DEFAULT_IV60, extra=1)))
_expect_fault("NONFINITE", lambda: variant_state(dict(DEFAULT_IV60, mode=9, memory21=math.nan)))
_expect_fault("NONFINITE", lambda: variant_state(dict(DEFAULT_IV60, query00=True)))
_expect_fault("INVALID_INPUT", lambda: variant_state(dict(DEFAULT_IV60, memory21=10**400)))
_expect_fault("INVALID_INPUT", lambda: variant_state(dict(DEFAULT_IV60, mode=1, key2=2)))
_expect_fault("INVALID_INPUT", lambda: _scalar_first(dict(DEFAULT_IV60, mode=1, key0=0), "1bad"))
_expect_fault("FULLY_MASKED_ROW", lambda: _scalar_first(dict(DEFAULT_IV60, mode=1, key0=0), "Valid"), _EMPTY_REASON)
_expect_fault("FULLY_MASKED_ROW", lambda: _scalar_first(dict(DEFAULT_IV60, key0=0, key1=0, key2=0), "Valid"), _EMPTY_REASON)
state = variant_state(dict(DEFAULT_IV60, mode=-0.0, key0=-0.0, q=-0.0))
_require(state["mode"] == 0 and state["key0"] == 0, "VALUE zeros rejected.")
_require(_word(state["q"]) == _word(-0.0), "WORD zero erased.")
state = variant_state(DEFAULT_IV60)
_require(state is not DEFAULT_IV60, "State was not detached.")
try:
state["q"] = 0
except TypeError:
pass
else:
raise AssertionError("State is mutable.")
collector = variant_trace()
collector.add("Existing", "Existing", "x=x", "Trusted existing frame", {"x": 1}, {"x": 1})
before = _freeze(dict(outputs=collector.outputs, steps=collector.steps, ids=sorted(collector._ids)))
_expect_fault("FULLY_MASKED_ROW", lambda: evaluate_variant(dict(DEFAULT_IV60, mode=1, key0=0), collector, "Valid"), _EMPTY_REASON)
after = _freeze(dict(outputs=collector.outputs, steps=collector.steps, ids=sorted(collector._ids)))
_require(before == after, "Empty-row preflight mutated existing collector.")
marker = RuntimeError("Unknown identity")
original = _ScalarGraph.native
def fail_native(self, identifier, kind, argument):
raise marker
_ScalarGraph.native = fail_native
try:
_expect_fault("FULLY_MASKED_ROW", lambda: _scalar_first(dict(DEFAULT_IV60, mode=1, key0=0), "Valid"))
try:
_scalar_first(DEFAULT_IV60, "Unknown")
except RuntimeError as error:
_require(error is marker, "Unknown exception identity replaced.")
else:
raise AssertionError("Native exception was swallowed.")
finally:
_ScalarGraph.native = original
def check_closure():
_explicit_checks_only()
_require(Path(_support.__file__).resolve() == Path(__file__).resolve().with_name("decoder_reference.py"),
"Support escaped same-folder closure.")
_require(_load_support() is _support, "Support loader identity changed.")
_require(NumericalFault is _support.NumericalFault, "Fault identity changed.")
_require(variant_trace is _support.decoder_trace, "Collector identity changed.")
_require(_freeze is _support._freeze, "Frozen record identity changed.")
_require(_capture_record is _support._capture_record and _prefix is _support._prefix,
"Generic boundary identity changed.")
_require(sys.modules.get("_book_iv_p15_decoder_reference") is _support, "Support cached key changed.")
_require(NumericalFault.__module__ == _support.__name__ and
variant_trace.__module__ == _support.__name__ and
variant_trace.__code__ is _support.decoder_trace.__code__, "Generic declaring module/code changed.")
_require(type(variant_trace()) is _support._PublicTrace, "Generic collector class identity changed.")
for function, arity in ((_load_support, 0), (variant_state, 1), (_preflight, 2), (_finite, 2),
(_ScalarGraph.__init__, 1), (_ScalarGraph.binary, 5), (_ScalarGraph.native, 4),
(_max_word, 2), (_scalar_first, 2), (evaluate_variant, 3), (_tensor, 6),
(_bind_variant, 3), (derive_iv60, 1), (_fault_record, 1), (_require, 2),
(_explicit_checks_only, 0), (_expect_fault, 3), (_word, 1), (_same, 2),
(check_mechanism, 0), (check_boundaries, 0), (check_closure, 0),
(check_public_binding, 0), (check_copies, 0), (check_capture_callbacks, 0)):
_require(function.__module__ == __name__ and function.__code__.co_argcount == arity and
Path(function.__code__.co_filename).resolve() == Path(__file__).resolve(),
"Local declaration/code identity changed.")
def _same(actual, expected):
"""Explicit-check comparison of complete ordered records and binary64 copies."""
if type(expected) in (dict, _support._FrozenDict):
_require(type(actual) in (dict, _support._FrozenDict) and tuple(actual) == tuple(expected),
"Ordered record keys differ.")
for key in expected:
_same(actual[key], expected[key])
elif type(expected) in (list, tuple, _support._FrozenList):
_require(type(actual) in (list, tuple, _support._FrozenList) and len(actual) == len(expected),
"Array shape differs.")
for left, right in zip(actual, expected):
_same(left, right)
elif type(expected) is float:
_require(type(actual) in (int, float) and (type(actual) is int or math.isfinite(actual)) and
-1.7976931348623157e308 <= actual <= 1.7976931348623157e308 and
_word(actual) == _word(expected), "WORD copy differs.")
else:
_require(type(actual) is type(expected) and actual == expected, "Literal/VALUE differs.")
def check_public_binding():
_explicit_checks_only()
tensor_names = ("Raw", "Query", "Memory", "KeyValidity", "SourceOrigins", "QuerySource",
"KeyValueSource", "QuerySourceOffsets", "KeyValueSourceOffsets", "WQ", "WK", "WV",
"QProducts", "KProducts", "VProducts", "Q", "K", "V", "Divisor", "ScoreProducts",
"Dots", "Scores", "Allowed", "Maxima", "Terms", "Denominators", "Probabilities",
"WeightedProducts", "WeightedPartials", "Output", "NativeArguments", "NativeKinds")
text_names = ("rawFields", "modeNames", "modeName", "sourceNames", "sourceRoles", "querySource",
"keyValueSource", "inactiveFields", "nativeIds", "nativeKinds", "nativeFields",
"projectionProductFields", "scoreProductFields", "scopePolicy", "sourcePolicy", "maskPolicy",
"arithmeticPolicy", "softmaxPolicy", "nativePolicy", "wordPolicy", "storagePolicy", "inactivePolicy",
"graphStages", "graphTensorIds", "tracePolicy", "summaryPolicy", "validationPolicy")
for mode in (0, 1, 2):
for bits in ((0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)):
value = dict(DEFAULT_IV60, mode=mode, key0=bits[0], key1=bits[1], key2=bits[2])
root = derive_iv60(value)
if (mode == 1 and bits[0] == 0) or not any(bits):
_same(root, dict(status="unavailable", code="FULLY_MASKED_ROW", reason=_EMPTY_REASON))
continue
tq, tk = (3 if mode == 0 else 2), (2 if mode == 1 else 3)
allowed_pairs = (2+bits[1] if mode == 1 else tq*sum(bits))
frame_count = 3+3*tq+4*tk+3*tq*tk
aliases = 28+8*tq+12*tk+10*tq*tk+allowed_pairs
summary_count = 13+2*tq
_require(tuple(root) == ("status", "outputs", "steps", "tensors", "texts") and root["status"] == "defined",
"Defined root schema differs.")
_require(len(root["steps"]) == frame_count and len(root["tensors"]) == 32 and
len(root["outputs"]) == aliases+2*summary_count, "Mode/padding inventory differs.")
_same([tensor["id"] for tensor in root["tensors"]], ["variant_"+name for name in tensor_names])
_require(tuple(root["texts"]) == text_names, "Ordered text inventory differs.")
_require(root["outputs"]["nativeElementaryCalls"] == 1+allowed_pairs, "Native cardinality differs.")
cells = 0
for index, tensor in enumerate(root["tensors"]):
_require(tuple(tensor) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision"),
"Tensor schema differs.")
expected_dtype = "bool" if index == 22 else "int32" if index in (3, 4, 7, 8, 31) else "float64"
_require(tensor["dtype"] == expected_dtype and tensor["precision"] == (8 if expected_dtype == "float64" else 0),
"Tensor dtype/precision differs.")
size = 1
for dimension in tensor["shape"]:
size *= dimension
_require(1 <= len(tensor["shape"]) <= 4 and len(tensor["axes"]) == len(tensor["shape"]) and
len(set(tensor["axes"])) == len(tensor["axes"]) and len(tensor["values"]) == size,
"Tensor shape/axes/storage differ.")
cells += size
_require(cells == 45+14*tq+16*tk+11*tq*tk+3*(1+allowed_pairs), "Mode/padding cell inventory differs.")
expected_aliases = dict(root["steps"][-1]["outputs"])
for step in root["steps"]:
_require(tuple(step) == ("id", "label", "equation", "explanation", "inputs", "outputs"), "Frame schema differs.")
for key, word in step["outputs"].items():
expected_aliases[step["id"]+"_"+key] = word
_same(root["outputs"], expected_aliases)
_require(root["steps"][0]["id"] == "variant_setup" and root["steps"][-1]["id"] == "finish",
"Wrapper inserted an early frame.")
_require(tuple(root["steps"][0]["inputs"]) == _FIELDS, "Raw declared capture order differs.")
for i in range(tq):
for d in range(2):
_same(root["outputs"][f"output{i}{d}"], root["tensors"][29]["values"][2*i+d])
_same(root["outputs"][f"finish_output{i}{d}"], root["tensors"][29]["values"][2*i+d])
state_input = dict(DEFAULT_IV60)
state = variant_state(state_input)
state_input["q"] = 0
_require(state["q"] == 1.0 and state is not DEFAULT_IV60, "State capture is not detached.")
trace = variant_trace()
helper = evaluate_variant(DEFAULT_IV60, trace, "Alias")
_require(tuple(helper) == ("state", "output", "natives", "tensors", "texts") and
helper["output"] is helper["tensors"][29], "Helper output alias/order differs.")
for target, key, value in ((helper, "output", None), (helper["output"], "precision", 0),
(helper["output"]["values"], 0, 99), (helper["state"], "q", 0),
(trace.steps[0]["outputs"], "q", 0)):
try:
target[key] = value
except TypeError:
pass
else:
raise AssertionError("Public snapshot is mutable.")
_expect_fault("INVALID_INPUT", lambda: evaluate_variant(DEFAULT_IV60, variant_trace(), "1bad"))
_expect_fault("INVALID_INPUT", lambda: variant_state(dict(DEFAULT_IV60, mode=0.5)),
"mode must be an integer in {0,1,2}.")
_expect_fault("NONFINITE", lambda: variant_state(dict(DEFAULT_IV60, mode=9, memory21=math.nan)),
"state.memory21 must be an actual finite number.")
_same(derive_iv60({}), dict(status="unavailable", code="INVALID_INPUT",
reason="state must have exactly "+", ".join(_FIELDS)+" as own fields."))
def check_copies():
_explicit_checks_only()
for mode in (0, 1, 2):
for key1 in (0, 1):
m, _ = _scalar_first(dict(DEFAULT_IV60, mode=mode, key1=key1,
query00=-0.0, q=-0.0, v=-1), "Copies")
trace = variant_trace()
helper = _bind_variant(m, trace, "Copies")
tq, tk = m["tq"], m["tk"]
tensor_sources = ([m["state"][key] for key in _FIELDS], m["query"], m["memory"],
[m["state"][key] for key in _KEYS],
[1 if m["q_origin"] == "memory" else 0, 1 if m["kv_origin"] == "memory" else 0],
m["qsource"], m["kvsource"],
[(5 if mode == 0 else 1)+i for i in range(2*tq)],
[(1 if mode == 1 else 5)+i for i in range(2*tk)],
m["weights"]["Q"], m["weights"]["K"], m["weights"]["V"],
m["projection_products"]["Q"], m["projection_products"]["K"], m["projection_products"]["V"],
m["projected"]["Q"], m["projected"]["K"], m["projected"]["V"], [m["divisor"]],
m["score_products"], m["dots"], m["scores"],
[keep for row in m["allowed"] for keep in row], m["maxima"], m["terms"],
m["denominators"], m["probabilities"], m["products"], m["partials"], m["output"],
[word for leaf in m["natives"] for word in (leaf["input"], leaf["output"])],
[0 if leaf["kind"] == "sqrt" else 1 for leaf in m["natives"]])
for tensor, expected in zip(helper["tensors"], tensor_sources):
_same(tensor["values"], expected)
_same(helper["state"], m["state"])
_same(trace.steps[0]["inputs"], m["state"])
_same({key: trace.steps[0]["outputs"][key] for key in _FIELDS}, m["state"])
by_id = {step["id"]: step for step in trace.steps}
for name, source, rows in (("Q", m["qsource"], tq), ("K", m["kvsource"], tk), ("V", m["kvsource"], tk)):
for i in range(rows):
for d in range(2):
frame = by_id[f"Copies_project_{name}_{i}_{d}"]
offset = 2*i+d
_same([frame["inputs"][key] for key in ("x0", "x1", "w0", "w1")],
[source[2*i], source[2*i+1], m["weights"][name][d], m["weights"][name][2+d]])
_same(list(frame["outputs"].values()),
[m["projection_products"][name][2*offset], m["projection_products"][name][2*offset+1],
m["projected"][name][offset]])
_same(by_id["Copies_scale"]["outputs"]["divisor"], m["divisor"])
leaf_index = 1
_same(helper["natives"][0], dict(id="Copies_sqrt", kind="sqrt", input=m["natives"][0]["input"],
output=m["natives"][0]["output"]))
for i in range(tq):
row = by_id[f"Copies_row_{i}"]
_same(row["outputs"]["max"], m["maxima"][i])
_same(row["outputs"]["denominator"], m["denominators"][i])
for j in range(tk):
offset = i*tk+j
score = by_id[f"Copies_score_{i}_{j}"]
_same([score["inputs"][key] for key in ("q0", "q1", "k0", "k1", "divisor")],
[m["projected"]["Q"][2*i], m["projected"]["Q"][2*i+1],
m["projected"]["K"][2*j], m["projected"]["K"][2*j+1], m["divisor"]])
_same(list(score["outputs"].values()), [m["score_products"][2*offset],
m["score_products"][2*offset+1], m["dots"][offset], m["scores"][offset]])
_same(row["inputs"][f"score{j}"], m["scores"][offset])
_same(row["outputs"][f"term{j}"], m["terms"][offset])
_same(row["outputs"][f"probability{j}"], m["probabilities"][offset])
if m["allowed"][i][j]:
_same(row["outputs"][f"shifted{j}"], m["shifts"][i][str(j)])
leaf = helper["natives"][leaf_index]
_same(leaf, dict(id=f"Copies_exp_{i}_{j}", kind="exp", input=m["natives"][leaf_index]["input"],
output=m["natives"][leaf_index]["output"]))
_same(leaf["input"], row["outputs"][f"shifted{j}"])
_same(leaf["output"], row["outputs"][f"term{j}"])
leaf_index += 1
else:
_require(f"shifted{j}" not in row["outputs"], "Forbidden shifted copy fabricated.")
for d in range(2):
pos = 2*offset+d
weighted = by_id[f"Copies_weighted_{i}_{j}_{d}"]
_same([weighted["inputs"][key] for key in ("probability", "value", "previous")],
[m["probabilities"][offset], m["projected"]["V"][2*j+d],
0.0 if j == 0 else m["partials"][pos-2]])
_same(list(weighted["outputs"].values()), [m["products"][pos], m["partials"][pos]])
_require(leaf_index == len(helper["natives"]), "Native occurrence missing or duplicated.")
aliases = {step["id"]+"_"+key: word for step in trace.steps for key, word in step["outputs"].items()}
_same(trace.outputs, aliases)
for key, expected in zip(("nativeIds", "nativeKinds"),
([leaf["id"] for leaf in helper["natives"]], [leaf["kind"] for leaf in helper["natives"]])):
_same(helper["texts"][key], expected)
# E's independent mixed-zero case binds own arguments, not only probabilities.
trace = variant_trace()
helper = evaluate_variant(dict(DEFAULT_IV60, query00=-0.0, query01=-0.0, memory10=0, memory11=-1), trace, "Mixed")
_same(helper["tensors"][15]["values"][:2], [-0.0, -0.0])
_same(helper["tensors"][21]["values"][:3], [-0.0, 0.0, -0.0])
_same(helper["tensors"][23]["values"][0], 0.0)
row = next(step for step in trace.steps if step["id"] == "Mixed_row_0")
_same([row["outputs"][f"shifted{j}"] for j in range(3)], [-0.0, 0.0, -0.0])
_same([leaf["input"] for leaf in helper["natives"][1:4]], [-0.0, 0.0, -0.0])
_same([leaf["output"] for leaf in helper["natives"][1:4]], [1.0, 1.0, 1.0])
_same(helper["tensors"][30]["values"][2:8], [-0.0, 1.0, 0.0, 1.0, -0.0, 1.0])
def check_capture_callbacks():
_explicit_checks_only()
original_first, original_binary, original_native = _scalar_first, _ScalarGraph.binary, _ScalarGraph.native
captured, visits = [], []
marker = RuntimeError("Observer identity")
def capture(value, prefix):
saved = original_first(value, prefix)
captured.append(saved)
return saved
def native(self, identifier, kind, argument):
visits.append(identifier)
return original_native(self, identifier, kind, argument)
def forbidden(*args):
raise AssertionError("Serialization performed scalar/native arithmetic.")
class Observer:
def __init__(self):
self.trace = variant_trace()
def add(self, identifier, label, equation, explanation, inputs, outputs):
_require(len(captured) == 1 and len(visits) == 7, "Callback preceded complete private capture.")
return self.trace.add(identifier, label, equation, explanation, inputs, outputs)
class FailingObserver:
def add(self, identifier, label, equation, explanation, inputs, outputs):
raise marker
globals()["_scalar_first"] = capture
_ScalarGraph.native = native
try:
observer = Observer()
actual = evaluate_variant(DEFAULT_IV60, observer, "Observe")
_require(len(captured) == 1 and len(visits) == 7, "Private capture or native occurrence repeated.")
_ScalarGraph.binary, _ScalarGraph.native = forbidden, forbidden
again_trace = variant_trace()
again = _bind_variant(captured[0][0], again_trace, "Observe")
_same(actual, again)
_same(observer.trace.steps, again_trace.steps)
_same(observer.trace.outputs, again_trace.outputs)
_ScalarGraph.binary, _ScalarGraph.native = original_binary, original_native
root_saved = original_first(DEFAULT_IV60, "variant")
root_calls = []
def saved_root(value, prefix):
_require(value is DEFAULT_IV60 and prefix == "variant", "Root capture call changed.")
root_calls.append(prefix)
return root_saved
globals()["_scalar_first"] = saved_root
_ScalarGraph.binary, _ScalarGraph.native = forbidden, forbidden
root = derive_iv60(DEFAULT_IV60)
_require(root_calls == ["variant"] and root["status"] == "defined", "Root recaptured or failed.")
_same(root["tensors"][29]["values"], root_saved[0]["output"])
_same(root["tensors"][30]["values"],
[word for leaf in root_saved[0]["natives"] for word in (leaf["input"], leaf["output"])])
globals()["_scalar_first"] = capture
_ScalarGraph.binary, _ScalarGraph.native = original_binary, original_native
try:
evaluate_variant(DEFAULT_IV60, FailingObserver(), "ObserverFailure")
except RuntimeError as error:
_require(error is marker, "Unknown observer error identity changed.")
else:
raise AssertionError("Observer error swallowed.")
finally:
globals()["_scalar_first"] = original_first
_ScalarGraph.binary, _ScalarGraph.native = original_binary, original_native
class Items:
def __init__(self):
self.visits = 0
def items(self):
self.visits += 1
return [("2", -0.0), ("0", 1.0), ("named", 2.0)]
inputs, outputs = Items(), Items()
trace = variant_trace()
trace.add("Once", "Once", "x=x", "Trusted once-items", inputs, outputs)
_require(inputs.visits == outputs.visits == 1, "Collector reread trusted operands.")
_require(tuple(trace.steps[0]["inputs"]) == ("0", "2", "named"), "Canonical index order changed.")
_same(trace.outputs["Once_2"], -0.0)
_expect_fault("INVALID_INPUT", lambda: trace.add("Once", "", "", "", None, None),
"Trace IDs must be nonempty and unique.")
_expect_fault("NONFINITE", lambda: trace.add("Bad", "", "", "", {"x": math.nan}, {}),
"Bad.inputs.x must be an actual finite number.")
_require("Bad" not in trace._ids and len(trace.steps) == 1, "Failing frame partially committed.")
capped = variant_trace()
for i in range(512):
capped.add("Cap"+str(i), "", "", "", {}, {})
_expect_fault("NONFINITE", lambda: capped.add("Beyond", "", "", "", {"x": math.nan}, {}))
_expect_fault("UNSUPPORTED_SIZE", lambda: capped.add("Beyond", "", "", "", {}, {}),
"At most 512 operations are supported.")
_require("Beyond" not in capped._ids and len(capped.steps) == 512, "Cap failure committed a frame.")
proto = variant_trace()
proto.add("_", "", "", "", {}, {"proto__": -0.0, "kept": 1.0})
_require("__proto__" not in proto.outputs and tuple(proto.steps[0]["outputs"]) == ("proto__", "kept"),
"Inherited setter alias omission changed.")
_same(proto.steps[0]["outputs"]["proto__"], -0.0)
class ThrowingItems:
def items(self):
raise marker
try:
proto.add("Unknown", "", "", "", ThrowingItems(), {})
except RuntimeError as error:
_require(error is marker and "Unknown" not in proto._ids, "Trusted observer error changed/committed.")
else:
raise AssertionError("Unknown operand observer error swallowed.")
def fail_public_native(self, identifier, kind, argument):
raise marker
_ScalarGraph.native = fail_public_native
try:
try:
derive_iv60(DEFAULT_IV60)
except RuntimeError as error:
_require(error is marker, "Root replaced unknown native error.")
else:
raise AssertionError("Root swallowed unknown native error.")
finally:
_ScalarGraph.native = original_native
3. Default, replacement and explicit-check entry: iv60.py
run() takes no arguments and derives the complete default cross record. derive_iv60(value) requires a complete replacement state; omitted fields are not filled from defaults. The command-line entry describes default, one complete JSON state, or standard input selected by -. Its parser rejects duplicate fields and nonfinite numbers, preserves integer -0, and limits integer tokens locally to 309 digits. Known parsing or numerical faults produce the unavailable record; unknown errors retain their identity. Checks are reached only by the explicit --self-check option, never by ordinary import or query.
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.
"""IV60 strict canonical entry with owner-adopted complete public records.
No checks run implicitly. All execution, including this entry, remains UNRUN.
The complete same-folder project closure is this entry, variants_reference.py,
and readonly decoder_reference.py; NumPy is an external storage dependency.
"""
import importlib.util
import json
from pathlib import Path
import sys
def _load_reference():
path = Path(__file__).resolve().with_name("variants_reference.py")
name = "_book_iv_p15_variants_reference"
if name in sys.modules:
module = sys.modules[name]
if Path(module.__file__).resolve() != path:
raise ImportError("IV60 reference module identity collision.")
return module
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError("IV60 reference loader unavailable.")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
try:
spec.loader.exec_module(module)
except BaseException:
if sys.modules.get(name) is module:
del sys.modules[name]
raise
return module
_reference = _load_reference()
NumericalFault = _reference.NumericalFault
DEFAULT_IV60 = _reference.DEFAULT_IV60
variant_state = _reference.variant_state
variant_trace = _reference.variant_trace
evaluate_variant = _reference.evaluate_variant
derive_iv60 = _reference.derive_iv60
def run():
"""Strict zero arguments; derive the complete default record."""
return derive_iv60(DEFAULT_IV60)
def _pairs(items):
result = {}
for key, value in items:
if key in result:
raise NumericalFault("INVALID_INPUT", "Duplicate JSON field: " + key)
result[key] = value
return result
def _integer(token):
digits = token[1:] if token.startswith("-") else token
if len(digits) > 309:
raise NumericalFault("INVALID_INPUT", "JSON integers are limited locally to 309 digits.")
return -0.0 if token == "-0" else int(token)
def _float(token):
value = float(token)
if not _reference.math.isfinite(value):
raise NumericalFault("NONFINITE", "JSON numbers must be finite.")
return value
def _constant(token):
raise NumericalFault("NONFINITE", "JSON numbers must be finite: " + token)
def _parse(text):
try:
return json.loads(text, object_pairs_hook=_pairs, parse_int=_integer,
parse_float=_float, parse_constant=_constant)
except json.JSONDecodeError as error:
raise NumericalFault("INVALID_INPUT", "Expected one complete JSON state.") from error
def _fault_record(fault):
return _reference._fault_record(fault)
def _dispatch_cli(arguments, reader):
option = arguments[0] if len(arguments) == 1 else ""
unknown_option = (option.startswith("-") and option not in ("-", "--self-check", "-Infinity")
and (len(option) < 2 or option[1] not in "0123456789"))
if len(arguments) > 1 or unknown_option:
return 2, "usage: iv60.py [COMPLETE_JSON_STATE | - | --self-check]"
if arguments == ["--self-check"]:
check_self()
return 0, "Explicit IV60 checks completed."
try:
if not arguments:
return 0, run()
text = reader() if arguments[0] == "-" else arguments[0]
return 0, derive_iv60(_parse(text))
except NumericalFault as fault:
return 0, _fault_record(fault)
def _cli(arguments, stdin, stdout, stderr):
status, record = _dispatch_cli(arguments, stdin.read)
if status == 2:
stderr.write(record + "\n")
else:
stdout.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")
return status
def check_cli():
_reference._explicit_checks_only()
import io
_require = _reference._require
_expect_fault = _reference._expect_fault
_expect_fault("INVALID_INPUT", lambda: _parse('{"q":1,"q":2}'))
_expect_fault("NONFINITE", lambda: _parse('{"q":NaN}'))
_expect_fault("NONFINITE", lambda: _parse('{"q":Infinity}'))
_expect_fault("NONFINITE", lambda: _parse('-Infinity'))
_expect_fault("NONFINITE", lambda: _parse('{"q":1e309}'))
_expect_fault("INVALID_INPUT", lambda: _parse("1"*310))
_expect_fault("INVALID_INPUT", lambda: _parse('{} {}'))
_expect_fault("INVALID_INPUT", lambda: _parse('[] trailing'))
_require(_reference._word(_parse('-0')) == _reference._word(-0.0), "JSON integer -0 erased.")
_require(_reference._word(_parse('-0.0')) == _reference._word(-0.0), "JSON float -0 erased.")
_require(type(_parse('1'*309)) is int, "309-digit local integer rejected.")
for arguments in (("--unknown",), ("-x",), ("{}", "{}"), ("--self-check", "{}")):
stdout, stderr = io.StringIO(), io.StringIO()
_require(_cli(list(arguments), io.StringIO(), stdout, stderr) == 2, "CLI misuse must exit2.")
_require(not stdout.getvalue() and bool(stderr.getvalue()), "CLI misuse output channel wrong.")
digit_limit = sys.get_int_max_str_digits() if hasattr(sys, "get_int_max_str_digits") else None
_parse('1'*309)
_require((sys.get_int_max_str_digits() if hasattr(sys, "get_int_max_str_digits") else None) == digit_limit,
"Parser changed a process-wide digit policy.")
original_self = check_self
def hidden_check():
raise AssertionError("Ordinary query invoked explicit checks.")
globals()["check_self"] = hidden_check
try:
_require(run()["status"] == "defined" and derive_iv60({})["status"] == "unavailable",
"Ordinary query/fault behavior changed.")
finally:
globals()["check_self"] = original_self
complete = json.dumps(dict(DEFAULT_IV60, q=0, query00=-0.0))
for arguments, incoming, state in (([], "", DEFAULT_IV60), ([complete], "", _parse(complete)),
(["-"], complete, _parse(complete))):
stdout, stderr = io.StringIO(), io.StringIO()
_require(_cli(arguments, io.StringIO(incoming), stdout, stderr) == 0, "Valid CLI must exit0.")
_require(not stderr.getvalue(), "Valid CLI wrote stderr.")
actual = _parse(stdout.getvalue())
_reference._same(actual, derive_iv60(state))
_require(tuple(actual) == ("status", "outputs", "steps", "tensors", "texts"), "CLI root schema changed.")
_require(_reference._word(_parse(complete)["query00"]) == _reference._word(-0.0), "CLI input -0 lost.")
for text, code in (('{}', "INVALID_INPUT"), ('{"q":1,"q":2}', "INVALID_INPUT"),
('{"q":1e309}', "NONFINITE"), ('1'*310, "INVALID_INPUT"),
('1'*309, "INVALID_INPUT"), ('-0', "INVALID_INPUT"),
('{"q":NaN}', "NONFINITE"), ('-Infinity', "NONFINITE"), ('{} {}', "INVALID_INPUT"),
(json.dumps(dict(DEFAULT_IV60, mode=1, key0=0)), "FULLY_MASKED_ROW")):
stdout, stderr = io.StringIO(), io.StringIO()
_require(_cli([text], io.StringIO(), stdout, stderr) == 0, "Known JSON/semantic fault must exit0.")
actual = _parse(stdout.getvalue())
_require(not stderr.getvalue() and tuple(actual) == ("status", "code", "reason") and
actual["status"] == "unavailable" and actual["code"] == code, "Actual fault JSON changed.")
original_derive, marker = derive_iv60, MemoryError("Resource identity")
try:
def fail(value):
raise marker
globals()["derive_iv60"] = fail
try:
_dispatch_cli([complete], lambda: "")
except MemoryError as error:
_require(error is marker, "Resource exception identity changed.")
else:
raise AssertionError("Resource error swallowed.")
finally:
globals()["derive_iv60"] = original_derive
try:
run(DEFAULT_IV60)
except TypeError:
pass
else:
raise AssertionError("run accepted an argument.")
_require(_load_reference() is _reference, "Reference loader identity changed.")
_require(Path(_reference.__file__).resolve() == Path(__file__).resolve().with_name("variants_reference.py"),
"Reference escaped same-folder closure.")
_require(NumericalFault is _reference._support.NumericalFault, "Entry fault identity changed.")
_require(sys.modules.get("_book_iv_p15_variants_reference") is _reference, "Reference cached key changed.")
for name in ("variant_state", "variant_trace", "evaluate_variant", "derive_iv60"):
function = globals()[name]
_require(function is getattr(_reference, name) and function.__code__ is getattr(_reference, name).__code__,
"Entry public code identity changed.")
for function, arity in ((_load_reference, 0), (run, 0), (_pairs, 1), (_integer, 1), (_float, 1),
(_constant, 1), (_parse, 1), (_fault_record, 1), (_dispatch_cli, 2), (_cli, 4),
(check_cli, 0), (check_self, 0)):
_require(function.__module__ == __name__ and function.__code__.co_argcount == arity and
Path(function.__code__.co_filename).resolve() == Path(__file__).resolve(),
"Entry declaration/code identity changed.")
def check_self():
_reference._explicit_checks_only()
_reference.check_mechanism()
_reference.check_boundaries()
_reference.check_closure()
_reference.check_public_binding()
_reference.check_copies()
_reference.check_capture_callbacks()
check_cli()
if __name__ == "__main__":
raise SystemExit(_cli(sys.argv[1:], sys.stdin, sys.stdout, sys.stderr))
The independent mathematical verifier has a separate four-project-file design: iv60_exact.py, variants_authority.py, readonly decoder_authority.py and readonly generic generalization_authority.py. Reuse there is limited to generic faults, word/RN arithmetic and independent native-reference mechanisms; old IV59 task adapters, verifiers and task checks cannot serve as IV60 proof. Completion and review of that independent binding belong to the owner. Each producer’s own actual native leaves must first meet the four-word-step admission rule, followed by exact rounded-operation and every-copy replay. These file counts describe source dependencies, not successful imports, native compliance or parity. Graph operation counts also make no hardware timing, throughput, memory-traffic or trained-capability claim.
Carry these distinctions forward
- Self-attention shares one source; cross-attention uses distinct query and K/V sources, with unequal lengths allowed.
- Causality limits positions within the decoder stream. Key padding intersects eligibility and retains every query row in this lesson.
- Softmax weights multiply values; equal default features do not establish equal provenance or general architectural equivalence.
- Empty allowed rows are undefined distributions. Zero gains do not repair them.
- The real-number worksheet explains the calculation; ordered floating-point products, native leaves and saved copies require their own evidence.
The next topic, Multi-Query and Grouped-Query Attention, asks how several query heads can share fewer key/value heads. That changes head routing and storage; it does not remove the need to track query/key origins and axes precisely.