The neural notebook
← All chapters

IV-64 / Part XV · Modern LLM Architectures

Inference Systems: Throughput and Latency

Count a disclosed decoder's weights, cache and matrix work; follow every operation of a fixed tiny MLP; distinguish these counts from later explicit local timing.

Review the ideas this chapter uses

Two people can ask the same model a question and wait different lengths of time. One supplies a long prompt; the other requests a long answer. A system might also group their requests together. To reason about these choices, first count what a disclosed model would store and calculate, then ask what a clock observation could establish.

Learning objective: Reason about prefill, decode, batching and memory-bound tradeoffs.

Start with a small manual anchor: the default hypothetical model has 512 weight bytes, 48 cache bytes after the prompt, and 80 cache bytes after two appended passes. Its matrix-work count is 1568 MACs. These are hand-derived counts, not printed program outputs, allocated memory, or measured times. Initial measurement status is NOT_MEASURED, with no numeric duration or rate.

Review IV-50 — KV Cache Memory, Latency and Invalidation for cache validity, IV-61 — Multi-Query and Grouped-Query Attention for shared keys and values, and IV-63 — Quantization and Numerical Approximation for actual quantization. Book II’s II.4 — Dot product, angle, and orthogonality and II.10 — Matrix × matrix as composition explain dot products and matrix composition; VIII.1 — Floating-point representation explains floating-point storage. Book III’s III-02 — Samples, Features, Labels and Targets separates samples from features, III-41 — Composition and Learned Representations develops composition, and III-39 — Reproducibility and Numerical Reliability discusses numerical reliability. Those connections help us distinguish a correct calculation from evidence for a broader claim.

Compute it yourself

Count a disclosed decoder, inspect a real tiny MLP

A prompt is processed first; each later appended pass processes one more token per sequence. Change eleven whole-number settings to inspect shared weights, retained K/V, dense versus allowed score pairs and every counted matrix term. Bytes and MACs describe this hypothetical model; they do not supply milliseconds.

Nine fields accept integers in their labeled ranges; weight/cache menus select 8, 16 or 32 bits. M must be divisible by Hq, Hq must be divisible by Hkv, and Hkv must be no greater than Hq. Invalid drafts withhold the evidence, timing buttons and grading; correct them or Reset. The real one/three-row MLP previews always stay binary64 and use hand-set weights.

Edits and Reset clear answers and invalidate timing even if the draft is invalid. Trace selection clears answers but preserves measurement revision; disclosure and grading preserve both. All saved evidence remains available through named, keyboard-focusable scrolling tables. Timing starts only from an explicit Measure button below, never from mount, edits, derive or seek.

d2
J2
groupWidth2
parameters256
Exact starting inputs for this saved calculation

d 2. J 2. groupWidth 2. parameters 256. Derive head widths and hypothetical scalar bytes. All eleven raw fields have already passed structural, finite, integer and sharing checks. Bit choices change logical payload only; the real toy always uses binary64.

Derive head widths and hypothetical scalar bytes

d=M/Hq; J=Hkv*d; groupWidth=Hq/Hkv; weightBytesPerScalar=weightBits/8; kvBytesPerScalar=kvBits/8

All eleven raw fields have already passed structural, finite, integer and sharing checks. Bit choices change logical payload only; the real toy always uses binary64.

Saved inputs

M
4
Hq
2
Hkv
1
weightBits
16
kvBits
16
bitsPerByte
8

Saved outputs

d
2
J
2
groupWidth
2
weightBytesPerScalar
2
kvBytesPerScalar
2

Whole saved planner: weights 512 bytes; prefill/final cache 48/80 bytes; dense/allowed cells 36/24; prefill/append/total MAC 912/656/1568. No absence: every requested append pass has its saved row, cache and scratch counts. Selected saved step systems_dimensions. Derive head widths and hypothetical scalar bytes. Equation: d=M/Hq; J=Hkv*d; groupWidth=Hq/Hkv; weightBytesPerScalar=weightBits/8; kvBytesPerScalar=kvBits/8. All eleven raw fields have already passed structural, finite, integer and sharing checks. Bit choices change logical payload only; the real toy always uses binary64. Inputs: M=4; Hq=2; Hkv=1; weightBits=16; kvBits=16; bitsPerByte=8. Outputs: d=2; J=2; groupWidth=2; weightBytesPerScalar=2; kvBytesPerScalar=2.

Current whole planner: counts before clocks

These values come from the complete saved root. The trace picker above highlights an actual saved operation; it does not replace the whole totals. Use Previous/Next or the keyboard-selectable step menu, then open the complete frame fallback to inspect every input and output in that selected operation.

Every saved analytical summary count; units follow each named field
Saved fieldSaved integer
d2
J2
groupWidth2
parameters256
weightBytes512
metadataBytes0
prefillKBytes24
prefillVBytes24
prefillCacheBytes48
finalKBytes40
finalVBytes40
finalCacheBytes80
cacheGrowthBytes16
prefillDenseCells36
prefillAllowedCells24
appendScoreCells36
baseMACPerToken256
prefillMAC912
appendMAC656
totalMAC1568
matrixFLOPs3136
prefillScratchBytes576
prefillAccountedBytes1136
finalScratchBytes224
finalAccountedBytes816
finalHistory5
selectedOutputsWithoutEOS3

Hypothetical bias-free decoder-shaped accounting: L distinct layers, tied embedding/readout [V,M] stored once, Q/O [M,M], K/V [M,J], ordinary FFN [M,F] then [F,M]. No norm, position, bias or gating parameters; no padding, EOS, early stop, scheduler or queue. All processed rows get readout. No hypothetical neural array is allocated.

Analytical shapes only: X [B,q,M], Q [B,Hq,q,d], each per-layer original K/V [B,Hkv,S,d], scores/probabilities [B,Hq,q,S], joined [B,q,M], logits [B,q,V]. Prefill q=S=T; append q=1,S=T+j. Layers contribute counts, never an allocated rank-five cache.

Exact nonnegative integer factors and ordered sums below 2^53. Dense computed prefill cells and causal-allowed cells are separate. Both K and V are counted once, using Hkv; score paths use Hq. MAC means a scalar matrix product term; matrix FLOPs=2*MAC, not all executed operations or fused instruction counts.

Saved parameter graph and represented weights

d is features per query head (M/Hq); J is the shared K/V projected width (Hkv*d); groupWidth is query heads per stored K/V group (Hq/Hkv). The saved dimensions frame retains these divisions and the assumed bytes per scalar.

The six rows count Q,K,V,O,FF1,FF2 per layer; their saved partial column exposes the ordered sum. Shared embedding/readout is stored once. These scalar ledgers do not allocate the hypothetical matrices.

All six per-layer parameter products and ordered partial sums
Saved rowinputWidthoutputWidthproductpartial
Q441616
K42824
V42832
O441648
FF1483280
FF28432112
Tied embedding, distinct layers and hypothetical represented bytes
Saved rowembeddingParameterslayerParametersparametersweightBytesPerScalarweightBytesmetadataBytesrepresentedBytes
shared weights3222425625120512
Every query head and its saved contiguous K/V sharing group
Query head (zero-based)Original K/V group
00
10

weightBits/kvBits choose uniform represented bytes only; metadata=0 is an explicit fictional raw-format assumption. No packing, scales, zero points, rounding, quantization, cast or quality experiment. Fixed toy inputs, weights and buffers remain binary64 at every planner choice.

Prefill, cache growth and every performed append

Separate K and V: one-position growth, prefill and every actual planned append
Saved rowhistoryKElementsVElementstotalElementsKBytesVBytestotalBytes
growth14488816
prefill3121224242448
append_14161632323264
append_25202040404080
Every prefill query: allowed-key count and saved causal partial
Saved rowkeyspreviouspartial
query 0101
query 1213
query 2336
Dense computed versus causal-allowed prefill; work, scratch and accounted bytes
Saved rowdenseCellsallowedCellsmatrixMACscratchBytesaccountedBytes
prefill36249125761136

No absence: every requested append pass has its saved row, cache and scratch counts.

Every performed append pass, including its own K/V and both increasing-j aggregates
Saved rowjhistoryscoreCellsmatrixMACKBytesVBytescacheBytesscratchBytesaccountedBytescumulativeScoreCellscumulativeMAC
append_1141632032326420878416320
append_2252033640408022481636656
Two actual append folds plus closed-form score and MAC component totals
Saved rowactualScoreCellsclosedScoreCellshistorySumbaseMACscoreMACmessageMACactualMAC
append aggregate363695127272656

The actual increasing-j folds are score cells and total MACs. Base, score and message MAC components are saved for each row and as closed-form totals; they are not three additional loop-fold reductions. At D=0 the aggregate is computed zero; no append or last-append row is invented.

D counts appended forward passes, not selected tokens. With nonempty prompt, G>=1, no EOS and stop after the final selection, D=G-1 and cache length T+D excludes the final selected token. Forwarding it is a different policy. No actual generation is performed.

Declared scratch: each saved factor and sum

Declared one-layer simultaneous buffer ledger only: five M-wide arrays, one F-wide hidden, one V-wide logits, separate scores and probabilities at hypothetical four bytes/scalar. Retain all-layer cache and shared weights separately. Exclude masks, IDs, selection buffers, headers, alignment, allocator reservation, library temporaries, traces, JIT/code/OS/device copies and traffic; no physical peak or bandwidth claim.

One-layer scratch at prefill and every performed append, with weights-plus-cache and accounted sums
Saved rowqhistoryBqfiveMplusFwidthfeatureElementsBHqheadQueriesscoreElementsprobabilityElementsscorePairtotalElementsscratchBytesweightAndCacheaccountedBytes
prefill333202836108261818361445765601136
append_11412028363622881652208576784
append_2151202836362210102056224592816

Two actual, untimed MLP previews

Independent one-row then three-row factories each run exactly once. Eight products and eight additions per row in affine paths, two ReLU decisions, plus two checksum additions and buffer/index/control work. Per coordinate start literal +0, compute both terms in increasing feature order; inactive ReLU is literal +0. Inspection and trace copy saved floats only. These hand-set untrained independent samples are not a transformer, attention, cache, token or server benchmark.

Raw state, counts, dimensions, indices, metadata and WorkCounts use VALUE (D=-0 equals zero). Every other toy tensor value and every toy floating frame operand/result/checksum/copy uses WORD, including literal +0, computed -0 and integral-looking floats. No native elementary functions or native witness fields exist.

In each affine table, the final axis is [left, right, product, previous, sum]; checksum folds use [previous, value, sum]. Each coordinate starts at literal +0 and executes both products/additions, including zero products. HiddenLinear precedes ReLU; Y then feeds the saved row-major checksum. The following tables copy every saved word without rounding or another computation. WorkCounts fields are [products, affineAdditions, reluDecisions, checksumAdditions].

Complete 1-row preview: X, W1, W2, every affine term, ReLU, Y and checksum

Algorithm iv64-mlp-ordered-fold-v1; evidence probe-correctness; saved checksum 3. This is correctness evidence from one untimed run, not a timing observation.

Open “Complete tensor fallback” below for these exact storage IDs: systems_toy1_X, systems_toy1_W1, systems_toy1_W2, systems_toy1_Affine1, systems_toy1_HiddenLinear, systems_toy1_Hidden, systems_toy1_Affine2, systems_toy1_Y, systems_toy1_ChecksumFolds, systems_toy1_Checksum, systems_toy1_WorkCounts. Each appears once there with all seven fields and every cell. The complete frame fallback also contains every ordered product/addition, both ReLU decisions per row and each checksum fold.

systems_toy1_X: complete preview words; shape [1, 2], axes [Row, Input]
Storage index (zero-based)Saved word or count
01
10
systems_toy1_W1: complete preview words; shape [2, 2], axes [Input, Hidden]
Storage index (zero-based)Saved word or count
01
1-1
21
31
systems_toy1_W2: complete preview words; shape [2, 2], axes [Hidden, Output]
Storage index (zero-based)Saved word or count
01
12
2-1
31
systems_toy1_Affine1: complete preview words; shape [1, 2, 2, 5], axes [Row, Hidden, Input, AffineField]
Storage index (zero-based)Saved word or count
01
11
21
30
41
50
61
70
81
91
101
11-1
12-1
130
14-1
150
161
170
18-1
19-1
systems_toy1_HiddenLinear: complete preview words; shape [1, 2], axes [Row, Hidden]
Storage index (zero-based)Saved word or count
01
1-1
systems_toy1_Hidden: complete preview words; shape [1, 2], axes [Row, Hidden]
Storage index (zero-based)Saved word or count
01
10
systems_toy1_Affine2: complete preview words; shape [1, 2, 2, 5], axes [Row, Output, Hidden, AffineField]
Storage index (zero-based)Saved word or count
01
11
21
30
41
50
6-1
7-0
81
91
101
112
122
130
142
150
161
170
182
192
systems_toy1_Y: complete preview words; shape [1, 2], axes [Row, Output]
Storage index (zero-based)Saved word or count
01
12
systems_toy1_ChecksumFolds: complete preview words; shape [1, 2, 3], axes [Row, Output, FoldField]
Storage index (zero-based)Saved word or count
00
11
21
31
42
53
systems_toy1_Checksum: complete preview words; shape [1], axes [Scalar]
Storage index (zero-based)Saved word or count
03
systems_toy1_WorkCounts: complete preview words; shape [4], axes [WorkCount]
Storage index (zero-based)Saved word or count
08
18
22
32
Complete 3-row preview: X, W1, W2, every affine term, ReLU, Y and checksum

Algorithm iv64-mlp-ordered-fold-v1; evidence probe-correctness; saved checksum 12. This is correctness evidence from one untimed run, not a timing observation.

Open “Complete tensor fallback” below for these exact storage IDs: systems_toy3_X, systems_toy3_W1, systems_toy3_W2, systems_toy3_Affine1, systems_toy3_HiddenLinear, systems_toy3_Hidden, systems_toy3_Affine2, systems_toy3_Y, systems_toy3_ChecksumFolds, systems_toy3_Checksum, systems_toy3_WorkCounts. Each appears once there with all seven fields and every cell. The complete frame fallback also contains every ordered product/addition, both ReLU decisions per row and each checksum fold.

systems_toy3_X: complete preview words; shape [3, 2], axes [Row, Input]
Storage index (zero-based)Saved word or count
01
10
20
31
41
51
systems_toy3_W1: complete preview words; shape [2, 2], axes [Input, Hidden]
Storage index (zero-based)Saved word or count
01
1-1
21
31
systems_toy3_W2: complete preview words; shape [2, 2], axes [Hidden, Output]
Storage index (zero-based)Saved word or count
01
12
2-1
31
systems_toy3_Affine1: complete preview words; shape [3, 2, 2, 5], axes [Row, Hidden, Input, AffineField]
Storage index (zero-based)Saved word or count
01
11
21
30
41
50
61
70
81
91
101
11-1
12-1
130
14-1
150
161
170
18-1
19-1
200
211
220
230
240
251
261
271
280
291
300
31-1
32-0
330
340
351
361
371
380
391
401
411
421
430
441
451
461
471
481
492
501
51-1
52-1
530
54-1
551
561
571
58-1
590
systems_toy3_HiddenLinear: complete preview words; shape [3, 2], axes [Row, Hidden]
Storage index (zero-based)Saved word or count
01
1-1
21
31
42
50
systems_toy3_Hidden: complete preview words; shape [3, 2], axes [Row, Hidden]
Storage index (zero-based)Saved word or count
01
10
21
31
42
50
systems_toy3_Affine2: complete preview words; shape [3, 2, 2, 5], axes [Row, Output, Hidden, AffineField]
Storage index (zero-based)Saved word or count
01
11
21
30
41
50
6-1
7-0
81
91
101
112
122
130
142
150
161
170
182
192
201
211
221
230
241
251
26-1
27-1
281
290
301
312
322
330
342
351
361
371
382
393
402
411
422
430
442
450
46-1
47-0
482
492
502
512
524
530
544
550
561
570
584
594
systems_toy3_Y: complete preview words; shape [3, 2], axes [Row, Output]
Storage index (zero-based)Saved word or count
01
12
20
33
42
54
systems_toy3_ChecksumFolds: complete preview words; shape [3, 2, 3], axes [Row, Output, FoldField]
Storage index (zero-based)Saved word or count
00
11
21
31
42
53
63
70
83
93
103
116
126
132
148
158
164
1712
systems_toy3_Checksum: complete preview words; shape [1], axes [Scalar]
Storage index (zero-based)Saved word or count
012
systems_toy3_WorkCounts: complete preview words; shape [4], axes [WorkCount]
Storage index (zero-based)Saved word or count
024
124
26
36

Pure-record timingStatus=NOT_MEASURED describes this clock-free numerical record even after a separate action below; local reports never enter its tensors, frames or canonical witness.

NOT_MEASURED has no numeric duration or rate. This pure model never samples a clock, warms up or repeats work. A separate parent-owned explicit-action controller must reuse createToyWork; synthetic clocks cannot establish real measurement. Counts and checksum correctness do not prove speedup, memory-boundness, hardware execution or quality.

Separate local timing of the fixed MLP

Measure one complete one-row or three-row MLP batch per work unit. These are independent sample rows, not generated tokens. Planner controls do not change this fixed binary64 workload. Opening the lesson and editing or seeking do not measure it.

NOT_MEASURED. Settings revision 0.

Each accepted action prepares buffers, runs two untimed warmup units, then three trials of128 units. The interval includes real MLP arithmetic, saved-buffer stores, loop/call work and checksum folding. It excludes setup, validation, rendering and yields. A synchronous128-unit trial finishes before cancellation is observed at the next yield. Equal clock endpoints mean insufficient resolution; no automatic retry or larger trial is used.

Every raw edit or Reset invalidates active work and drops both reports, including invalid drafts. Seeking, opening evidence and grading preserve the timing revision. Only complete observations at the current revision appear; earlier complete reports retained during another action are labeled prior. No numeric measurement placeholder exists before completion.

All eleven current saved controls in capture order
Complete saved raw11; every control including inactive D0 fields
FieldSaved value
B1
L2
T3
D2
M4
Hq2
Hkv1
F8
V8
weightBits16
kvBits16
Complete tensor fallback: all seven fields and every cell (33 tensors)

All tensors are included once here. Shape and axes locate flattened storage. VALUE counts and indices remain distinct from WORD toy operands/results, including -0. Declared display precision does not alter the shown saved values. No table is truncated and no hypothetical-size neural array is allocated.

systems_RawState

Shape [11] · axes [RawField] · float64 · declared display precision 0

All eleven captured raw VALUE fields in texts.rawFields order; D=-0 is VALUE zero.

systems_RawState: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
12
23
32
44
52
61
78
88
916
1016

systems_HeadToGroup

Shape [2] · axes [QueryHead] · float64 · declared display precision 0

Contiguous shared K/V group per query head; no expanded cache is allocated.

systems_HeadToGroup: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10

systems_ParameterLedger

Shape [6, 4] · axes [Matrix, ParameterField] · float64 · declared display precision 0

Q,K,V,O,FF1,FF2 rows; inputWidth,outputWidth,product,partial. Only scalar count evidence, never allocated model weights.

systems_ParameterLedger: every saved cell in row-major storage order
Storage index (zero-based)Saved value
04
14
216
316
44
52
68
724
84
92
108
1132
124
134
1416
1548
164
178
1832
1980
208
214
2232
23112

systems_WeightLedger

Shape [7] · axes [WeightField] · float64 · declared display precision 0

embeddingParameters,layerParameters,parameters,weightBytesPerScalar,weightBytes,metadataBytes,representedBytes; zero metadata is an assumption.

systems_WeightLedger: every saved cell in row-major storage order
Storage index (zero-based)Saved value
032
1224
2256
32
4512
50
6512

systems_CacheLedger

Shape [4, 7] · axes [CacheStage, CacheField] · float64 · declared display precision 0

Rows: one-position growth, prefill, then performed append passes in increasing j. Fields: history,KElements,VElements,totalElements,KBytes,VBytes,totalBytes. No hypothetical cache tensor is allocated.

systems_CacheLedger: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
14
24
38
48
58
616
73
812
912
1024
1124
1224
1348
144
1516
1616
1732
1832
1932
2064
215
2220
2320
2440
2540
2640
2780

systems_CausalRows

Shape [3, 3] · axes [PromptQuery, CausalField] · float64 · declared display precision 0

keys,previous,partial for actual increasing-query causal eligibility; dense computed work stays separate.

systems_CausalRows: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
10
21
32
41
53
63
73
86

systems_PrefillCounts

Shape [5] · axes [PrefillField] · float64 · declared display precision 0

denseCells,allowedCells,matrixMAC,scratchBytes,accountedBytes for prefill; counts are not observations.

systems_PrefillCounts: every saved cell in row-major storage order
Storage index (zero-based)Saved value
036
124
2912
3576
41136

systems_AppendRows

Shape [2, 11] · axes [AppendPass, AppendField] · float64 · declared display precision 0

j,history,scoreCells,matrixMAC,KBytes,VBytes,cacheBytes,scratchBytes,accountedBytes,cumulativeScoreCells,cumulativeMAC for performed passes only. Absent when D=0.

systems_AppendRows: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
14
216
3320
432
532
664
7208
8784
916
10320
112
125
1320
14336
1540
1640
1780
18224
19816
2036
21656

systems_AppendTotals

Shape [7] · axes [AppendTotalField] · float64 · declared display precision 0

actualScoreCells,closedScoreCells,historySum,baseMAC,scoreMAC,messageMAC,actualMAC; a computed zero aggregate is retained at D=0.

systems_AppendTotals: every saved cell in row-major storage order
Storage index (zero-based)Saved value
036
136
29
3512
472
572
6656

systems_ScratchLedger

Shape [3, 16] · axes [ScratchStage, ScratchField] · float64 · declared display precision 0

Prefill then performed append rows. q,history,Bq,fiveM,plusF,width,featureElements,BHq,headQueries,scoreElements,probabilityElements,scorePair,totalElements,scratchBytes,weightAndCache,accountedBytes. Declared one-layer buffers only, not physical peak memory.

systems_ScratchLedger: every saved cell in row-major storage order
Storage index (zero-based)Saved value
03
13
23
320
428
536
6108
72
86
918
1018
1136
12144
13576
14560
151136
161
174
181
1920
2028
2136
2236
232
242
258
268
2716
2852
29208
30576
31784
321
335
341
3520
3628
3736
3836
392
402
4110
4210
4320
4456
45224
46592
47816

systems_AnalyticalSummary

Shape [27] · axes [AnalyticalField] · float64 · declared display precision 0

Saved analytical VALUE counts in texts.analyticalFields order; no toy float, clock, duration or rate.

systems_AnalyticalSummary: every saved cell in row-major storage order
Storage index (zero-based)Saved value
02
12
22
3256
4512
50
624
724
848
940
1040
1180
1216
1336
1424
1536
16256
17912
18656
191568
203136
21576
221136
23224
24816
255
263

systems_toy1_X

Shape [1, 2] · axes [Row, Input] · float64 · declared display precision 8

Actual fixed binary64 row-feature input; independent sample rows, not autoregressive tokens.

systems_toy1_X: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
10

systems_toy1_W1

Shape [2, 2] · axes [Input, Hidden] · float64 · declared display precision 8

Actual fixed untrained row-feature first weights [[1,-1],[1,1]]; zero biases are omitted, not added.

systems_toy1_W1: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
1-1
21
31

systems_toy1_W2

Shape [2, 2] · axes [Hidden, Output] · float64 · declared display precision 8

Actual fixed untrained row-feature second weights [[1,2],[-1,1]]; shared by all rows.

systems_toy1_W2: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
12
2-1
31

systems_toy1_Affine1

Shape [1, 2, 2, 5] · axes [Row, Hidden, Input, AffineField] · float64 · declared display precision 8

Saved left,right,product,previous,sum per first-affine term, in row,hidden,input order. Every entry is a binary64 WORD, including +0 and computed -0.

systems_toy1_Affine1: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
11
21
30
41
50
61
70
81
91
101
11-1
12-1
130
14-1
150
161
170
18-1
19-1

systems_toy1_HiddenLinear

Shape [1, 2] · axes [Row, Hidden] · float64 · declared display precision 8

Saved final first-affine partials before ReLU; no floating recomputation while inspecting or tracing.

systems_toy1_HiddenLinear: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
1-1

systems_toy1_Hidden

Shape [1, 2] · axes [Row, Hidden] · float64 · declared display precision 8

Saved actual ReLU outputs, with literal +0 for linear<=0.

systems_toy1_Hidden: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
10

systems_toy1_Affine2

Shape [1, 2, 2, 5] · axes [Row, Output, Hidden, AffineField] · float64 · declared display precision 8

Saved left,right,product,previous,sum per second-affine term, in row,output,hidden order. All zero products execute.

systems_toy1_Affine2: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
11
21
30
41
50
6-1
7-0
81
91
101
112
122
130
142
150
161
170
182
192

systems_toy1_Y

Shape [1, 2] · axes [Row, Output] · float64 · declared display precision 8

Saved actual second-affine outputs consumed by the checksum; no constant-result replacement.

systems_toy1_Y: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
12

systems_toy1_ChecksumFolds

Shape [1, 2, 3] · axes [Row, Output, FoldField] · float64 · declared display precision 8

Saved previous,value,sum per actual row-major checksum addition, initialized literal +0.

systems_toy1_ChecksumFolds: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
11
21
31
42
53

systems_toy1_Checksum

Shape [1] · axes [Scalar] · float64 · declared display precision 8

Copy of the completed factory checksum WORD; deterministic correctness only, never a duration or measurement.

systems_toy1_Checksum: every saved cell in row-major storage order
Storage index (zero-based)Saved value
03

systems_toy1_WorkCounts

Shape [4] · axes [WorkCount] · float64 · declared display precision 0

products,affineAdditions,reluDecisions,checksumAdditions for one complete batch; loop/index/control/buffer stores are additional.

systems_toy1_WorkCounts: every saved cell in row-major storage order
Storage index (zero-based)Saved value
08
18
22
32

systems_toy3_X

Shape [3, 2] · axes [Row, Input] · float64 · declared display precision 8

Actual fixed binary64 row-feature input; independent sample rows, not autoregressive tokens.

systems_toy3_X: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
10
20
31
41
51

systems_toy3_W1

Shape [2, 2] · axes [Input, Hidden] · float64 · declared display precision 8

Actual fixed untrained row-feature first weights [[1,-1],[1,1]]; zero biases are omitted, not added.

systems_toy3_W1: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
1-1
21
31

systems_toy3_W2

Shape [2, 2] · axes [Hidden, Output] · float64 · declared display precision 8

Actual fixed untrained row-feature second weights [[1,2],[-1,1]]; shared by all rows.

systems_toy3_W2: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
12
2-1
31

systems_toy3_Affine1

Shape [3, 2, 2, 5] · axes [Row, Hidden, Input, AffineField] · float64 · declared display precision 8

Saved left,right,product,previous,sum per first-affine term, in row,hidden,input order. Every entry is a binary64 WORD, including +0 and computed -0.

systems_toy3_Affine1: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
11
21
30
41
50
61
70
81
91
101
11-1
12-1
130
14-1
150
161
170
18-1
19-1
200
211
220
230
240
251
261
271
280
291
300
31-1
32-0
330
340
351
361
371
380
391
401
411
421
430
441
451
461
471
481
492
501
51-1
52-1
530
54-1
551
561
571
58-1
590

systems_toy3_HiddenLinear

Shape [3, 2] · axes [Row, Hidden] · float64 · declared display precision 8

Saved final first-affine partials before ReLU; no floating recomputation while inspecting or tracing.

systems_toy3_HiddenLinear: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
1-1
21
31
42
50

systems_toy3_Hidden

Shape [3, 2] · axes [Row, Hidden] · float64 · declared display precision 8

Saved actual ReLU outputs, with literal +0 for linear<=0.

systems_toy3_Hidden: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
10
21
31
42
50

systems_toy3_Affine2

Shape [3, 2, 2, 5] · axes [Row, Output, Hidden, AffineField] · float64 · declared display precision 8

Saved left,right,product,previous,sum per second-affine term, in row,output,hidden order. All zero products execute.

systems_toy3_Affine2: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
11
21
30
41
50
6-1
7-0
81
91
101
112
122
130
142
150
161
170
182
192
201
211
221
230
241
251
26-1
27-1
281
290
301
312
322
330
342
351
361
371
382
393
402
411
422
430
442
450
46-1
47-0
482
492
502
512
524
530
544
550
561
570
584
594

systems_toy3_Y

Shape [3, 2] · axes [Row, Output] · float64 · declared display precision 8

Saved actual second-affine outputs consumed by the checksum; no constant-result replacement.

systems_toy3_Y: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
12
20
33
42
54

systems_toy3_ChecksumFolds

Shape [3, 2, 3] · axes [Row, Output, FoldField] · float64 · declared display precision 8

Saved previous,value,sum per actual row-major checksum addition, initialized literal +0.

systems_toy3_ChecksumFolds: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
11
21
31
42
53
63
70
83
93
103
116
126
132
148
158
164
1712

systems_toy3_Checksum

Shape [1] · axes [Scalar] · float64 · declared display precision 8

Copy of the completed factory checksum WORD; deterministic correctness only, never a duration or measurement.

systems_toy3_Checksum: every saved cell in row-major storage order
Storage index (zero-based)Saved value
012

systems_toy3_WorkCounts

Shape [4] · axes [WorkCount] · float64 · declared display precision 0

products,affineAdditions,reluDecisions,checksumAdditions for one complete batch; loop/index/control/buffer stores are additional.

systems_toy3_WorkCounts: every saved cell in row-major storage order
Storage index (zero-based)Saved value
024
124
26
36
Complete frame fallback: every field of every saved operation (79 frames)

Each frame retains id, label, equation, explanation, complete inputs and complete outputs. All frames remain visible in this disclosure; the selected frame is marked in text and with aria-current. Read operands in their saved insertion order; these values are never recomputed here.

Derive head widths and hypothetical scalar bytes

systems_dimensions — selected saved step

d=M/Hq; J=Hkv*d; groupWidth=Hq/Hkv; weightBytesPerScalar=weightBits/8; kvBytesPerScalar=kvBits/8

All eleven raw fields have already passed structural, finite, integer and sharing checks. Bit choices change logical payload only; the real toy always uses binary64.

Saved inputs
M
4
Hq
2
Hkv
1
weightBits
16
kvBits
16
bitsPerByte
8
Saved outputs
d
2
J
2
groupWidth
2
weightBytesPerScalar
2
kvBytesPerScalar
2

Query head 0: shared K and V group

systems_map_0

group=floor(h/groupWidth)

Contiguous sharing uses this same group for keys and values. It does not merge query heads or expand the stored KV groups.

Saved inputs
h
0
groupWidth
2
Saved outputs
group
0

Query head 1: shared K and V group

systems_map_1

group=floor(h/groupWidth)

Contiguous sharing uses this same group for keys and values. It does not merge query heads or expand the stored KV groups.

Saved inputs
h
1
groupWidth
2
Saved outputs
group
0

Per-layer Q weights

systems_parameter_0

product=inputWidth*outputWidth; partial=previous+product

Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set.

Saved inputs
n
0
inputWidth
4
outputWidth
4
previous
0
Saved outputs
product
16
partial
16

Per-layer K weights

systems_parameter_1

product=inputWidth*outputWidth; partial=previous+product

Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set.

Saved inputs
n
1
inputWidth
4
outputWidth
2
previous
16
Saved outputs
product
8
partial
24

Per-layer V weights

systems_parameter_2

product=inputWidth*outputWidth; partial=previous+product

Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set.

Saved inputs
n
2
inputWidth
4
outputWidth
2
previous
24
Saved outputs
product
8
partial
32

Per-layer O weights

systems_parameter_3

product=inputWidth*outputWidth; partial=previous+product

Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set.

Saved inputs
n
3
inputWidth
4
outputWidth
4
previous
32
Saved outputs
product
16
partial
48

Per-layer FF1 weights

systems_parameter_4

product=inputWidth*outputWidth; partial=previous+product

Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set.

Saved inputs
n
4
inputWidth
4
outputWidth
8
previous
48
Saved outputs
product
32
partial
80

Per-layer FF2 weights

systems_parameter_5

product=inputWidth*outputWidth; partial=previous+product

Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set.

Saved inputs
n
5
inputWidth
8
outputWidth
4
previous
80
Saved outputs
product
32
partial
112

Store tied embeddings once and distinct layers separately

systems_weights

embeddingParameters=V*M; layerParameters=L*A; parameters=embeddingParameters+layerParameters; weightBytes=parameters*weightBytesPerScalar; metadataBytes=0; representedBytes=weightBytes+metadataBytes

The input embedding and all-row output readout share one table. Zero metadata is an explicit fictional raw-format assumption, not a claim about actual quantized checkpoints.

Saved inputs
V
8
M
4
L
2
A
112
weightBytesPerScalar
2
Saved outputs
embeddingParameters
32
layerParameters
224
parameters
256
weightBytes
512
metadataBytes
0
representedBytes
512

Matrix terms for one processed token

systems_base

layerMatrixMAC=L*A; readoutMAC=M*V; baseMACPerToken=layerMatrixMAC+readoutMAC

Every processed row gets all layer projections, the ordinary two-matrix FFN and the tied-table readout. Attention contractions are added separately.

Saved inputs
L
2
A
112
M
4
V
8
Saved outputs
layerMatrixMAC
224
readoutMAC
32
baseMACPerToken
256

Logical K plus V payload: growth

systems_cache_growth

kBL=B*L; kGroups=kBL*Hkv; kRows=kGroups*history; KElements=kRows*d; KBytes=KElements*kvBytesPerScalar; vBL=B*L; vGroups=vBL*Hkv; vRows=vGroups*history; VElements=vRows*d; VBytes=VElements*kvBytesPerScalar; totalElements=KElements+VElements; totalBytes=KBytes+VBytes

Count original K and V groups separately, then sum once. This is logical represented storage across layers, without query tensors, expanded KV copies, allocator overhead or measured traffic. The growth row counts one added history position.

Saved inputs
B
1
L
2
Hkv
1
history
1
d
2
kvBytesPerScalar
2
Saved outputs
history
1
kBL
2
kGroups
2
kRows
2
KElements
4
KBytes
8
vBL
2
vGroups
2
vRows
2
VElements
4
VBytes
8
totalElements
8
totalBytes
16

Dense computed prefill score cells

systems_dense

BL=B*L; BLHq=BL*Hq; prefillHeadQueries=BLHq*T; prefillDenseCells=prefillHeadQueries*T

The declared dense algorithm computes forbidden future scores and dense probability-times-value products too. Hq counts score paths; Hkv is not the score multiplier.

Saved inputs
B
1
L
2
Hq
2
T
3
Saved outputs
BL
2
BLHq
4
prefillHeadQueries
12
prefillDenseCells
36

Prompt query 0: count allowed keys

systems_causal_0

keys=i+1; partial=previous+keys

Causal eligibility includes this position itself. This ordered triangle describes allowed cells, not reduced dense matrix work.

Saved inputs
i
0
previous
0
Saved outputs
keys
1
partial
1

Prompt query 1: count allowed keys

systems_causal_1

keys=i+1; partial=previous+keys

Causal eligibility includes this position itself. This ordered triangle describes allowed cells, not reduced dense matrix work.

Saved inputs
i
1
previous
1
Saved outputs
keys
2
partial
3

Prompt query 2: count allowed keys

systems_causal_2

keys=i+1; partial=previous+keys

Causal eligibility includes this position itself. This ordered triangle describes allowed cells, not reduced dense matrix work.

Saved inputs
i
2
previous
3
Saved outputs
keys
3
partial
6

Separate causal eligibility from dense computed cells

systems_allowed

nextT=T+1; triangleProduct=T*nextT; triangle=triangleProduct/2; prefillAllowedCells=BLHq*causalSum; closedAllowedCells=BLHq*triangle

The actual increasing-query sum and its closed form are both retained. Dense computed cells remain the arithmetic multiplier.

Saved inputs
T
3
BLHq
4
causalSum
6
divisor
2
Saved outputs
nextT
4
triangleProduct
12
triangle
6
prefillAllowedCells
24
closedAllowedCells
24

Logical K plus V payload: prefill

systems_cache_prefill

kBL=B*L; kGroups=kBL*Hkv; kRows=kGroups*history; KElements=kRows*d; KBytes=KElements*kvBytesPerScalar; vBL=B*L; vGroups=vBL*Hkv; vRows=vGroups*history; VElements=vRows*d; VBytes=VElements*kvBytesPerScalar; totalElements=KElements+VElements; totalBytes=KBytes+VBytes

Count original K and V groups separately, then sum once. This is logical represented storage across layers, without query tensors, expanded KV copies, allocator overhead or measured traffic. The growth row counts one added history position.

Saved inputs
B
1
L
2
Hkv
1
history
3
d
2
kvBytesPerScalar
2
Saved outputs
history
3
kBL
2
kGroups
2
kRows
6
KElements
12
KBytes
24
vBL
2
vGroups
2
vRows
6
VElements
12
VBytes
24
totalElements
24
totalBytes
48

Declared one-layer scratch: prefill

systems_scratch_prefill

Bq=B*q; fiveM=5*M; plusF=fiveM+F; width=plusF+V; featureElements=Bq*width; BHq=B*Hq; headQueries=BHq*q; scoreElements=headQueries*history; probabilityElements=headQueries*history; scorePair=scoreElements+probabilityElements; totalElements=featureElements+scorePair; scratchBytes=4*totalElements; weightAndCache=representedBytes+cacheBytes; accountedBytes=weightAndCache+scratchBytes

Five M-wide buffers are X/residual, Q, joined messages, attention projection and FFN output; also retain F-wide hidden, V-wide logits and separate one-layer scores/probabilities. Four bytes per scalar is hypothetical activation accounting. This ledger is not physical peak allocation, bandwidth or runtime heap usage.

Saved inputs
B
1
q
3
history
3
M
4
F
8
V
8
Hq
2
featureBuffers
5
activationBytes
4
representedBytes
512
cacheBytes
48
Saved outputs
q
3
history
3
Bq
3
fiveM
20
plusF
28
width
36
featureElements
108
BHq
2
headQueries
6
scoreElements
18
probabilityElements
18
scorePair
36
totalElements
144
scratchBytes
576
weightAndCache
560
accountedBytes
1136

Matrix MACs for the actual planned prefill

systems_prefill

prefillRows=B*T; prefillBaseMAC=prefillRows*baseMACPerToken; prefillScoreMAC=d*prefillDenseCells; prefillMessageMAC=d*prefillDenseCells; prefillBaseAndScores=prefillBaseMAC+prefillScoreMAC; prefillMAC=prefillBaseAndScores+prefillMessageMAC

Both dense attention contractions count every computed cell. Matrix MACs exclude softmax, ReLU, residuals, lookup, control, copies, checksum, allocation and data movement.

Saved inputs
B
1
T
3
baseMACPerToken
256
d
2
prefillDenseCells
36
Saved outputs
prefillRows
3
prefillBaseMAC
768
prefillScoreMAC
72
prefillMessageMAC
72
prefillBaseAndScores
840
prefillMAC
912

Append pass 1: include its own K and V

systems_append_1

history=T+j; scoreCells=BLHq*history; baseMAC=B*baseMACPerToken; scoreMAC=d*scoreCells; messageMAC=d*scoreCells; baseAndScores=baseMAC+scoreMAC; matrixMAC=baseAndScores+messageMAC; appendScoreCells=previousCells+scoreCells; appendMAC=previousMAC+matrixMAC

One new query per sequence attends through T+j, including its own position. Increase j in order and retain the real computed row and both running totals.

Saved inputs
T
3
j
1
BLHq
4
B
1
baseMACPerToken
256
d
2
previousCells
0
previousMAC
0
Saved outputs
history
4
scoreCells
16
baseMAC
256
scoreMAC
32
messageMAC
32
baseAndScores
288
matrixMAC
320
appendScoreCells
16
appendMAC
320

Logical K plus V payload: append_1

systems_cache_append_1

kBL=B*L; kGroups=kBL*Hkv; kRows=kGroups*history; KElements=kRows*d; KBytes=KElements*kvBytesPerScalar; vBL=B*L; vGroups=vBL*Hkv; vRows=vGroups*history; VElements=vRows*d; VBytes=VElements*kvBytesPerScalar; totalElements=KElements+VElements; totalBytes=KBytes+VBytes

Count original K and V groups separately, then sum once. This is logical represented storage across layers, without query tensors, expanded KV copies, allocator overhead or measured traffic. The growth row counts one added history position.

Saved inputs
B
1
L
2
Hkv
1
history
4
d
2
kvBytesPerScalar
2
Saved outputs
history
4
kBL
2
kGroups
2
kRows
8
KElements
16
KBytes
32
vBL
2
vGroups
2
vRows
8
VElements
16
VBytes
32
totalElements
32
totalBytes
64

Declared one-layer scratch: append_1

systems_scratch_append_1

Bq=B*q; fiveM=5*M; plusF=fiveM+F; width=plusF+V; featureElements=Bq*width; BHq=B*Hq; headQueries=BHq*q; scoreElements=headQueries*history; probabilityElements=headQueries*history; scorePair=scoreElements+probabilityElements; totalElements=featureElements+scorePair; scratchBytes=4*totalElements; weightAndCache=representedBytes+cacheBytes; accountedBytes=weightAndCache+scratchBytes

Five M-wide buffers are X/residual, Q, joined messages, attention projection and FFN output; also retain F-wide hidden, V-wide logits and separate one-layer scores/probabilities. Four bytes per scalar is hypothetical activation accounting. This ledger is not physical peak allocation, bandwidth or runtime heap usage.

Saved inputs
B
1
q
1
history
4
M
4
F
8
V
8
Hq
2
featureBuffers
5
activationBytes
4
representedBytes
512
cacheBytes
64
Saved outputs
q
1
history
4
Bq
1
fiveM
20
plusF
28
width
36
featureElements
36
BHq
2
headQueries
2
scoreElements
8
probabilityElements
8
scorePair
16
totalElements
52
scratchBytes
208
weightAndCache
576
accountedBytes
784

Append pass 2: include its own K and V

systems_append_2

history=T+j; scoreCells=BLHq*history; baseMAC=B*baseMACPerToken; scoreMAC=d*scoreCells; messageMAC=d*scoreCells; baseAndScores=baseMAC+scoreMAC; matrixMAC=baseAndScores+messageMAC; appendScoreCells=previousCells+scoreCells; appendMAC=previousMAC+matrixMAC

One new query per sequence attends through T+j, including its own position. Increase j in order and retain the real computed row and both running totals.

Saved inputs
T
3
j
2
BLHq
4
B
1
baseMACPerToken
256
d
2
previousCells
16
previousMAC
320
Saved outputs
history
5
scoreCells
20
baseMAC
256
scoreMAC
40
messageMAC
40
baseAndScores
296
matrixMAC
336
appendScoreCells
36
appendMAC
656

Logical K plus V payload: append_2

systems_cache_append_2

kBL=B*L; kGroups=kBL*Hkv; kRows=kGroups*history; KElements=kRows*d; KBytes=KElements*kvBytesPerScalar; vBL=B*L; vGroups=vBL*Hkv; vRows=vGroups*history; VElements=vRows*d; VBytes=VElements*kvBytesPerScalar; totalElements=KElements+VElements; totalBytes=KBytes+VBytes

Count original K and V groups separately, then sum once. This is logical represented storage across layers, without query tensors, expanded KV copies, allocator overhead or measured traffic. The growth row counts one added history position.

Saved inputs
B
1
L
2
Hkv
1
history
5
d
2
kvBytesPerScalar
2
Saved outputs
history
5
kBL
2
kGroups
2
kRows
10
KElements
20
KBytes
40
vBL
2
vGroups
2
vRows
10
VElements
20
VBytes
40
totalElements
40
totalBytes
80

Declared one-layer scratch: append_2

systems_scratch_append_2

Bq=B*q; fiveM=5*M; plusF=fiveM+F; width=plusF+V; featureElements=Bq*width; BHq=B*Hq; headQueries=BHq*q; scoreElements=headQueries*history; probabilityElements=headQueries*history; scorePair=scoreElements+probabilityElements; totalElements=featureElements+scorePair; scratchBytes=4*totalElements; weightAndCache=representedBytes+cacheBytes; accountedBytes=weightAndCache+scratchBytes

Five M-wide buffers are X/residual, Q, joined messages, attention projection and FFN output; also retain F-wide hidden, V-wide logits and separate one-layer scores/probabilities. Four bytes per scalar is hypothetical activation accounting. This ledger is not physical peak allocation, bandwidth or runtime heap usage.

Saved inputs
B
1
q
1
history
5
M
4
F
8
V
8
Hq
2
featureBuffers
5
activationBytes
4
representedBytes
512
cacheBytes
80
Saved outputs
q
1
history
5
Bq
1
fiveM
20
plusF
28
width
36
featureElements
36
BHq
2
headQueries
2
scoreElements
10
probabilityElements
10
scorePair
20
totalElements
56
scratchBytes
224
weightAndCache
592
accountedBytes
816

Retain the append closed form alongside actual rows

systems_appendClosed

DT=D*T; nextD=D+1; appendTriangleProduct=D*nextD; appendTriangle=appendTriangleProduct/2; historySum=DT+appendTriangle; closedAppendCells=BLHq*historySum; batchAppends=B*D; appendBaseMAC=batchAppends*baseMACPerToken; appendScoreMAC=d*closedAppendCells; appendMessageMAC=d*closedAppendCells; appendBaseAndScores=appendBaseMAC+appendScoreMAC; closedAppendMAC=appendBaseAndScores+appendMessageMAC

The closed form checks the increasing-j row aggregate without substituting a fictional table. D=0 gives real zero aggregate work and no append rows.

Saved inputs
D
2
T
3
BLHq
4
B
1
baseMACPerToken
256
d
2
divisor
2
appendScoreCells
36
appendMAC
656
Saved outputs
DT
6
nextD
3
appendTriangleProduct
6
appendTriangle
3
historySum
9
closedAppendCells
36
batchAppends
2
appendBaseMAC
512
appendScoreMAC
72
appendMessageMAC
72
appendBaseAndScores
584
closedAppendMAC
656

Keep analytical resources separate from neural correctness and time

systems_totals

totalMAC=prefillMAC+appendMAC; matrixFLOPs=2*totalMAC; finalHistory=T+D; selectedOutputsWithoutEOS=D+1; other fields copy saved counts

D counts appended forward passes. With a nonempty prompt, no EOS and stopping immediately after the final selection, G=D+1 selected outputs leaves the final selected token outside cache. FLOPs mean matrix operations only. No elapsed time follows.

Saved inputs
prefillMAC
912
appendMAC
656
T
3
D
2
two
2
Saved outputs
d
2
J
2
groupWidth
2
parameters
256
weightBytes
512
metadataBytes
0
prefillKBytes
24
prefillVBytes
24
prefillCacheBytes
48
finalKBytes
40
finalVBytes
40
finalCacheBytes
80
cacheGrowthBytes
16
prefillDenseCells
36
prefillAllowedCells
24
appendScoreCells
36
baseMACPerToken
256
prefillMAC
912
appendMAC
656
totalMAC
1568
matrixFLOPs
3136
prefillScratchBytes
576
prefillAccountedBytes
1136
finalScratchBytes
224
finalAccountedBytes
816
finalHistory
5
selectedOutputsWithoutEOS
3

Toy 1: first affine row 0, hidden 0, term 0

systems_toy1_a1_0_0_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
0
k
0
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 1: first affine row 0, hidden 0, term 1

systems_toy1_a1_0_0_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
0
k
1
left
0
right
1
previous
1
Saved outputs
product
0
sum
1

Toy 1: ReLU row 0, hidden 0

systems_toy1_relu_0_0

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
0
c
0
linear
1
zero
0
Saved outputs
value
1

Toy 1: first affine row 0, hidden 1, term 0

systems_toy1_a1_0_1_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
1
k
0
left
1
right
-1
previous
0
Saved outputs
product
-1
sum
-1

Toy 1: first affine row 0, hidden 1, term 1

systems_toy1_a1_0_1_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
1
k
1
left
0
right
1
previous
-1
Saved outputs
product
0
sum
-1

Toy 1: ReLU row 0, hidden 1

systems_toy1_relu_0_1

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
0
c
1
linear
-1
zero
0
Saved outputs
value
0

Toy 1: second affine row 0, output 0, term 0

systems_toy1_a2_0_0_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
0
k
0
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 1: second affine row 0, output 0, term 1

systems_toy1_a2_0_0_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
0
k
1
left
0
right
-1
previous
1
Saved outputs
product
-0
sum
1

Toy 1: second affine row 0, output 1, term 0

systems_toy1_a2_0_1_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
1
k
0
left
1
right
2
previous
0
Saved outputs
product
2
sum
2

Toy 1: second affine row 0, output 1, term 1

systems_toy1_a2_0_1_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
1
k
1
left
0
right
1
previous
2
Saved outputs
product
0
sum
2

Toy 1: consume output row 0, coordinate 0

systems_toy1_checksum_0_0

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
0
c
0
previous
0
value
1
Saved outputs
sum
1

Toy 1: consume output row 0, coordinate 1

systems_toy1_checksum_0_1

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
0
c
1
previous
1
value
2
Saved outputs
sum
3

Toy 1: one complete untimed batch

systems_toy1_complete

checksum=copied saved fold; products=rows*8; additions=rows*8; reluDecisions=rows*2; checksumAdditions=rows*2

The pure helper creates this independent workspace and runs it exactly once. No warmup, repetition, clock, asynchronous work or hypothetical planner dtype conversion occurs. Buffer stores and loop/index/control work are additional factory work.

Saved inputs
rows
1
returnedChecksum
3
productsPerRow
8
additionsPerRow
8
reluPerRow
2
Saved outputs
checksum
3
products
8
additions
8
reluDecisions
2
checksumAdditions
2

Toy 3: first affine row 0, hidden 0, term 0

systems_toy3_a1_0_0_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
0
k
0
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 3: first affine row 0, hidden 0, term 1

systems_toy3_a1_0_0_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
0
k
1
left
0
right
1
previous
1
Saved outputs
product
0
sum
1

Toy 3: ReLU row 0, hidden 0

systems_toy3_relu_0_0

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
0
c
0
linear
1
zero
0
Saved outputs
value
1

Toy 3: first affine row 0, hidden 1, term 0

systems_toy3_a1_0_1_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
1
k
0
left
1
right
-1
previous
0
Saved outputs
product
-1
sum
-1

Toy 3: first affine row 0, hidden 1, term 1

systems_toy3_a1_0_1_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
0
c
1
k
1
left
0
right
1
previous
-1
Saved outputs
product
0
sum
-1

Toy 3: ReLU row 0, hidden 1

systems_toy3_relu_0_1

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
0
c
1
linear
-1
zero
0
Saved outputs
value
0

Toy 3: second affine row 0, output 0, term 0

systems_toy3_a2_0_0_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
0
k
0
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 3: second affine row 0, output 0, term 1

systems_toy3_a2_0_0_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
0
k
1
left
0
right
-1
previous
1
Saved outputs
product
-0
sum
1

Toy 3: second affine row 0, output 1, term 0

systems_toy3_a2_0_1_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
1
k
0
left
1
right
2
previous
0
Saved outputs
product
2
sum
2

Toy 3: second affine row 0, output 1, term 1

systems_toy3_a2_0_1_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
0
c
1
k
1
left
0
right
1
previous
2
Saved outputs
product
0
sum
2

Toy 3: consume output row 0, coordinate 0

systems_toy3_checksum_0_0

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
0
c
0
previous
0
value
1
Saved outputs
sum
1

Toy 3: consume output row 0, coordinate 1

systems_toy3_checksum_0_1

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
0
c
1
previous
1
value
2
Saved outputs
sum
3

Toy 3: first affine row 1, hidden 0, term 0

systems_toy3_a1_1_0_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
1
c
0
k
0
left
0
right
1
previous
0
Saved outputs
product
0
sum
0

Toy 3: first affine row 1, hidden 0, term 1

systems_toy3_a1_1_0_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
1
c
0
k
1
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 3: ReLU row 1, hidden 0

systems_toy3_relu_1_0

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
1
c
0
linear
1
zero
0
Saved outputs
value
1

Toy 3: first affine row 1, hidden 1, term 0

systems_toy3_a1_1_1_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
1
c
1
k
0
left
0
right
-1
previous
0
Saved outputs
product
-0
sum
0

Toy 3: first affine row 1, hidden 1, term 1

systems_toy3_a1_1_1_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
1
c
1
k
1
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 3: ReLU row 1, hidden 1

systems_toy3_relu_1_1

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
1
c
1
linear
1
zero
0
Saved outputs
value
1

Toy 3: second affine row 1, output 0, term 0

systems_toy3_a2_1_0_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
1
c
0
k
0
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 3: second affine row 1, output 0, term 1

systems_toy3_a2_1_0_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
1
c
0
k
1
left
1
right
-1
previous
1
Saved outputs
product
-1
sum
0

Toy 3: second affine row 1, output 1, term 0

systems_toy3_a2_1_1_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
1
c
1
k
0
left
1
right
2
previous
0
Saved outputs
product
2
sum
2

Toy 3: second affine row 1, output 1, term 1

systems_toy3_a2_1_1_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
1
c
1
k
1
left
1
right
1
previous
2
Saved outputs
product
1
sum
3

Toy 3: consume output row 1, coordinate 0

systems_toy3_checksum_1_0

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
1
c
0
previous
3
value
0
Saved outputs
sum
3

Toy 3: consume output row 1, coordinate 1

systems_toy3_checksum_1_1

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
1
c
1
previous
3
value
3
Saved outputs
sum
6

Toy 3: first affine row 2, hidden 0, term 0

systems_toy3_a1_2_0_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
2
c
0
k
0
left
1
right
1
previous
0
Saved outputs
product
1
sum
1

Toy 3: first affine row 2, hidden 0, term 1

systems_toy3_a1_2_0_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
2
c
0
k
1
left
1
right
1
previous
1
Saved outputs
product
1
sum
2

Toy 3: ReLU row 2, hidden 0

systems_toy3_relu_2_0

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
2
c
0
linear
2
zero
0
Saved outputs
value
2

Toy 3: first affine row 2, hidden 1, term 0

systems_toy3_a1_2_1_0

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
2
c
1
k
0
left
1
right
-1
previous
0
Saved outputs
product
-1
sum
-1

Toy 3: first affine row 2, hidden 1, term 1

systems_toy3_a1_2_1_1

product=left*right; sum=previous+product

Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.

Saved inputs
r
2
c
1
k
1
left
1
right
1
previous
-1
Saved outputs
product
1
sum
0

Toy 3: ReLU row 2, hidden 1

systems_toy3_relu_2_1

value=linear>0 ? linear : +0

Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.

Saved inputs
r
2
c
1
linear
0
zero
0
Saved outputs
value
0

Toy 3: second affine row 2, output 0, term 0

systems_toy3_a2_2_0_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
2
c
0
k
0
left
2
right
1
previous
0
Saved outputs
product
2
sum
2

Toy 3: second affine row 2, output 0, term 1

systems_toy3_a2_2_0_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
2
c
0
k
1
left
0
right
-1
previous
2
Saved outputs
product
-0
sum
2

Toy 3: second affine row 2, output 1, term 0

systems_toy3_a2_2_1_0

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
2
c
1
k
0
left
2
right
2
previous
0
Saved outputs
product
4
sum
4

Toy 3: second affine row 2, output 1, term 1

systems_toy3_a2_2_1_1

product=left*right; sum=previous+product

Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.

Saved inputs
r
2
c
1
k
1
left
0
right
1
previous
4
Saved outputs
product
0
sum
4

Toy 3: consume output row 2, coordinate 0

systems_toy3_checksum_2_0

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
2
c
0
previous
6
value
2
Saved outputs
sum
8

Toy 3: consume output row 2, coordinate 1

systems_toy3_checksum_2_1

sum=previous+value

Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.

Saved inputs
r
2
c
1
previous
8
value
4
Saved outputs
sum
12

Toy 3: one complete untimed batch

systems_toy3_complete

checksum=copied saved fold; products=rows*8; additions=rows*8; reluDecisions=rows*2; checksumAdditions=rows*2

The pure helper creates this independent workspace and runs it exactly once. No warmup, repetition, clock, asynchronous work or hypothetical planner dtype conversion occurs. Buffer stores and loop/index/control work are additional factory work.

Saved inputs
rows
3
returnedChecksum
12
productsPerRow
8
additionsPerRow
8
reluPerRow
2
Saved outputs
checksum
12
products
24
additions
24
reluDecisions
6
checksumAdditions
6

Retain resource counts and real untimed toy correctness separately

finish

summary=copied saved analytical counts and toy checksums; frames=helperFrames+1; tensorCount=saved tensors length

All eleven raw fields and the prefix passed before any frame. Analytical integers describe the disclosed hypothetical model. Toy checksum words come from two independent actual one-run previews. No clock, duration, throughput, native elementary function or runtime validation is implied.

Saved inputs
oneRowChecksum
3
threeRowChecksum
12
frames
79
tensorCount
33
Saved outputs
d
2
J
2
groupWidth
2
parameters
256
weightBytes
512
metadataBytes
0
prefillKBytes
24
prefillVBytes
24
prefillCacheBytes
48
finalKBytes
40
finalVBytes
40
finalCacheBytes
80
cacheGrowthBytes
16
prefillDenseCells
36
prefillAllowedCells
24
appendScoreCells
36
baseMACPerToken
256
prefillMAC
912
appendMAC
656
totalMAC
1568
matrixFLOPs
3136
prefillScratchBytes
576
prefillAccountedBytes
1136
finalScratchBytes
224
finalAccountedBytes
816
finalHistory
5
selectedOutputsWithoutEOS
3
oneRowChecksum
3
threeRowChecksum
12
frames
79
tensorCount
33

Open the house “Inspect all stored values, text metadata and tensor storage” disclosure after this view for every root output/alias and all29 text fields, including the full policy and column-name arrays. Nothing is limited to the four headline outputs.

SOURCE ONLY: all executable checks, canonical/oracle parity, typecheck, build, browser, accessibility, offline and timing checks remain UNRUN under the human FluxGeo hold. Owner adoption is separate from runtime acceptance.

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.

systems_RawState

RawField=11 · float64 · precision 0 · All eleven captured raw VALUE fields in texts.rawFields order; D=-0 is VALUE zero.

Zero-based storage indexStored value
01
12
23
32
44
52
61
78
88
916
1016

systems_HeadToGroup

QueryHead=2 · float64 · precision 0 · Contiguous shared K/V group per query head; no expanded cache is allocated.

Zero-based storage indexStored value
00
10

systems_ParameterLedger

Matrix=6 × ParameterField=4 · float64 · precision 0 · Q,K,V,O,FF1,FF2 rows; inputWidth,outputWidth,product,partial. Only scalar count evidence, never allocated model weights.

Zero-based storage indexStored value
04
14
216
316
44
52
68
724
84
92
108
1132
124
134
1416
1548
164
178
1832
1980
208
214
2232
23112

systems_WeightLedger

WeightField=7 · float64 · precision 0 · embeddingParameters,layerParameters,parameters,weightBytesPerScalar,weightBytes,metadataBytes,representedBytes; zero metadata is an assumption.

Zero-based storage indexStored value
032
1224
2256
32
4512
50
6512

systems_CacheLedger

CacheStage=4 × CacheField=7 · float64 · precision 0 · Rows: one-position growth, prefill, then performed append passes in increasing j. Fields: history,KElements,VElements,totalElements,KBytes,VBytes,totalBytes. No hypothetical cache tensor is allocated.

Zero-based storage indexStored value
01
14
24
38
48
58
616
73
812
912
1024
1124
1224
1348
144
1516
1616
1732
1832
1932
2064
215
2220
2320
2440
2540
2640
2780

systems_CausalRows

PromptQuery=3 × CausalField=3 · float64 · precision 0 · keys,previous,partial for actual increasing-query causal eligibility; dense computed work stays separate.

Zero-based storage indexStored value
01
10
21
32
41
53
63
73
86

systems_PrefillCounts

PrefillField=5 · float64 · precision 0 · denseCells,allowedCells,matrixMAC,scratchBytes,accountedBytes for prefill; counts are not observations.

Zero-based storage indexStored value
036
124
2912
3576
41136

systems_AppendRows

AppendPass=2 × AppendField=11 · float64 · precision 0 · j,history,scoreCells,matrixMAC,KBytes,VBytes,cacheBytes,scratchBytes,accountedBytes,cumulativeScoreCells,cumulativeMAC for performed passes only. Absent when D=0.

Zero-based storage indexStored value
01
14
216
3320
432
532
664
7208
8784
916
10320
112
125
1320
14336
1540
1640
1780
18224
19816
2036
21656

systems_AppendTotals

AppendTotalField=7 · float64 · precision 0 · actualScoreCells,closedScoreCells,historySum,baseMAC,scoreMAC,messageMAC,actualMAC; a computed zero aggregate is retained at D=0.

Zero-based storage indexStored value
036
136
29
3512
472
572
6656

systems_ScratchLedger

ScratchStage=3 × ScratchField=16 · float64 · precision 0 · Prefill then performed append rows. q,history,Bq,fiveM,plusF,width,featureElements,BHq,headQueries,scoreElements,probabilityElements,scorePair,totalElements,scratchBytes,weightAndCache,accountedBytes. Declared one-layer buffers only, not physical peak memory.

Zero-based storage indexStored value
03
13
23
320
428
536
6108
72
86
918
1018
1136
12144
13576
14560
151136
161
174
181
1920
2028
2136
2236
232
242
258
268
2716
2852
29208
30576
31784
321
335
341
3520
3628
3736
3836
392
402
4110
4210
4320
4456
45224
46592
47816

systems_AnalyticalSummary

AnalyticalField=27 · float64 · precision 0 · Saved analytical VALUE counts in texts.analyticalFields order; no toy float, clock, duration or rate.

Zero-based storage indexStored value
02
12
22
3256
4512
50
624
724
848
940
1040
1180
1216
1336
1424
1536
16256
17912
18656
191568
203136
21576
221136
23224
24816
255
263

systems_toy1_X

Row=1 × Input=2 · float64 · precision 8 · Actual fixed binary64 row-feature input; independent sample rows, not autoregressive tokens.

Zero-based storage indexStored value
01
10

systems_toy1_W1

Input=2 × Hidden=2 · float64 · precision 8 · Actual fixed untrained row-feature first weights [[1,-1],[1,1]]; zero biases are omitted, not added.

Zero-based storage indexStored value
01
1-1
21
31

systems_toy1_W2

Hidden=2 × Output=2 · float64 · precision 8 · Actual fixed untrained row-feature second weights [[1,2],[-1,1]]; shared by all rows.

Zero-based storage indexStored value
01
12
2-1
31

systems_toy1_Affine1

Row=1 × Hidden=2 × Input=2 × AffineField=5 · float64 · precision 8 · Saved left,right,product,previous,sum per first-affine term, in row,hidden,input order. Every entry is a binary64 WORD, including +0 and computed -0.

Zero-based storage indexStored value
01
11
21
30
41
50
61
70
81
91
101
11-1
12-1
130
14-1
150
161
170
18-1
19-1

systems_toy1_HiddenLinear

Row=1 × Hidden=2 · float64 · precision 8 · Saved final first-affine partials before ReLU; no floating recomputation while inspecting or tracing.

Zero-based storage indexStored value
01
1-1

systems_toy1_Hidden

Row=1 × Hidden=2 · float64 · precision 8 · Saved actual ReLU outputs, with literal +0 for linear<=0.

Zero-based storage indexStored value
01
10

systems_toy1_Affine2

Row=1 × Output=2 × Hidden=2 × AffineField=5 · float64 · precision 8 · Saved left,right,product,previous,sum per second-affine term, in row,output,hidden order. All zero products execute.

Zero-based storage indexStored value
01
11
21
30
41
50
6-1
7-0
81
91
101
112
122
130
142
150
161
170
182
192

systems_toy1_Y

Row=1 × Output=2 · float64 · precision 8 · Saved actual second-affine outputs consumed by the checksum; no constant-result replacement.

Zero-based storage indexStored value
01
12

systems_toy1_ChecksumFolds

Row=1 × Output=2 × FoldField=3 · float64 · precision 8 · Saved previous,value,sum per actual row-major checksum addition, initialized literal +0.

Zero-based storage indexStored value
00
11
21
31
42
53

systems_toy1_Checksum

Scalar=1 · float64 · precision 8 · Copy of the completed factory checksum WORD; deterministic correctness only, never a duration or measurement.

Zero-based storage indexStored value
03

systems_toy1_WorkCounts

WorkCount=4 · float64 · precision 0 · products,affineAdditions,reluDecisions,checksumAdditions for one complete batch; loop/index/control/buffer stores are additional.

Zero-based storage indexStored value
08
18
22
32

systems_toy3_X

Row=3 × Input=2 · float64 · precision 8 · Actual fixed binary64 row-feature input; independent sample rows, not autoregressive tokens.

Zero-based storage indexStored value
01
10
20
31
41
51

systems_toy3_W1

Input=2 × Hidden=2 · float64 · precision 8 · Actual fixed untrained row-feature first weights [[1,-1],[1,1]]; zero biases are omitted, not added.

Zero-based storage indexStored value
01
1-1
21
31

systems_toy3_W2

Hidden=2 × Output=2 · float64 · precision 8 · Actual fixed untrained row-feature second weights [[1,2],[-1,1]]; shared by all rows.

Zero-based storage indexStored value
01
12
2-1
31

systems_toy3_Affine1

Row=3 × Hidden=2 × Input=2 × AffineField=5 · float64 · precision 8 · Saved left,right,product,previous,sum per first-affine term, in row,hidden,input order. Every entry is a binary64 WORD, including +0 and computed -0.

Zero-based storage indexStored value
01
11
21
30
41
50
61
70
81
91
101
11-1
12-1
130
14-1
150
161
170
18-1
19-1
200
211
220
230
240
251
261
271
280
291
300
31-1
32-0
330
340
351
361
371
380
391
401
411
421
430
441
451
461
471
481
492
501
51-1
52-1
530
54-1
551
561
571
58-1
590

systems_toy3_HiddenLinear

Row=3 × Hidden=2 · float64 · precision 8 · Saved final first-affine partials before ReLU; no floating recomputation while inspecting or tracing.

Zero-based storage indexStored value
01
1-1
21
31
42
50

systems_toy3_Hidden

Row=3 × Hidden=2 · float64 · precision 8 · Saved actual ReLU outputs, with literal +0 for linear<=0.

Zero-based storage indexStored value
01
10
21
31
42
50

systems_toy3_Affine2

Row=3 × Output=2 × Hidden=2 × AffineField=5 · float64 · precision 8 · Saved left,right,product,previous,sum per second-affine term, in row,output,hidden order. All zero products execute.

Zero-based storage indexStored value
01
11
21
30
41
50
6-1
7-0
81
91
101
112
122
130
142
150
161
170
182
192
201
211
221
230
241
251
26-1
27-1
281
290
301
312
322
330
342
351
361
371
382
393
402
411
422
430
442
450
46-1
47-0
482
492
502
512
524
530
544
550
561
570
584
594

systems_toy3_Y

Row=3 × Output=2 · float64 · precision 8 · Saved actual second-affine outputs consumed by the checksum; no constant-result replacement.

Zero-based storage indexStored value
01
12
20
33
42
54

systems_toy3_ChecksumFolds

Row=3 × Output=2 × FoldField=3 · float64 · precision 8 · Saved previous,value,sum per actual row-major checksum addition, initialized literal +0.

Zero-based storage indexStored value
00
11
21
31
42
53
63
70
83
93
103
116
126
132
148
158
164
1712

systems_toy3_Checksum

Scalar=1 · float64 · precision 8 · Copy of the completed factory checksum WORD; deterministic correctness only, never a duration or measurement.

Zero-based storage indexStored value
012

systems_toy3_WorkCounts

WorkCount=4 · float64 · precision 0 · products,affineAdditions,reluDecisions,checksumAdditions for one complete batch; loop/index/control/buffer stores are additional.

Zero-based storage indexStored value
024
124
26
36

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.

1. What evidence does the pure planner establish before any explicit local timing action?
2. Fixed default B1,L2,T3,D2,M4,Hq2,Hkv1,F8,V8,bits16/16: what are dense computed / causal-allowed prefill cells across layers, and the score shape for ONE layer?
3. Fixed default worksheet: change only B from 1 to 2. What happens to weight payload, final KV payload and total matrix MACs?
4. Fixed default architecture and T=3: request G=3 output selections, no EOS, and stop immediately after the third selection. Which appended-pass policy matches?
5. Current WHOLE saved planner: B=1, L=2, T=3, D=2, M=4, Hq=2, Hkv=1, F=8, V=8, weightBits=16, kvBits=16. Saved analytical summary: d=2; J=2; groupWidth=2; parameters=256; weightBytes=512; metadataBytes=0; prefillKBytes=24; prefillVBytes=24; prefillCacheBytes=48; finalKBytes=40; finalVBytes=40; finalCacheBytes=80; cacheGrowthBytes=16; prefillDenseCells=36; prefillAllowedCells=24; appendScoreCells=36; baseMACPerToken=256; prefillMAC=912; appendMAC=656; totalMAC=1568; matrixFLOPs=3136; prefillScratchBytes=576; prefillAccountedBytes=1136; finalScratchBytes=224; finalAccountedBytes=816; finalHistory=5; selectedOutputsWithoutEOS=3. Byte fields count bytes, cell fields count score cells, MAC fields count matrix product terms, and matrixFLOPs uses the declared two-per-MAC convention. No absence: every requested append pass has its saved row, cache and scratch counts. Which branch describes this actual record? Trace selection does not change this question.

Five corrective questions follow the saved evidence. The first checks evidence vocabulary, the next three name fixed worksheets, and the fifth uses the current whole planner.

Explore the saved calculation

Start with Independent sequences (B): change 1 to 2 and compare shared weight bytes with cache and matrix work. The nine number fields advance in integer steps of one; the two payload menus choose exactly 8, 16 or 32 bits per scalar. Reset example restores all eleven defaults. The table below gives every domain. M must be divisible by Hq; Hkv must be no greater than Hq; Hq must be divisible by Hkv. The lab reports a violation rather than changing another control for you.

An empty, malformed, nonfinite, fractional or out-of-range draft withholds computed evidence, trace, timing buttons and grading. Individually valid inputs that violate a sharing condition also withhold the whole result with its reason. Correct the inputs or reset; no previous successful plan is presented as the invalid draft’s answer. Every raw edit and reset clears answers and invalidates timing, including an edit that leaves the draft invalid.

Use Previous step, Calculation step or Next step to select an immutable saved operation. Editing begins a fresh calculation at its first step. Seeking clears graded answers but preserves the timing revision; opening a disclosure or answering a question preserves that revision too. The selected operation’s equation, explanation and all operands are shown together. Selection never replaces the whole planner’s totals or the fifth question’s current-state premise.

Read the complete analytical summary, the six parameter products, contiguous head-to-group map, separate K/V histories, allowed-query partials, every performed append and the scratch ledger. AppendTotals retains two actual increasing-j folds: score cells and total MACs. Each row also saves base, score and message MAC components; their closed-form totals are separate calculations, not three extra loop reductions. At D=0 the append aggregate is computed zero, while AppendRows and last-append details are absent with the saved reason.

Open each Complete 1-row preview or Complete 3-row preview disclosure for every actual input, weight, affine product/partial, hidden value, output and checksum fold. The pure model creates independent fixed workspaces and runs each preset once per derivation. This is untimed correctness work; it performs no measurement warmup or repeated trial. The planner’s sizes and bit choices never enlarge or quantize it. Complete tensor fallback retains all seven tensor fields and every cell; Complete frame fallback retains every field and operand of every operation, marking the selected step. The house Inspect all stored values, text metadata and tensor storage disclosure also exposes every root alias and all text policies. These named scrolling tables accept keyboard focus and preserve saved zero signs; display precision never feeds arithmetic.

The separate Measure one-row MLP and Measure three-row MLP buttons initiate only their stated local workload; Cancel measurement applies to an active action. Opening the lesson, editing, seeking, inspecting or grading never starts timing. The timing section below explains the fixed cap, cancellation and clock limitations.

Begin with the units and the two different workloads

A token is one sequence item, which need not be a whole word. Prefill processes the supplied prompt. An appended forward pass feeds one further token per sequence through the model, retaining its keys and values for later use. A logit is an unnormalized score for a possible next token. Selecting a token from logits is different from forwarding that selected token through the model.

A batch groups independent sequences. A row is one token position within one sequence; its features are numerical coordinates, not extra requests. A layer is one repeated transformation with its own parameters. Our hypothetical layers have the same shapes and distinct weights; sequences share those weights. A tensor is an array with named axes, and its shape lists their lengths. A parameter is a stored model number, such as a weight.

Latency is elapsed time for a stated unit of work. Throughput is completed stated units divided by elapsed time. Batching can share the use of weights while increasing the work and cache across the batch. Whether this improves actual throughput, and what it does to one request’s wait, requires execution evidence and a scheduling model.

A byte contains eight bits. Payload is the represented numerical data; metadata describes a representation, such as its quantization scales. Counts below use exact integer bytes, not rounded kilobytes. A MAC counts one scalar multiplication term accumulated into a matrix product. The conventional matrix FLOP count is twice the MAC count, where FLOP means floating-point operation. This convention excludes other operations.

“Memory-bound” describes an execution limited more by moving data than by arithmetic capacity. Stored bytes do not tell us how many bytes cross a memory bus, how often weights are reused, or which resource limits a real machine. We cannot diagnose a bottleneck from this ledger alone.

There are two workloads in this lesson. The planner counts a hypothetical decoder without allocating its neural arrays. A separate fixed tiny MLP, or multilayer perceptron, evaluates a disclosed matrix–ReLU–matrix computation when its preview is evaluated. ReLU, the rectified linear unit, keeps a positive coordinate and otherwise returns +0. That toy has no attention, token generation or cache. The later explicit local timing procedure repeats only that fixed toy. Changing planner dimensions or bits never changes the toy’s values or numerical representation.

Eleven raw inputs, with no silent repairs

The complete raw field order is B, L, T, D, M, Hq, Hkv, F, V, weightBits, kvBits. Each value must be a finite number in its own domain; the default is a complete example rather than a rule for filling missing fields.

FieldMeaning and unitDefaultDomain
BIndependent sequences in the batch1Integer 1 through 4
LDistinct layers2Integer 1 through 4
TPrompt tokens per sequence3Integer 1 through 16
DAppended forward passes per sequence2Integer 0 through 8
MModel features per token4Integer 2 through 16
HqQuery heads per layer2Integer 1 through 4
HkvShared key/value groups per layer1Integer 1 through 4
FHidden feed-forward features8Integer 1 through 32
VVocabulary entries8Integer 2 through 32
weightBitsHypothetical bits per weight16Exactly 8, 16 or 32
kvBitsHypothetical bits per cached scalar16Exactly 8, 16 or 32

Here D counts passes, not feature width. Other chapters use D for features; this lesson uses M for that axis. Likewise V in the input table is vocabulary size; “values” below means the attention value tensor, a different use of the letter.

After individual domains, require M divisible by Hq, then Hkv no greater than Hq, then Hq divisible by Hkv. Divisible means the quotient is an integer. Do not round a head width, change another input, add padding or clamp a value. For example M=5,Hq=2 fails the first condition; M=6,Hq=3,Hkv=2 fails the last; Hq=2,Hkv=3 fails the middle condition. T=0, D=1/2, numeric strings and unsupported three-bit storage are invalid. Even when D=0, kvBits must remain valid. Allowed D=-0 has the integer value zero in the planner.

The boundary accepts only an ordinary or null-prototype plain record with exactly these eleven own data fields. It rejects arrays, missing/extra/symbol fields, inherited substitutes and accessors. A descriptor describes an object’s field; a data descriptor contains a stored value, while an accessor could run a getter. Inspect all descriptors before requiring every value finite; require all finite before checking any individual domain in raw order. Sharing checks follow; the ASCII trace-name prefix is checked last. No invalid request gets a partial successful planner result or a previous result relabeled as current.

Shapes and what is shared

Define head width d=M/Hq, total shared KV width J=Hkv*d, and heads per sharing group g=Hq/Hkv. Head index h starts at zero; it reads both K and V from group floor(h/g), where floor rounds downward to an integer. At Hq=4,Hkv=2 the map is [0,0,1,1]. It is not [0,1,0,1].

A query compares one position with keys; normalized matching scores weight the corresponding values to form its message. A head is a separate query comparison/message path. GQA, grouped-query attention, shares K/V groups among heads. MQA, multi-query attention, uses Hkv=1; MHA, ordinary multi-head attention, uses Hkv=Hq. The default 2/1 is the MQA endpoint of this sharing scheme. Every query head keeps its own score path even when its K/V storage is shared.

Let q count newly processed rows per sequence, and S count available key positions. Prefill has q=S=T; appended pass j has q=1,S=T+j, for j from 1 through D. Its new token contributes its own K/V before its query attends. Indices b, i, h and f select a sequence, position, head and feature; their counts are the corresponding shape lengths. A layer index selects one of the L distinct layers.

QuantityShapeMeaning
Tied embedding E[V,M]Token lookup table, also used transposed for readout
Input/residual X[B,q,M]Sequence, new row, model feature
WQ and WO per layerEach [M,M]Query and joined-message output projections
WK and WV per layerEach [M,J]Project once into shared key/value width
W1 and W2 per layer[M,F], [F,M]Ordinary feed-forward expansion and return
Split queries Q[B,Hq,q,d]Separate query-head paths
Cached K and values per layerEach [B,Hkv,S,d]Original shared storage, no expanded copies
Scores and probabilities per layerEach [B,Hq,q,S]Query rows by available keys
Head messages[B,Hq,q,d]Independent messages before joining
Joined messages[B,q,M]Head features placed side by side in head order
Readout logits[B,q,V]Scores for every vocabulary item

A projection multiplies an M-feature row by an [M,J] matrix, summing over the matching M axis to produce J features. A query/key dot product sums d products. A value mixture sums over S positions. Joining heads is an explicit rearrangement because Hq*d=M, not an implicit broadcast. In Book II’s column convention, each row-feature weight matrix here is the transpose of the corresponding column-map matrix.

A tied embedding is one parameter array serving two purposes: input lookup and output readout. The readout uses E transposed, with shape [M,V]. Store E once, but count its readout multiplication for every processed row, including every prompt row. Merely storing a table once does not eliminate its later work.

This model is bias-free: it adds no offset parameters. Its ordinary two-matrix feed-forward network expands features, applies ReLU and returns to the model width. It has no extra activation gate and no mixture-of-experts routing that selects among alternative feed-forward networks. It omits normalization (rescaling a feature vector), positional parameters (representing sequence position), padding, early stopping, queueing and allocator overhead. A residual adds a sublayer result back to its input; such additions are outside the matrix MAC subtotal. These assumptions describe this worksheet, not a named production LLM.

Build the default count from products

All worksheets in this chapter are manual derivations. Their integers are exact at the stated bounds. No program, counter, reference, oracle or timing was run to obtain them.

At defaults, d=4/2=2, J=1*2=2, g=2/1=2. Define A as weights per layer, P as all stored parameters, bw as bytes per weight and bk as bytes per cached scalar. Thus bw=16/8=2, bk=16/8=2. These symbols carry units: A and P count scalar parameters, bw and bk are bytes per scalar. The fixed activation-accounting factor is four bytes per scalar, independently of those choices.

Weights and per-token matrix work

MatrixProduct in scalar parametersOrdered subtotal
WQ4*4=160+16=16
WK4*2=816+8=24
WV4*2=824+8=32
WO4*4=1632+16=48
W14*8=3248+32=80
W28*4=3280+32=112=A

In symbols, A=2*M*M+2*M*J+2*M*F. Here Q/O contribute 2*4*4=32, K/V contribute 2*4*2=16, and the feed-forward pair contributes 2*4*8=64; (32+16)+64=112. The tied embedding contributes V*M=8*4=32. The L distinct layers contribute 2*112=224; hence P=32+224=256, and weight payload is 256*2=512 bytes.

Metadata is zero by an explicit fictional uniform-format assumption. This is not a claim that real quantized weights need no scales, zero points, headers or alignment. An untied readout would add another 32 parameters here; it is a different model.

Define Cbase=L*A+M*V, the matrix MACs per processed token before attention score/message contractions. The default is 2*112+4*8=224+32=256 MACs. The input embedding is a lookup, not a counted matrix multiplication. B does not multiply stored weights because sequences share them; L does because layers have distinct weights.

Cache: keep K and values separate until the sum

At history S, each cache side contains B*L*Hkv*S*d scalars. Add K and values once, then multiply by bk. Thus cache bytes are 2*B*L*Hkv*S*d*bk. Prefill uses S=T; final history is T+D. One appended pass grows each side by B*L*Hkv*d scalars across the batch.

PhaseSK scalarsValue scalarsSeparate bytes, then combined
Prefill312132=1212132=12K:122=24; values:122=24; 24+24=48 bytes
Append j=13+1=412142=1612142=16K:162=32; values:162=32; 32+32=64 bytes
Append j=23+2=512152=2012152=20K:202=40; values:202=40; 40+40=80 bytes
Growth each passOne new position per sequence121*2=4121*2=4K:42=8; values:42=8; 8+8=16 bytes

The ordered history ledger is 48+16=64, then 64+16=80. Do not multiply by two again after adding both cache sides. Do not substitute Hq for Hkv: stored K/V groups and independent query paths count different things.

Dense work and allowed pairs

A causal mask permits a key only at or before its query position. Default prompt row0 allows one key, row1 two and row2 three: (1+2)+3=6 pairs per head per layer per sequence. The dense algorithm still computes all 3*3=9 scores and the dense value products including masked zeros. Dense and allowed counts answer different questions.

Let c=B*L*Hq=1*2*2=4, the across-layer query-head factor. Prefill dense cells are c*T*T=4*3*3=36; allowed cells are c*T*(T+1)/2=4*3*4/2=24. Each layer’s actual hypothetical score shape is [1,2,3,3], with 18 cells. Summing layers’ work does not make all layers’ scratch simultaneously live.

Append pass j has one last query with all S=T+j keys allowed: cells(j)=c*(T+j). The complete default ordered accumulation is 0+16=16, then 16+20=36 cells, from S4 and S5. Independently the closed form is c*[D*T+D*(D+1)/2]=4*[2*3+2*3/2]=4*(6+3)=36. A closed form explains a total; it does not replace the individual passes.

Matrix work for every phase

Each score dot product takes d MACs, and its corresponding weighted-value work takes d more. That accounts for 2*d=4 MACs per dense score cell in the default. Prefill work is B*T*Cbase+2*d*denseCells; each appended pass is B*Cbase+2*d*cells(j).

PhaseProjection/feed-forward/readout MACsScore and value MACsPhase totalOrdered append subtotal
Prefill q3,S313256=7682236=144768+144=912Not an append
Append j1,q1,S41*256=2562216=64256+64=3200+320=320
Append j2,q1,S51*256=2562220=80256+80=336320+336=656

The saved operation graph separates both attention terms before adding them. Prefill is (768+72)+72=912; j1 is (256+32)+32=320; j2 is (256+40)+40=336, where each pair of equal terms counts scores then value messages. The actual increasing-j reductions are 16+20=36 cells and 320+336=656 total MACs. The separately computed closed component totals are base512, scores72 and messages72, giving (512+72)+72=656; they are not three additional loop folds.

The independent append expression gives B*D*Cbase+2*d*appendCells=1*2*256+4*36=512+144=656. Add prefill once: 912+656=1568 MACs; double once: 2*1568=3136 matrix FLOPs.

These FLOPs exclude score scaling, softmax maxima/subtractions/exponentials/divisions, masks, embedding lookup, ReLU decisions, residual additions, cache writes, copying, checksum/control, allocation, token selection, tokenization, validation and display. Normalization, position operations, training and gradients are absent from this model. A MAC convention is not a claim about fused hardware instructions or an elapsed interval.

Disclosed one-layer scratch and accounted bytes

Scratch means temporary numerical arrays for this chosen ledger. Retain five [B,q,M] arrays together: input/residual, queries before splitting, joined messages, attention projection and feed-forward output. Retain hidden [B,q,F], logits [B,q,V], and separate score/probability [B,Hq,q,S] arrays for one layer. K/V live in the separately counted cache, with no extra projection copies. Do not multiply these scratch arrays by L.

The formula is scratch(q,S)=4*[B*q*(5*M+F+V)+2*B*Hq*q*S] bytes. The leading 4 is hypothetical bytes per activation scalar, not a layer count. For defaults 5*M+F+V=(5*4+8)+8=36.

PhaseFive model-width arrays; hidden; logitsScores and probabilitiesScratch scalar sum and bytesWeight plus cache plus scratch
Prefill q3,S35*(134)=60; 138=24; 138=24; (60+24)+24=108Each 123*3=18; 18+18=36108+36=144; 4*144=576 bytes512+48=560; 560+576=1136 bytes
Append j1,q1,S45*(114)=20; 118=8; 118=8; (20+8)+8=36Each 121*4=8; 8+8=1636+16=52; 4*52=208 bytes512+64=576; 576+208=784 bytes
Append j2,q1,S55*(114)=20; 118=8; 118=8; (20+8)+8=36Each 121*5=10; 10+10=2036+20=56; 4*56=224 bytes512+80=592; 592+224=816 bytes

“Accounted” means the sum of these categories at one phase, not their sum across time. This is not measured heap/RAM, physical peak memory, bandwidth or traffic. A backend might fuse buffers or introduce new workspace. Excluded storage includes token IDs, explicit masks, selection buffers, objects/headers/pointers, alignment, allocator reservations, library workspace, trace/inspector copies, device copies, code/JIT and operating-system memory. JIT means just-in-time compilation. An exclusion does not claim a real object costs zero bytes.

Change one assumption at a time

The following complete changed cases keep every unmentioned field at default. They are count comparisons, with no timing result.

CaseParameters; weight bytesCache prefill; j1; j2; growth bytesDense/allowed prefill; append cellsPrefill; j1; j2; append sum; total MACs
B=2256; 51296;128;160;3272/48;32+40=721824;640;672;1312;3136
Hkv=2, MHA endpoint288;57696;128;160;3236/24;16+20=361008;352;368;720;1728
weightBits=kvBits=8256;25624;32;40;836/24;16+20=36912;320;336;656;1568

For B2, prefill=2*3*256+4*72=1536+288=1824; j1 is 512+4*32=640, j2 is 512+4*40=672; 640+672=1312, 1824+1312=3136. Weight storage remains 512 bytes. Scratch doubles to 1152,416,448 bytes; accounted bytes are 512+96+1152=1760, 512+128+416=1056, 512+160+448=1120. Matrix FLOPs are 2*3136=6272. Doubling rows does not establish a throughput or latency ratio.

For Hkv2, J=2*2=4; A=(32+32)+64=128, P=32+2*128=288, and weight bytes are 288*2=576. Cbase=2*128+32=288; prefill is 3*288+144=1008, j1 288+64=352, j2 288+80=368; (352+368)+1008=1728, or 3456 matrix FLOPs. Scratch stays 576,208,224 bytes; accounted bytes become 1248,912,960. Default sharing halves cache relative to this MHA case, but not the score counts or total matrix work. It provides no lossless conversion or model-quality guarantee.

For eight-bit assumptions, bw=bk=8/8=1. Weight bytes halve to 256, cache bytes halve, and matrix work stays the same. Scratch remains 576,208,224 because activation accounting stays four bytes. Accounted bytes are 856,496,520. Changing only weightBits would halve only weights; changing only kvBits would halve only cache. Neither choice quantizes the actual toy, packs a checkpoint, measures reconstruction error, proves a physical allocation, or demonstrates faster execution. Actual approximation belongs to IV-63.

A selected token is not necessarily a forwarded token

Let G be the number of requested output selections, with G at least one and no early end-of-sequence token. Stop immediately after the last selection. Prefill’s last prompt row already supplies logits for output1; there is no appended pass before that first choice. Consequently D=G-1.

Event at T=3Newly forwarded dataOutput selectedCache history
PrefillThree prompt tokensoutput13 positions, 48 bytes
Append j1output1output24 positions, 64 bytes
Append j2output2output35 positions, 80 bytes
StopNo further forward passoutput3 is already selectedStill 5 positions, 80 bytes

Thus G3 uses D2 and 1568 MACs. Setting D3 describes a different policy: also forward the final selection. At S6 that adds 1*2*2*6=24 cells and 256+4*24=352 MACs, giving 1568+352=1920 MACs and cache 2*1*2*1*6*2*2=96 bytes. The extra pass even produces logits beyond the requested answer. Naming a selected output count without this policy makes a comparison ambiguous.

For G1, D0: final cache equals prefill’s 48 bytes, append cells and work are computed zero, total work is 912 MACs and 1824 matrix FLOPs. There is no append row, last-append scratch table or tensor: the pass did not occur. Report that absence with its reason; do not fill an unperformed pass with zeros. Prefill scratch/accounted bytes remain 576/1136. For G2, D1 gives 64 final cache bytes and 912+320=1232 MACs. The planner’s chosen D is hypothetical scheduled work, not a claim to have observed an EOS decision or generation.

Hand bounds, without a search program

Consider the valid upper scenario B4,L4,T16,D8,M16,Hq4,Hkv4,F32,V32,weightBits32,kvBits32. Here d=16/4=4, J=4*4=16; A=(2*16*16+2*16*16)+2*16*32=(512+512)+1024=2048. P=32*16+4*2048=512+8192=8704; weights 8704*4=34816 bytes, Cbase=8192+512=8704.

Prefill dense cells are 4*4*4*16*16=16384; allowed cells are 64*16*17/2=8704. Prefill MACs are 4*16*8704+8*16384=557056+131072=688128. All eight append histories are needed:

jSCells=64*SOrdered cellsMACs=34816+8*cellsOrdered MACs
11710880+1088=108834816+8704=435200+43520=43520
21811521088+1152=224034816+9216=4403243520+44032=87552
31912162240+1216=345634816+9728=4454487552+44544=132096
42012803456+1280=473634816+10240=45056132096+45056=177152
52113444736+1344=608034816+10752=45568177152+45568=222720
62214086080+1408=748834816+11264=46080222720+46080=268800
72314727488+1472=896034816+11776=46592268800+46592=315392
82415368960+1536=1049634816+12288=47104315392+47104=362496

The history sum is 17+18+19+20+21+22+23+24=164; closed-form cells are 64*(8*16+8*9/2)=64*(128+36)=10496. Append MACs also equal 4*8*8704+8*10496=278528+83968=362496; total is 688128+362496=1050624, matrix FLOPs 2*1050624=2101248.

At prefill, each cache side has 4*4*4*16*4=4096 scalars, or 16384 bytes; both give 32768 bytes. At final S24, each has 6144 scalars/24576 bytes, both 49152 bytes. Growth is (256+256)*4=2048 bytes per appended batch pass. The scratch width factor is 5*16+32+32=144; prefill scratch is 4*[4*16*144+2*4*4*16*16]=4*(9216+8192)=69632 bytes; accounted prefill is 34816+32768+69632=137216 bytes. Last-append scratch is 4*[4*144+2*4*4*1*24]=4*(576+768)=5376; accounted last append is 34816+49152+5376=89344 bytes.

Why do these bound the small planner’s totals? Valid sharing gives J no greater than M. Hence A is at most 2048 and P at most 8704. The score-contraction factor simplifies using d*Hq=M: fewer, wider heads do not secretly increase that work. Nonnegative counts grow with B,L,T,D,M,F,V and represented bytes. Prefill scratch uses q=S=T; append scratch uses q1,S at most24. The largest scalar total above, 2101248, is below 2^22=4194304, far below binary64’s exact-integer limit 2^53. This is a manual bound on the disclosed integer graph, not an exhaustive program search or bound on physical RAM.

A final counterexample: reading logits only at the final prompt row would remove (3-1)*4*8=64 default MACs, giving 848 prefill and 1504 total. That is another declared algorithm. Similarly, replacing 36 dense cells by 24 allowed cells silently assumes a different attention implementation. Counts can expose such assumptions, but cannot choose them or prove their speed.

The actual fixed toy: every product and partial sum

The tiny network is untrained and has eight hand-set scalar parameters. Here binary64 means the 64-bit floating-point format used for the actual arithmetic. Choosing eight-bit planner payloads never casts these operands. All displayed nonzero toy anchors are exact binary64 integers. Positive zero +0 and negative zero -0 are distinct floating-point words even though both have numeric value zero.

Let n be the chosen number of independent sample rows, either 1 or 3. This n is not the planner’s B. The complete matrices are:

  • One-row input: X=[[1,+0]], shape [1,2].
  • Three-row input: X=[[1,+0],[+0,1],[1,1]], shape [3,2].
  • First row-feature weights: W1=[[1,-1],[1,1]], shape [2,2].
  • Second row-feature weights: W2=[[1,2],[-1,1]], shape [2,2].

Define hidden linear values Z by the row-feature product XW1. Define hidden activations H by applying ReLU, the rectified linear unit, to each Z coordinate: keep a value if it is greater than zero, otherwise return literal +0. Define outputs Y by HW2. Every intermediate has shape [n,2]; matching inner length 2 makes both products legal. There are zero biases, with no bias additions performed. Coordinate k=0 or1 selects a hidden feature, while o=0 or1 selects an output feature; input feature index f runs 0 then1. These coordinates are dimensionless toy values, not seconds, bytes or probabilities.

For each Z or Y coordinate, the signed source convention begins with its own literal +0, forms the first product, adds it, then forms and adds the second product. Read the following table from left to right. The first hidden row serves the one-row preset and is also row0 of the three-row preset; it is not a shortcut allowing the later preset to skip its computation.

Input row rHidden coordinate kFirst productFirst partial from +0Second productFinal hidden linear Z[r,k]
0: [1,+0]01*1=1(+0)+1=1(+0)*1=+01+(+0)=1
0: [1,+0]11*(-1)=-1(+0)+(-1)=-1(+0)*1=+0-1+(+0)=-1
1: [+0,1]0(+0)*1=+0(+0)+(+0)=+01*1=1(+0)+1=1
1: [+0,1]1(+0)*(-1)=-0(+0)+(-0)=+01*1=1(+0)+1=1
2: [1,1]01*1=1(+0)+1=11*1=11+1=2
2: [1,1]11*(-1)=-1(+0)+(-1)=-11*1=1-1+1=+0

Thus the complete three-row hidden linear matrix is Z=[[1,-1],[1,1],[2,+0]]. Apply both ReLU decisions in every row: (1,-1) becomes (1,+0), (1,1) stays (1,1), and (2,+0) becomes (2,+0). Even the zero coordinate takes the declared decision. The hidden matrix is H=[[1,+0],[1,1],[2,+0]]. The one-row preset has only the first row of each matrix.

Hidden row rOutput coordinate oFirst productFirst partial from +0Second productFinal output Y[r,o]
0: [1,+0]01*1=1(+0)+1=1(+0)*(-1)=-01+(-0)=1
0: [1,+0]11*2=2(+0)+2=2(+0)*1=+02+(+0)=2
1: [1,1]01*1=1(+0)+1=11*(-1)=-11+(-1)=+0
1: [1,1]11*2=2(+0)+2=21*1=12+1=3
2: [2,+0]02*1=2(+0)+2=2(+0)*(-1)=-02+(-0)=2
2: [2,+0]12*2=4(+0)+4=4(+0)*1=+04+(+0)=4

The complete outputs are Y=[[1,2]] or Y=[[1,2],[+0,3],[2,4]]. A checksum is a small summary that consumes every output in a specified order; it is not a replacement for inspecting those outputs. Initialize one checksum to +0, then visit rows in order and output coordinate 0 before1:

Output consumedThree-row running checksumOne-row running checksum
Y[0,0]=1(+0)+1=1(+0)+1=1
Y[0,1]=21+2=31+2=3, final
Y[1,0]=+03+(+0)=3No row1 in this preset
Y[1,1]=33+3=6No row1 in this preset
Y[2,0]=26+2=8No row2 in this preset
Y[2,1]=48+4=12, finalNo row2 in this preset

Each row has four affine coordinates, each with two products and two additions from +0: eight products and eight additions, plus two ReLU decisions. The three-row batch has 24 products, 24 affine additions and six ReLU decisions. Checksum additions, buffer stores and loop/control work are additional. The signed +0 fold refines the preparation paper’s direct-two-term expression: p0+p1 has one written addition, while (+0+p0)+p1 executes two. No zero product is skipped, no precomputed output is substituted, and no fused multiply-add or reassociation changes the order. A fused multiply-add combines a product and addition with one rounding; it is not this source convention.

The pure model uses two independent tiny workspaces, one per preset, each run once and then inspected. A workspace owns prepared inputs, weights and reusable buffers. Inspection retains operands, products, partial sums, hidden values, outputs and checksum from completed work; it does not recompute floating-point results. Inspection before a completed run is unavailable. Immutable detached evidence means the learner cannot change the workspace by editing an inspection copy. This chapter’s hand worksheet does not claim those previews were executed during authoring.

Source evidence uses VALUE roles for counts, indices and shapes, meaning their numeric value is compared, and WORD roles for actual floating-point operands/results, including integral-looking values and signed zeros. The distinction preserves the -0 products above; integer-looking toy results do not become planner counters. Display rounding never feeds a later calculation. Preview correctness and hypothetical resource counts remain separate from timing evidence.

What a later explicit timing action would measure

Initial state is NOT_MEASURED: there is no numeric milliseconds field, rate or placeholder checksum. Here ms means milliseconds, one thousandth of a second. Opening or importing the lesson, mounting a widget, editing analytical inputs, deriving counts, inspecting the toy or running a reference/oracle must not start the repeated workload or read a clock.

The pure numerical record’s texts.timingStatus always remains NOT_MEASURED, even if the separate timing panel later reports COMPLETE. It describes the clock-free planner and preview witness. Local observations have their own revision, work identity and provenance; they are never spliced into that record’s outputs, tensors, frames, Python witness or mathematical authority.

The later controller reuses the same actual fixed-work computation. The fixed workload unit is one complete chosen batch, with either one or three independent rows. A unit is not a generated token, a transformer layer or a request to a server.

The bounded procedure has two untimed actual units, each checksum-checked, followed by a yield and three measured trials of 128 units each. A yield lets the event loop handle other work before continuation. A full successful action therefore performs 2+3*128=386 units, or 386 row evaluations with the one-row preset and 386*3=1158 with the three-row preset. Early failure can stop sooner. The measured part has 384 units; each individual trial’s ordered checksum must be 128*3=384 or 128*12=1536. These are hand-derived correctness witnesses, not elapsed observations. Two warm-up calls do not prove the machine has reached a stable performance regime.

Prepare private reusable buffers outside the intervals. Initialize a trial checksum to +0 before its beginning clock sample. Inside one interval, do exactly 128 synchronous real unit calls, adding each returned checksum in order, then immediately obtain the ending sample. There is no await, render, trace construction, inspection, serialization, validation or yield between those two samples. The interval includes real toy arithmetic, saved buffer stores, calls, loops and checksum accumulation. Verification, publication and yields occur outside the interval. No per-unit allocation or expanding workload is intended; no setup/render time is included in the stated trial duration.

A revision identifies the current settings; a private run identity distinguishes one attempt from another. Snapshot the revision and chosen preset at start. Check both, as well as cancellation, before and after each bounded trial and before publication. An input edit makes previous reports stale even though planner settings never alter this fixed neural kernel. Selecting only a read-only explanation cursor need not invalidate the observation.

StateMeaning and evidence boundary
NOT_MEASUREDNo admitted observation; no numeric duration or rate
RUNNINGOne accepted action is in progress; no completed aggregate yet
COMPLETEAll three trials admitted; timing data retain work identity and provenance
CANCELLEDRun identity invalidated; an old continuation cannot publish success
STALESettings changed; prior reports are not current evidence
UNAVAILABLEA required condition failed; show its reason, no numeric fallback

At most one run is active. A repeated start while active is refused or disabled, not allowed to create overlapping loops. At most two completed current-revision observations are retained, one per preset. Edit, cancel, unmount or disposal invalidates the relevant run identity; an old continuation must neither publish nor clear a newer run. Disposal means ending this controller’s lifetime, after which it cannot start, sample a clock or publish.

In this lab, every raw edit or Reset example publishes STALE, drops both prior reports and invalidates active work, including when the new draft is invalid. During another action, completed reports from the same revision may remain visible with the label prior completed observation at this same settings revision. A report labeled current completed action belongs to the selected preset’s COMPLETE action. A prior report is not proof that a running, cancelled or unavailable new action completed; older-revision values are not displayed as current evidence.

Cancellation is cooperative. A synchronous 128-unit interval finishes before JavaScript can observe a cancel action; cancellation takes effect at the next yield, with the surrounding identity checks. Promise neither immediate preemption nor background continuation.

Use the ordinary browser performance.now path only after an explicit action. Provenance says where the evidence came from. Any injected clock or scheduling environment is automatically a SYNTHETIC_HARNESS, even if it returns plausible numbers. A synthetic harness can exercise cancellation, staleness and clock rejection; it cannot label itself a real local observation. Ordinary source provenance is descriptive, not trusted hardware attestation against arbitrary changes to the JavaScript environment.

Require actual finite, nonnegative clock samples and nondecreasing samples across the whole run. Require each end strictly greater than its begin. Equal samples mean insufficient clock resolution, the smallest distinction the clock can reveal: no zero-duration success, epsilon adjustment, infinite rate, retry, calibration or automatically increased work. Descending, nonnumeric or nonfinite samples are unavailable; there is no Date/wall-clock fallback or absolute-value repair. A checksum mismatch or failed trial withholds the entire aggregate. Finite means an ordinary number excluding not-a-number and positive/negative infinity.

Unknown thrown clock, yield, callback, programmer or resource errors must retain their identity. Cleanup must leave a terminal outcome rather than stranding RUNNING, and must never invent COMPLETE. An oracle can establish arithmetic facts, not the truth of elapsed time. Synthetic state-machine evidence, deterministic toy correctness, analytical counts and real local observations are four different kinds of evidence.

Only after three admitted positive finite durations may the controller choose the median, the middle duration after sorting. Let m denote that median trial duration in milliseconds, n the rows per unit and R=128 the units per trial. Then the possible reports are R*1000/m complete batch units per second, n*R*1000/m row evaluations per second, and m/R amortized milliseconds per complete unit. Amortized means an interval total divided among its units, not a directly observed latency of one isolated request. Every derived rate must itself be positive and finite. No numerical m or rate is asserted here.

Even a successful real run describes only this fixed local JavaScript toy, with its actual work identity, all three trial durations and admitted checksums. Comparing the one-row and three-row presets must disclose both row counts and intervals. A raw duration ratio is not a same-work speedup. No tokens/second, time to first token, LLM prefill/decode latency, network/server latency, peak hardware performance, training performance or production model-quality conclusion follows. Do not fit milliseconds per planner MAC, extrapolate using its bit counts, or infer memory-boundness from this different workload.

Read the lab’s five graded questions

Use the five radio questions in the lab above; this walkthrough explains that same set and adds no second grader. Feedback appears after a choice. Questions 1 through 4 name fixed premises, even after controls change. Question 5 reads all eleven current saved raw inputs, all 27 saved analytical fields and the saved absence reason from the whole result. It never uses only the selected operation or substitutes the default worksheet. Invalid or unavailable inputs withhold all five graders.

  1. Counts versus time. The first option is correct: declared logical bytes and matrix-operation counts, plus separate deterministic toy correctness. A byte or MAC is not a clock sample; a correct checksum supplies neither transformer latency nor production quality. Pure-record timingStatus remains NOT_MEASURED even if a later separate timing action completes.

  2. Dense, allowed and shape. In the named fixed default, choose the second option: 36 dense cells, 24 causal-allowed cells and one-layer score shape [1,2,3,3] with axes [B,Hq,query,key]. Hq counts score paths. L contributes to the work total, not a fifth live tensor axis. Masking does not establish that forbidden dense products were skipped.

  3. Batching and shared weights. For the named default changed only to B2, choose the third option: weights stay 512 bytes, final KV becomes 160 bytes and total work becomes 3136 MACs. Counting two copies of the weights confuses shared parameters with separate histories. Keeping all counts unchanged omits the second sequence. Neither count choice supplies a throughput claim.

  4. Three selections, two appended passes. Choose the first option: D2, final history5, cache80 bytes, total1568 MACs. Prefill selects output1; forwarding output1 selects output2; forwarding output2 selects output3, then selection stops. D3/cache96/total1920 additionally forwards output3. D0 produces the first selection only under this policy.

  5. Your current whole planner. Read the complete saved numbers printed in this question. Choose the first option when D=0: final cache copies prefill, append work is a real zero aggregate, and AppendRows is absent. Otherwise choose the second option when Hkv < Hq: appended passes retain shared K/V while every query-head score path remains. Choose the third when Hkv = Hq: each query head has a stored K/V group, including the one-head endpoint. D0 takes precedence even when heads share K/V. The default uses the second option; after edits, follow the current whole record. Fictional payload bits never quantize the actual binary64 toy, and none of these branches proves timing, speedup or model quality.

Read the actual Python computation in dependency order

These three panels display the complete adjacent canonical files as repository text, without excerpts or rewritten examples. Opening a panel does not run Python. Keep all three files together: the project-source closure is iv64.py → systems_reference.py → decoder_reference.py. The support file imports ordinary NumPy; this lesson adds no dependency or installation step. Its older decoder tasks and their checks are not called by IV64.

Start in systems_state, which captures all eleven raw values, requires every value finite before any domain, checks divisibility/sharing in order and rejects a huge integer before binary64 conversion. _first validates the prefix last and captures the independent integer planner plus both scalar MLP previews. _planner retains the two increasing-j append totals; _planner_details saves the additional factors, partials and separate base/score/message components before public projection. No hypothetical model-sized array is allocated.

_affine starts every coordinate at literal +0 and evaluates both products and additions in feature order. _toy applies ReLU, computes Y, writes it through ordinary indexed NumPy storage, then reads all Y words at [0,row,column] into ordinary output operands before the checksum fold. Storage shapes are [1,1,2] and [1,3,2]; public Y shapes are [1,2] and [3,2]. NumPy supplies real indexed storage here, not a matrix contraction or a substitute for the scalar arithmetic. Zeros, including computed -0 products, retain their WORD roles.

On success, the entire private planner capture and both stored-output previews exist before public collector callbacks. _count_binding, _inspection and _preview_binding copy saved numerical evidence into the adopted frame/tensor/text metadata; they do not replay floating-point products, ReLU or checksum arithmetic. Indices and shapes still need ordinary bookkeeping. This callback-after-private-capture order describes saved semantic operations, not physical interception of every machine instruction. An unknown callback exception propagates unchanged and can leave the supplied collector’s actual partial history.

toy_inspection(rows) gives one completed selected preview’s immutable saved inspection. It is not the JavaScript factory capability with callable run/inspect methods. derive_iv64(value) assembles the complete result and all actual frame-output aliases, refusing collisions. Known admitted faults produce only status, code and reason; foreign/subtype/unknown failures retain their identity. Neither Python nor its checks sample a clock, measure this browser workload or attest hardware execution.

The entry’s run() takes zero function arguments and reads process arguments. With no command-line argument it produces the complete default record. One JSON argument supplies a full replacement raw11 record; it is never merged with defaults, so {} is invalid. A sole - reads that JSON from standard input. The strict parser rejects duplicate fields at every level, nonfinite/overflowing numbers, malformed or trailing values and integers beyond its local 309-digit limit. It retains signed-zero input spellings; planner D still has VALUE semantics. Only errors from the admitted parser origin become input faults.

Known parse or semantic faults print their JSON unavailable record with exit status 0; inspect the record’s status rather than treating exit 0 as numerical success. Misuse, multiple arguments or an unknown option exits 2. This canonical entry has no --verify mode. Only explicit --self-check invokes its aggregate; imports, normal helpers and default/replacement/stdin queries never invoke checks. Every newly named check/helper/hook immediately refuses optimized Python -O; production validation remains active.

1. Generic support: decoder_reference.py

IV64 uses its fault, immutable-copy, prefix, trace and ordinary indexed-storage facilities. The complete file also contains earlier decoder mathematics, not invoked by this planner.

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. Independent scalar/integer planner and saved toy evidence: systems_reference.py

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.

"""IV64 independent integer/scalar FIRST with signed public source binding.

Source only: all checks UNRUN. No clocks, decoder task, native math or verifier.
"""
import importlib.util
from pathlib import Path
import sys
from types import FunctionType, ModuleType


def _module_identity(module, path):
    if type(module) is not ModuleType:
        raise ImportError("Unknown IV64 owned module identity.")
    namespace = module.__dict__
    certificate = namespace.get("_IV64_CERTIFICATE")
    if (type(certificate) is not tuple or len(certificate) != 6
            or certificate[0] is not module or certificate[1] != path
            or type(namespace.get("__file__")) is not str
            or str(Path(namespace["__file__"]).resolve()) != path
            or namespace.get("__spec__") is not certificate[5]
            or type(certificate[5].origin) is not str
            or str(Path(certificate[5].origin).resolve()) != path):
        raise ImportError("Unknown or incomplete IV64 source identity.")
    for key, function, code in certificate[2]:
        owner, dot, member = key.partition(".")
        actual = namespace.get(owner)
        if dot:
            actual = actual.__dict__.get(member) if isinstance(actual, type) else None
        if (actual is not function or type(function) is not FunctionType or function.__code__ is not code
                or str(Path(code.co_filename).resolve()) != path):
            raise ImportError("IV64 function or code identity changed.")
    for name, dependency in certificate[3]:
        if name not in sys.modules or sys.modules[name] is not dependency:
            raise ImportError("IV64 dependency cache identity changed.")
    for key, dependency in certificate[4]:
        if namespace.get(key) is not dependency:
            raise ImportError("IV64 dependency alias changed.")
    return module


def _load_support():
    name = "_book_iv64_generic59"
    path = str(Path(__file__).resolve().with_name("decoder_reference.py"))
    if name in sys.modules:
        return _module_identity(sys.modules[name], path)
    spec = importlib.util.spec_from_file_location(name, path)
    if name in sys.modules:
        raise ImportError("IV64 support appeared during specification creation.")
    if spec is None or spec.loader is None:
        raise ImportError("Cannot load adjacent IV64 generic support.")
    staged = importlib.util.module_from_spec(spec)
    if name in sys.modules:
        raise ImportError("IV64 support appeared during module creation.")
    transaction = globals().get("_IV64_TRANSACTION")
    if transaction is not None:
        transaction.append((name, staged))
    sys.modules[name] = staged
    try:
        spec.loader.exec_module(staged)
        if name not in sys.modules or sys.modules[name] is not staged:
            raise ImportError("IV64 support changed during loading.")
        functions = tuple((key, staged.__dict__[key], staged.__dict__[key].__code__)
                          for key in ("_freeze", "_prefix", "_storage", "decoder_trace", "_numeric", "_trace_entries"))
        functions += tuple((owner + "." + key, staged.__dict__[owner].__dict__[key],
                            staged.__dict__[owner].__dict__[key].__code__)
                           for owner, keys in (("NumericalFault", ("__init__",)),
                               ("_FrozenDict", ("_readonly", "__setitem__", "__delitem__", "clear", "pop", "popitem", "setdefault", "update", "__ior__")),
                               ("_FrozenList", ("_readonly", "__setitem__", "__delitem__", "append", "clear", "extend", "insert", "pop", "remove", "reverse", "sort", "__iadd__", "__imul__")),
                               ("_PublicTrace", ("__init__", "__setattr__", "__delattr__", "add"))) for key in keys)
        aliases = tuple((key, staged.__dict__[key]) for key in
                        ("np", "math", "re", "NumericalFault", "_FrozenDict", "_FrozenList", "_PublicTrace"))
        dependencies = (("numpy", staged.np), ("math", staged.math), ("re", staged.re))
        staged._IV64_CERTIFICATE = (staged, path, functions, dependencies, aliases, spec)
        return _module_identity(staged, path)
    except BaseException:
        if name in sys.modules and sys.modules[name] is staged:
            del sys.modules[name]
        raise


_support = _load_support()
NumericalFault = _support.NumericalFault
_freeze = _support._freeze
systems_trace = _support.decoder_trace
DEFAULT_IV64 = _freeze(dict(B=1, L=2, T=3, D=2, M=4, Hq=2, Hkv=1, F=8, V=8,
                           weightBits=16, kvBits=16))
_FIELDS = tuple(DEFAULT_IV64)
_BOUNDS = ((1, 4), (1, 4), (1, 16), (0, 8), (2, 16), (1, 4), (1, 4), (1, 32), (2, 32))


def systems_state(value):
    """Capture every raw data item, all finite values, then ordered domains."""
    if type(value) not in (dict, _support._FrozenDict):
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    keys = tuple(value)
    if (len(keys) != 11 or any(type(key) is not str for key in keys)
            or set(keys) != set(_FIELDS)):
        raise NumericalFault("INVALID_INPUT", "state must have exactly " + ", ".join(_FIELDS) + " as own fields.")
    captured = {key: value[key] for key in _FIELDS}
    for key, item in captured.items():
        if (type(item) not in (int, float)
                or not -1.7976931348623157e308 <= item <= 1.7976931348623157e308):
            raise NumericalFault("NONFINITE", "state." + key + " must be an actual finite number.")
    for index, key in enumerate(_FIELDS):
        item = captured[key]
        if index < 9:
            lower, upper = _BOUNDS[index]
            if not lower <= item <= upper or (type(item) is float and not item.is_integer()):
                raise NumericalFault("INVALID_INPUT", f"{key} must be an integer from {lower} to {upper}.")
        elif item not in (8, 16, 32):
            raise NumericalFault("INVALID_INPUT", key + " must be exactly 8, 16 or 32.")
    if captured["M"] % captured["Hq"] != 0:
        raise NumericalFault("INVALID_INPUT", "M must be divisible by Hq.")
    if captured["Hkv"] > captured["Hq"]:
        raise NumericalFault("INVALID_INPUT", "Hkv must be no greater than Hq.")
    if captured["Hq"] % captured["Hkv"] != 0:
        raise NumericalFault("INVALID_INPUT", "Hq must be divisible by Hkv.")
    return _freeze({key: int(captured[key]) for key in _FIELDS})


class _Capture:
    """Independent private numerical evidence; no producer metadata or callbacks."""
    def __init__(self):
        self.operations = []

    def add(self, stage, inputs, outputs):
        before, after = dict(inputs), dict(outputs)
        for record in (before, after):
            for key, value in record.items():
                if type(key) is not str:
                    raise TypeError("Private IV64 capture keys must be strings.")
                _support._numeric(value, stage + "/" + key)
        self.operations.append((stage, _freeze(before), _freeze(after)))


def _product(capture, stage, factors):
    running, inputs, outputs = 1, {}, {}
    for index, factor in enumerate(factors):
        if type(factor) is not int or not 0 <= factor < 2**53:
            raise RuntimeError("IV64 planner factors must be nonnegative exact integers.")
        inputs["factor" + str(index)] = factor
        running = running * factor
        if not 0 <= running < 2**53:
            raise RuntimeError("IV64 planner product exceeds the exact integer boundary.")
        outputs["partial" + str(index)] = running
    outputs["value"] = running
    capture.add(stage, inputs, outputs)
    return running


def _sum(capture, stage, terms):
    running, inputs, outputs = 0, {}, {}
    for index, term in enumerate(terms):
        if type(term) is not int or not 0 <= term < 2**53:
            raise RuntimeError("IV64 planner terms must be nonnegative exact integers.")
        inputs["term" + str(index)] = term
        running = running + term
        if not 0 <= running < 2**53:
            raise RuntimeError("IV64 planner sum exceeds the exact integer boundary.")
        outputs["partial" + str(index)] = running
    outputs["value"] = running
    capture.add(stage, inputs, outputs)
    return running


def _quotient(capture, stage, numerator, denominator):
    if type(numerator) is not int or type(denominator) is not int or denominator <= 0 or numerator % denominator:
        raise RuntimeError("IV64 planner quotient must be exact.")
    result = numerator // denominator
    capture.add(stage, dict(numerator=numerator, denominator=denominator), dict(value=result))
    return result


def _cache(capture, state, history, d, byte_width):
    factors = [state["B"], state["L"], state["Hkv"], history, d]
    k_elements = _product(capture, "cache K elements", factors)
    v_elements = _product(capture, "cache V elements", factors)
    k_bytes = _product(capture, "cache K bytes", [k_elements, byte_width])
    v_bytes = _product(capture, "cache V bytes", [v_elements, byte_width])
    total = _sum(capture, "cache K plus V bytes", [k_bytes, v_bytes])
    return dict(history=history, kElements=k_elements, vElements=v_elements,
                kBytes=k_bytes, vBytes=v_bytes, bytes=total)


def _scratch(capture, state, queries, history):
    five_m = _product(capture, "scratch five M", [5, state["M"]])
    features = _sum(capture, "scratch listed feature widths", [five_m, state["F"], state["V"]])
    feature_cells = _product(capture, "scratch feature cells", [state["B"], queries, features])
    score_cells = _product(capture, "scratch separate scores and probabilities", [2, state["B"], state["Hq"], queries, history])
    cells = _sum(capture, "scratch listed cells", [feature_cells, score_cells])
    byte_count = _product(capture, "scratch fixed four-byte accounting", [4, cells])
    return dict(queries=queries, history=history, featureCells=feature_cells,
                scoreCells=score_cells, cells=cells, bytes=byte_count)


def _planner(state, capture):
    B, L, T, D, M, Hq, Hkv, F, V, weight_bits, kv_bits = (state[key] for key in _FIELDS)
    d = _quotient(capture, "head width", M, Hq)
    J = _product(capture, "shared projected width", [Hkv, d])
    group_width = _quotient(capture, "query heads per KV group", Hq, Hkv)
    groups = []
    for head in range(Hq):
        group = head // group_width
        capture.add("contiguous sharing", dict(head=head, groupWidth=group_width), dict(group=group))
        groups.append(group)
    weight_bytes_each = _quotient(capture, "weight bytes per scalar", weight_bits, 8)
    cache_bytes_each = _quotient(capture, "cache bytes per scalar", kv_bits, 8)
    matrices = [_product(capture, label, shape) for label, shape in
                (("WQ parameters", [M, M]), ("WK parameters", [M, J]), ("WV parameters", [M, J]),
                 ("WO parameters", [M, M]), ("W1 parameters", [M, F]), ("W2 parameters", [F, M]))]
    layer_parameters = _sum(capture, "six matrices per layer", matrices)
    layer_total = _product(capture, "distinct layers", [L, layer_parameters])
    embedding = _product(capture, "one tied embedding readout", [V, M])
    parameters = _sum(capture, "all parameters", [embedding, layer_total])
    weight_bytes = _product(capture, "uniform weight payload", [parameters, weight_bytes_each])
    base = _sum(capture, "per-token matrix base", [layer_total, embedding])
    prefill_cache = _cache(capture, state, T, d, cache_bytes_each)
    growth = _cache(capture, state, 1, d, cache_bytes_each)
    dense = _product(capture, "computed dense prefill scores", [B, L, Hq, T, T])
    t_plus_one = _sum(capture, "T plus one", [T, 1])
    triangular_twice = _product(capture, "twice causal triangle", [T, t_plus_one])
    triangular = _quotient(capture, "causal triangle", triangular_twice, 2)
    allowed = _product(capture, "allowed causal prefill scores", [B, L, Hq, triangular])
    prefill_base = _product(capture, "prefill base MAC", [B, T, base])
    prefill_attention = _product(capture, "prefill score and value MAC", [2, d, dense])
    prefill_mac = _sum(capture, "prefill matrix MAC", [prefill_base, prefill_attention])
    prefill_scratch = _scratch(capture, state, T, T)
    prefill_accounted = _sum(capture, "prefill accounted bytes", [weight_bytes, prefill_cache["bytes"], prefill_scratch["bytes"]])
    appends, cell_terms, mac_terms = [], [], []
    for j in range(1, D + 1):
        history = _sum(capture, "append includes own KV", [T, j])
        cells = _product(capture, "append score cells", [B, L, Hq, history])
        base_mac = _product(capture, "append base MAC", [B, base])
        attention_mac = _product(capture, "append score and value MAC", [2, d, cells])
        mac = _sum(capture, "append matrix MAC", [base_mac, attention_mac])
        cache = _cache(capture, state, history, d, cache_bytes_each)
        scratch = _scratch(capture, state, 1, history)
        accounted = _sum(capture, "append accounted bytes", [weight_bytes, cache["bytes"], scratch["bytes"]])
        appends.append(dict(j=j, history=history, cells=cells, baseMAC=base_mac, attentionMAC=attention_mac,
                            mac=mac, cache=cache, scratch=scratch, accountedBytes=accounted))
        cell_terms.append(cells)
        mac_terms.append(mac)
    appended_cells = _sum(capture, "increasing-j score total", cell_terms)
    appended_mac = _sum(capture, "increasing-j MAC total", mac_terms)
    d_times_t = _product(capture, "closed-form D times T", [D, T])
    d_plus_one = _sum(capture, "D plus one", [D, 1])
    d_triangle_twice = _product(capture, "twice appended triangle", [D, d_plus_one])
    d_triangle = _quotient(capture, "appended triangle", d_triangle_twice, 2)
    history_sum = _sum(capture, "closed-form appended history sum", [d_times_t, d_triangle])
    closed_cells = _product(capture, "closed-form appended score total", [B, L, Hq, history_sum])
    closed_base = _product(capture, "closed-form append base MAC", [B, D, base])
    closed_attention = _product(capture, "closed-form append attention MAC", [2, d, closed_cells])
    closed_mac = _sum(capture, "closed-form append MAC", [closed_base, closed_attention])
    if appended_cells != closed_cells or appended_mac != closed_mac:
        raise RuntimeError("IV64 ordered append totals must match the closed form.")
    total_mac = _sum(capture, "prefill plus append MAC", [prefill_mac, appended_mac])
    matrix_flops = _product(capture, "matrix FLOPs convention only", [2, total_mac])
    final_history = _sum(capture, "final forwarded history", [T, D])
    final_cache = _cache(capture, state, final_history, d, cache_bytes_each)
    result = dict(d=d, J=J, groupWidth=group_width, groups=groups, matrixParameters=matrices,
                  layerParameters=layer_parameters, embeddingParameters=embedding,
                  parameters=parameters, weightBytesEach=weight_bytes_each, cacheBytesEach=cache_bytes_each,
                  weightBytes=weight_bytes, metadataBytes=0, activationBytesEach=4, baseMAC=base,
                  prefillCache=prefill_cache, growthCache=growth, denseCells=dense, allowedCells=allowed,
                  prefillMAC=prefill_mac, prefillScratch=prefill_scratch, prefillAccountedBytes=prefill_accounted,
                  appends=appends, appendCells=appended_cells, closedAppendCells=closed_cells,
                  appendMAC=appended_mac, closedAppendMAC=closed_mac, totalMAC=total_mac,
                  matrixFLOPs=matrix_flops, finalHistory=final_history, finalCache=final_cache)
    if appends:
        result["lastAppend"] = appends[-1]
    else:
        result["appendAbsence"] = "D=0: no appended forward pass, append-row table or last-append scratch exists."
    return result


def _affine(source, weights, capture, stage):
    output = []
    for row in range(len(source) // 2):
        for column in range(2):
            running = 0.0
            for feature in range(2):
                operand, weight = source[2 * row + feature], weights[2 * feature + column]
                previous = running
                product = operand * weight
                running = previous + product
                capture.add(stage, dict(row=row, column=column, feature=feature,
                            operand=operand, weight=weight, previous=previous),
                            dict(product=product, partial=running))
            output.append(running)
    return output


def _toy(rows, capture):
    if type(rows) not in (int, float) or not -1.7976931348623157e308 <= rows <= 1.7976931348623157e308:
        raise NumericalFault("NONFINITE", "rows must be an actual finite number.")
    if rows not in (1, 3):
        raise NumericalFault("INVALID_INPUT", "rows must be exactly 1 or 3.")
    rows = int(rows)
    x = [1.0, 0.0] if rows == 1 else [1.0, 0.0, 0.0, 1.0, 1.0, 1.0]
    w1, w2 = [1.0, -1.0, 1.0, 1.0], [1.0, 2.0, -1.0, 1.0]
    start = len(capture.operations)
    linear = _affine(x, w1, capture, "toy first affine")
    hidden = []
    for index, value in enumerate(linear):
        activated = value if value > 0.0 else 0.0
        capture.add("toy ReLU", dict(index=index, linear=value), dict(activated=activated))
        hidden.append(activated)
    computed_y = _affine(hidden, w2, capture, "toy second affine")
    stored = _support._storage(computed_y, rows, 2)
    # Storage is consumed in full before any saved projection or external callback.
    y = []
    for row in range(rows):
        for column in range(2):
            actual = float(stored[0, row, column])
            _support._numeric(actual, "stored toy Y")
            y.append(actual)
    checksum, folds = 0.0, []
    for row in range(rows):
        for column in range(2):
            actual = y[2 * row + column]
            previous = checksum
            checksum = previous + actual
            folds.append(checksum)
            capture.add("toy ordinary indexed checksum", dict(row=row, column=column, actual=actual, previous=previous),
                        dict(checksum=checksum))
    return dict(rows=rows, x=x, w1=w1, w2=w2, linear=linear, hidden=hidden,
                y=y, checksumFolds=folds, checksum=checksum,
                workCounts=[rows * 8, rows * 8, rows * 2, rows * 2],
                operations=capture.operations[start:])


def _first(value, prefix):
    """Complete private capture BEFORE public projection or supplied callbacks."""
    state = systems_state(value)
    _support._prefix(prefix)
    capture = _Capture()
    planner = _planner(state, capture)
    counts = _planner_details(state, planner)
    one = _toy(1, capture)
    three = _toy(3, capture)
    return _freeze(dict(state=state, planner=planner, counts=counts, one=one, three=three, operations=capture.operations))


def check_mechanism():
    if not __debug__:
        raise RuntimeError("Explicit IV64 math check refuses optimized Python (-O).")
    import struct
    evidence = _first(dict(DEFAULT_IV64), "first")
    p = evidence["planner"]
    assert (p["d"], p["J"], p["groups"], p["matrixParameters"]) == (2, 2, [0, 0], [16, 8, 8, 16, 32, 32])
    assert (p["layerParameters"], p["parameters"], p["weightBytes"], p["baseMAC"]) == (112, 256, 512, 256)
    assert (p["denseCells"], p["allowedCells"], p["appendCells"], p["closedAppendCells"]) == (36, 24, 36, 36)
    assert (p["prefillMAC"], p["appendMAC"], p["totalMAC"], p["matrixFLOPs"]) == (912, 656, 1568, 3136)
    assert (p["prefillCache"]["bytes"], p["finalCache"]["bytes"], p["growthCache"]["bytes"]) == (48, 80, 16)
    assert (p["prefillScratch"]["bytes"], p["prefillAccountedBytes"]) == (576, 1136)
    assert [(a["history"], a["cells"], a["mac"], a["cache"]["bytes"], a["scratch"]["bytes"], a["accountedBytes"])
            for a in p["appends"]] == [(4, 16, 320, 64, 208, 784), (5, 20, 336, 80, 224, 816)]
    b2 = _first(dict(DEFAULT_IV64, B=2), "batch")["planner"]
    assert (b2["weightBytes"], b2["finalCache"]["bytes"], b2["totalMAC"]) == (512, 160, 3136)
    mha = _first(dict(DEFAULT_IV64, Hkv=2), "mha")["planner"]
    assert (mha["J"], mha["layerParameters"], mha["parameters"], mha["weightBytes"], mha["totalMAC"]) == (4, 128, 288, 576, 1728)
    assert (mha["prefillCache"]["bytes"], mha["finalCache"]["bytes"], mha["denseCells"]) == (96, 160, 36)
    bits8 = _first(dict(DEFAULT_IV64, weightBits=8, kvBits=8), "bits")["planner"]
    assert (bits8["weightBytes"], bits8["prefillCache"]["bytes"], bits8["finalCache"]["bytes"], bits8["totalMAC"]) == (256, 24, 40, 1568)
    zero = _first(dict(DEFAULT_IV64, D=-0.0), "zero")["planner"]
    assert zero["appends"] == [] and "lastAppend" not in zero and "appendAbsence" in zero
    assert zero["appendMAC"] == zero["closedAppendMAC"] == zero["appendCells"] == zero["closedAppendCells"] == 0
    assert zero["finalCache"] == zero["prefillCache"] and zero["totalMAC"] == 912
    materialized = _first(dict(DEFAULT_IV64, D=3), "last")["planner"]
    assert materialized["totalMAC"] == 1920 and materialized["lastAppend"]["mac"] == 352
    assert materialized["finalCache"]["bytes"] == 96
    upper = _first(dict(B=4, L=4, T=16, D=8, M=16, Hq=4, Hkv=4, F=32, V=32,
                        weightBits=32, kvBits=32), "upper")["planner"]
    assert (upper["d"], upper["J"], upper["layerParameters"], upper["parameters"], upper["weightBytes"], upper["baseMAC"]) == (4, 16, 2048, 8704, 34816, 8704)
    assert (upper["denseCells"], upper["appendCells"], upper["prefillMAC"], upper["appendMAC"], upper["totalMAC"], upper["matrixFLOPs"]) == (16384, 10496, 688128, 362496, 1050624, 2101248)
    assert (upper["prefillCache"]["bytes"], upper["finalCache"]["bytes"], upper["growthCache"]["bytes"]) == (32768, 49152, 2048)
    assert (upper["prefillScratch"]["bytes"], upper["lastAppend"]["scratch"]["bytes"], upper["prefillAccountedBytes"], upper["lastAppend"]["accountedBytes"]) == (69632, 5376, 137216, 89344)
    assert _first(dict(DEFAULT_IV64, M=8, Hq=4, Hkv=2), "groups")["planner"]["groups"] == [0, 0, 1, 1]
    one, three = evidence["one"], evidence["three"]
    assert one["linear"] == [1, -1] and one["hidden"] == [1, 0] and one["y"] == [1, 2]
    assert three["linear"] == [1, -1, 1, 1, 2, 0] and three["hidden"] == [1, 0, 1, 1, 2, 0]
    assert three["y"] == [1, 2, 0, 3, 2, 4] and three["checksumFolds"] == [1, 3, 3, 6, 8, 12]
    assert one["checksumFolds"] == [1, 3] and (one["checksum"], three["checksum"]) == (3, 12)
    # These literal tables are manual products/partials, never generated success gold.
    hidden_products = [[1.0, 0.0, -1.0, 0.0], [0.0, 1.0, -0.0, 1.0], [1.0, 1.0, -1.0, 1.0]]
    hidden_partials = [[1.0, 1.0, -1.0, -1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 2.0, -1.0, 0.0]]
    output_products = [[1.0, -0.0, 2.0, 0.0], [1.0, -1.0, 2.0, 1.0], [2.0, -0.0, 4.0, 0.0]]
    output_partials = [[1.0, 1.0, 2.0, 2.0], [1.0, 0.0, 2.0, 3.0], [2.0, 2.0, 4.0, 4.0]]
    for toy in (one, three):
        for stage, products, partials in (("toy first affine", hidden_products, hidden_partials),
                                         ("toy second affine", output_products, output_partials)):
            saved = [operation for operation in toy["operations"] if operation[0] == stage]
            assert len(saved) == 4 * toy["rows"]
            for index, (_, before, after) in enumerate(saved):
                row, cell = divmod(index, 4)
                assert struct.pack(">d", after["product"]) == struct.pack(">d", products[row][cell])
                assert struct.pack(">d", after["partial"]) == struct.pack(">d", partials[row][cell])
                if before["feature"] == 0:
                    assert struct.pack(">d", before["previous"]) == struct.pack(">d", 0.0)
        assert len([op for op in toy["operations"] if op[0] == "toy ReLU"]) == 2 * toy["rows"]
    for _, before, after in evidence["operations"]:
        assert all(type(item) in (int, float) for item in before.values())
        assert all(type(item) in (int, float) for item in after.values())
    try:
        three["y"][0] = 9
    except TypeError:
        pass
    else:
        raise AssertionError("Private evidence must be detached and immutable.")


def check_guards():
    if not __debug__:
        raise RuntimeError("Explicit IV64 guard check refuses optimized Python (-O).")
    default = dict(DEFAULT_IV64)
    cases = [({}, "INVALID_INPUT"), (dict(default, extra=1), "INVALID_INPUT"),
             (list(default.values()), "INVALID_INPUT")]
    for key in _FIELDS:
        for invalid in (True, "1", None, float("nan"), float("inf"), -(10**400), 10**400):
            cases.append((dict(default, **{key: invalid}), "NONFINITE"))
    for index, key in enumerate(_FIELDS[:9]):
        lower, upper = _BOUNDS[index]
        for invalid in (lower - 1, upper + 1, lower + 0.5):
            cases.append((dict(default, **{key: invalid}), "INVALID_INPUT"))
    for key in _FIELDS[9:]:
        for invalid in (0, 7, 8.5, 64):
            cases.append((dict(default, D=0, **{key: invalid}), "INVALID_INPUT"))
    cases += [(dict(default, M=5), "INVALID_INPUT"), (dict(default, Hkv=3), "INVALID_INPUT"),
              (dict(default, M=6, Hq=3, Hkv=2), "INVALID_INPUT"),
              (dict(default, B=0, kvBits=float("nan")), "NONFINITE")]
    for value, expected in cases:
        try:
            _first(value, "!")
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == expected
            assert "prefix" not in error.reason
        else:
            raise AssertionError("Invalid raw state must fail before prefix.")
    for value, reason in ((dict(default, M=5, Hkv=3), "M must be divisible by Hq."),
                          (dict(default, Hkv=3), "Hkv must be no greater than Hq."),
                          (dict(default, M=6, Hq=3, Hkv=2), "Hq must be divisible by Hkv.")):
        try:
            systems_state(value)
        except NumericalFault as error:
            assert error.reason == reason
        else:
            raise AssertionError("Sharing preflight must keep declared precedence.")
    for prefix in ("", "_x", "1x", "é", "a-b", 1, None):
        try:
            _first(default, prefix)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == "INVALID_INPUT" and "prefix" in error.reason
        else:
            raise AssertionError("ASCII prefix must validate last.")
    assert systems_state(dict(default, D=-0.0))["D"] == 0
    for invalid in (True, 0, 2, 4, 1.5, float("nan"), 10**400):
        capture = _Capture()
        try:
            _toy(invalid, capture)
        except NumericalFault as error:
            assert type(error) is NumericalFault and capture.operations == []
        else:
            raise AssertionError("Toy row admission must precede work.")


def check_storage_and_public():
    if not __debug__:
        raise RuntimeError("Explicit IV64 storage check refuses optimized Python (-O).")
    original = _support._storage
    reads, calls = [], []

    class Stored:
        def __init__(self, values, rows):
            if not __debug__:
                raise RuntimeError("Explicit IV64 storage constructor refuses -O.")
            self.values, self.rows = values, rows

        def __getitem__(self, index):
            if not __debug__:
                raise RuntimeError("Explicit IV64 storage indexing hook refuses -O.")
            reads.append((self.rows, index))
            _, row, column = index
            return self.values[2 * row + column] + (1.0 if row == column == 0 else 0.0)

    def storage(values, rows, cols):
        if not __debug__:
            raise RuntimeError("Explicit IV64 storage hook refuses optimized Python (-O).")
        calls.append((rows, cols, list(values)))
        return Stored(values, rows)

    class Observer:
        def add(self, *args):
            if not __debug__:
                raise RuntimeError("Explicit IV64 observer hook refuses optimized Python (-O).")
            assert len(reads) == 8 and len(calls) == 2
            observed.append(args)

    try:
        _support._storage = storage
        evidence = _first(dict(DEFAULT_IV64), "storage")
        assert calls == [(1, 2, [1, 2]), (3, 2, [1, 2, 0, 3, 2, 4])]
        assert reads == [(1, (0, 0, 0)), (1, (0, 0, 1)), (3, (0, 0, 0)), (3, (0, 0, 1)),
                         (3, (0, 1, 0)), (3, (0, 1, 1)), (3, (0, 2, 0)), (3, (0, 2, 1))]
        assert evidence["one"]["y"] == [2, 2] and evidence["one"]["checksum"] == 4
        assert evidence["three"]["y"] == [2, 2, 0, 3, 2, 4] and evidence["three"]["checksum"] == 13
        reads.clear()
        calls.clear()
        observed = []
        result = evaluate_systems(dict(DEFAULT_IV64), Observer(), "storage")
        assert len(observed) == 78
        assert result["summary"]["oneRowChecksum"] == 4 and result["summary"]["threeRowChecksum"] == 13
        assert next(t for t in result["tensors"] if t["id"] == "storage_toy3_Y")["values"] == [2, 2, 0, 3, 2, 4]
        unknown = MemoryError("storage identity")

        def failed_storage(values, rows, cols):
            if not __debug__:
                raise RuntimeError("Explicit IV64 failing storage hook refuses -O.")
            raise unknown

        _support._storage = failed_storage
        try:
            _first(dict(DEFAULT_IV64), "unknown")
        except BaseException as error:
            assert error is unknown
        else:
            raise AssertionError("Unknown storage error must preserve identity.")
    finally:
        _support._storage = original
    trace = systems_trace()
    assert systems_trace is _support.decoder_trace
    result = evaluate_systems(dict(DEFAULT_IV64), trace, "ordinary")
    assert tuple(result) == ("state", "summary", "tensors", "texts")
    assert len(trace.steps) == 78 and len(result["tensors"]) == 33


def source_self_check():
    if not __debug__:
        raise RuntimeError("Explicit IV64 reference aggregate refuses optimized Python (-O).")
    check_mechanism()
    check_guards()
    check_storage_and_public()
    check_inspection()
    check_public()
    check_once_capture()
    check_trace()


# Additional integer partials are captured here, never recovered during serialization.
def _save_count(frames, tag, inputs, outputs):
    for item in outputs.values():
        if type(item) is not int or not 0 <= item < 2**53:
            raise NumericalFault("UNSUPPORTED_SIZE", "IV64 count intermediates must be nonnegative safe integers.")
    frames.append((tag, dict(inputs), dict(outputs)))


def _cache_details(state, saved):
    B, L, Hkv = state["B"], state["L"], state["Hkv"]
    kBL = B * L
    kGroups = kBL * Hkv
    kRows = kGroups * saved["history"]
    vBL = B * L
    vGroups = vBL * Hkv
    vRows = vGroups * saved["history"]
    totalElements = saved["kElements"] + saved["vElements"]
    return dict(history=saved["history"], kBL=kBL, kGroups=kGroups, kRows=kRows,
                KElements=saved["kElements"], KBytes=saved["kBytes"], vBL=vBL, vGroups=vGroups,
                vRows=vRows, VElements=saved["vElements"], VBytes=saved["vBytes"],
                totalElements=totalElements, totalBytes=saved["bytes"])


def _scratch_details(state, saved, weight_bytes, cache_bytes):
    Bq = state["B"] * saved["queries"]
    fiveM = 5 * state["M"]
    plusF = fiveM + state["F"]
    width = plusF + state["V"]
    featureElements = Bq * width
    BHq = state["B"] * state["Hq"]
    headQueries = BHq * saved["queries"]
    scoreElements = headQueries * saved["history"]
    probabilityElements = headQueries * saved["history"]
    scorePair = scoreElements + probabilityElements
    totalElements = featureElements + scorePair
    weightAndCache = weight_bytes + cache_bytes
    accountedBytes = weightAndCache + saved["bytes"]
    return dict(q=saved["queries"], history=saved["history"], Bq=Bq, fiveM=fiveM, plusF=plusF,
                width=width, featureElements=featureElements, BHq=BHq, headQueries=headQueries,
                scoreElements=scoreElements, probabilityElements=probabilityElements, scorePair=scorePair,
                totalElements=totalElements, scratchBytes=saved["bytes"], weightAndCache=weightAndCache,
                accountedBytes=accountedBytes)


def _planner_details(s, p):
    """Save every adopted integer intermediate alongside the independent FIRST."""
    B, L, T, D, M, Hq, Hkv, F, V, weightBits, kvBits = (s[key] for key in _FIELDS)
    frames, parameterLedger, cacheLedger, causalRows, scratchLedger, appendRows = [], [], [], [], [], []
    d, J, groupWidth = p["d"], p["J"], p["groupWidth"]
    weightBytesPerScalar, kvBytesPerScalar = p["weightBytesEach"], p["cacheBytesEach"]
    _save_count(frames, "dimensions", dict(M=M, Hq=Hq, Hkv=Hkv, weightBits=weightBits, kvBits=kvBits, bitsPerByte=8),
                dict(d=d, J=J, groupWidth=groupWidth, weightBytesPerScalar=weightBytesPerScalar, kvBytesPerScalar=kvBytesPerScalar))
    for h, group in enumerate(p["groups"]):
        _save_count(frames, "map_" + str(h), dict(h=h, groupWidth=groupWidth), dict(group=group))
    partial = 0
    for n, (inputWidth, outputWidth) in enumerate(((M, M), (M, J), (M, J), (M, M), (M, F), (F, M))):
        previous, product = partial, p["matrixParameters"][n]
        partial = previous + product
        parameterLedger.extend((inputWidth, outputWidth, product, partial))
        _save_count(frames, "parameter_" + str(n), dict(n=n, inputWidth=inputWidth, outputWidth=outputWidth, previous=previous),
                    dict(product=product, partial=partial))
    A = p["layerParameters"]
    embeddingParameters = p["embeddingParameters"]
    layerParameters = L * A
    parameters, weightBytes, metadataBytes = p["parameters"], p["weightBytes"], p["metadataBytes"]
    representedBytes = weightBytes + metadataBytes
    weights = dict(embeddingParameters=embeddingParameters, layerParameters=layerParameters, parameters=parameters,
                   weightBytes=weightBytes, metadataBytes=metadataBytes, representedBytes=representedBytes)
    _save_count(frames, "weights", dict(V=V, M=M, L=L, A=A, weightBytesPerScalar=weightBytesPerScalar), weights)
    layerMatrixMAC, readoutMAC = L * A, M * V
    baseMACPerToken = p["baseMAC"]
    _save_count(frames, "base", dict(L=L, A=A, M=M, V=V),
                dict(layerMatrixMAC=layerMatrixMAC, readoutMAC=readoutMAC, baseMACPerToken=baseMACPerToken))
    growth = _cache_details(s, p["growthCache"])
    cacheInputs = dict(B=B, L=L, Hkv=Hkv, history=1, d=d, kvBytesPerScalar=kvBytesPerScalar)
    _save_count(frames, "cache_growth", cacheInputs, growth)
    cacheLedger.extend(growth[key] for key in ("history", "KElements", "VElements", "totalElements", "KBytes", "VBytes", "totalBytes"))
    BL = B * L
    BLHq = BL * Hq
    prefillHeadQueries = BLHq * T
    prefillDenseCells = p["denseCells"]
    _save_count(frames, "dense", dict(B=B, L=L, Hq=Hq, T=T),
                dict(BL=BL, BLHq=BLHq, prefillHeadQueries=prefillHeadQueries, prefillDenseCells=prefillDenseCells))
    causalSum = 0
    for i in range(T):
        keys, previous = i + 1, causalSum
        causalSum = previous + keys
        causalRows.extend((keys, previous, causalSum))
        _save_count(frames, "causal_" + str(i), dict(i=i, previous=previous), dict(keys=keys, partial=causalSum))
    nextT = T + 1
    triangleProduct = T * nextT
    triangle = triangleProduct // 2
    prefillAllowedCells = BLHq * causalSum
    closedAllowedCells = BLHq * triangle
    if prefillAllowedCells != closedAllowedCells or prefillAllowedCells != p["allowedCells"]:
        raise RuntimeError("IV64 causal counts must match the closed form.")
    _save_count(frames, "allowed", dict(T=T, BLHq=BLHq, causalSum=causalSum, divisor=2),
                dict(nextT=nextT, triangleProduct=triangleProduct, triangle=triangle,
                     prefillAllowedCells=prefillAllowedCells, closedAllowedCells=closedAllowedCells))
    prefillCache = _cache_details(s, p["prefillCache"])
    _save_count(frames, "cache_prefill", dict(cacheInputs, history=T), prefillCache)
    cacheLedger.extend(prefillCache[key] for key in ("history", "KElements", "VElements", "totalElements", "KBytes", "VBytes", "totalBytes"))
    prefillScratch = _scratch_details(s, p["prefillScratch"], representedBytes, prefillCache["totalBytes"])
    scratchInputs = dict(B=B, q=T, history=T, M=M, F=F, V=V, Hq=Hq, featureBuffers=5, activationBytes=4,
                         representedBytes=representedBytes, cacheBytes=prefillCache["totalBytes"])
    _save_count(frames, "scratch_prefill", scratchInputs, prefillScratch)
    scratchLedger.extend(prefillScratch.values())
    prefillRows = B * T
    prefillBaseMAC = prefillRows * baseMACPerToken
    prefillScoreMAC = d * prefillDenseCells
    prefillMessageMAC = d * prefillDenseCells
    prefillBaseAndScores = prefillBaseMAC + prefillScoreMAC
    prefillMAC = p["prefillMAC"]
    _save_count(frames, "prefill", dict(B=B, T=T, baseMACPerToken=baseMACPerToken, d=d, prefillDenseCells=prefillDenseCells),
                dict(prefillRows=prefillRows, prefillBaseMAC=prefillBaseMAC, prefillScoreMAC=prefillScoreMAC,
                     prefillMessageMAC=prefillMessageMAC, prefillBaseAndScores=prefillBaseAndScores, prefillMAC=prefillMAC))
    appendScoreCells, appendMAC = 0, 0
    finalCache, finalScratch = prefillCache, prefillScratch
    for row in p["appends"]:
        j, history, scoreCells, baseMAC, matrixMAC = (row[key] for key in ("j", "history", "cells", "baseMAC", "mac"))
        scoreMAC = d * scoreCells
        messageMAC = d * scoreCells
        baseAndScores = baseMAC + scoreMAC
        previousCells, previousMAC = appendScoreCells, appendMAC
        appendScoreCells = previousCells + scoreCells
        appendMAC = previousMAC + matrixMAC
        _save_count(frames, "append_" + str(j), dict(T=T, j=j, BLHq=BLHq, B=B, baseMACPerToken=baseMACPerToken,
                    d=d, previousCells=previousCells, previousMAC=previousMAC),
                    dict(history=history, scoreCells=scoreCells, baseMAC=baseMAC, scoreMAC=scoreMAC, messageMAC=messageMAC,
                         baseAndScores=baseAndScores, matrixMAC=matrixMAC, appendScoreCells=appendScoreCells, appendMAC=appendMAC))
        finalCache = _cache_details(s, row["cache"])
        _save_count(frames, "cache_append_" + str(j), dict(cacheInputs, history=history), finalCache)
        cacheLedger.extend(finalCache[key] for key in ("history", "KElements", "VElements", "totalElements", "KBytes", "VBytes", "totalBytes"))
        finalScratch = _scratch_details(s, row["scratch"], representedBytes, finalCache["totalBytes"])
        _save_count(frames, "scratch_append_" + str(j), dict(scratchInputs, q=1, history=history, cacheBytes=finalCache["totalBytes"]), finalScratch)
        scratchLedger.extend(finalScratch.values())
        appendRows.extend((j, history, scoreCells, matrixMAC, finalCache["KBytes"], finalCache["VBytes"], finalCache["totalBytes"],
                           finalScratch["scratchBytes"], finalScratch["accountedBytes"], appendScoreCells, appendMAC))
    DT, nextD = D * T, D + 1
    appendTriangleProduct = D * nextD
    appendTriangle = appendTriangleProduct // 2
    historySum = DT + appendTriangle
    closedAppendCells, closedAppendMAC = p["closedAppendCells"], p["closedAppendMAC"]
    batchAppends = B * D
    appendBaseMAC = batchAppends * baseMACPerToken
    appendScoreMAC = d * closedAppendCells
    appendMessageMAC = d * closedAppendCells
    appendBaseAndScores = appendBaseMAC + appendScoreMAC
    if appendScoreCells != closedAppendCells or appendMAC != closedAppendMAC:
        raise RuntimeError("IV64 ordered append totals must match the closed form.")
    _save_count(frames, "appendClosed", dict(D=D, T=T, BLHq=BLHq, B=B, baseMACPerToken=baseMACPerToken, d=d,
                divisor=2, appendScoreCells=appendScoreCells, appendMAC=appendMAC),
                dict(DT=DT, nextD=nextD, appendTriangleProduct=appendTriangleProduct, appendTriangle=appendTriangle,
                     historySum=historySum, closedAppendCells=closedAppendCells, batchAppends=batchAppends,
                     appendBaseMAC=appendBaseMAC, appendScoreMAC=appendScoreMAC, appendMessageMAC=appendMessageMAC,
                     appendBaseAndScores=appendBaseAndScores, closedAppendMAC=closedAppendMAC))
    analytical = dict(d=d, J=J, groupWidth=groupWidth, parameters=parameters, weightBytes=weightBytes, metadataBytes=metadataBytes,
                     prefillKBytes=prefillCache["KBytes"], prefillVBytes=prefillCache["VBytes"], prefillCacheBytes=prefillCache["totalBytes"],
                     finalKBytes=finalCache["KBytes"], finalVBytes=finalCache["VBytes"], finalCacheBytes=finalCache["totalBytes"], cacheGrowthBytes=growth["totalBytes"],
                     prefillDenseCells=prefillDenseCells, prefillAllowedCells=prefillAllowedCells, appendScoreCells=appendScoreCells,
                     baseMACPerToken=baseMACPerToken, prefillMAC=prefillMAC, appendMAC=appendMAC, totalMAC=p["totalMAC"], matrixFLOPs=p["matrixFLOPs"],
                     prefillScratchBytes=prefillScratch["scratchBytes"], prefillAccountedBytes=prefillScratch["accountedBytes"],
                     finalScratchBytes=finalScratch["scratchBytes"], finalAccountedBytes=finalScratch["accountedBytes"],
                     finalHistory=p["finalHistory"], selectedOutputsWithoutEOS=nextD)
    _save_count(frames, "totals", dict(prefillMAC=prefillMAC, appendMAC=appendMAC, T=T, D=D, two=2), analytical)
    return dict(frames=frames, analytical=analytical, parameterLedger=parameterLedger,
                weightLedger=[embeddingParameters, layerParameters, parameters, weightBytesPerScalar, weightBytes, metadataBytes, representedBytes],
                cacheLedger=cacheLedger, causalRows=causalRows,
                prefillCounts=[prefillDenseCells, prefillAllowedCells, prefillMAC, prefillScratch["scratchBytes"], prefillScratch["accountedBytes"]],
                appendRows=appendRows, appendTotals=[appendScoreCells, closedAppendCells, historySum, appendBaseMAC, appendScoreMAC, appendMessageMAC, appendMAC],
                scratchLedger=scratchLedger)


def _inspection(toy):
    """Copy saved independent scalar evidence; no floating arithmetic here."""
    affine1, affine2, folds = [], [], []
    for stage, before, after in toy["operations"]:
        if stage in ("toy first affine", "toy second affine"):
            target = affine1 if stage == "toy first affine" else affine2
            target.extend((before["operand"], before["weight"], after["product"], before["previous"], after["partial"]))
        elif stage == "toy ordinary indexed checksum":
            folds.extend((before["previous"], before["actual"], after["checksum"]))
    return _freeze(dict(algorithm="iv64-mlp-ordered-fold-v1", rows=toy["rows"], X=toy["x"], W1=toy["w1"], W2=toy["w2"],
                        affine1=affine1, hiddenLinear=toy["linear"], hidden=toy["hidden"], affine2=affine2,
                        Y=toy["y"], checksumFolds=folds, checksum=toy["checksum"], productsPerRow=8, additionsPerRow=8, reluPerRow=2))


def toy_inspection(rows):
    """One independent completed run's saved inspection, not a callable factory."""
    return _inspection(_toy(rows, _Capture()))


# Owner-adopted literal prose only; numerical evidence remains independently computed.
_COUNT_METADATA = {
    "dimensions": ("Derive head widths and hypothetical scalar bytes",
        "d=M/Hq; J=Hkv*d; groupWidth=Hq/Hkv; weightBytesPerScalar=weightBits/8; kvBytesPerScalar=kvBits/8",
        "All eleven raw fields have already passed structural, finite, integer and sharing checks. Bit choices change logical payload only; the real toy always uses binary64."),
    "map": ("Query head {h}: shared K and V group", "group=floor(h/groupWidth)",
        "Contiguous sharing uses this same group for keys and values. It does not merge query heads or expand the stored KV groups."),
    "parameter": ("Per-layer {name} weights", "product=inputWidth*outputWidth; partial=previous+product",
        "Count every scalar in this bias-free row-feature matrix, then add it in Q,K,V,O,FF1,FF2 order. Distinct layers will each store this complete set."),
    "weights": ("Store tied embeddings once and distinct layers separately",
        "embeddingParameters=V*M; layerParameters=L*A; parameters=embeddingParameters+layerParameters; weightBytes=parameters*weightBytesPerScalar; metadataBytes=0; representedBytes=weightBytes+metadataBytes",
        "The input embedding and all-row output readout share one table. Zero metadata is an explicit fictional raw-format assumption, not a claim about actual quantized checkpoints."),
    "base": ("Matrix terms for one processed token", "layerMatrixMAC=L*A; readoutMAC=M*V; baseMACPerToken=layerMatrixMAC+readoutMAC",
        "Every processed row gets all layer projections, the ordinary two-matrix FFN and the tied-table readout. Attention contractions are added separately."),
    "cache": ("Logical K plus V payload: {tag}",
        "kBL=B*L; kGroups=kBL*Hkv; kRows=kGroups*history; KElements=kRows*d; KBytes=KElements*kvBytesPerScalar; vBL=B*L; vGroups=vBL*Hkv; vRows=vGroups*history; VElements=vRows*d; VBytes=VElements*kvBytesPerScalar; totalElements=KElements+VElements; totalBytes=KBytes+VBytes",
        "Count original K and V groups separately, then sum once. This is logical represented storage across layers, without query tensors, expanded KV copies, allocator overhead or measured traffic. The growth row counts one added history position."),
    "dense": ("Dense computed prefill score cells", "BL=B*L; BLHq=BL*Hq; prefillHeadQueries=BLHq*T; prefillDenseCells=prefillHeadQueries*T",
        "The declared dense algorithm computes forbidden future scores and dense probability-times-value products too. Hq counts score paths; Hkv is not the score multiplier."),
    "causal": ("Prompt query {i}: count allowed keys", "keys=i+1; partial=previous+keys",
        "Causal eligibility includes this position itself. This ordered triangle describes allowed cells, not reduced dense matrix work."),
    "allowed": ("Separate causal eligibility from dense computed cells",
        "nextT=T+1; triangleProduct=T*nextT; triangle=triangleProduct/2; prefillAllowedCells=BLHq*causalSum; closedAllowedCells=BLHq*triangle",
        "The actual increasing-query sum and its closed form are both retained. Dense computed cells remain the arithmetic multiplier."),
    "scratch": ("Declared one-layer scratch: {tag}",
        "Bq=B*q; fiveM=5*M; plusF=fiveM+F; width=plusF+V; featureElements=Bq*width; BHq=B*Hq; headQueries=BHq*q; scoreElements=headQueries*history; probabilityElements=headQueries*history; scorePair=scoreElements+probabilityElements; totalElements=featureElements+scorePair; scratchBytes=4*totalElements; weightAndCache=representedBytes+cacheBytes; accountedBytes=weightAndCache+scratchBytes",
        "Five M-wide buffers are X/residual, Q, joined messages, attention projection and FFN output; also retain F-wide hidden, V-wide logits and separate one-layer scores/probabilities. Four bytes per scalar is hypothetical activation accounting. This ledger is not physical peak allocation, bandwidth or runtime heap usage."),
    "prefill": ("Matrix MACs for the actual planned prefill",
        "prefillRows=B*T; prefillBaseMAC=prefillRows*baseMACPerToken; prefillScoreMAC=d*prefillDenseCells; prefillMessageMAC=d*prefillDenseCells; prefillBaseAndScores=prefillBaseMAC+prefillScoreMAC; prefillMAC=prefillBaseAndScores+prefillMessageMAC",
        "Both dense attention contractions count every computed cell. Matrix MACs exclude softmax, ReLU, residuals, lookup, control, copies, checksum, allocation and data movement."),
    "append": ("Append pass {j}: include its own K and V",
        "history=T+j; scoreCells=BLHq*history; baseMAC=B*baseMACPerToken; scoreMAC=d*scoreCells; messageMAC=d*scoreCells; baseAndScores=baseMAC+scoreMAC; matrixMAC=baseAndScores+messageMAC; appendScoreCells=previousCells+scoreCells; appendMAC=previousMAC+matrixMAC",
        "One new query per sequence attends through T+j, including its own position. Increase j in order and retain the real computed row and both running totals."),
    "appendClosed": ("Retain the append closed form alongside actual rows",
        "DT=D*T; nextD=D+1; appendTriangleProduct=D*nextD; appendTriangle=appendTriangleProduct/2; historySum=DT+appendTriangle; closedAppendCells=BLHq*historySum; batchAppends=B*D; appendBaseMAC=batchAppends*baseMACPerToken; appendScoreMAC=d*closedAppendCells; appendMessageMAC=d*closedAppendCells; appendBaseAndScores=appendBaseMAC+appendScoreMAC; closedAppendMAC=appendBaseAndScores+appendMessageMAC",
        "The closed form checks the increasing-j row aggregate without substituting a fictional table. D=0 gives real zero aggregate work and no append rows."),
    "totals": ("Keep analytical resources separate from neural correctness and time",
        "totalMAC=prefillMAC+appendMAC; matrixFLOPs=2*totalMAC; finalHistory=T+D; selectedOutputsWithoutEOS=D+1; other fields copy saved counts",
        "D counts appended forward passes. With a nonempty prompt, no EOS and stopping immediately after the final selection, G=D+1 selected outputs leaves the final selected token outside cache. FLOPs mean matrix operations only. No elapsed time follows."),
}
_PARAMETER_NAMES = ("Q", "K", "V", "O", "FF1", "FF2")
_TEXTS = dict(
    parameterFields=["inputWidth", "outputWidth", "product", "partial"],
    weightFields=["embeddingParameters", "layerParameters", "parameters", "weightBytesPerScalar", "weightBytes", "metadataBytes", "representedBytes"],
    cacheFields=["history", "KElements", "VElements", "totalElements", "KBytes", "VBytes", "totalBytes"],
    causalFields=["keys", "previous", "partial"], prefillFields=["denseCells", "allowedCells", "matrixMAC", "scratchBytes", "accountedBytes"],
    appendFields=["j", "history", "scoreCells", "matrixMAC", "KBytes", "VBytes", "cacheBytes", "scratchBytes", "accountedBytes", "cumulativeScoreCells", "cumulativeMAC"],
    appendTotalFields=["actualScoreCells", "closedScoreCells", "historySum", "baseMAC", "scoreMAC", "messageMAC", "actualMAC"],
    scratchFields=["q", "history", "Bq", "fiveM", "plusF", "width", "featureElements", "BHq", "headQueries", "scoreElements", "probabilityElements", "scorePair", "totalElements", "scratchBytes", "weightAndCache", "accountedBytes"],
    affineFields=["left", "right", "product", "previous", "sum"], foldFields=["previous", "value", "sum"],
    workCountFields=["products", "affineAdditions", "reluDecisions", "checksumAdditions"],
    toyAlgorithm="iv64-mlp-ordered-fold-v1", toyEvidence="probe-correctness", timingStatus="NOT_MEASURED",
    architecturePolicy="Hypothetical bias-free decoder-shaped accounting: L distinct layers, tied embedding/readout [V,M] stored once, Q/O [M,M], K/V [M,J], ordinary FFN [M,F] then [F,M]. No norm, position, bias or gating parameters; no padding, EOS, early stop, scheduler or queue. All processed rows get readout. No hypothetical neural array is allocated.",
    axesPolicy="Analytical shapes only: X [B,q,M], Q [B,Hq,q,d], each per-layer original K/V [B,Hkv,S,d], scores/probabilities [B,Hq,q,S], joined [B,q,M], logits [B,q,V]. Prefill q=S=T; append q=1,S=T+j. Layers contribute counts, never an allocated rank-five cache.",
    countPolicy="Exact nonnegative integer factors and ordered sums below 2^53. Dense computed prefill cells and causal-allowed cells are separate. Both K and V are counted once, using Hkv; score paths use Hq. MAC means a scalar matrix product term; matrix FLOPs=2*MAC, not all executed operations or fused instruction counts.",
    scratchPolicy="Declared one-layer simultaneous buffer ledger only: five M-wide arrays, one F-wide hidden, one V-wide logits, separate scores and probabilities at hypothetical four bytes/scalar. Retain all-layer cache and shared weights separately. Exclude masks, IDs, selection buffers, headers, alignment, allocator reservation, library temporaries, traces, JIT/code/OS/device copies and traffic; no physical peak or bandwidth claim.",
    representationPolicy="weightBits/kvBits choose uniform represented bytes only; metadata=0 is an explicit fictional raw-format assumption. No packing, scales, zero points, rounding, quantization, cast or quality experiment. Fixed toy inputs, weights and buffers remain binary64 at every planner choice.",
    generationPolicy="D counts appended forward passes, not selected tokens. With nonempty prompt, G>=1, no EOS and stop after the final selection, D=G-1 and cache length T+D excludes the final selected token. Forwarding it is a different policy. No actual generation is performed.",
    toyPolicy="Independent one-row then three-row factories each run exactly once. Eight products and eight additions per row in affine paths, two ReLU decisions, plus two checksum additions and buffer/index/control work. Per coordinate start literal +0, compute both terms in increasing feature order; inactive ReLU is literal +0. Inspection and trace copy saved floats only. These hand-set untrained independent samples are not a transformer, attention, cache, token or server benchmark.",
    rolePolicy="Raw state, counts, dimensions, indices, metadata and WorkCounts use VALUE (D=-0 equals zero). Every other toy tensor value and every toy floating frame operand/result/checksum/copy uses WORD, including literal +0, computed -0 and integral-looking floats. No native elementary functions or native witness fields exist.",
    timingPolicy="NOT_MEASURED has no numeric duration or rate. This pure model never samples a clock, warms up or repeats work. A separate parent-owned explicit-action controller must reuse createToyWork; synthetic clocks cannot establish real measurement. Counts and checksum correctness do not prove speedup, memory-boundness, hardware execution or quality.",
    validationPolicy="SOURCE ONLY: all executable checks, canonical/oracle parity, typecheck, build, browser, accessibility, offline and timing checks remain UNRUN under the human FluxGeo hold. Owner adoption is separate from runtime acceptance.",
)


def _tensor(identifier, shape, axes, values, provenance, precision):
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64", values=list(values),
                provenance=provenance, precision=precision)


def _count_binding(counts, trace, prefix):
    for tag, inputs, outputs in counts["frames"]:
        category, _, suffix = tag.partition("_")
        label, equation, explanation = _COUNT_METADATA[category]
        if category == "map":
            label = label.format(h=inputs["h"])
        elif category == "parameter":
            label = label.format(name=_PARAMETER_NAMES[inputs["n"]])
        elif category == "causal":
            label = label.format(i=inputs["i"])
        elif category in ("cache", "scratch"):
            label = label.format(tag=suffix)
        elif category == "append":
            label = label.format(j=inputs["j"])
        trace.add(prefix + "_" + tag, label, equation, explanation, inputs, outputs)


def _preview_binding(toy, trace, prefix, tensors):
    p = _inspection(toy)
    rows = p["rows"]
    tag = prefix + "_toy" + str(rows)
    for r in range(rows):
        for c in range(2):
            for k in range(2):
                offset = ((r * 2 + c) * 2 + k) * 5
                trace.add(f"{tag}_a1_{r}_{c}_{k}", f"Toy {rows}: first affine row {r}, hidden {c}, term {k}",
                    "product=left*right; sum=previous+product",
                    "Copy the actual saved binary64 operands, product and partial from the one completed factory run. The first partial starts at literal +0; no zero product is skipped and no arithmetic is replayed here.",
                    dict(r=r, c=c, k=k, left=p["affine1"][offset], right=p["affine1"][offset + 1], previous=p["affine1"][offset + 3]),
                    dict(product=p["affine1"][offset + 2], sum=p["affine1"][offset + 4]))
            trace.add(f"{tag}_relu_{r}_{c}", f"Toy {rows}: ReLU row {r}, hidden {c}", "value=linear>0 ? linear : +0",
                "Copy the saved hidden value after the actual ReLU decision. Literal +0 is the inactive branch; no bias is added.",
                dict(r=r, c=c, linear=p["hiddenLinear"][2 * r + c], zero=0.0), dict(value=p["hidden"][2 * r + c]))
        for c in range(2):
            for k in range(2):
                offset = ((r * 2 + c) * 2 + k) * 5
                trace.add(f"{tag}_a2_{r}_{c}_{k}", f"Toy {rows}: second affine row {r}, output {c}, term {k}",
                    "product=left*right; sum=previous+product",
                    "Copy saved hidden/weight operands, product and partial. Both terms were multiplied and added in increasing hidden-feature order from literal +0, with separate binary64 operations.",
                    dict(r=r, c=c, k=k, left=p["affine2"][offset], right=p["affine2"][offset + 1], previous=p["affine2"][offset + 3]),
                    dict(product=p["affine2"][offset + 2], sum=p["affine2"][offset + 4]))
        for c in range(2):
            offset = (2 * r + c) * 3
            trace.add(f"{tag}_checksum_{r}_{c}", f"Toy {rows}: consume output row {r}, coordinate {c}", "sum=previous+value",
                "Copy the actual saved row-major checksum fold after both output coordinates of this row were computed. This is correctness evidence, with no elapsed-time claim.",
                dict(r=r, c=c, previous=p["checksumFolds"][offset], value=p["checksumFolds"][offset + 1]), dict(sum=p["checksumFolds"][offset + 2]))
    products, additions, reluDecisions, checksumAdditions = toy["workCounts"]
    trace.add(tag + "_complete", f"Toy {rows}: one complete untimed batch",
        "checksum=copied saved fold; products=rows*8; additions=rows*8; reluDecisions=rows*2; checksumAdditions=rows*2",
        "The pure helper creates this independent workspace and runs it exactly once. No warmup, repetition, clock, asynchronous work or hypothetical planner dtype conversion occurs. Buffer stores and loop/index/control work are additional factory work.",
        dict(rows=rows, returnedChecksum=p["checksum"], productsPerRow=p["productsPerRow"], additionsPerRow=p["additionsPerRow"], reluPerRow=p["reluPerRow"]),
        dict(checksum=p["checksum"], products=products, additions=additions, reluDecisions=reluDecisions, checksumAdditions=checksumAdditions))
    specs = (
        ("X", [rows, 2], ["Row", "Input"], "X", "Actual fixed binary64 row-feature input; independent sample rows, not autoregressive tokens."),
        ("W1", [2, 2], ["Input", "Hidden"], "W1", "Actual fixed untrained row-feature first weights [[1,-1],[1,1]]; zero biases are omitted, not added."),
        ("W2", [2, 2], ["Hidden", "Output"], "W2", "Actual fixed untrained row-feature second weights [[1,2],[-1,1]]; shared by all rows."),
        ("Affine1", [rows, 2, 2, 5], ["Row", "Hidden", "Input", "AffineField"], "affine1", "Saved left,right,product,previous,sum per first-affine term, in row,hidden,input order. Every entry is a binary64 WORD, including +0 and computed -0."),
        ("HiddenLinear", [rows, 2], ["Row", "Hidden"], "hiddenLinear", "Saved final first-affine partials before ReLU; no floating recomputation while inspecting or tracing."),
        ("Hidden", [rows, 2], ["Row", "Hidden"], "hidden", "Saved actual ReLU outputs, with literal +0 for linear<=0."),
        ("Affine2", [rows, 2, 2, 5], ["Row", "Output", "Hidden", "AffineField"], "affine2", "Saved left,right,product,previous,sum per second-affine term, in row,output,hidden order. All zero products execute."),
        ("Y", [rows, 2], ["Row", "Output"], "Y", "Saved actual second-affine outputs consumed by the checksum; no constant-result replacement."),
        ("ChecksumFolds", [rows, 2, 3], ["Row", "Output", "FoldField"], "checksumFolds", "Saved previous,value,sum per actual row-major checksum addition, initialized literal +0."),
    )
    for suffix, shape, axes, field, provenance in specs:
        tensors.append(_tensor(tag + "_" + suffix, shape, axes, p[field], provenance, 8))
    tensors.append(_tensor(tag + "_Checksum", [1], ["Scalar"], [p["checksum"]],
        "Copy of the completed factory checksum WORD; deterministic correctness only, never a duration or measurement.", 8))
    tensors.append(_tensor(tag + "_WorkCounts", [4], ["WorkCount"], toy["workCounts"],
        "products,affineAdditions,reluDecisions,checksumAdditions for one complete batch; loop/index/control/buffer stores are additional.", 0))
    return p["checksum"]


def evaluate_systems(value, trace, prefix):
    """Project one complete saved capture; observer callbacks occur afterward."""
    evidence = _first(value, prefix)
    state, counts = evidence["state"], evidence["counts"]
    D, T, Hq = state["D"], state["T"], state["Hq"]
    _count_binding(counts, trace, prefix)
    specs = [
        ("RawState", [11], ["RawField"], [state[key] for key in _FIELDS], "All eleven captured raw VALUE fields in texts.rawFields order; D=-0 is VALUE zero."),
        ("HeadToGroup", [Hq], ["QueryHead"], evidence["planner"]["groups"], "Contiguous shared K/V group per query head; no expanded cache is allocated."),
        ("ParameterLedger", [6, 4], ["Matrix", "ParameterField"], counts["parameterLedger"], "Q,K,V,O,FF1,FF2 rows; inputWidth,outputWidth,product,partial. Only scalar count evidence, never allocated model weights."),
        ("WeightLedger", [7], ["WeightField"], counts["weightLedger"], "embeddingParameters,layerParameters,parameters,weightBytesPerScalar,weightBytes,metadataBytes,representedBytes; zero metadata is an assumption."),
        ("CacheLedger", [D + 2, 7], ["CacheStage", "CacheField"], counts["cacheLedger"], "Rows: one-position growth, prefill, then performed append passes in increasing j. Fields: history,KElements,VElements,totalElements,KBytes,VBytes,totalBytes. No hypothetical cache tensor is allocated."),
        ("CausalRows", [T, 3], ["PromptQuery", "CausalField"], counts["causalRows"], "keys,previous,partial for actual increasing-query causal eligibility; dense computed work stays separate."),
        ("PrefillCounts", [5], ["PrefillField"], counts["prefillCounts"], "denseCells,allowedCells,matrixMAC,scratchBytes,accountedBytes for prefill; counts are not observations."),
    ]
    if D > 0:
        specs.append(("AppendRows", [D, 11], ["AppendPass", "AppendField"], counts["appendRows"],
            "j,history,scoreCells,matrixMAC,KBytes,VBytes,cacheBytes,scratchBytes,accountedBytes,cumulativeScoreCells,cumulativeMAC for performed passes only. Absent when D=0."))
    specs.extend((
        ("AppendTotals", [7], ["AppendTotalField"], counts["appendTotals"], "actualScoreCells,closedScoreCells,historySum,baseMAC,scoreMAC,messageMAC,actualMAC; a computed zero aggregate is retained at D=0."),
        ("ScratchLedger", [D + 1, 16], ["ScratchStage", "ScratchField"], counts["scratchLedger"], "Prefill then performed append rows. q,history,Bq,fiveM,plusF,width,featureElements,BHq,headQueries,scoreElements,probabilityElements,scorePair,totalElements,scratchBytes,weightAndCache,accountedBytes. Declared one-layer buffers only, not physical peak memory."),
        ("AnalyticalSummary", [27], ["AnalyticalField"], list(counts["analytical"].values()), "Saved analytical VALUE counts in texts.analyticalFields order; no toy float, clock, duration or rate."),
    ))
    tensors = [_tensor(prefix + "_" + suffix, shape, axes, values, provenance, 0) for suffix, shape, axes, values, provenance in specs]
    oneRowChecksum = _preview_binding(evidence["one"], trace, prefix, tensors)
    threeRowChecksum = _preview_binding(evidence["three"], trace, prefix, tensors)
    summary = dict(counts["analytical"], oneRowChecksum=oneRowChecksum, threeRowChecksum=threeRowChecksum)
    texts = dict(rawFields=list(_FIELDS), analyticalFields=list(counts["analytical"]), parameterNames=list(_PARAMETER_NAMES),
                 parameterFields=_TEXTS["parameterFields"], weightFields=_TEXTS["weightFields"],
                 cacheStages=["growth", "prefill"] + ["append_" + str(j) for j in range(1, D + 1)])
    for key in ("cacheFields", "causalFields", "prefillFields", "appendFields", "appendTotalFields", "scratchFields", "affineFields", "foldFields", "workCountFields",
                "toyAlgorithm", "toyEvidence", "timingStatus"):
        texts[key] = _TEXTS[key]
    texts["appendAbsence"] = (
        "D=0: no appended forward pass occurred; AppendRows and last-append detail are absent. Final cache and scratch copy prefill; append aggregates are computed zero."
        if D == 0 else "No absence: every requested append pass has its saved row, cache and scratch counts.")
    for key in ("architecturePolicy", "axesPolicy", "countPolicy", "scratchPolicy", "representationPolicy", "generationPolicy", "toyPolicy", "rolePolicy", "timingPolicy", "validationPolicy"):
        texts[key] = _TEXTS[key]
    return _freeze(dict(state=state, summary=summary, tensors=tensors, texts=texts))


def _check_words(actual, expected):
    if not __debug__:
        raise RuntimeError("Explicit IV64 word comparison refuses optimized Python (-O).")
    import struct
    if type(expected) in (dict, _support._FrozenDict):
        assert type(actual) in (dict, _support._FrozenDict) and tuple(actual) == tuple(expected)
        for key in expected:
            _check_words(actual[key], expected[key])
    elif type(expected) in (list, tuple, _support._FrozenList):
        assert type(actual) in (list, tuple, _support._FrozenList) and len(actual) == len(expected)
        for left, right in zip(actual, expected):
            _check_words(left, right)
    elif type(expected) in (int, float):
        assert type(actual) in (int, float) and struct.pack(">d", actual) == struct.pack(">d", expected)
    else:
        assert type(actual) is type(expected) and actual == expected


def check_inspection():
    if not __debug__:
        raise RuntimeError("Explicit IV64 inspection check refuses optimized Python (-O).")
    keys = ("algorithm", "rows", "X", "W1", "W2", "affine1", "hiddenLinear", "hidden", "affine2", "Y", "checksumFolds",
            "checksum", "productsPerRow", "additionsPerRow", "reluPerRow")
    a1 = [
        1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0,
        1.0, -1.0, -1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0, -1.0,
        0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0,
        0.0, -1.0, -0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0,
        1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0,
        1.0, -1.0, -1.0, 0.0, -1.0, 1.0, 1.0, 1.0, -1.0, 0.0,
    ]
    a2 = [
        1.0, 1.0, 1.0, 0.0, 1.0, 0.0, -1.0, -0.0, 1.0, 1.0,
        1.0, 2.0, 2.0, 0.0, 2.0, 0.0, 1.0, 0.0, 2.0, 2.0,
        1.0, 1.0, 1.0, 0.0, 1.0, 1.0, -1.0, -1.0, 1.0, 0.0,
        1.0, 2.0, 2.0, 0.0, 2.0, 1.0, 1.0, 1.0, 2.0, 3.0,
        2.0, 1.0, 2.0, 0.0, 2.0, 0.0, -1.0, -0.0, 2.0, 2.0,
        2.0, 2.0, 4.0, 0.0, 4.0, 0.0, 1.0, 0.0, 4.0, 4.0,
    ]
    folds = [0.0, 1.0, 1.0, 1.0, 2.0, 3.0, 3.0, 0.0, 3.0, 3.0, 3.0, 6.0, 6.0, 2.0, 8.0, 8.0, 4.0, 12.0]
    for rows in (1, 3):
        p = toy_inspection(rows)
        assert tuple(p) == keys
        expected = dict(algorithm="iv64-mlp-ordered-fold-v1", rows=rows,
                        X=[1.0, 0.0] if rows == 1 else [1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
                        W1=[1.0, -1.0, 1.0, 1.0], W2=[1.0, 2.0, -1.0, 1.0],
                        affine1=a1[:20 * rows], hiddenLinear=[1.0, -1.0, 1.0, 1.0, 2.0, 0.0][:2 * rows],
                        hidden=[1.0, 0.0, 1.0, 1.0, 2.0, 0.0][:2 * rows], affine2=a2[:20 * rows],
                        Y=[1.0, 2.0, 0.0, 3.0, 2.0, 4.0][:2 * rows], checksumFolds=folds[:6 * rows],
                        checksum=3.0 if rows == 1 else 12.0, productsPerRow=8, additionsPerRow=8, reluPerRow=2)
        _check_words(p, expected)
        again = toy_inspection(rows)
        assert p is not again
        for field in keys[2:11]:
            assert p[field] is not again[field]
            try:
                p[field][0] = 7.0
            except TypeError:
                pass
            else:
                raise AssertionError("Inspection arrays must be detached immutable copies.")
        try:
            p["checksum"] = 0.0
        except TypeError:
            pass
        else:
            raise AssertionError("Inspection record must be immutable.")
    for rows, code, reason in ((True, "NONFINITE", "rows must be an actual finite number."),
                               (10**400, "NONFINITE", "rows must be an actual finite number."),
                               (2, "INVALID_INPUT", "rows must be exactly 1 or 3.")):
        try:
            toy_inspection(rows)
        except NumericalFault as error:
            assert type(error) is NumericalFault and (error.code, error.reason) == (code, reason)
        else:
            raise AssertionError("Inspection rows must validate before allocation.")


def check_public():
    if not __debug__:
        raise RuntimeError("Explicit IV64 public helper check refuses optimized Python (-O).")
    expected_summary = dict(d=2, J=2, groupWidth=2, parameters=256, weightBytes=512, metadataBytes=0,
        prefillKBytes=24, prefillVBytes=24, prefillCacheBytes=48, finalKBytes=40, finalVBytes=40, finalCacheBytes=80,
        cacheGrowthBytes=16, prefillDenseCells=36, prefillAllowedCells=24, appendScoreCells=36, baseMACPerToken=256,
        prefillMAC=912, appendMAC=656, totalMAC=1568, matrixFLOPs=3136, prefillScratchBytes=576, prefillAccountedBytes=1136,
        finalScratchBytes=224, finalAccountedBytes=816, finalHistory=5, selectedOutputsWithoutEOS=3,
        oneRowChecksum=3.0, threeRowChecksum=12.0)
    trace = systems_trace()
    result = evaluate_systems(dict(DEFAULT_IV64), trace, "probe")
    assert tuple(result) == ("state", "summary", "tensors", "texts")
    assert tuple(result["state"]) == _FIELDS
    _check_words(result["summary"], expected_summary)
    assert len(trace.steps) == 78 and len(trace.outputs) == 296 and len(result["tensors"]) == 33
    assert sum(len(t["values"]) for t in result["tensors"]) == 432
    assert len(result["texts"]) == 29 and result["texts"]["timingStatus"] == "NOT_MEASURED"
    assert tuple(result["texts"]) == ("rawFields", "analyticalFields", "parameterNames", "parameterFields", "weightFields", "cacheStages", "cacheFields",
        "causalFields", "prefillFields", "appendFields", "appendTotalFields", "scratchFields", "affineFields", "foldFields", "workCountFields", "toyAlgorithm",
        "toyEvidence", "timingStatus", "appendAbsence", "architecturePolicy", "axesPolicy", "countPolicy", "scratchPolicy", "representationPolicy", "generationPolicy",
        "toyPolicy", "rolePolicy", "timingPolicy", "validationPolicy")
    expected_tags = ["dimensions", "map_0", "map_1"] + ["parameter_" + str(i) for i in range(6)]
    expected_tags += ["weights", "base", "cache_growth", "dense", "causal_0", "causal_1", "causal_2", "allowed", "cache_prefill", "scratch_prefill", "prefill",
                      "append_1", "cache_append_1", "scratch_append_1", "append_2", "cache_append_2", "scratch_append_2", "appendClosed", "totals"]
    assert [frame["id"] for frame in trace.steps[:28]] == ["probe_" + tag for tag in expected_tags]
    aliases = {}
    for frame in trace.steps:
        assert tuple(frame) == ("id", "label", "equation", "explanation", "inputs", "outputs")
        assert all(type(frame[key]) is str and frame[key] for key in ("id", "label", "equation", "explanation"))
        for key, item in frame["outputs"].items():
            alias = frame["id"] + "_" + key
            assert alias not in aliases
            aliases[alias] = item
    _check_words(trace.outputs, aliases)
    for t in result["tensors"]:
        assert tuple(t) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
        assert t["dtype"] == "float64" and len(t["shape"]) == len(t["axes"]) <= 4
        cells = 1
        for size in t["shape"]:
            assert 1 <= size <= 64
            cells *= size
        assert cells == len(t["values"]) <= 4096
        assert t["provenance"]
    tensors = {t["id"]: t for t in result["tensors"]}
    assert tensors["probe_ParameterLedger"]["values"] == [4, 4, 16, 16, 4, 2, 8, 24, 4, 2, 8, 32, 4, 4, 16, 48, 4, 8, 32, 80, 8, 4, 32, 112]
    assert tensors["probe_CacheLedger"]["values"] == [1, 4, 4, 8, 8, 8, 16, 3, 12, 12, 24, 24, 24, 48, 4, 16, 16, 32, 32, 32, 64, 5, 20, 20, 40, 40, 40, 80]
    assert tensors["probe_CausalRows"]["values"] == [1, 0, 1, 2, 1, 3, 3, 3, 6]
    assert tensors["probe_AppendTotals"]["values"] == [36, 36, 9, 512, 72, 72, 656]
    assert tensors["probe_AppendRows"]["values"] == [1, 4, 16, 320, 32, 32, 64, 208, 784, 16, 320, 2, 5, 20, 336, 40, 40, 80, 224, 816, 36, 656]
    assert tensors["probe_ScratchLedger"]["values"] == [3, 3, 3, 20, 28, 36, 108, 2, 6, 18, 18, 36, 144, 576, 560, 1136,
        1, 4, 1, 20, 28, 36, 36, 2, 2, 8, 8, 16, 52, 208, 576, 784,
        1, 5, 1, 20, 28, 36, 36, 2, 2, 10, 10, 20, 56, 224, 592, 816]
    frames = {frame["id"]: frame for frame in trace.steps}
    numeric_frames = {
        "dimensions": dict(d=2, J=2, groupWidth=2, weightBytesPerScalar=2, kvBytesPerScalar=2),
        "weights": dict(embeddingParameters=32, layerParameters=224, parameters=256, weightBytes=512, metadataBytes=0, representedBytes=512),
        "base": dict(layerMatrixMAC=224, readoutMAC=32, baseMACPerToken=256),
        "dense": dict(BL=2, BLHq=4, prefillHeadQueries=12, prefillDenseCells=36),
        "allowed": dict(nextT=4, triangleProduct=12, triangle=6, prefillAllowedCells=24, closedAllowedCells=24),
        "prefill": dict(prefillRows=3, prefillBaseMAC=768, prefillScoreMAC=72, prefillMessageMAC=72, prefillBaseAndScores=840, prefillMAC=912),
        "append_1": dict(history=4, scoreCells=16, baseMAC=256, scoreMAC=32, messageMAC=32, baseAndScores=288, matrixMAC=320, appendScoreCells=16, appendMAC=320),
        "append_2": dict(history=5, scoreCells=20, baseMAC=256, scoreMAC=40, messageMAC=40, baseAndScores=296, matrixMAC=336, appendScoreCells=36, appendMAC=656),
        "appendClosed": dict(DT=6, nextD=3, appendTriangleProduct=6, appendTriangle=3, historySum=9, closedAppendCells=36, batchAppends=2,
            appendBaseMAC=512, appendScoreMAC=72, appendMessageMAC=72, appendBaseAndScores=584, closedAppendMAC=656),
        "totals": {key: item for key, item in expected_summary.items() if key not in ("oneRowChecksum", "threeRowChecksum")},
    }
    for h in range(2):
        numeric_frames["map_" + str(h)] = dict(group=0)
    for n, (product, partial) in enumerate(((16, 16), (8, 24), (8, 32), (16, 48), (32, 80), (32, 112))):
        numeric_frames["parameter_" + str(n)] = dict(product=product, partial=partial)
    for i, (keys, partial) in enumerate(((1, 1), (2, 3), (3, 6))):
        numeric_frames["causal_" + str(i)] = dict(keys=keys, partial=partial)
    for tag, values in (
        ("growth", [1, 2, 2, 2, 4, 8, 2, 2, 2, 4, 8, 8, 16]),
        ("prefill", [3, 2, 2, 6, 12, 24, 2, 2, 6, 12, 24, 24, 48]),
        ("append_1", [4, 2, 2, 8, 16, 32, 2, 2, 8, 16, 32, 32, 64]),
        ("append_2", [5, 2, 2, 10, 20, 40, 2, 2, 10, 20, 40, 40, 80])):
        numeric_frames["cache_" + tag] = dict(zip(("history", "kBL", "kGroups", "kRows", "KElements", "KBytes", "vBL", "vGroups", "vRows", "VElements", "VBytes", "totalElements", "totalBytes"), values))
    for tag, values in (
        ("prefill", [3, 3, 3, 20, 28, 36, 108, 2, 6, 18, 18, 36, 144, 576, 560, 1136]),
        ("append_1", [1, 4, 1, 20, 28, 36, 36, 2, 2, 8, 8, 16, 52, 208, 576, 784]),
        ("append_2", [1, 5, 1, 20, 28, 36, 36, 2, 2, 10, 10, 20, 56, 224, 592, 816])):
        numeric_frames["scratch_" + tag] = dict(zip(("q", "history", "Bq", "fiveM", "plusF", "width", "featureElements", "BHq", "headQueries", "scoreElements", "probabilityElements", "scorePair", "totalElements", "scratchBytes", "weightAndCache", "accountedBytes"), values))
    assert set(numeric_frames) == set(expected_tags)
    for suffix, expected in numeric_frames.items():
        _check_words(frames["probe_" + suffix]["outputs"], expected)
    for rows in (1, 3):
        p = toy_inspection(rows)
        tag = "probe_toy" + str(rows)
        for suffix, field in (("X", "X"), ("W1", "W1"), ("W2", "W2"), ("Affine1", "affine1"), ("HiddenLinear", "hiddenLinear"),
                              ("Hidden", "hidden"), ("Affine2", "affine2"), ("Y", "Y"), ("ChecksumFolds", "checksumFolds")):
            t = tensors[tag + "_" + suffix]
            _check_words(t["values"], p[field])
            assert t["precision"] == 8 and t["values"] is not p[field]
        _check_words(tensors[tag + "_Checksum"]["values"], [p["checksum"]])
        assert tensors[tag + "_WorkCounts"]["values"] == [rows * 8, rows * 8, rows * 2, rows * 2]
        assert tensors[tag + "_WorkCounts"]["precision"] == 0
        for r in range(rows):
            for c in range(2):
                for kind in ("a1", "a2"):
                    field = "affine1" if kind == "a1" else "affine2"
                    for k in range(2):
                        offset = ((r * 2 + c) * 2 + k) * 5
                        frame = frames[f"{tag}_{kind}_{r}_{c}_{k}"]
                        _check_words(frame["inputs"], dict(r=r, c=c, k=k, left=p[field][offset], right=p[field][offset + 1], previous=p[field][offset + 3]))
                        _check_words(frame["outputs"], dict(product=p[field][offset + 2], sum=p[field][offset + 4]))
                relu = frames[f"{tag}_relu_{r}_{c}"]
                _check_words(relu["inputs"], dict(r=r, c=c, linear=p["hiddenLinear"][2 * r + c], zero=0.0))
                _check_words(relu["outputs"], dict(value=p["hidden"][2 * r + c]))
                fold = frames[f"{tag}_checksum_{r}_{c}"]
                offset = (2 * r + c) * 3
                _check_words(fold["inputs"], dict(r=r, c=c, previous=p["checksumFolds"][offset], value=p["Y"][2 * r + c]))
                _check_words(fold["outputs"], dict(sum=p["checksumFolds"][offset + 2]))
        _check_words(frames[tag + "_complete"]["outputs"], dict(checksum=p["checksum"], products=rows * 8, additions=rows * 8, reluDecisions=rows * 2, checksumAdditions=rows * 2))
    for state, frame_count, tensor_count, cells, aliases_count in (
        (dict(DEFAULT_IV64, D=-0.0), 72, 32, 364, 220),
        (dict(B=4, L=4, T=16, D=8, M=16, Hq=4, Hkv=4, F=32, V=32, weightBits=32, kvBits=32), 111, 33, 677, 552)):
        collector = systems_trace()
        public = evaluate_systems(state, collector, "edge")
        assert (len(collector.steps), len(public["tensors"]), sum(len(t["values"]) for t in public["tensors"]), len(collector.outputs)) == (frame_count, tensor_count, cells, aliases_count)
        if state["D"] == 0:
            assert not any(t["id"] == "edge_AppendRows" for t in public["tensors"])
            assert public["texts"]["cacheStages"] == ["growth", "prefill"]
            assert "D=0:" in public["texts"]["appendAbsence"]
            assert public["summary"]["appendMAC"] == public["summary"]["appendScoreCells"] == 0
            assert public["summary"]["finalCacheBytes"] == public["summary"]["prefillCacheBytes"]
            assert public["summary"]["finalScratchBytes"] == public["summary"]["prefillScratchBytes"]


def check_once_capture():
    if not __debug__:
        raise RuntimeError("Explicit IV64 once-capture check refuses optimized Python (-O).")
    global _first, _planner, _planner_details, _toy, _affine
    saved_first, saved_planner, saved_details, saved_toy, saved_affine = _first, _planner, _planner_details, _toy, _affine
    saved_storage = _support._storage
    calls, toy_calls = [], []
    raw = dict(DEFAULT_IV64)
    collector = systems_trace()

    def forbidden(*args):
        if not __debug__:
            raise RuntimeError("Explicit IV64 no-replay hook refuses optimized Python (-O).")
        raise AssertionError("Projection must not replay numerical work or access NumPy storage.")

    def toy(rows, capture):
        if not __debug__:
            raise RuntimeError("Explicit IV64 toy counter refuses optimized Python (-O).")
        toy_calls.append(rows)
        return saved_toy(rows, capture)

    def first(value, prefix):
        if not __debug__:
            raise RuntimeError("Explicit IV64 capture hook refuses optimized Python (-O).")
        global _planner, _planner_details, _toy, _affine
        calls.append((value, prefix))
        evidence = saved_first(value, prefix)
        _planner = _planner_details = _toy = _affine = forbidden
        _support._storage = forbidden
        return evidence

    class Observer:
        def add(self, *args):
            if not __debug__:
                raise RuntimeError("Explicit IV64 after-capture observer refuses optimized Python (-O).")
            assert toy_calls == [1, 3] and len(calls) == 1
            raw["M"] = 16
            collector.add(*args)

    try:
        _toy, _first = toy, first
        result = evaluate_systems(raw, Observer(), "once")
        assert len(calls) == 1 and toy_calls == [1, 3] and result["state"]["M"] == 4
        assert result["summary"]["parameters"] == 256 and result["summary"]["threeRowChecksum"] == 12
        assert len(collector.steps) == 78
    finally:
        _first, _planner, _planner_details, _toy, _affine = saved_first, saved_planner, saved_details, saved_toy, saved_affine
        _support._storage = saved_storage
    collector = systems_trace()
    unknown = MemoryError("observer identity")

    class FailingObserver:
        def add(self, *args):
            if not __debug__:
                raise RuntimeError("Explicit IV64 failing observer refuses optimized Python (-O).")
            if len(collector.steps) == 2:
                raise unknown
            collector.add(*args)

    try:
        evaluate_systems(dict(DEFAULT_IV64), FailingObserver(), "partial")
    except BaseException as error:
        assert error is unknown and len(collector.steps) == 2
    else:
        raise AssertionError("Unknown callback exception must preserve identity and actual partial history.")
    for value, prefix in (({}, "ok"), (dict(DEFAULT_IV64), "!")):
        untouched = systems_trace()
        try:
            evaluate_systems(value, untouched, prefix)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Invalid helper input must fail before callbacks.")
        assert untouched.steps == [] and untouched.outputs == {}
    existing = systems_trace()
    existing.add("prior", "label", "equation", "explanation", {}, dict(saved=7.0))
    evaluate_systems(dict(DEFAULT_IV64), existing, "priorHelper")
    assert len(existing.steps) == 79 and existing.steps[0]["id"] == "prior" and existing.outputs["prior_saved"] == 7.0


def check_trace():
    if not __debug__:
        raise RuntimeError("Explicit IV64 generic trace check refuses optimized Python (-O).")
    trace = systems_trace()
    assert systems_trace is _support.decoder_trace
    reads = []

    class Items:
        def items(self):
            if not __debug__:
                raise RuntimeError("Explicit IV64 items-once hook refuses optimized Python (-O).")
            reads.append(True)
            return [("z", -0.0), ("10", 10), ("2", 2), ("01", 1), ("0", 0), ("4294967295", 7)]

    trace.add("numeric", "label", "equation", "explanation", Items(), dict(huge=10**100, large=1000000000000000128))
    assert reads == [True]
    frame = trace.steps[0]
    assert tuple(frame["inputs"]) == ("0", "2", "10", "z", "01", "4294967295")
    _check_words(frame["inputs"]["z"], -0.0)
    _check_words(frame["outputs"], dict(huge=1e100, large=1000000000000000100.0))
    reuse = systems_trace()
    reuse.add("reuse", "l", "e", "x", frame["inputs"], frame["outputs"])
    _check_words(reuse.steps[0]["inputs"], frame["inputs"])
    raw = dict(z=-0.0)
    trace.add("saved", "l", "e", "x", {}, raw)
    raw["z"] = 9.0
    _check_words(trace.steps[1]["outputs"]["z"], -0.0)
    trace.add("_", "l", "e", "x", {}, dict(proto__=1))
    assert "__proto__" not in trace.outputs and trace.steps[-1]["outputs"]["proto__"] == 1
    trace.add("a", "l", "e", "x", {}, dict(b_c=1.0))
    trace.add("a_b", "l", "e", "x", {}, dict(c=2.0))
    assert trace.outputs["a_b_c"] == 2.0
    for identifier, inputs, outputs, code, reason in (
        ("a", dict(bad=float("nan")), {}, "INVALID_INPUT", "Trace IDs must be nonempty and unique."),
        ("", {}, {}, "INVALID_INPUT", "Trace IDs must be nonempty and unique."),
        ("bad", dict(x=10**400), {}, "NONFINITE", "bad.inputs.x must be an actual finite number."),
        ("bad", {}, dict(x=True), "NONFINITE", "bad.outputs.x must be an actual finite number.")):
        before = len(trace.steps)
        try:
            trace.add(identifier, "l", "e", "x", inputs, outputs)
        except NumericalFault as error:
            assert type(error) is NumericalFault and (error.code, error.reason) == (code, reason)
        else:
            raise AssertionError("Trace preflight must preserve order and exact reasons.")
        assert len(trace.steps) == before
    full = systems_trace()
    for index in range(512):
        full.add("f" + str(index), "l", "e", "x", {}, {})
    for outputs, code in ((dict(x=float("inf")), "NONFINITE"), (dict(x=0.0), "UNSUPPORTED_SIZE")):
        try:
            full.add("overflow", "l", "e", "x", {}, outputs)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == code
        else:
            raise AssertionError("Finite preflight must precede the collector cap.")
        assert len(full.steps) == 512
    unknown = ValueError("trusted items identity")

    class BrokenItems:
        def items(self):
            if not __debug__:
                raise RuntimeError("Explicit IV64 throwing items hook refuses optimized Python (-O).")
            raise unknown

    try:
        systems_trace().add("unknown", "l", "e", "x", BrokenItems(), {})
    except BaseException as error:
        assert error is unknown
    else:
        raise AssertionError("Trusted observer errors must retain identity.")

3. Canonical entry, strict input and explicit checks: iv64.py

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.

"""IV64 canonical independent producer with signed complete public binding.

No verifier, implicit self-check or timer. All executable checks remain UNRUN.
"""
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import FunctionType, ModuleType


def _load_reference():
    name = "_book_iv64_systems"
    path = str(Path(__file__).resolve().with_name("systems_reference.py"))
    if name in sys.modules:
        incumbent = sys.modules[name]
        if type(incumbent) is not ModuleType:
            raise ImportError("Unknown IV64 reference cache identity.")
        namespace = incumbent.__dict__
        certificate = namespace.get("_IV64_CERTIFICATE")
        if (type(certificate) is not tuple or len(certificate) != 6
                or certificate[0] is not incumbent or certificate[1] != path
                or type(namespace.get("__file__")) is not str
                or str(Path(namespace["__file__"]).resolve()) != path
                or namespace.get("__spec__") is not certificate[5]
                or type(certificate[5].origin) is not str
                or str(Path(certificate[5].origin).resolve()) != path):
            raise ImportError("Unknown or incomplete IV64 reference source.")
        for key, function, code in certificate[2]:
            owner, dot, member = key.partition(".")
            actual = namespace.get(owner)
            if dot:
                actual = actual.__dict__.get(member) if isinstance(actual, type) else None
            if (actual is not function or type(function) is not FunctionType or function.__code__ is not code
                    or str(Path(code.co_filename).resolve()) != path):
                raise ImportError("IV64 reference function identity changed.")
        for cache_name, dependency in certificate[3]:
            if cache_name not in sys.modules or sys.modules[cache_name] is not dependency:
                raise ImportError("IV64 reference dependency cache changed.")
        for key, owned_object in certificate[4]:
            if namespace.get(key) is not owned_object:
                raise ImportError("IV64 reference alias changed.")
        incumbent._module_identity(namespace["_support"], str(Path(path).with_name("decoder_reference.py")))
        return incumbent
    spec = importlib.util.spec_from_file_location(name, path)
    if name in sys.modules:
        raise ImportError("IV64 reference appeared during specification creation.")
    if spec is None or spec.loader is None:
        raise ImportError("Cannot load adjacent IV64 reference.")
    staged = importlib.util.module_from_spec(spec)
    if name in sys.modules:
        raise ImportError("IV64 reference appeared during module creation.")
    transaction = [(name, staged)]
    staged._IV64_TRANSACTION = transaction
    sys.modules[name] = staged
    try:
        spec.loader.exec_module(staged)
        if name not in sys.modules or sys.modules[name] is not staged:
            raise ImportError("IV64 reference changed during loading.")
        functions = tuple((key, item, item.__code__) for key, item in staged.__dict__.items()
                          if type(item) is FunctionType and item.__module__ == name)
        functions += tuple(("_Capture." + key, staged._Capture.__dict__[key], staged._Capture.__dict__[key].__code__)
                           for key in ("__init__", "add"))
        aliases = tuple((key, staged.__dict__[key]) for key in
                        ("_support", "NumericalFault", "_freeze", "systems_trace", "DEFAULT_IV64",
                         "_Capture", "_FIELDS", "_BOUNDS", "_COUNT_METADATA", "_PARAMETER_NAMES", "_TEXTS"))
        staged._IV64_CERTIFICATE = (staged, path, functions,
                                   (("_book_iv64_generic59", staged._support),), aliases, spec)
        staged._module_identity(staged, path)
        staged.__dict__.pop("_IV64_TRANSACTION", None)
        return staged
    except BaseException:
        for cache_name, owned_object in reversed(transaction):
            if cache_name in sys.modules and sys.modules[cache_name] is owned_object:
                del sys.modules[cache_name]
        raise


_reference = _load_reference()
NumericalFault = _reference.NumericalFault
DEFAULT_IV64 = _reference.DEFAULT_IV64
systems_state = _reference.systems_state
systems_trace = _reference.systems_trace
evaluate_systems = _reference.evaluate_systems
toy_inspection = _reference.toy_inspection
_KNOWN_CODES = ("INVALID_INPUT", "SHAPE_MISMATCH", "NONFINITE", "UNSUPPORTED_SIZE", "FULLY_MASKED_ROW", "UNAVAILABLE")


class _JsonInputError(ValueError):
    """Local parser admission failure only."""


def _integer(token):
    digits = token[1:] if token.startswith("-") else token
    if len(digits) > 309:
        raise _JsonInputError("JSON integer exceeds the local 309-digit limit.")
    return _real(token)


def _real(token):
    value = float(token)
    if not math.isfinite(value):
        raise _JsonInputError("JSON numbers must be finite binary64 values.")
    return value


def _constant(token):
    raise _JsonInputError("Non-JSON numeric constant: " + token)


def _object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise _JsonInputError("Duplicate JSON object field: " + key)
        result[key] = value
    return result


_JSON_ERROR = json.JSONDecodeError
_JSON_PARSE_CODES = (json.JSONDecoder.decode.__code__, json.JSONDecoder.raw_decode.__code__)
_JSON_LOCAL_CODES = (_integer.__code__, _real.__code__, _constant.__code__, _object.__code__)
_JSON_DECODE = json.JSONDecoder(parse_int=_integer, parse_float=_real,
                                parse_constant=_constant, object_pairs_hook=_object).decode


def strict_json(text):
    try:
        return _JSON_DECODE(text)
    except (_JsonInputError, _JSON_ERROR) as error:
        origin = error.__traceback__
        while origin.tb_next is not None:
            origin = origin.tb_next
        if type(error) is _JsonInputError and origin.tb_frame.f_code in _JSON_LOCAL_CODES:
            raise NumericalFault("INVALID_INPUT", str(error)) from error
        if type(error) is _JSON_ERROR and origin.tb_frame.f_code in _JSON_PARSE_CODES:
            raise NumericalFault("INVALID_INPUT", "Expected one finite strict JSON value.") from error
        raise


def _fault_record(error):
    if (type(error) is not NumericalFault or type(error.code) is not str
            or error.code not in _KNOWN_CODES or type(error.reason) is not str):
        raise error
    return _reference._freeze(dict(status="unavailable", code=error.code, reason=error.reason))


def derive_iv64(value):
    """Complete adopted root, with every actual frame-output alias retained."""
    try:
        trace = systems_trace()
        evaluated = evaluate_systems(value, trace, "systems")
        tensors, texts = evaluated["tensors"], evaluated["texts"]
        summary = dict(evaluated["summary"], frames=len(trace.steps) + 1, tensorCount=len(tensors))
        trace.add("finish", "Retain resource counts and real untimed toy correctness separately",
            "summary=copied saved analytical counts and toy checksums; frames=helperFrames+1; tensorCount=saved tensors length",
            "All eleven raw fields and the prefix passed before any frame. Analytical integers describe the disclosed hypothetical model. Toy checksum words come from two independent actual one-run previews. No clock, duration, throughput, native elementary function or runtime validation is implied.",
            dict(oneRowChecksum=evaluated["summary"]["oneRowChecksum"], threeRowChecksum=evaluated["summary"]["threeRowChecksum"],
                 frames=summary["frames"], tensorCount=summary["tensorCount"]), summary)
        outputs = dict(summary)
        for step in trace.steps:
            for key, item in step["outputs"].items():
                alias = step["id"] + "_" + key
                if alias in outputs:
                    raise RuntimeError("IV64 output aliases must be unique.")
                outputs[alias] = item
        return _reference._freeze(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))
    except NumericalFault as error:
        return _fault_record(error)


def run():
    """Zero arguments: process argv chooses default, replacement JSON, stdin/check."""
    args = sys.argv[1:]
    if args == ["--self-check"]:
        source_self_check()
        print("IV64 explicit source checks completed; runtime acceptance is separate.")
        return 0
    if len(args) > 1 or (args and args[0].startswith("--")):
        print("Usage: iv64.py [JSON|-|--self-check]", file=sys.stderr)
        return 2
    try:
        value = dict(DEFAULT_IV64) if not args else strict_json(sys.stdin.read() if args[0] == "-" else args[0])
        result = derive_iv64(value)
    except NumericalFault as error:
        result = _fault_record(error)
    print(json.dumps(result, allow_nan=False))
    return 0


def check_parser():
    if not __debug__:
        raise RuntimeError("Explicit IV64 parser check refuses optimized Python (-O).")
    import struct
    for source in ("-0", "-0.0", "-0e0"):
        assert struct.pack(">d", strict_json(source)) == struct.pack(">d", -0.0)
    assert strict_json("1" + "0" * 308) == 1e308
    assert strict_json('{"D":-0}') == {"D": -0.0}
    for source in ("1" + "0" * 309, "9" * 309, "1e309", "NaN", "Infinity", "-Infinity",
                   '{"B":1,"B":2}', '{"a":{"x":0,"x":1}}', "{} {}", "", '{"B":01}'):
        try:
            strict_json(source)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Local strict JSON admission must reject this input.")
    global _JSON_DECODE
    original = _JSON_DECODE

    class JsonSubtype(_JSON_ERROR):
        pass

    class LocalSubtype(_JsonInputError):
        pass

    for unknown in (ValueError("foreign value"), _JSON_ERROR("foreign syntax", "", 0),
                    _JsonInputError("foreign local-shaped error"), JsonSubtype("subtype", "", 0),
                    LocalSubtype("subtype"), MemoryError("resource"), KeyboardInterrupt("interrupt")):
        def injected(text):
            if not __debug__:
                raise RuntimeError("Explicit IV64 parser hook refuses optimized Python (-O).")
            raise unknown

        try:
            _JSON_DECODE = injected
            try:
                strict_json("{}")
            except BaseException as error:
                assert error is unknown
            else:
                raise AssertionError("Foreign parser error or subtype must retain identity.")
        finally:
            _JSON_DECODE = original


def check_faults():
    if not __debug__:
        raise RuntimeError("Explicit IV64 fault check refuses optimized Python (-O).")
    global evaluate_systems
    original = evaluate_systems

    class FaultSubtype(NumericalFault):
        pass

    for unknown in (NumericalFault("FOREIGN", "unknown code"), FaultSubtype("INVALID_INPUT", "subtype"),
                    ValueError("programmer"), MemoryError("resource"), KeyboardInterrupt("interrupt")):
        def foreign(value, trace, prefix):
            if not __debug__:
                raise RuntimeError("Explicit IV64 fault hook refuses optimized Python (-O).")
            raise unknown

        try:
            evaluate_systems = foreign
            try:
                derive_iv64(dict(DEFAULT_IV64))
            except BaseException as error:
                assert error is unknown
            else:
                raise AssertionError("Unknown code/class must escape before public conversion.")
        finally:
            evaluate_systems = original
    defined = derive_iv64(dict(DEFAULT_IV64))
    assert tuple(defined) == ("status", "outputs", "steps", "tensors", "texts") and defined["status"] == "defined"
    assert derive_iv64({})["code"] == "INVALID_INPUT"
    assert derive_iv64(dict(DEFAULT_IV64, B=0, kvBits=float("nan")))["code"] == "NONFINITE"


def check_cli():
    if not __debug__:
        raise RuntimeError("Explicit IV64 CLI check refuses optimized Python (-O).")
    import contextlib
    import io
    global derive_iv64, source_self_check
    saved_derive, saved_check, saved_argv, saved_stdin = derive_iv64, source_self_check, sys.argv, sys.stdin
    seen, checked = [], []

    def producer(value):
        if not __debug__:
            raise RuntimeError("Explicit IV64 CLI producer hook refuses optimized Python (-O).")
        seen.append(value)
        return dict(status="unavailable", code="UNAVAILABLE", reason="CLI plumbing only")

    def aggregate():
        if not __debug__:
            raise RuntimeError("Explicit IV64 CLI aggregate hook refuses optimized Python (-O).")
        checked.append(True)

    def foreign(value):
        if not __debug__:
            raise RuntimeError("Explicit IV64 CLI failure hook refuses optimized Python (-O).")
        raise unknown

    try:
        derive_iv64, source_self_check = producer, aggregate
        for args, source, expected in (([], "", dict(DEFAULT_IV64)), (["{}"], "", {}),
                                      (["-"], '{"D":0}', {"D": 0.0})):
            sys.argv, sys.stdin = ["iv64.py"] + args, io.StringIO(source)
            output = io.StringIO()
            with contextlib.redirect_stdout(output):
                assert run() == 0
            assert seen[-1] == expected and checked == []
            assert json.loads(output.getvalue())["reason"] == "CLI plumbing only"
        sys.argv = ["iv64.py", "--self-check"]
        with contextlib.redirect_stdout(io.StringIO()):
            assert run() == 0
        assert checked == [True]
        for args in (["--verify"], ["--unknown"], ["{}", "{}"], ["--self-check", "{}"]):
            sys.argv = ["iv64.py"] + args
            with contextlib.redirect_stderr(io.StringIO()):
                assert run() == 2
        for args in (["NaN"], ['{"B":1,"B":2}']):
            sys.argv = ["iv64.py"] + args
            output = io.StringIO()
            with contextlib.redirect_stdout(output):
                assert run() == 0
            assert json.loads(output.getvalue())["code"] == "INVALID_INPUT"
        unknown = ValueError("foreign CLI producer")
        derive_iv64, sys.argv = foreign, ["iv64.py", "{}"]
        try:
            run()
        except BaseException as error:
            assert error is unknown
        else:
            raise AssertionError("Unknown CLI producer failure must retain identity.")
        derive_iv64 = saved_derive
        default_json = json.dumps(dict(DEFAULT_IV64))
        for args, source, code in (([], "", None), ([default_json], "", None),
                                   (["-"], default_json, None), (["{}"], "", "INVALID_INPUT"),
                                   (["NaN"], "", "INVALID_INPUT")):
            sys.argv, sys.stdin = ["iv64.py"] + args, io.StringIO(source)
            output = io.StringIO()
            with contextlib.redirect_stdout(output):
                assert run() == 0
            result = json.loads(output.getvalue())
            if code is None:
                assert tuple(result) == ("status", "outputs", "steps", "tensors", "texts") and result["status"] == "defined"
                assert result["outputs"]["totalMAC"] == 1568 and result["outputs"]["frames"] == 79
            else:
                assert tuple(result) == ("status", "code", "reason") and result["code"] == code
    finally:
        derive_iv64, source_self_check, sys.argv, sys.stdin = saved_derive, saved_check, saved_argv, saved_stdin


def check_loader():
    if not __debug__:
        raise RuntimeError("Explicit IV64 loader check refuses optimized Python (-O).")
    name, support_name = "_book_iv64_systems", "_book_iv64_generic59"
    original, support = sys.modules[name], sys.modules[support_name]
    saved_state, saved_state_code = original.systems_state, original.systems_state.__code__
    saved_capture, saved_capture_code = original._Capture.add, original._Capture.add.__code__
    saved_inspect, saved_inspect_code = original.toy_inspection, original.toy_inspection.__code__
    saved_numeric, saved_file, saved_spec = support._numeric, support.__file__, support.__spec__
    saved_fields = original._FIELDS
    saved_texts = original._TEXTS

    def foreign(*args):
        if not __debug__:
            raise RuntimeError("Explicit IV64 foreign code hook refuses optimized Python (-O).")
        raise AssertionError("Foreign function must never execute.")

    try:
        assert _load_reference() is original and original._load_support() is support
        for key, loader, incumbent in ((name, _load_reference, original),
                                        (support_name, original._load_support, support)):
            for unknown in (None, object(), ModuleType(key)):
                sys.modules[key] = unknown
                try:
                    loader()
                except ImportError:
                    assert key in sys.modules and sys.modules[key] is unknown
                else:
                    raise AssertionError("All unknown incumbents, including None, must be preserved.")
                finally:
                    sys.modules[key] = incumbent
        for replacement in (None, ModuleType(support_name)):
            sys.modules[support_name] = replacement
            try:
                _load_reference()
            except ImportError:
                assert sys.modules[support_name] is replacement
            else:
                raise AssertionError("Warm entry must validate the actual dependency cache.")
            finally:
                sys.modules[support_name] = support
        del sys.modules[support_name]
        try:
            _load_reference()
        except ImportError:
            assert support_name not in sys.modules
        else:
            raise AssertionError("A deleted warm dependency cannot silently reload.")
        finally:
            sys.modules[support_name] = support
        original.systems_state = foreign
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Actual declaring function must match.")
        original.systems_state = saved_state
        original.toy_inspection = foreign
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("New inspection declaration must match its certificate.")
        original.toy_inspection = saved_inspect
        saved_inspect.__code__ = foreign.__code__
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Inspection code identity must match even on the same function.")
        saved_inspect.__code__ = saved_inspect_code
        saved_state.__code__ = foreign.__code__
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("The same function with different code must fail identity.")
        saved_state.__code__ = saved_state_code
        original._Capture.add = foreign
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Private capture class method must match.")
        original._Capture.add = saved_capture
        saved_capture.__code__ = foreign.__code__
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Private capture method code must match.")
        saved_capture.__code__ = saved_capture_code
        support._numeric = foreign
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Reachable readonly generic function must match.")
        support._numeric = saved_numeric
        support.__file__ = str(Path(saved_file).with_name("iv64.py"))
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Resolved actual support source path must match.")
        support.__file__ = saved_file
        support.__spec__ = None
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Actual support specification must match.")
        support.__spec__ = saved_spec
        original._FIELDS = tuple(reversed(saved_fields))
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Captured dependency aliases must match.")
        original._FIELDS = saved_fields
        original._TEXTS = dict(saved_texts)
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Adopted metadata aliases must retain their actual identity.")
    finally:
        original.systems_state, saved_state.__code__ = saved_state, saved_state_code
        original._Capture.add, saved_capture.__code__ = saved_capture, saved_capture_code
        original._FIELDS = saved_fields
        original._TEXTS = saved_texts
        original.toy_inspection, saved_inspect.__code__ = saved_inspect, saved_inspect_code
        support._numeric, support.__file__, support.__spec__ = saved_numeric, saved_file, saved_spec
        sys.modules[name], sys.modules[support_name] = original, support


def check_loader_staging():
    if not __debug__:
        raise RuntimeError("Explicit IV64 staging check refuses optimized Python (-O).")
    name, support_name = "_book_iv64_systems", "_book_iv64_generic59"
    original, support = sys.modules[name], sys.modules[support_name]
    saved_spec, saved_create = importlib.util.spec_from_file_location, importlib.util.module_from_spec

    def appearing_spec(cache_name, path):
        if not __debug__:
            raise RuntimeError("Explicit IV64 specification hook refuses optimized Python (-O).")
        spec = saved_spec(cache_name, path)
        sys.modules[target] = None
        return spec

    def appearing_create(spec):
        if not __debug__:
            raise RuntimeError("Explicit IV64 creation hook refuses optimized Python (-O).")
        module = saved_create(spec)
        sys.modules[target] = None
        return module

    try:
        for target, loader in ((name, _load_reference), (support_name, original._load_support)):
            for phase in ("spec", "creation"):
                sys.modules.pop(target, None)
                importlib.util.spec_from_file_location = appearing_spec if phase == "spec" else saved_spec
                importlib.util.module_from_spec = appearing_create if phase == "creation" else saved_create
                try:
                    loader()
                except ImportError:
                    assert target in sys.modules and sys.modules[target] is None
                else:
                    raise AssertionError("Prestage incumbents must be preserved after BOTH phases.")
                finally:
                    importlib.util.spec_from_file_location, importlib.util.module_from_spec = saved_spec, saved_create
                    sys.modules[name], sys.modules[support_name] = original, support
    finally:
        importlib.util.spec_from_file_location, importlib.util.module_from_spec = saved_spec, saved_create
        sys.modules[name], sys.modules[support_name] = original, support


def check_loader_rollback():
    if not __debug__:
        raise RuntimeError("Explicit IV64 rollback check refuses optimized Python (-O).")
    name, support_name = "_book_iv64_systems", "_book_iv64_generic59"
    original, support = sys.modules[name], sys.modules[support_name]
    saved_spec = importlib.util.spec_from_file_location
    replacement, unknown = object(), MemoryError("IV64 loader resource identity")

    class FailingLoader:
        def __init__(self, actual):
            if not __debug__:
                raise RuntimeError("Explicit IV64 loader wrapper refuses optimized Python (-O).")
            self.actual = actual

        def create_module(self, spec):
            if not __debug__:
                raise RuntimeError("Explicit IV64 loader creation hook refuses optimized Python (-O).")
            return self.actual.create_module(spec)

        def exec_module(self, module):
            if not __debug__:
                raise RuntimeError("Explicit IV64 loader execution hook refuses optimized Python (-O).")
            self.actual.exec_module(module)
            if mutation == "replace":
                sys.modules[target] = replacement
            elif mutation == "none":
                sys.modules[target] = None
            elif mutation == "delete":
                sys.modules.pop(target, None)
            raise unknown

    def failing_spec(cache_name, path):
        if not __debug__:
            raise RuntimeError("Explicit IV64 failing-spec hook refuses optimized Python (-O).")
        spec = saved_spec(cache_name, path)
        if cache_name == target:
            spec.loader = FailingLoader(spec.loader)
        return spec

    try:
        for target, loader in ((name, _load_reference), (support_name, original._load_support)):
            for mutation in ("keep", "replace", "none", "delete"):
                for preexisting in (False, True) if target == name else (False,):
                    sys.modules.pop(target, None)
                    if target == name:
                        sys.modules.pop(support_name, None)
                        if preexisting:
                            sys.modules[support_name] = support
                    importlib.util.spec_from_file_location = failing_spec
                    try:
                        loader()
                    except BaseException as error:
                        assert error is unknown
                    else:
                        raise AssertionError("Unknown loader failure must escape unchanged.")
                    finally:
                        importlib.util.spec_from_file_location = saved_spec
                    if mutation == "replace":
                        assert sys.modules[target] is replacement
                    elif mutation == "none":
                        assert target in sys.modules and sys.modules[target] is None
                    else:
                        assert target not in sys.modules
                    if target == name:
                        if preexisting:
                            assert sys.modules[support_name] is support
                        else:
                            assert support_name not in sys.modules
                    sys.modules[name], sys.modules[support_name] = original, support
        sys.modules.pop(name, None)
        sys.modules.pop(support_name, None)
        cold = _load_reference()
        assert cold is sys.modules[name] and cold is not original
        assert cold._support is sys.modules[support_name] and cold._support is not support
        assert cold._first(dict(cold.DEFAULT_IV64), "cold")["three"]["checksum"] == 12
        cold_trace = cold.systems_trace()
        cold_result = cold.evaluate_systems(dict(cold.DEFAULT_IV64), cold_trace, "cold")
        assert len(cold_trace.steps) == 78 and len(cold_result["tensors"]) == 33
        assert cold.toy_inspection(3)["checksum"] == 12
    finally:
        importlib.util.spec_from_file_location = saved_spec
        sys.modules[name], sys.modules[support_name] = original, support


def source_self_check():
    if not __debug__:
        raise RuntimeError("Explicit IV64 entry aggregate refuses optimized Python (-O).")
    _reference.source_self_check()
    check_root()
    check_parser()
    check_faults()
    check_cli()
    check_loader()
    check_loader_staging()
    check_loader_rollback()


def check_root():
    if not __debug__:
        raise RuntimeError("Explicit IV64 root/copy check refuses optimized Python (-O).")
    global systems_trace
    result = derive_iv64(dict(DEFAULT_IV64))
    assert tuple(result) == ("status", "outputs", "steps", "tensors", "texts") and result["status"] == "defined"
    assert (len(result["steps"]), len(result["tensors"]), len(result["outputs"]), len(result["texts"])) == (79, 33, 358, 29)
    finish = result["steps"][-1]
    assert finish["id"] == "finish"
    assert finish["label"] == "Retain resource counts and real untimed toy correctness separately"
    assert tuple(finish["inputs"]) == ("oneRowChecksum", "threeRowChecksum", "frames", "tensorCount")
    assert tuple(result["outputs"])[:31] == tuple(finish["outputs"])
    assert finish["outputs"]["frames"] == 79 and finish["outputs"]["tensorCount"] == 33
    for key, item in finish["outputs"].items():
        _reference._check_words(result["outputs"][key], item)
    expected_aliases = []
    for frame in result["steps"]:
        for key, item in frame["outputs"].items():
            alias = frame["id"] + "_" + key
            expected_aliases.append(alias)
            _reference._check_words(result["outputs"][alias], item)
    assert tuple(result["outputs"])[31:] == tuple(expected_aliases)
    again = derive_iv64(dict(DEFAULT_IV64))
    _reference._check_words(result, again)
    assert result is not again and result["steps"] is not again["steps"]
    for field in ("outputs", "steps", "tensors", "texts"):
        assert result[field] is not again[field]
    for target, key in ((result["outputs"], "totalMAC"), (finish["outputs"], "oneRowChecksum"),
                        (result["tensors"][0]["values"], 0), (result["texts"]["rawFields"], 0)):
        try:
            target[key] = 9
        except TypeError:
            pass
        else:
            raise AssertionError("All root/copy families must remain immutable.")
    for state, frames, tensors, outputs in ((dict(DEFAULT_IV64, D=-0.0), 73, 32, 282),
        (dict(B=4, L=4, T=16, D=8, M=16, Hq=4, Hkv=4, F=32, V=32, weightBits=32, kvBits=32), 112, 33, 614)):
        edge = derive_iv64(state)
        assert (len(edge["steps"]), len(edge["tensors"]), len(edge["outputs"])) == (frames, tensors, outputs)
        assert edge["outputs"]["frames"] == frames and edge["outputs"]["tensorCount"] == tensors
    assert toy_inspection is _reference.toy_inspection
    assert systems_state is _reference.systems_state and systems_trace is _reference.systems_trace
    assert evaluate_systems is _reference.evaluate_systems and DEFAULT_IV64 is _reference.DEFAULT_IV64
    # A deliberately supplied collector can collide; refuse rather than overwrite.
    ordinary_trace = systems_trace

    def colliding_trace():
        if not __debug__:
            raise RuntimeError("Explicit IV64 collision hook refuses optimized Python (-O).")
        trace = ordinary_trace()
        trace.add("systems", "l", "e", "x", {}, dict(dimensions_d=99))
        return trace

    try:
        systems_trace = colliding_trace
        try:
            derive_iv64(dict(DEFAULT_IV64))
        except RuntimeError as error:
            assert str(error) == "IV64 output aliases must be unique."
        else:
            raise AssertionError("Root aliases must not overwrite one another.")
    finally:
        systems_trace = ordinary_trace


if __name__ == "__main__":
    raise SystemExit(run())

Recap and bridge

  • Keep weights, K/V payload and the disclosed one-layer scratch separate; their accounted sum is not physical peak memory.
  • Keep query paths separate from shared K/V groups, and dense work separate from allowed pairs.
  • Count forwarded tokens according to the stopping policy: G selections can require D=G-1 appended passes.
  • Read the fixed toy’s actual arithmetic independently of hypothetical planner dimensions and bits.
  • Require explicit current, correctly sourced clock evidence before quoting a local duration or rate; respect what that workload cannot establish.

IV-65, Evaluating LLMs, Leakage and Reliability, will extend this habit of asking what evidence supports a claim.