The neural notebook
← All chapters

IV-63 / Part XV · Modern LLM Architectures

Quantization and Numerical Approximation

Reconstruct six weights from small integer codes, follow every output contribution, and distinguish clipping, rounding, saturation and independently measured squared errors.

Review the ideas this chapter uses

A weight tells us how much one input contributes to an answer. Suppose we keep a small integer label for each weight, then reconstruct an approximate weight when we need it. How much does the answer change? We can answer that question with six weights and three inputs, without hiding the arithmetic inside a large language model.

Learning objective: Quantize small weight tensors and measure reconstructed output error.

The numbers here are hand-set teaching inputs, not learned parameters or measurements. The worksheets below are manual derivations, not printed program results. The lab computes the original, clipped and reconstructed answers from the same three inputs.

Compute it yourself

Reconstruct six weights, then compare the actual outputs

A small integer code names a reconstructed weight. Change the code width or fit a separate scale for each output column, then compare the saved original, clipped and reconstructed calculations using the same three inputs.

The fixed starting worksheet has global scale1 and zero point1. Its W[1,1]=1/2 rounds to integer0 before adding the zero point, so code1 reconstructs zero. The hand-derived starting outputs are [-3,1/2], [-3,1/2] and [-3,-1]. Current results below come from the saved computation.

The two menus select bits and grouping. The clipping threshold and all nine weight/input fields accept continuous finite numbers within their labeled bounds, including -0 for weights and inputs. Open the weight and input groups to edit them. Invalid drafts withhold results and grading; correct the draft or choose Reset example. Editing, resetting and selecting a trace step clear answers; opening a disclosure preserves them. Replay selection highlights saved evidence and never substitutes a cursor value for the whole result.

bits2
mode0
inputFeatures3
outputFeatures2
Six original weights: input-feature rows, output-feature columns
Three input features: the same input for all three output paths
Exact starting inputs for this saved calculation

bits 2. mode 0. inputFeatures 3. outputFeatures 2. Capture all twelve validated raw controls. All own data descriptors, then all finite operands, then all domains and finally the ASCII prefix were checked before this first frame. Weights use InputFeature,OutputFeature row storage.

Capture all twelve validated raw controls

Q=2**bits-1; groups=(mode==0?1:2)

All own data descriptors, then all finite operands, then all domains and finally the ASCII prefix were checked before this first frame. Weights use InputFeature,OutputFeature row storage.

Saved inputs

bits
2
mode
0
clip
2
w00
-1
w01
0.25
w10
0
w11
0.5
w20
2
w21
0.75
x0
1
x1
2
x2
-1

Saved outputs

Q
3
groups
1

Saved whole outputs: original [-3, 0.5]; clipped [-3, 0.5]; reconstructed [-3, -1]. Total output SSE,maxAbs [2.25, 1.5]; squared-underflow flags [0, 0]. Selected saved step quantization_inputs. Capture all twelve validated raw controls. Equation: Q=2**bits-1; groups=(mode==0?1:2). All own data descriptors, then all finite operands, then all domains and finally the ASCII prefix were checked before this first frame. Weights use InputFeature,OutputFeature row storage. Inputs: bits=2; mode=0; clip=2; w00=-1; w01=0.25; w10=0; w11=0.5; w20=2; w21=0.75; x0=1; x1=2; x2=-1. Outputs: Q=3; groups=1.

Three outputs from the same three inputs

W has three input-feature rows and two output-feature columns. Each output adds three input contributions. These are complete saved outputs; selecting a step only highlights a frame.

Current whole outputs and total output error
Original YClipped YReconstructed YTotal SSE (squared output units)Total maxAbs (output units)Squared-underflow flags
[-3, 0.5][-3, 0.5][-3, -1]2.251.5[0, 0]

Isolated authored weight-only affine xW toy, not a quantized transformer, training run, integer hardware kernel or packed allocation. No speed, RAM, latency, throughput, quality, perplexity or deployment claim. No model/API/download or hidden computation.

Every original, clipped and reconstructed weight

Six connections in original row-major order; flags are distinct saved decisions
W cell [input,output]Original WClipped WReconstructed WGroupCodeClipped flagSaturated / low endpoint / high endpoint / zero-point code
[0,0]-1-1-1000[0, 1, 0, 0]
[0,1]0.250.250010[0, 0, 0, 1]
[1,0]000010[0, 0, 0, 1]
[1,1]0.50.50010[0, 0, 0, 1]
[2,0]222030[0, 0, 1, 0]
[2,1]0.750.751020[0, 0, 0, 0]
Whole-tensor decision counts; endpoint occupancy does not imply saturation
DecisionSaved count
clipped0
saturated0
lowEndpoint1
highEndpoint1
zeroPointCode3

Fit each actual group, including zero

Actual stored binary64 quotient first; nearest represented integer with exact ties to even, including negative halves; integer zero canonical +0. Never Math.round, epsilon, decimal preprocessing or RNE(scaled+zeroPoint). Public RNE input bound [-512,512].

Group 0

quantization_g0: nonzero calibration; actual span/Q, (-lower)/scale, integer nearest-even then zero-point clamp; every cell divides by the stored scale, rounds before adding zeroPoint, clamps, centers and multiplies.

Group 0: fitted bounds, actual scale and saved zero-point decision
Calibration fieldSaved value
lower-1
upper2
span3
scale1
zeroGroup (1=assigned zero policy)0
zeroPoint1
Group 0: all members, fit operands/partials, code stages and counts

FitPartials columns: lower, upper. ZeroPointOperands: negativeLower, zeroRatio. IntegerStages columns: rounded, candidate, code, centered. Counts: clipped, saturated, lowEndpoint, highEndpoint, zeroPointCode.

quantization_g0_Members

Shape [6] · GroupCell=6 · int32 · declared display precision 0

Actual row-major weight-cell indices in this calibration group, in fit and quantization visit order.

quantization_g0_Members: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
11
22
33
44
55

quantization_g0_FitOperands

Shape [7] · FitOperand=7 · float64 · declared display precision 8

Literal +0 followed by the actual clipped group words used by both ordered fit folds.

quantization_g0_FitOperands: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
1-1
20.25
30
40.5
52
60.75

quantization_g0_FitPartials

Shape [6, 2] · GroupCell=6 × FitBound=2 · float64 · declared display precision 8

Actual lower,upper after each group member; retain lower -0 and upper +0 as produced.

quantization_g0_FitPartials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
2-1
30.25
4-1
50.25
6-1
70.5
8-1
92
10-1
112

quantization_g0_Calibration

Shape [4] · CalibrationField=4 · float64 · declared display precision 8

Saved lower,upper,span,scale WORDs. For a zero group scale=1 is an explicit assigned policy, not a division result.

quantization_g0_Calibration: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
12
23
31

quantization_g0_ZeroGroup

Shape [1] · Scalar=1 · int32 · declared display precision 0

Decision 1 for span==0, otherwise 0; this does not classify a positive-span zero-scale fault as a zero group.

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

quantization_g0_ZeroPoint

Shape [1] · Scalar=1 · int32 · declared display precision 0

Saved integer zero point; assigned 0 for a zero group, otherwise clamped actual RNE((-lower)/scale).

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

quantization_g0_ZeroPointOperands

Shape [2] · ZeroPointOperand=2 · float64 · declared display precision 8

Actual unary -lower and stored (-lower)/scale operands; no ideal rational quotient substitution.

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

quantization_g0_RoundedZero

Shape [1] · Scalar=1 · int32 · declared display precision 0

Actual nearest-even integer decision on the stored zero-point quotient, before clamping.

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

quantization_g0_Scaled

Shape [6] · GroupCell=6 · float64 · declared display precision 8

Actual clipped/scale binary64 quotient for each listed group member, before integer RNE.

quantization_g0_Scaled: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
20
30.5
42
50.75

quantization_g0_IntegerStages

Shape [6, 4] · GroupCell=6 × IntegerStage=4 · int32 · declared display precision 0

Actual rounded,candidate,code,centered integer decisions for each listed group member; RNE precedes zero-point addition.

quantization_g0_IntegerStages: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
20
3-1
40
51
61
70
80
91
101
110
120
131
141
150
162
173
183
192
201
212
222
231

quantization_g0_Counts

Shape [5] · CountField=5 · int32 · declared display precision 0

Independently accumulated group counts: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode; occupancy does not imply saturation.

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

Zero span assigns scale1,zeroPoint0,codes0,reconstructed+0 without fictitious division/RNE/dequantization arithmetic. Per-group absent tensors and reasons are saved in uncomputed. A nonzero span producing scale0 throws UNAVAILABLE before division by that scale.

Every affine product and partial sum

All floating arithmetic is separately binary64 RN-even with gradual underflow. Three complete affine paths independently compute every product then ordered +0 accumulation; all cell/feature orders and WORD signs are retained. No native elementary calls.

original: saved products and ordered partial sums from +0
Output featureProducts at inputs 0,1,2Partials after inputs 0,1,2Final Y
0[-1, 0, -2][-1, -1, -3]-3
1[0.25, 1, -0.75][0.25, 1.25, 0.5]0.5
clipped: saved products and ordered partial sums from +0
Output featureProducts at inputs 0,1,2Partials after inputs 0,1,2Final Y
0[-1, 0, -2][-1, -1, -3]-3
1[0.25, 1, -0.75][0.25, 1.25, 0.5]0.5
reconstructed: saved products and ordered partial sums from +0
Output featureProducts at inputs 0,1,2Partials after inputs 0,1,2Final Y
0[-1, 0, -2][-1, -1, -3]-3
1[0, 0, -1][0, 0, -1]-1

Six independent error reductions

Three direct weight differences and three direct output differences each own their squares, absolutes, underflow flags and ordered SSE/maxAbs reductions. SSE uses squared units, maxAbs original units. No sqrt, relative norm, tolerance or inferred total from components; SSE0 is numeric zero, not WORD identity.

Weight errors

weight clipping: saved SSE=0; maxAbs=0

SSE uses squared weight units; maxAbs uses weight units. Clipping compares clipped with original; quantization compares reconstructed with clipped; total compares reconstructed with original. Weight cells are row-major; output cells are output-feature order.

weight clipping: every residual, square, underflow flag and reduction partial
Error cellDirect differenceSquareAbsoluteSquared-underflow flagSSE after cellmaxAbs after cell
0000000
1000000
2000000
3000000
4000000
5000000
weight quantization: saved SSE=0.375; maxAbs=0.5

SSE uses squared weight units; maxAbs uses weight units. Clipping compares clipped with original; quantization compares reconstructed with clipped; total compares reconstructed with original. Weight cells are row-major; output cells are output-feature order.

weight quantization: every residual, square, underflow flag and reduction partial
Error cellDirect differenceSquareAbsoluteSquared-underflow flagSSE after cellmaxAbs after cell
0000000
1-0.250.06250.2500.06250.25
200000.06250.25
3-0.50.250.500.31250.5
400000.31250.5
50.250.06250.2500.3750.5
weight total: saved SSE=0.375; maxAbs=0.5

SSE uses squared weight units; maxAbs uses weight units. Clipping compares clipped with original; quantization compares reconstructed with clipped; total compares reconstructed with original. Weight cells are row-major; output cells are output-feature order.

weight total: every residual, square, underflow flag and reduction partial
Error cellDirect differenceSquareAbsoluteSquared-underflow flagSSE after cellmaxAbs after cell
0000000
1-0.250.06250.2500.06250.25
200000.06250.25
3-0.50.250.500.31250.5
400000.31250.5
50.250.06250.2500.3750.5

Output errors

output clipping: saved SSE=0; maxAbs=0

SSE uses squared output units; maxAbs uses output units. Clipping compares clipped with original; quantization compares reconstructed with clipped; total compares reconstructed with original. Weight cells are row-major; output cells are output-feature order.

output clipping: every residual, square, underflow flag and reduction partial
Error cellDirect differenceSquareAbsoluteSquared-underflow flagSSE after cellmaxAbs after cell
0000000
1000000
output quantization: saved SSE=2.25; maxAbs=1.5

SSE uses squared output units; maxAbs uses output units. Clipping compares clipped with original; quantization compares reconstructed with clipped; total compares reconstructed with original. Weight cells are row-major; output cells are output-feature order.

output quantization: every residual, square, underflow flag and reduction partial
Error cellDirect differenceSquareAbsoluteSquared-underflow flagSSE after cellmaxAbs after cell
0000000
1-1.52.251.502.251.5
output total: saved SSE=2.25; maxAbs=1.5

SSE uses squared output units; maxAbs uses output units. Clipping compares clipped with original; quantization compares reconstructed with clipped; total compares reconstructed with original. Weight cells are row-major; output cells are output-feature order.

output total: every residual, square, underflow flag and reduction partial
Error cellDirect differenceSquareAbsoluteSquared-underflow flagSSE after cellmaxAbs after cell
0000000
1-1.52.251.502.251.5
All twelve current saved controls and the three input words

Exactly twelve own data descriptors are captured before all finite guards, all finite guards before any domains, then prefix last; no coercion, getters, merge or reread. bits/mode are VALUE; all ten remaining raw floats and their copies are WORD including -0.

Complete saved raw12 in capture order
FieldSaved value
bits2
mode0
clip2
w00-1
w010.25
w100
w110.5
w202
w210.75
x01
x12
x2-1

quantization_X

Shape [3] · InputFeature=3 · float64 · declared display precision 8

Actual captured x0,x1,x2 words; one row-feature input, no bias.

quantization_X: every saved cell in row-major storage order
Storage index (zero-based)Saved value
01
12
2-1
Complete tensor fallback: every cell and all seven metadata fields (66 tensors)

Values show saved words without display rounding, including -0. Shape and axes locate each row-major storage index. Index arithmetic only locates saved cells; the view does not quantize, multiply, subtract errors or reduce them.

All sixteen primary summary fields and their finish aliases use VALUE choices, dimensions, decisions or source counts. Raw tensor fields0,1 use VALUE and fields2..11 WORD. Other floating operands/results/copies use WORD including -0; explicitly structural integers use VALUE. Helper output is the very same saved reconstructed_Y TensorRecord in its tensors list. No natives field or empty-native tensor.

quantization_Raw

Shape [12] · RawField=12 · float64 · declared display precision 8

Captured raw12 in declared order: bits,mode VALUE; clip,all six weights,all three inputs WORD including -0.

quantization_Raw: every saved cell in row-major storage order
Storage index (zero-based)Saved value
02
10
22
3-1
40.25
50
60.5
72
80.75
91
102
11-1

quantization_X

Shape [3] · InputFeature=3 · float64 · declared display precision 8

Actual captured x0,x1,x2 words; one row-feature input, no bias.

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

quantization_WOriginal

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

All six captured original weight words in w00,w01,w10,w11,w20,w21 row-major order; explicit transpose of column-weight notation.

quantization_WOriginal: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
20
30.5
42
50.75

quantization_WClipped

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual max(-clip,min(clip,w)) selections before calibration; original W remains unchanged.

quantization_WClipped: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
20
30.5
42
50.75

quantization_ClipFlags

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · int32 · declared display precision 0

Strict original<-clip or original>clip decisions; endpoints equal to clip are not clipped.

quantization_ClipFlags: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_CellGroups

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · int32 · declared display precision 0

Global mode maps all cells to group0; per-output mode maps output feature j to group j.

quantization_CellGroups: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_g0_Members

Shape [6] · GroupCell=6 · int32 · declared display precision 0

Actual row-major weight-cell indices in this calibration group, in fit and quantization visit order.

quantization_g0_Members: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
11
22
33
44
55

quantization_g0_FitOperands

Shape [7] · FitOperand=7 · float64 · declared display precision 8

Literal +0 followed by the actual clipped group words used by both ordered fit folds.

quantization_g0_FitOperands: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
1-1
20.25
30
40.5
52
60.75

quantization_g0_FitPartials

Shape [6, 2] · GroupCell=6 × FitBound=2 · float64 · declared display precision 8

Actual lower,upper after each group member; retain lower -0 and upper +0 as produced.

quantization_g0_FitPartials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
2-1
30.25
4-1
50.25
6-1
70.5
8-1
92
10-1
112

quantization_g0_Calibration

Shape [4] · CalibrationField=4 · float64 · declared display precision 8

Saved lower,upper,span,scale WORDs. For a zero group scale=1 is an explicit assigned policy, not a division result.

quantization_g0_Calibration: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
12
23
31

quantization_g0_ZeroGroup

Shape [1] · Scalar=1 · int32 · declared display precision 0

Decision 1 for span==0, otherwise 0; this does not classify a positive-span zero-scale fault as a zero group.

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

quantization_g0_ZeroPoint

Shape [1] · Scalar=1 · int32 · declared display precision 0

Saved integer zero point; assigned 0 for a zero group, otherwise clamped actual RNE((-lower)/scale).

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

quantization_g0_ZeroPointOperands

Shape [2] · ZeroPointOperand=2 · float64 · declared display precision 8

Actual unary -lower and stored (-lower)/scale operands; no ideal rational quotient substitution.

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

quantization_g0_RoundedZero

Shape [1] · Scalar=1 · int32 · declared display precision 0

Actual nearest-even integer decision on the stored zero-point quotient, before clamping.

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

quantization_g0_Scaled

Shape [6] · GroupCell=6 · float64 · declared display precision 8

Actual clipped/scale binary64 quotient for each listed group member, before integer RNE.

quantization_g0_Scaled: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
20
30.5
42
50.75

quantization_g0_IntegerStages

Shape [6, 4] · GroupCell=6 × IntegerStage=4 · int32 · declared display precision 0

Actual rounded,candidate,code,centered integer decisions for each listed group member; RNE precedes zero-point addition.

quantization_g0_IntegerStages: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
20
3-1
40
51
61
70
80
91
101
110
120
131
141
150
162
173
183
192
201
212
222
231

quantization_g0_Counts

Shape [5] · CountField=5 · int32 · declared display precision 0

Independently accumulated group counts: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode; occupancy does not imply saturation.

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

quantization_Codes

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · int32 · declared display precision 0

Actual code integers restored to original row-major weight order; ordinary int32 records, not packed b-bit allocations.

quantization_Codes: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
11
21
31
43
52

quantization_WReconstructed

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual centered*scale words for nonzero groups; explicit policy +0 for zero groups, restored to original weight order.

quantization_WReconstructed: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
20
30
42
51

quantization_CodeFlags

Shape [3, 2, 4] · InputFeature=3 × OutputFeature=2 × CodeDecision=4 · int32 · declared display precision 0

Per-cell saturated,lowEndpoint,highEndpoint,zeroPointCode flags; zero policy assigns 0,1,0,1.

quantization_CodeFlags: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
11
20
30
40
50
60
71
80
90
100
111
120
130
140
151
160
170
181
190
200
210
220
230

quantization_Counts

Shape [5] · CountField=5 · int32 · declared display precision 0

Actual whole-tensor counts independently accumulated from cell decisions: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode.

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

quantization_original_Products

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature.

quantization_original_Products: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
20
31
4-2
5-0.75

quantization_original_Partials

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual running binary64 sums after each product; each output starts from literal +0.

quantization_original_Partials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
2-1
31.25
4-3
50.5

quantization_original_Y

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction.

quantization_original_Y: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-3
10.5

quantization_clipped_Products

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature.

quantization_clipped_Products: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
20
31
4-2
5-0.75

quantization_clipped_Partials

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual running binary64 sums after each product; each output starts from literal +0.

quantization_clipped_Partials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10.25
2-1
31.25
4-3
50.5

quantization_clipped_Y

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction.

quantization_clipped_Y: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-3
10.5

quantization_reconstructed_Products

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature.

quantization_reconstructed_Products: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
20
30
4-2
5-1

quantization_reconstructed_Partials

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual running binary64 sums after each product; each output starts from literal +0.

quantization_reconstructed_Partials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-1
10
2-1
30
4-3
5-1

quantization_reconstructed_Y

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction.

quantization_reconstructed_Y: every saved cell in row-major storage order
Storage index (zero-based)Saved value
0-3
1-1

quantization_weight_clipping_Difference

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

quantization_weight_clipping_Difference: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_weight_clipping_Squares

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

quantization_weight_clipping_Squares: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_weight_clipping_Absolute

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual Math.abs of each saved difference, in the original weight or output units.

quantization_weight_clipping_Absolute: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_weight_clipping_SquaredUnderflow

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · int32 · declared display precision 0

Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

quantization_weight_clipping_SquaredUnderflow: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_weight_clipping_ReductionPartials

Shape [6, 2] · ErrorCell=6 × ReductionField=2 · float64 · declared display precision 8

Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

quantization_weight_clipping_ReductionPartials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50
60
70
80
90
100
110

quantization_weight_clipping_Summary

Shape [2] · ReductionField=2 · float64 · declared display precision 8

Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

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

quantization_weight_quantization_Difference

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

quantization_weight_quantization_Difference: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
1-0.25
20
3-0.5
40
50.25

quantization_weight_quantization_Squares

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

quantization_weight_quantization_Squares: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10.0625
20
30.25
40
50.0625

quantization_weight_quantization_Absolute

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual Math.abs of each saved difference, in the original weight or output units.

quantization_weight_quantization_Absolute: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10.25
20
30.5
40
50.25

quantization_weight_quantization_SquaredUnderflow

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · int32 · declared display precision 0

Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

quantization_weight_quantization_SquaredUnderflow: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_weight_quantization_ReductionPartials

Shape [6, 2] · ErrorCell=6 × ReductionField=2 · float64 · declared display precision 8

Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

quantization_weight_quantization_ReductionPartials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20.0625
30.25
40.0625
50.25
60.3125
70.5
80.3125
90.5
100.375
110.5

quantization_weight_quantization_Summary

Shape [2] · ReductionField=2 · float64 · declared display precision 8

Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

quantization_weight_quantization_Summary: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00.375
10.5

quantization_weight_total_Difference

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

quantization_weight_total_Difference: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
1-0.25
20
3-0.5
40
50.25

quantization_weight_total_Squares

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

quantization_weight_total_Squares: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10.0625
20
30.25
40
50.0625

quantization_weight_total_Absolute

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · float64 · declared display precision 8

Actual Math.abs of each saved difference, in the original weight or output units.

quantization_weight_total_Absolute: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10.25
20
30.5
40
50.25

quantization_weight_total_SquaredUnderflow

Shape [3, 2] · InputFeature=3 × OutputFeature=2 · int32 · declared display precision 0

Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

quantization_weight_total_SquaredUnderflow: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20
30
40
50

quantization_weight_total_ReductionPartials

Shape [6, 2] · ErrorCell=6 × ReductionField=2 · float64 · declared display precision 8

Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

quantization_weight_total_ReductionPartials: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
10
20.0625
30.25
40.0625
50.25
60.3125
70.5
80.3125
90.5
100.375
110.5

quantization_weight_total_Summary

Shape [2] · ReductionField=2 · float64 · declared display precision 8

Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

quantization_weight_total_Summary: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00.375
10.5

quantization_output_clipping_Difference

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

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

quantization_output_clipping_Squares

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

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

quantization_output_clipping_Absolute

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual Math.abs of each saved difference, in the original weight or output units.

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

quantization_output_clipping_SquaredUnderflow

Shape [2] · OutputFeature=2 · int32 · declared display precision 0

Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

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

quantization_output_clipping_ReductionPartials

Shape [2, 2] · ErrorCell=2 × ReductionField=2 · float64 · declared display precision 8

Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

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

quantization_output_clipping_Summary

Shape [2] · ReductionField=2 · float64 · declared display precision 8

Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

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

quantization_output_quantization_Difference

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

quantization_output_quantization_Difference: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
1-1.5

quantization_output_quantization_Squares

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

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

quantization_output_quantization_Absolute

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual Math.abs of each saved difference, in the original weight or output units.

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

quantization_output_quantization_SquaredUnderflow

Shape [2] · OutputFeature=2 · int32 · declared display precision 0

Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

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

quantization_output_quantization_ReductionPartials

Shape [2, 2] · ErrorCell=2 × ReductionField=2 · float64 · declared display precision 8

Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

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

quantization_output_quantization_Summary

Shape [2] · ReductionField=2 · float64 · declared display precision 8

Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

quantization_output_quantization_Summary: every saved cell in row-major storage order
Storage index (zero-based)Saved value
02.25
11.5

quantization_output_total_Difference

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

quantization_output_total_Difference: every saved cell in row-major storage order
Storage index (zero-based)Saved value
00
1-1.5

quantization_output_total_Squares

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

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

quantization_output_total_Absolute

Shape [2] · OutputFeature=2 · float64 · declared display precision 8

Actual Math.abs of each saved difference, in the original weight or output units.

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

quantization_output_total_SquaredUnderflow

Shape [2] · OutputFeature=2 · int32 · declared display precision 0

Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

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

quantization_output_total_ReductionPartials

Shape [2, 2] · ErrorCell=2 × ReductionField=2 · float64 · declared display precision 8

Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

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

quantization_output_total_Summary

Shape [2] · ReductionField=2 · float64 · declared display precision 8

Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

quantization_output_total_Summary: every saved cell in row-major storage order
Storage index (zero-based)Saved value
02.25
11.5
Complete operation fallback: all six fields of every saved frame (67 frames)

Exact unchanged decoderTrace alias. Empty/duplicate IDs fail before finite operands; the 512-frame cap follows operand capture. Frames are detached finite six-field snapshots. Full raw/domain/prefix preflight precedes the first frame; a positive-span zero-scale fault retains only the actual collector prefix. Every saved frame output is copied to root outputs as frameId_key.

Capture all twelve validated raw controls

quantization_inputs — selected saved step

Q=2**bits-1; groups=(mode==0?1:2)

All own data descriptors, then all finite operands, then all domains and finally the ASCII prefix were checked before this first frame. Weights use InputFeature,OutputFeature row storage.

Saved inputs
bits
2
mode
0
clip
2
w00
-1
w01
0.25
w10
0
w11
0.5
w20
2
w21
0.75
x0
1
x1
2
x2
-1
Saved outputs
Q
3
groups
1

Clip weight cell 0

quantization_clip_0

clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)

Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0.

Saved inputs
cell
0
original
-1
clip
2
Saved outputs
clipped
-1
clippedFlag
0

Clip weight cell 1

quantization_clip_1

clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)

Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0.

Saved inputs
cell
1
original
0.25
clip
2
Saved outputs
clipped
0.25
clippedFlag
0

Clip weight cell 2

quantization_clip_2

clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)

Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0.

Saved inputs
cell
2
original
0
clip
2
Saved outputs
clipped
0
clippedFlag
0

Clip weight cell 3

quantization_clip_3

clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)

Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0.

Saved inputs
cell
3
original
0.5
clip
2
Saved outputs
clipped
0.5
clippedFlag
0

Clip weight cell 4

quantization_clip_4

clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)

Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0.

Saved inputs
cell
4
original
2
clip
2
Saved outputs
clipped
2
clippedFlag
0

Clip weight cell 5

quantization_clip_5

clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)

Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0.

Saved inputs
cell
5
original
0.75
clip
2
Saved outputs
clipped
0.75
clippedFlag
0

Group 0: include cell 0 in calibration

quantization_g0_fit_0

lower=min(previousLower,clipped); upper=max(previousUpper,clipped)

Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0.

Saved inputs
group
0
cell
0
previousLower
0
previousUpper
0
clipped
-1
Saved outputs
lower
-1
upper
0

Group 0: include cell 1 in calibration

quantization_g0_fit_1

lower=min(previousLower,clipped); upper=max(previousUpper,clipped)

Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0.

Saved inputs
group
0
cell
1
previousLower
-1
previousUpper
0
clipped
0.25
Saved outputs
lower
-1
upper
0.25

Group 0: include cell 2 in calibration

quantization_g0_fit_2

lower=min(previousLower,clipped); upper=max(previousUpper,clipped)

Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0.

Saved inputs
group
0
cell
2
previousLower
-1
previousUpper
0.25
clipped
0
Saved outputs
lower
-1
upper
0.25

Group 0: include cell 3 in calibration

quantization_g0_fit_3

lower=min(previousLower,clipped); upper=max(previousUpper,clipped)

Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0.

Saved inputs
group
0
cell
3
previousLower
-1
previousUpper
0.25
clipped
0.5
Saved outputs
lower
-1
upper
0.5

Group 0: include cell 4 in calibration

quantization_g0_fit_4

lower=min(previousLower,clipped); upper=max(previousUpper,clipped)

Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0.

Saved inputs
group
0
cell
4
previousLower
-1
previousUpper
0.5
clipped
2
Saved outputs
lower
-1
upper
2

Group 0: include cell 5 in calibration

quantization_g0_fit_5

lower=min(previousLower,clipped); upper=max(previousUpper,clipped)

Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0.

Saved inputs
group
0
cell
5
previousLower
-1
previousUpper
2
clipped
0.75
Saved outputs
lower
-1
upper
2

Group 0: classify the actual span

quantization_g0_span

span=upper-lower; zeroGroup=(span==0)

Including zero makes span zero exactly for a clipped all-zero group. A positive span whose scale underflows is a different branch.

Saved inputs
group
0
lower
-1
upper
2
Saved outputs
span
3
zeroGroup
0

Group 0: divide the nonzero span by Q

quantization_g0_scale

scale=span/Q

This is the actual stored binary64 quotient. If it is zero the computation becomes unavailable before any division by this scale; no epsilon or minimum-scale repair is allowed.

Saved inputs
group
0
span
3
Q
3
Saved outputs
scale
1

Group 0: round the stored zero-point quotient

quantization_g0_zero_point

negativeLower=-lower; zeroRatio=negativeLower/scale; roundedZero=RNE(zeroRatio); zeroPoint=max(0,min(Q,roundedZero))

Integer nearest-even acts on the stored binary64 division result. Zero point and rounding decisions are small exact integers; the operand WORD signs are retained.

Saved inputs
group
0
lower
-1
scale
1
Q
3
Saved outputs
negativeLower
1
zeroRatio
1
roundedZero
1
zeroPoint
1

Group 0: quantize cell 0 using its stored quotient

quantization_g0_quantize_0

scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale

Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product.

Saved inputs
group
0
cell
0
clipped
-1
scale
1
zeroPoint
1
Q
3
Saved outputs
scaled
-1
rounded
-1
candidate
0
code
0
centered
-1
reconstructed
-1
saturated
0
lowEndpoint
1
highEndpoint
0
zeroPointCode
0

Group 0: quantize cell 1 using its stored quotient

quantization_g0_quantize_1

scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale

Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product.

Saved inputs
group
0
cell
1
clipped
0.25
scale
1
zeroPoint
1
Q
3
Saved outputs
scaled
0.25
rounded
0
candidate
1
code
1
centered
0
reconstructed
0
saturated
0
lowEndpoint
0
highEndpoint
0
zeroPointCode
1

Group 0: quantize cell 2 using its stored quotient

quantization_g0_quantize_2

scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale

Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product.

Saved inputs
group
0
cell
2
clipped
0
scale
1
zeroPoint
1
Q
3
Saved outputs
scaled
0
rounded
0
candidate
1
code
1
centered
0
reconstructed
0
saturated
0
lowEndpoint
0
highEndpoint
0
zeroPointCode
1

Group 0: quantize cell 3 using its stored quotient

quantization_g0_quantize_3

scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale

Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product.

Saved inputs
group
0
cell
3
clipped
0.5
scale
1
zeroPoint
1
Q
3
Saved outputs
scaled
0.5
rounded
0
candidate
1
code
1
centered
0
reconstructed
0
saturated
0
lowEndpoint
0
highEndpoint
0
zeroPointCode
1

Group 0: quantize cell 4 using its stored quotient

quantization_g0_quantize_4

scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale

Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product.

Saved inputs
group
0
cell
4
clipped
2
scale
1
zeroPoint
1
Q
3
Saved outputs
scaled
2
rounded
2
candidate
3
code
3
centered
2
reconstructed
2
saturated
0
lowEndpoint
0
highEndpoint
1
zeroPointCode
0

Group 0: quantize cell 5 using its stored quotient

quantization_g0_quantize_5

scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale

Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product.

Saved inputs
group
0
cell
5
clipped
0.75
scale
1
zeroPoint
1
Q
3
Saved outputs
scaled
0.75
rounded
1
candidate
2
code
2
centered
1
reconstructed
1
saturated
0
lowEndpoint
0
highEndpoint
0
zeroPointCode
0

Group 0: save the five decision counts

quantization_g0_counts

counts=sum(each actual cell decision in this group)

Each decision is counted from its actual current cell; clipping, strict saturation and endpoint/zero-point occupancy remain distinct.

Saved inputs
group
0
cells
6
Saved outputs
clipped
0
saturated
0
lowEndpoint
1
highEndpoint
1
zeroPointCode
3

Save whole-tensor decision counts

quantization_counts

counts=sum(each actual cell decision across groups)

These exact source decisions describe this quantizer, not measured hardware or model quality.

Saved inputs
cells
6
groups
1
Saved outputs
clipped
0
saturated
0
lowEndpoint
1
highEndpoint
1
zeroPointCode
3

original: input 0 contributes to output 0

quantization_original_0_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
0
outputFeature
0
x
1
weight
-1
previous
0
Saved outputs
product
-1
partial
-1

original: input 1 contributes to output 0

quantization_original_1_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
1
outputFeature
0
x
2
weight
0
previous
-1
Saved outputs
product
0
partial
-1

original: input 2 contributes to output 0

quantization_original_2_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
2
outputFeature
0
x
-1
weight
2
previous
-1
Saved outputs
product
-2
partial
-3

original: input 0 contributes to output 1

quantization_original_0_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
0
outputFeature
1
x
1
weight
0.25
previous
0
Saved outputs
product
0.25
partial
0.25

original: input 1 contributes to output 1

quantization_original_1_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
1
outputFeature
1
x
2
weight
0.5
previous
0.25
Saved outputs
product
1
partial
1.25

original: input 2 contributes to output 1

quantization_original_2_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
2
outputFeature
1
x
-1
weight
0.75
previous
1.25
Saved outputs
product
-0.75
partial
0.5

clipped: input 0 contributes to output 0

quantization_clipped_0_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
0
outputFeature
0
x
1
weight
-1
previous
0
Saved outputs
product
-1
partial
-1

clipped: input 1 contributes to output 0

quantization_clipped_1_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
1
outputFeature
0
x
2
weight
0
previous
-1
Saved outputs
product
0
partial
-1

clipped: input 2 contributes to output 0

quantization_clipped_2_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
2
outputFeature
0
x
-1
weight
2
previous
-1
Saved outputs
product
-2
partial
-3

clipped: input 0 contributes to output 1

quantization_clipped_0_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
0
outputFeature
1
x
1
weight
0.25
previous
0
Saved outputs
product
0.25
partial
0.25

clipped: input 1 contributes to output 1

quantization_clipped_1_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
1
outputFeature
1
x
2
weight
0.5
previous
0.25
Saved outputs
product
1
partial
1.25

clipped: input 2 contributes to output 1

quantization_clipped_2_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
2
outputFeature
1
x
-1
weight
0.75
previous
1.25
Saved outputs
product
-0.75
partial
0.5

reconstructed: input 0 contributes to output 0

quantization_reconstructed_0_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
0
outputFeature
0
x
1
weight
-1
previous
0
Saved outputs
product
-1
partial
-1

reconstructed: input 1 contributes to output 0

quantization_reconstructed_1_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
1
outputFeature
0
x
2
weight
0
previous
-1
Saved outputs
product
0
partial
-1

reconstructed: input 2 contributes to output 0

quantization_reconstructed_2_0

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
2
outputFeature
0
x
-1
weight
2
previous
-1
Saved outputs
product
-2
partial
-3

reconstructed: input 0 contributes to output 1

quantization_reconstructed_0_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
0
outputFeature
1
x
1
weight
0
previous
0
Saved outputs
product
0
partial
0

reconstructed: input 1 contributes to output 1

quantization_reconstructed_1_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
1
outputFeature
1
x
2
weight
0
previous
0
Saved outputs
product
0
partial
0

reconstructed: input 2 contributes to output 1

quantization_reconstructed_2_1

product=x*weight; partial=previous+product

Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product.

Saved inputs
inputFeature
2
outputFeature
1
x
-1
weight
1
previous
0
Saved outputs
product
-1
partial
-1

Error cell 0: direct difference and independent reductions

quantization_weight_clipping_0

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
0
reference
-1
actual
-1
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 1: direct difference and independent reductions

quantization_weight_clipping_1

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
1
reference
0.25
actual
0.25
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 2: direct difference and independent reductions

quantization_weight_clipping_2

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
2
reference
0
actual
0
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 3: direct difference and independent reductions

quantization_weight_clipping_3

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
3
reference
0.5
actual
0.5
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 4: direct difference and independent reductions

quantization_weight_clipping_4

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
4
reference
2
actual
2
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 5: direct difference and independent reductions

quantization_weight_clipping_5

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
5
reference
0.75
actual
0.75
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 0: direct difference and independent reductions

quantization_weight_quantization_0

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
0
reference
-1
actual
-1
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 1: direct difference and independent reductions

quantization_weight_quantization_1

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
1
reference
0.25
actual
0
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
-0.25
square
0.0625
absolute
0.25
squaredUnderflow
0
sse
0.0625
maxAbs
0.25

Error cell 2: direct difference and independent reductions

quantization_weight_quantization_2

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
2
reference
0
actual
0
previousSSE
0.0625
previousMaxAbs
0.25
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0.0625
maxAbs
0.25

Error cell 3: direct difference and independent reductions

quantization_weight_quantization_3

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
3
reference
0.5
actual
0
previousSSE
0.0625
previousMaxAbs
0.25
Saved outputs
difference
-0.5
square
0.25
absolute
0.5
squaredUnderflow
0
sse
0.3125
maxAbs
0.5

Error cell 4: direct difference and independent reductions

quantization_weight_quantization_4

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
4
reference
2
actual
2
previousSSE
0.3125
previousMaxAbs
0.5
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0.3125
maxAbs
0.5

Error cell 5: direct difference and independent reductions

quantization_weight_quantization_5

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
5
reference
0.75
actual
1
previousSSE
0.3125
previousMaxAbs
0.5
Saved outputs
difference
0.25
square
0.0625
absolute
0.25
squaredUnderflow
0
sse
0.375
maxAbs
0.5

Error cell 0: direct difference and independent reductions

quantization_weight_total_0

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
0
reference
-1
actual
-1
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 1: direct difference and independent reductions

quantization_weight_total_1

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
1
reference
0.25
actual
0
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
-0.25
square
0.0625
absolute
0.25
squaredUnderflow
0
sse
0.0625
maxAbs
0.25

Error cell 2: direct difference and independent reductions

quantization_weight_total_2

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
2
reference
0
actual
0
previousSSE
0.0625
previousMaxAbs
0.25
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0.0625
maxAbs
0.25

Error cell 3: direct difference and independent reductions

quantization_weight_total_3

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
3
reference
0.5
actual
0
previousSSE
0.0625
previousMaxAbs
0.25
Saved outputs
difference
-0.5
square
0.25
absolute
0.5
squaredUnderflow
0
sse
0.3125
maxAbs
0.5

Error cell 4: direct difference and independent reductions

quantization_weight_total_4

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
4
reference
2
actual
2
previousSSE
0.3125
previousMaxAbs
0.5
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0.3125
maxAbs
0.5

Error cell 5: direct difference and independent reductions

quantization_weight_total_5

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
5
reference
0.75
actual
1
previousSSE
0.3125
previousMaxAbs
0.5
Saved outputs
difference
0.25
square
0.0625
absolute
0.25
squaredUnderflow
0
sse
0.375
maxAbs
0.5

Error cell 0: direct difference and independent reductions

quantization_output_clipping_0

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
0
reference
-3
actual
-3
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 1: direct difference and independent reductions

quantization_output_clipping_1

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
1
reference
0.5
actual
0.5
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 0: direct difference and independent reductions

quantization_output_quantization_0

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
0
reference
-3
actual
-3
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 1: direct difference and independent reductions

quantization_output_quantization_1

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
1
reference
0.5
actual
-1
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
-1.5
square
2.25
absolute
1.5
squaredUnderflow
0
sse
2.25
maxAbs
1.5

Error cell 0: direct difference and independent reductions

quantization_output_total_0

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
0
reference
-3
actual
-3
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
0
square
0
absolute
0
squaredUnderflow
0
sse
0
maxAbs
0

Error cell 1: direct difference and independent reductions

quantization_output_total_1

difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))

Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error.

Saved inputs
cell
1
reference
0.5
actual
-1
previousSSE
0
previousMaxAbs
0
Saved outputs
difference
-1.5
square
2.25
absolute
1.5
squaredUnderflow
0
sse
2.25
maxAbs
1.5

Save the actual quantizer source graph counts

finish

output=quantization_reconstructed_Y; counts=quantization_Counts; nativeElementaryCalls=0

Copy the saved whole-tensor decisions and source graph sizes after all three actual affine paths and all six direct error reductions. Source counts do not measure hardware speed, storage or model quality.

Saved inputs
bits
2
mode
0
groups
1
codeMax
3
Saved outputs
bits
2
mode
0
inputFeatures
3
outputFeatures
2
groups
1
codeMax
3
clipped
0
saturated
0
lowEndpoint
1
highEndpoint
1
zeroPointCode
3
expCalls
0
sqrtCalls
0
nativeElementaryCalls
0
frames
67
tensorCount
66
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.

quantization_Raw

RawField=12 · float64 · precision 8 · Captured raw12 in declared order: bits,mode VALUE; clip,all six weights,all three inputs WORD including -0.

Zero-based storage indexStored value
02
10
22
3-1
40.25
50
60.5
72
80.75
91
102
11-1

quantization_X

InputFeature=3 · float64 · precision 8 · Actual captured x0,x1,x2 words; one row-feature input, no bias.

Zero-based storage indexStored value
01
12
2-1

quantization_WOriginal

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · All six captured original weight words in w00,w01,w10,w11,w20,w21 row-major order; explicit transpose of column-weight notation.

Zero-based storage indexStored value
0-1
10.25
20
30.5
42
50.75

quantization_WClipped

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual max(-clip,min(clip,w)) selections before calibration; original W remains unchanged.

Zero-based storage indexStored value
0-1
10.25
20
30.5
42
50.75

quantization_ClipFlags

InputFeature=3 × OutputFeature=2 · int32 · precision 0 · Strict original<-clip or original>clip decisions; endpoints equal to clip are not clipped.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_CellGroups

InputFeature=3 × OutputFeature=2 · int32 · precision 0 · Global mode maps all cells to group0; per-output mode maps output feature j to group j.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_g0_Members

GroupCell=6 · int32 · precision 0 · Actual row-major weight-cell indices in this calibration group, in fit and quantization visit order.

Zero-based storage indexStored value
00
11
22
33
44
55

quantization_g0_FitOperands

FitOperand=7 · float64 · precision 8 · Literal +0 followed by the actual clipped group words used by both ordered fit folds.

Zero-based storage indexStored value
00
1-1
20.25
30
40.5
52
60.75

quantization_g0_FitPartials

GroupCell=6 × FitBound=2 · float64 · precision 8 · Actual lower,upper after each group member; retain lower -0 and upper +0 as produced.

Zero-based storage indexStored value
0-1
10
2-1
30.25
4-1
50.25
6-1
70.5
8-1
92
10-1
112

quantization_g0_Calibration

CalibrationField=4 · float64 · precision 8 · Saved lower,upper,span,scale WORDs. For a zero group scale=1 is an explicit assigned policy, not a division result.

Zero-based storage indexStored value
0-1
12
23
31

quantization_g0_ZeroGroup

Scalar=1 · int32 · precision 0 · Decision 1 for span==0, otherwise 0; this does not classify a positive-span zero-scale fault as a zero group.

Zero-based storage indexStored value
00

quantization_g0_ZeroPoint

Scalar=1 · int32 · precision 0 · Saved integer zero point; assigned 0 for a zero group, otherwise clamped actual RNE((-lower)/scale).

Zero-based storage indexStored value
01

quantization_g0_ZeroPointOperands

ZeroPointOperand=2 · float64 · precision 8 · Actual unary -lower and stored (-lower)/scale operands; no ideal rational quotient substitution.

Zero-based storage indexStored value
01
11

quantization_g0_RoundedZero

Scalar=1 · int32 · precision 0 · Actual nearest-even integer decision on the stored zero-point quotient, before clamping.

Zero-based storage indexStored value
01

quantization_g0_Scaled

GroupCell=6 · float64 · precision 8 · Actual clipped/scale binary64 quotient for each listed group member, before integer RNE.

Zero-based storage indexStored value
0-1
10.25
20
30.5
42
50.75

quantization_g0_IntegerStages

GroupCell=6 × IntegerStage=4 · int32 · precision 0 · Actual rounded,candidate,code,centered integer decisions for each listed group member; RNE precedes zero-point addition.

Zero-based storage indexStored value
0-1
10
20
3-1
40
51
61
70
80
91
101
110
120
131
141
150
162
173
183
192
201
212
222
231

quantization_g0_Counts

CountField=5 · int32 · precision 0 · Independently accumulated group counts: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode; occupancy does not imply saturation.

Zero-based storage indexStored value
00
10
21
31
43

quantization_Codes

InputFeature=3 × OutputFeature=2 · int32 · precision 0 · Actual code integers restored to original row-major weight order; ordinary int32 records, not packed b-bit allocations.

Zero-based storage indexStored value
00
11
21
31
43
52

quantization_WReconstructed

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual centered*scale words for nonzero groups; explicit policy +0 for zero groups, restored to original weight order.

Zero-based storage indexStored value
0-1
10
20
30
42
51

quantization_CodeFlags

InputFeature=3 × OutputFeature=2 × CodeDecision=4 · int32 · precision 0 · Per-cell saturated,lowEndpoint,highEndpoint,zeroPointCode flags; zero policy assigns 0,1,0,1.

Zero-based storage indexStored value
00
11
20
30
40
50
60
71
80
90
100
111
120
130
140
151
160
170
181
190
200
210
220
230

quantization_Counts

CountField=5 · int32 · precision 0 · Actual whole-tensor counts independently accumulated from cell decisions: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode.

Zero-based storage indexStored value
00
10
21
31
43

quantization_original_Products

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature.

Zero-based storage indexStored value
0-1
10.25
20
31
4-2
5-0.75

quantization_original_Partials

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual running binary64 sums after each product; each output starts from literal +0.

Zero-based storage indexStored value
0-1
10.25
2-1
31.25
4-3
50.5

quantization_original_Y

OutputFeature=2 · float64 · precision 8 · Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction.

Zero-based storage indexStored value
0-3
10.5

quantization_clipped_Products

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature.

Zero-based storage indexStored value
0-1
10.25
20
31
4-2
5-0.75

quantization_clipped_Partials

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual running binary64 sums after each product; each output starts from literal +0.

Zero-based storage indexStored value
0-1
10.25
2-1
31.25
4-3
50.5

quantization_clipped_Y

OutputFeature=2 · float64 · precision 8 · Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction.

Zero-based storage indexStored value
0-3
10.5

quantization_reconstructed_Products

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature.

Zero-based storage indexStored value
0-1
10
20
30
4-2
5-1

quantization_reconstructed_Partials

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual running binary64 sums after each product; each output starts from literal +0.

Zero-based storage indexStored value
0-1
10
2-1
30
4-3
5-1

quantization_reconstructed_Y

OutputFeature=2 · float64 · precision 8 · Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction.

Zero-based storage indexStored value
0-3
1-1

quantization_weight_clipping_Difference

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_weight_clipping_Squares

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_weight_clipping_Absolute

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual Math.abs of each saved difference, in the original weight or output units.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_weight_clipping_SquaredUnderflow

InputFeature=3 × OutputFeature=2 · int32 · precision 0 · Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_weight_clipping_ReductionPartials

ErrorCell=6 × ReductionField=2 · float64 · precision 8 · Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

Zero-based storage indexStored value
00
10
20
30
40
50
60
70
80
90
100
110

quantization_weight_clipping_Summary

ReductionField=2 · float64 · precision 8 · Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

Zero-based storage indexStored value
00
10

quantization_weight_quantization_Difference

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

Zero-based storage indexStored value
00
1-0.25
20
3-0.5
40
50.25

quantization_weight_quantization_Squares

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

Zero-based storage indexStored value
00
10.0625
20
30.25
40
50.0625

quantization_weight_quantization_Absolute

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual Math.abs of each saved difference, in the original weight or output units.

Zero-based storage indexStored value
00
10.25
20
30.5
40
50.25

quantization_weight_quantization_SquaredUnderflow

InputFeature=3 × OutputFeature=2 · int32 · precision 0 · Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_weight_quantization_ReductionPartials

ErrorCell=6 × ReductionField=2 · float64 · precision 8 · Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

Zero-based storage indexStored value
00
10
20.0625
30.25
40.0625
50.25
60.3125
70.5
80.3125
90.5
100.375
110.5

quantization_weight_quantization_Summary

ReductionField=2 · float64 · precision 8 · Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

Zero-based storage indexStored value
00.375
10.5

quantization_weight_total_Difference

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

Zero-based storage indexStored value
00
1-0.25
20
3-0.5
40
50.25

quantization_weight_total_Squares

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

Zero-based storage indexStored value
00
10.0625
20
30.25
40
50.0625

quantization_weight_total_Absolute

InputFeature=3 × OutputFeature=2 · float64 · precision 8 · Actual Math.abs of each saved difference, in the original weight or output units.

Zero-based storage indexStored value
00
10.25
20
30.5
40
50.25

quantization_weight_total_SquaredUnderflow

InputFeature=3 × OutputFeature=2 · int32 · precision 0 · Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

Zero-based storage indexStored value
00
10
20
30
40
50

quantization_weight_total_ReductionPartials

ErrorCell=6 × ReductionField=2 · float64 · precision 8 · Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

Zero-based storage indexStored value
00
10
20.0625
30.25
40.0625
50.25
60.3125
70.5
80.3125
90.5
100.375
110.5

quantization_weight_total_Summary

ReductionField=2 · float64 · precision 8 · Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

Zero-based storage indexStored value
00.375
10.5

quantization_output_clipping_Difference

OutputFeature=2 · float64 · precision 8 · Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

Zero-based storage indexStored value
00
10

quantization_output_clipping_Squares

OutputFeature=2 · float64 · precision 8 · Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

Zero-based storage indexStored value
00
10

quantization_output_clipping_Absolute

OutputFeature=2 · float64 · precision 8 · Actual Math.abs of each saved difference, in the original weight or output units.

Zero-based storage indexStored value
00
10

quantization_output_clipping_SquaredUnderflow

OutputFeature=2 · int32 · precision 0 · Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

Zero-based storage indexStored value
00
10

quantization_output_clipping_ReductionPartials

ErrorCell=2 × ReductionField=2 · float64 · precision 8 · Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

Zero-based storage indexStored value
00
10
20
30

quantization_output_clipping_Summary

ReductionField=2 · float64 · precision 8 · Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

Zero-based storage indexStored value
00
10

quantization_output_quantization_Difference

OutputFeature=2 · float64 · precision 8 · Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

Zero-based storage indexStored value
00
1-1.5

quantization_output_quantization_Squares

OutputFeature=2 · float64 · precision 8 · Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

Zero-based storage indexStored value
00
12.25

quantization_output_quantization_Absolute

OutputFeature=2 · float64 · precision 8 · Actual Math.abs of each saved difference, in the original weight or output units.

Zero-based storage indexStored value
00
11.5

quantization_output_quantization_SquaredUnderflow

OutputFeature=2 · int32 · precision 0 · Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

Zero-based storage indexStored value
00
10

quantization_output_quantization_ReductionPartials

ErrorCell=2 × ReductionField=2 · float64 · precision 8 · Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

Zero-based storage indexStored value
00
10
22.25
31.5

quantization_output_quantization_Summary

ReductionField=2 · float64 · precision 8 · Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

Zero-based storage indexStored value
02.25
11.5

quantization_output_total_Difference

OutputFeature=2 · float64 · precision 8 · Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences.

Zero-based storage indexStored value
00
1-1.5

quantization_output_total_Squares

OutputFeature=2 · float64 · precision 8 · Actual difference*difference binary64 products; zero squares can conceal nonzero residuals.

Zero-based storage indexStored value
00
12.25

quantization_output_total_Absolute

OutputFeature=2 · float64 · precision 8 · Actual Math.abs of each saved difference, in the original weight or output units.

Zero-based storage indexStored value
00
11.5

quantization_output_total_SquaredUnderflow

OutputFeature=2 · int32 · precision 0 · Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.

Zero-based storage indexStored value
00
10

quantization_output_total_ReductionPartials

ErrorCell=2 × ReductionField=2 · float64 · precision 8 · Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0.

Zero-based storage indexStored value
00
10
22.25
31.5

quantization_output_total_Summary

ReductionField=2 · float64 · precision 8 · Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator.

Zero-based storage indexStored value
02.25
11.5

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. Fixed default global worksheet: bits=2, mode=0, clip=2, W=[[-1,1/4],[0,1/2],[2,3/4]], x=[1,2,-1]. How can unsigned code 0 represent weight -1?
2. Fixed default global worksheet: bits=2, mode=0, clip=2, W=[[-1,1/4],[0,1/2],[2,3/4]], x=[1,2,-1]. What happens to W[1,1]=1/2, and what is reconstructed output column1?
3. Fixed clipping intervention: default W=[[-1,1/4],[0,1/2],[2,3/4]], x=[1,2,-1], bits=2, mode=0, clip=3/4. In order, what are yClipped-yOriginal, yReconstructed-yClipped and yReconstructed-yOriginal?
4. Fixed changed-matrix worksheet: W=[[-1,-1/2],[1/2,1/4],[2,1]], x=[1,2,-1], bits=2, clip=2. What happens when mode changes from global0 to per-output1?
5. Current WHOLE saved root: bits=2, mode=0, clip=2, w00=-1, w01=0.25, w10=0, w11=0.5, w20=2, w21=0.75, x0=1, x1=2, x2=-1. Saved original_Y=[-3, 0.5]; clipped_Y=[-3, 0.5]; reconstructed_Y=[-3, -1]; output_total_Summary [sse,maxAbs]=[2.25, 1.5]; output_total_SquaredUnderflow=[0, 0]. Which statement describes this saved total output error? Read these saved values, independently of the selected trace step.

Five corrective questions follow the evidence. The first four name fixed worksheets; the fifth reads this current whole saved calculation.

Explore the saved calculation

Start with the two menus: choose 2, 3, 4 or 8 bits, then one scale for the whole tensor or a separate scale for each output column. The clipping threshold accepts any finite value from 1/4 to 4. Open the weight and input groups to edit all six weights and three inputs, each from -4 to 4. These ten number fields are continuous; weights and inputs also admit signed zero. Reset example restores all twelve defaults. Changing an input changes the answer even when the weight codes stay the same.

An empty, malformed, nonfinite or out-of-range draft withholds all computed outputs, trace, inspectors and graded questions; correct it or reset. A valid draft can instead reach a model boundary: if a nonzero calibration span produces a stored scale of zero, the whole result is unavailable with its reason. The lab hides all computed evidence and grades in that case too. It does not display the helper’s retained partial collector as a successful calculation.

Use Previous step, Calculation step or Next step to seek through immutable saved operations. Selection highlights the chosen frame; it does not change the complete current outputs or the fifth question’s premise. Editing starts a fresh calculation at the first step. Editing, reset and seeking clear answers; opening an inspection disclosure preserves them. The lab’s five radio questions give corrective explanations immediately after a selection. Their first four worksheets name fixed inputs; only the fifth follows your current complete saved calculation.

Read the saved group bounds, span, scale and zero point beside their policy. Open a group’s details for every fit operand, fit partial and computed code stage. An all-zero group omits four arithmetic tensors—ZeroPointOperands, RoundedZero, Scaled and IntegerStages—and gives the saved reasons under Arithmetic not performed. Its policy values remain visible. A mixed pair of output groups keeps the nonzero group’s actual arithmetic.

The three affine tables retain every product and partial sum. Each of the six error disclosures retains direct residuals, squares, absolute values, underflow flags and both reduction partials. If SSE is zero, compare maxAbs and the squared-underflow flags before calling the outputs equal. The Complete tensor fallback shows every saved cell with its shape, axes, dtype, provenance and declared precision; the Complete operation fallback shows every field and operand of every frame. The house inspector also exposes all scalar aliases and text evidence. These views read saved values; display precision never changes a later operand.

Start with the weights and their meanings

A tensor is an array with named axes. A matrix is a two-axis tensor. Our weight matrix has three input-feature rows and two output-feature columns:

W=[−11/401/223/4],x=(1,2,−1),y=xW.W=\begin{bmatrix}-1&1/4\\0&1/2\\2&3/4\end{bmatrix}, \qquad x=(1,2,-1),\qquad y=xW.

A feature is one numerical coordinate. The input storage has shape [3], the weights [3,2], and the output [2]. Index i selects input feature 0, 1 or 2; index j selects output feature 0 or 1. Thus W[i,j] connects input i to output j. Written with an explicit sample axis, [1,3] times [3,2] gives [1,2]: the two lengths 3 match because we sum over input features.

This is row-feature storage. In the column-vector convention of earlier books, the same operation is W transposed times the input column: [2,3] times [3,1] gives [2,1]. An output channel here means a column of W, not a row. No bias or activation is added.

Review IV-59, Decoder-Only Transformer Anatomy for row-feature products and the place of weights in a decoder. Review Book II VIII.1, Floating-point representation for stored binary numbers. VIII.1 refers to Book II, not Book IV’s positional-information Part. This lesson isolates one small multiplication; it does not quantize that decoder.

All toy values are dimensionless, but keep their roles separate. A scale has weight units per code step. Weight differences have weight units; output differences have input-times-weight units. Squaring a difference squares those units.

The selected input contract has twelve fields, in order:

FieldMeaningSelected defaultAllowed values
bitsLogical code width b22, 3, 4 or 8
modeScale grouping00: whole tensor; 1: each output column
clipSymmetric threshold c21/4 through 4
w00, w01Input-feature 0 weights-1, 1/4Each -4 through 4
w10, w11Input-feature 1 weights0, 1/2Each -4 through 4
w20, w21Input-feature 2 weights2, 3/4Each -4 through 4
x0, x1, x2Input features1, 2, -1Each -4 through 4

All operands must be actual finite numbers. An all-zero weight group does not make an invalid input acceptable. Changing bits changes the available integer labels; changing mode changes which weights share calibration. Changing c can change both clipping and calibration. Changing x changes output contributions without changing the weight codes.

Turn weights into codes, then back into weights

Quantization replaces weights by a limited set of representable choices. A code q is an integer label. With b bits, there are 2 to the power b labels; write their largest value as Q, so Q equals that number minus one. At b=2 the codes are 0, 1, 2 and 3.

First clip every original weight to the interval from -c to c. Call the resulting matrix C. Clipping selects the nearer endpoint for a weight outside the interval; equality with an endpoint is not clipping. Keep W as well as C, so the original calculation remains a separate reference.

Calibration fits a range to a group of clipped weights. Per-tensor mode uses all six cells, in row order. Per-output-channel mode fits column 0 using rows 0, 1, 2, then column 1 in that same row order. Always include zero: a is the smallest of zero and the group cells, d is the largest, and h is d minus a. Including zero ensures that a constant positive group still has positive span; it does not get mistaken for an all-zero group.

Two rounding operations need different names. RN rounds one arithmetic result to the binary64 floating-point format, using nearest/even. RNE rounds an already stored number to an integer, with halfway ties choosing the even integer. Display formatting is neither operation and must never feed back into the calculation.

For a nonzero span, follow these stages. After computing s, require it to be strictly positive; if it rounded to zero, stop before computing t or any cell quotient.

h=RN⁡(d−a),s=RN⁡(h/Q),t=RN⁡((−a)/s),z=clamp⁡(RNE⁡(t),0,Q).h=\operatorname{RN}(d-a),\quad s=\operatorname{RN}(h/Q),\quad t=\operatorname{RN}((-a)/s),\quad z=\operatorname{clamp}(\operatorname{RNE}(t),0,Q).

Here clamp means restrict to the indicated interval. The positive scale s is the weight increment for one code step. The integer zero point z is the code that reconstructs zero. For each clipped weight C[i,j], compute:

v=RN⁡(C[i,j]/s),r=RNE⁡(v),u=r+z,q=clamp⁡(u,0,Q),k=q−z,R[i,j]=RN⁡(ks).v=\operatorname{RN}(C[i,j]/s),\quad r=\operatorname{RNE}(v),\quad u=r+z,\quad q=\operatorname{clamp}(u,0,Q),\quad k=q-z,\quad R[i,j]=\operatorname{RN}(ks).

R is the reconstructed weight matrix. Dequantization is this reconstruction, not recovery of discarded information. The additions and subtractions between these bounded integers are exact. The zero point is subtracted from each code before multiplication by s; it is not an output bias. Unsigned code 0 can therefore represent a negative weight.

Why fit groups separately? A column whose weights occupy a narrow interval can use a finer grid than a whole matrix whose other column has a large span. This uses two scale/zero-point pairs instead of one. It creates a useful choice to investigate, not a universal quality guarantee.

Halfway means exactly halfway, including for negative numbers

Let n be the greatest integer no larger than the stored quotient v, and let f=v-n. Choose n when f is below 1/2, n+1 when it is above 1/2, and the even neighbor when f equals 1/2. Floor is not truncation toward zero: for v=-3/2, n=-2 and f=1/2.

Stored quotient v-5/2-3/2-1/21/23/25/2
RNE(v)-2-20022

Integer zero is canonical positive zero. Floating-point operands retain their zero signs. Do not use a near-half tolerance or round a displayed decimal first. JavaScript’s Math.round uses a different halfway convention.

Round before adding z. With v=1/2 and z=1, the selected stages give RNE(1/2)+1=1. Moving the addition inside gives RNE(3/2)=2. At v=-1/2, the selected stages give 1, while RNE(-1/2+1)=0. Both changes select a different code. This stage order is part of this lesson’s policy; other quantizers need their own disclosed rules.

Every default cell, product and partial sum

For the default c=2, clipping changes nothing: C=W. At b=2, per-tensor calibration gives a=-1, d=2, h=3, s=1, t=1 and z=1. The reconstruction endpoints are -1 and 2.

Cell [i,j]Original WClipped Cv=C/srCandidate uCode qCentered kReconstructed R
[0,0]-1-1-1-100-1-1
[0,1]1/41/41/401100
[1,0]00001100
[1,1]1/21/21/201100
[2,0]22223322
[2,1]3/43/43/412211

The reconstructed rows are (-1,0), (0,0), (2,1). Every clipping flag is zero, and every saturation flag is zero. Two cells occupy endpoint codes, yet neither needed a code clamp. Three cells use code z=1 and reconstruct zero.

Compute three separate outputs: y=xW, yC=xC and yR=xR. For each path, visit output column 0 then 1. Start a fresh running sum at literal +0. For input rows 0, 1, 2, first round the product, then round its addition to the previous partial sum. Retain zero products; do not combine multiplication and addition into one fused operation or reorder a reduction.

Path / output columnProduct for i=0Product for i=1Product for i=2Three partial sums from +0Output
Original / 01 times -1 = -12 times 0 = 0-1 times 2 = -2-1, -1, -3-3
Original / 11 times 1/4 = 1/42 times 1/2 = 1-1 times 3/4 = -3/41/4, 5/4, 1/21/2
Clipped / 0-10-2-1, -1, -3-3
Clipped / 11/41-3/41/4, 5/4, 1/21/2
Reconstructed / 01 times -1 = -12 times 0 = 0-1 times 2 = -2-1, -1, -3-3
Reconstructed / 11 times 0 = 02 times 0 = 0-1 times 1 = -10, 0, -1-1

All these values are dyadic fractions, meaning their denominators are powers of two, and these small operations are exactly representable in binary64. The table suppresses floating zero signs for readability; it makes no assertion that all zero products have the same word. Fractions here express a manual calculation, not a machine run.

Three error families, each with its own reference

An error means computed minus reference. Compute clipping differences C-W, quantization differences R-C and total differences R-W independently. For outputs, independently subtract yC-y, yR-yC and yR-y. Even though their signed decomposition holds over exact real numbers, rounded component differences must not be added to manufacture a direct total difference.

SSE, sum of squared errors, is obtained by squaring every difference and adding from +0 in declared order. maxAbs is the greatest absolute difference, starting its comparison fold at +0. SSE has squared units; maxAbs has the original units. The Euclidean norm would take a square root of a vector SSE, and the Frobenius norm would do so for a matrix. We report SSE, not either norm, and do not perform a square root.

In row-major cell order [0,0], [0,1], [1,0], [1,1], [2,0], [2,1]:

Default weight familySix differencesSix squaresSix SSE partial sumsSSE; maxAbs
Clipping0, 0, 0, 0, 0, 00, 0, 0, 0, 0, 00, 0, 0, 0, 0, 00; 0
Quantization0, -1/4, 0, -1/2, 0, 1/40, 1/16, 0, 1/4, 0, 1/160, 1/16, 1/16, 5/16, 5/16, 3/83/8; 1/2
Total0, -1/4, 0, -1/2, 0, 1/40, 1/16, 0, 1/4, 0, 1/160, 1/16, 1/16, 5/16, 5/16, 3/83/8; 1/2

The quantization and total absolute differences are 0, 1/4, 0, 1/2, 0, 1/4; their maxAbs partial values are 0, 1/4, 1/4, 1/2, 1/2, 1/2. The clipping absolute values and maxima are all zero.

Default output familyDifferences in columns 0, 1SquaresSSE partial sumsSSE; maxAbs
Clipping0, 00, 00, 00; 0
Quantization0, -3/20, 9/40, 9/49/4; 3/2
Total0, -3/20, 9/40, 9/49/4; 3/2

For the last two rows the absolute differences and running maxima are 0, 3/2. Weight SSE 3/8 and output SSE 9/4 measure different things. An input of magnitude 2 doubles its weight error contribution before output errors are squared.

Fit each output column instead

Keep every default number, but use mode 1. Column 0 has a=-1, d=2, h=3, s=1, t=1, z=1; its v values are -1,0,2, its r values -1,0,2, codes 0,1,3, centered values -1,0,2 and reconstructed values -1,0,2. Column 1 has a=0, d=3/4, h=3/4, s=1/4, t=0, z=0; its v and r values are 1,2,3, codes 1,2,3, centered values 1,2,3 and reconstructed values 1/4,1/2,3/4. No candidate is clamped.

Every numerical weight is reconstructed exactly in this default. The reconstructed products for column 0 are -1,0,-2, with partial sums -1,-1,-3. For column 1 they are 1/4,1,-3/4, with partial sums 1/4,5/4,1/2. Original and clipped paths remain as above. All three weight-error families and all three output-error families have zero differences, squares, SSE and maxAbs. This is a property of these values; edited signed zeros still require a separate word comparison.

Clipping, endpoint occupancy and saturation are different events

Use the original default matrix, bits 2 and global mode, but change c to 3/4. This is a separate manual intervention with a dyadic scale. The clipped rows become (-3/4,1/4), (0,1/2), (3/4,3/4). Only W[0,0] and W[2,0] are clipped. W[2,1] equals c and is not clipped.

Now a=-3/4, d=3/4, h=3/2, s=1/2, t=3/2 and z=2. The grid endpoints are -1 and 1/2: a reconstructed endpoint can lie outside the fitted interval after the zero point is rounded.

CellWCvruqkRClipped?Saturated?
[0,0]-1-3/4-3/2-200-2-1yesno
[0,1]1/41/41/202200nono
[1,0]00002200nono
[1,1]1/21/2113311/2nono
[2,0]23/43/224311/2yesyes
[2,1]3/43/43/224311/2noyes

Saturation means the candidate u is strictly below 0 or above Q, so the integer clamp changes it. Endpoint occupancy only means the final q is 0 or Q. Here four cells occupy endpoints; two saturate. One clipped cell does not saturate, and one saturating cell was never clipped. Neither flag can be inferred from the other.

Original products and partial sums remain those in the default worksheet; y=(-3,1/2). Compute the other two paths afresh:

Path / columnThree products in input orderThree partial sumsOutput
Clipped / 0-3/4, 0, -3/4-3/4, -3/4, -3/2-3/2
Clipped / 11/4, 1, -3/41/4, 5/4, 1/21/2
Reconstructed / 0-1, 0, -1/2-1, -1, -3/2-3/2
Reconstructed / 10, 1, -1/20, 1, 1/21/2
Weight familyRow-major differencesRow-major squaresSSE; maxAbs
Clipping1/4, 0, 0, 0, -5/4, 01/16, 0, 0, 0, 25/16, 013/8; 5/4
Quantization-1/4, -1/4, 0, 0, -1/4, -1/41/16, 1/16, 0, 0, 1/16, 1/161/4; 1/4
Total0, -1/4, 0, 0, -3/2, -1/40, 1/16, 0, 0, 9/4, 1/1619/8; 3/2

Clipping output difference is (3/2,0), with squares (9/4,0), SSE 9/4 and maxAbs 3/2. Quantization output difference is (0,0), with zero squares, SSE and maxAbs. Total output difference is (3/2,0), with squares (9/4,0), SSE 9/4 and maxAbs 3/2. Zero output error relative to C conceals the error relative to W if we show only one reference. Weight SSEs do not add: 13/8+1/4 differs from 19/8 because squaring a sum includes cross terms.

A valid zero-group policy is different from scale underflow

If all clipped cells in a group are numerically zero, its span is zero. Choose the explicit policy s=1, z=0, every code 0 and every reconstructed weight +0. Scale 1 is a convention, not an estimated resolution. Save the fitted bounds and policy decision. There was no division for a zero-point ratio or cell quotient, no integer rounding of such a quotient, and no arithmetic reconstruction to pretend happened. Those stages are uncomputed, rather than fabricated rows of arithmetic zeros. A zero column can coexist with a nonzero column in mode 1.

For contrast, set column 0 to (0,0,m), where m is the smallest positive binary64 subnormal, 2 to the power -1074, and column 1 to zero. Use mode 1, bits 2 and c=2. The positive span of column 0 is m, but RN(m/3)=0. This is a nonzero group whose scale underflowed. Stop before dividing by that zero scale, with the selected unavailable reason: A nonzero calibration span produced a zero scale; choose a larger span or fewer bits. This particular minimum-subnormal example fails even at the smallest allowed bit width; increasing its span is necessary within this lesson’s choices. An epsilon or substituting scale 1 changes the computation. The valid zero column cannot repair the other column’s failure.

Underflow means a result is too tiny for its ordinary representation; gradual underflow permits subnormal numbers, and some operations round to zero. There is a second place to notice it: a nonzero error e can have RN(e times e)=0. Keep e, its absolute value and an explicit squared-error-underflow indicator, true exactly when e is nonzero and its computed square is zero. A zero SSE can therefore hide a nonzero residual.

For a concrete manual example, retain the default first column (-1,0,2), replace the second column by (2 to the power -600,0,0), and use global mode, bits 2 and c=2. The span is 3 and scale is 1, so this is not scale underflow. The tiny positive weight rounds to integer 0 and reconstructs 0. Its difference is negative 2 to the power -600, but its square, 2 to the power -1200, rounds to +0. All other weights reconstruct exactly. Weight SSE is numerically zero while maxAbs is positive, 2 to the power -600, and that cell’s squared-error-underflow indicator is true. Preserve the residual rather than replacing it with the square’s zero.

Binary64 also distinguishes +0 and -0 words. Clipping can retain an original -0, while the zero-group reconstruction policy assigns +0. Their arithmetic difference can be zero although their words differ. Hence zero SSE is neither a proof of word identity nor, by itself, a proof that every residual was zero. Codes, indices and integer choices have value semantics; floating operands and copies retain their words.

Why the stored scale can change an integer code

This counterexample concerns actual rounding stages, not a decimal display. Replace W by rows (0,0), (1 minus 2 to the power -53,0), (2,0); choose x=(0,1,0), bits 2, global mode and c=2. All input weights are exactly representable. The lower bound is 0, upper bound 2, span 2 and zero point 0.

With an ideal, unrounded scale s*=2/3, the middle quotient is:

(1−2−53)/(2/3)=3/2−3 2−54.(1-2^{-53})/(2/3)=3/2-3\,2^{-54}.

It is strictly below 3/2, so ideal integer RNE chooses code 1. But the stored scale is different. Let D=6004799503160661, so 3D equals 2 to the power 54 minus one. Then:

s=RN⁡(2/3)=D/253,(1−2−53)/s=(253−1)/D=3/2−1/(2D).s=\operatorname{RN}(2/3)=D/2^{53},\qquad (1-2^{-53})/s=(2^{53}-1)/D=3/2-1/(2D).

Why is that the stored scale? Its distance below 2/3 is 1 divided by (3 times 2 to the power 53). The binary64 spacing at this scale is 2 to the power -53. The exact 2/3 is one third of a spacing above s and two thirds below the next stored number, so RN chooses s.

The second quotient is still below 3/2 before division rounding. Binary64 spacing around 3/2 is 2 to the power -52, so half a spacing is 2 to the power -53. Because D is greater than 2 to the power 52, the distance 1/(2D) is smaller than that half spacing. RN of the division is exactly 3/2. Integer RNE then chooses 2. Rounding the scale and rounding the quotient both matter.

The complete ideal code rows are (0,0), (1,0), (3,0). The actual-RN graph’s code rows are (0,0), (2,0), (3,0). For the last weight, the exact quotient 2/s is 3+1/D, close enough that RN returns 3. Also 3s is 2 minus 2 to the power -53, a midpoint, so RN(3s)=2 by ties/even. Reconstruction rows are therefore (0,0), (2s,0), (2,0).

Only the middle input feature is active. For original column 0 the products are 0, 1 minus 2 to the power -53, 0, and the partial sums are 0, that middle value, that middle value. The clipped path is identical. Reconstructed column 0 has products 0,2s,0 and partial sums 0,2s,2s. Column 1 has zero products and partial sums on all paths. The directly subtracted first output difference is exactly representable as:

2s−(1−2−53)=(D+1)/254.2s-(1-2^{-53})=(D+1)/2^{54}.

An ideal rational quantizer would predict a different integer code. A reference for this machine operation graph must round each primitive before making its next decision. An output tolerance cannot turn a wrong integer code into a correct one. These conclusions are symbolic manual proofs; no numerical program was run.

Smaller weight SSE can give larger output SSE

Return to dyadic numbers, but use this explicitly changed matrix and the default input:

W=[−1−1/21/21/421],x=(1,2,−1).W=\begin{bmatrix}-1&-1/2\\1/2&1/4\\2&1\end{bmatrix},\qquad x=(1,2,-1).

Use bits 2 and c=2, so C=W. Original column 0 products are -1,1,-2, with partial sums -1,0,-2; column 1 products are -1/2,1/2,-1, with partial sums -1/2,0,-1. Thus y=yC=(-2,-1).

Global calibration gives a=-1, d=2, s=1, z=1. Its row-major quotients are -1,-1/2,1/2,1/4,2,1; integer rounding gives -1,0,0,0,2,1; codes are 0,1,1,1,3,2. Reconstructed rows are (-1,0), (0,0), (2,1). Column 0 products -1,0,-2 have partial sums -1,-1,-3. Column 1 products 0,0,-1 have partial sums 0,0,-1. Its output is (-3,-1).

Per-output calibration retains s=1,z=1 for column 0 and uses a=-1/2,d=1,h=3/2,s=1/2,t=1,z=1 for column 1. That column’s quotients are -1,1/2,2, rounded integers -1,0,2 and codes 0,1,3. Reconstructed rows are (-1,-1/2), (0,0), (2,1). Column 0 products/partials remain -1,0,-2 / -1,-1,-3. Column 1 products are -1/2,0,-1, with partial sums -1/2,-1/2,-3/2. Its output is (-3,-3/2).

QuantityGlobal scalingPer-output scaling
Row-major total weight differences0, 1/2, -1/2, -1/4, 0, 00, 0, -1/2, -1/4, 0, 0
Weight squares0, 1/4, 1/4, 1/16, 0, 00, 0, 1/4, 1/16, 0, 0
Weight SSE9/165/16
Output differences-1, 0-1, -1/2
Output squares1, 01, 1/4
Output SSE15/4

Clipping differences are zero; quantization differences equal total differences in this intervention. Global second-column weight errors contribute (1/2) times 1 and (-1/4) times 2, which cancel. Per-output scaling removes the first contribution and leaves the second. It reduces weight SSE while increasing this input’s output SSE. At x=(1,0,0), per-output scaling instead has zero output error, while global scaling has second-coordinate error 1/2. At x=(0,0,0), both have zero output error despite changed weights. Output error depends on the input and on cancellation, not just a weight summary.

Reading the five graded questions

Answer the five questions in the lab above. The guide below explains that same set; it adds no second grader. The first four keys use their explicitly named fixed worksheets even after you edit the controls. The fifth reads all twelve saved inputs, all three saved outputs, total output SSE/maxAbs and squared-underflow flags from the current whole result, independently of the selected trace frame.

  1. Vocabulary: what does a zero point do? In the named default global example, explain how unsigned code 0 represents -1. Answer: s(q-z)=1(0-1)=-1. If you answered that unsigned codes imply nonnegative weights, subtract z before interpreting the weight. If you called z an output bias, revisit its application to each weight.

  2. Shape and arithmetic: follow one connection. In the named default, find the code and reconstruction of W[1,1]=1/2, then the three products for output column 1. Answer: v=1/2, r=0, u=q=1, k=0 and reconstructed weight 0; products are 0,0,-1 and the output is -1. An answer of code 2 rounded after adding the odd zero point. An answer with three output coordinates confused the summed input axis with the two output columns.

  3. Two references: what did clipping change? For the named c=3/4 intervention, give the clipping, quantization and total output differences. Answer: (3/2,0), (0,0), (3/2,0). Zero error relative to the clipped matrix does not remove the change relative to the original. Use the three independently accumulated outputs rather than adding SSEs.

  4. Prediction: does per-output scaling always improve the answer? For the disclosed cancellation matrix at x=(1,2,-1), compare both SSEs. Answer: weight SSE falls from 9/16 to 5/16, while output SSE rises from 1 to 5/4. If you predicted that both improve, account for the lost cancellation in column 1. A smaller weight SSE is not a promise for every input.

  5. Transfer to the CURRENT whole saved calculation. Classify its saved total output error. Choose the first option when maxAbs is zero: the outputs agree numerically for this input. Choose the second when SSE is zero but maxAbs is positive: a nonzero residual’s square underflowed. Choose the third when SSE is positive: the stored squared-error aggregate is nonzero. Read the displayed actual SSE and underflow flags even in that third case. For the named default global root the manual anchor is 9/4 and the third option applies, but that constant is not an edited-state key. None of these conclusions proves identical weight words or model quality: signed zero, squared-error underflow and input cancellation are distinct concerns. If scale underflow makes the whole root unavailable, the lab offers no numeric answer or grader. A valid all-zero group still has its explicit saved policy.

Read the actual Python computation in dependency order

The three complete source panels below show the adjacent files used by the canonical producer. They are imported directly as text, with no excerpt or rewritten demonstration. Opening a panel does not run Python. Start with the helper’s quantization_state, _round_details and _capture_quantization functions when tracing the equations, then follow evaluate_quantization into the saved projection and the entry’s derive_iv63 into the complete result.

The helper first captures and validates all twelve inputs and the prefix. Its scalar loops clip and fit the groups, round stored quotients, assign codes and reconstruct weights. _affine independently evaluates original, clipped and reconstructed products and sums; _error_family computes the six direct error families. The reconstructed output is actually written through generic support’s indexed NumPy storage and read back into the ordinary two-coordinate Y before it is used by the output-error calculations. Its logical public shape is [2]; the storage helper’s internal array is [1,1,2]. NumPy performs storage here, not a matrix contraction.

On success, every private scalar capture and storage-derived copy is completed before _project_frames and _project_success copy saved values into public records. Only then does _flush call the supplied collector. The public callbacks therefore describe saved operations after private computation; they are not callbacks interleaved with each multiplication. The helper’s output is the very same saved reconstructed_Y tensor present in its tensors list. Projection performs no floating-point recomputation or native elementary calls.

On the known nonzero-span/zero-scale failure, the current source retains the stopped private captures, projects only that actual prefix, flushes it and rethrows the same owned fault. No reconstructed output, NumPy storage or later error work is invented. An unknown observer exception can interrupt the flush and propagates unchanged. This trusted helper-collector behavior is distinct from the chapter’s whole-result boundary: derive_iv63 and the browser’s deriveIV63 return only unavailable status, code and reason for a known fault, so the lab exposes no private prefix, numeric fallback or grades.

The entry supplies the default or a full replacement input, strict finite JSON parsing and the complete saved result. Its self-check path is explicit; imports and ordinary production queries do not invoke checks. No Python, parity, self-check or browser result is claimed here.

1. Generic support: decoder_reference.py

Only the generic fault, immutable-copy, prefix, trace and indexed-storage facilities support this quantizer. This complete support file also contains IV-59 decoder mathematics and its checks; those tasks are not invoked by IV-63.

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. Scalar quantizer and saved projection: quantization_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.

"""IV63 independent scalar FIRST with owner-adopted saved-only public binding.

Source only; every check is UNRUN. No producer/oracle source supplied this graph.
NumPy stores the actual reconstructed output, consumed before saved projection.
"""
import importlib.util
import math
from pathlib import Path
import sys
from types import FunctionType, ModuleType


# Cache certificates retain actual objects and code, never just a completion flag.
def _module_identity(module, path):
    if type(module) is not ModuleType:
        raise ImportError("Unknown IV63 owned module identity.")
    namespace = module.__dict__
    certificate = namespace.get("_IV63_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 str(Path(certificate[5].origin).resolve()) != path):
        raise ImportError("Unknown or incomplete IV63 owned source identity.")
    for name, function, code in certificate[2]:
        owner, dot, member = name.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("IV63 owned function identity changed.")
    for name, dependency in certificate[3]:
        if name not in sys.modules or sys.modules[name] is not dependency:
            raise ImportError("IV63 dependency cache identity changed.")
    for name, owned_object in certificate[4]:
        if namespace.get(name) is not owned_object:
            raise ImportError("IV63 owned dependency alias changed.")
    return module


def _load_support():
    name = "_book_iv63_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("IV63 support identity appeared during specification creation.")
    if spec is None or spec.loader is None:
        raise ImportError("Cannot load adjacent generic59 source.")
    # Creation itself can install an incumbent: inspect again BEFORE staging.
    staged = importlib.util.module_from_spec(spec)
    if name in sys.modules:
        raise ImportError("IV63 support identity appeared during creation.")
    transaction = globals().get("_IV63_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("IV63 support identity 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", "NumericalFault", "_FrozenDict", "_FrozenList", "_PublicTrace"))
        staged._IV63_CERTIFICATE = (staged, path, functions, (("numpy", staged.np),), 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
quantization_trace = _support.decoder_trace
DEFAULT_IV63 = _freeze(dict(bits=2, mode=0, clip=2.0, w00=-1.0, w01=0.25,
                           w10=0.0, w11=0.5, w20=2.0, w21=0.75,
                           x0=1.0, x1=2.0, x2=-1.0))
_FIELDS = tuple(DEFAULT_IV63)
_COUNT_FIELDS = ("clipped", "saturated", "lowEndpoint", "highEndpoint", "zeroPointCode")
_SCALE_UNDERFLOW = "A nonzero calibration span produced a zero scale; choose a larger span or fewer bits."


def _finite(value, label):
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", label + " must be finite.")
    return value


def quantization_state(value):
    """Capture all own built-in data before finite checks, then 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) != len(_FIELDS) 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 finite.")
    for key, item in captured.items():
        if key == "bits":
            if item not in (2, 3, 4, 8):
                raise NumericalFault("INVALID_INPUT", "bits must be an integer in {2,3,4,8}.")
        elif key == "mode":
            if item not in (0, 1):
                raise NumericalFault("INVALID_INPUT", "mode must be an integer in {0,1}.")
        else:
            lower, upper = (0.25, 4) if key == "clip" else (-4, 4)
            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 ("bits", "mode") else float(captured[key])
                    for key in _FIELDS})


def _round_details(value):
    if (type(value) not in (int, float)
            or not -1.7976931348623157e308 <= value <= 1.7976931348623157e308):
        raise NumericalFault("NONFINITE", "roundTiesToEven input must be finite.")
    if not -512 <= value <= 512:
        raise NumericalFault("INVALID_INPUT", "roundTiesToEven input must be between -512 and 512.")
    lower = math.floor(value)
    fraction = value - lower
    if fraction < 0.5:
        rounded = lower
    elif fraction > 0.5:
        rounded = lower + 1
    else:
        rounded = lower if lower % 2 == 0 else lower + 1
    return dict(lower=lower, fraction=fraction, halfway=int(fraction == 0.5), rounded=rounded)


def round_ties_to_even(value):
    return _round_details(value)["rounded"]


def _minimum(left, right):
    if left == 0.0 and right == 0.0:
        return -0.0 if math.copysign(1.0, left) < 0 or math.copysign(1.0, right) < 0 else 0.0
    return left if left < right else right


def _maximum(left, right):
    if left == 0.0 and right == 0.0:
        return 0.0 if math.copysign(1.0, left) > 0 or math.copysign(1.0, right) > 0 else -0.0
    return left if left > right else right


class _Capture:
    """Private scalar tuples, deliberately without public IDs or metadata."""
    def __init__(self):
        self.operations = []
        self.fault = None

    def add(self, stage, inputs, outputs):
        before, after = dict(inputs), dict(outputs)
        for record in (before, after):
            for key, item in record.items():
                if type(key) is not str or type(item) not in (int, float):
                    raise TypeError("Private IV63 captures require numeric scalar data.")
                _finite(item, stage + "/" + key)
        self.operations.append((stage, _freeze(before), _freeze(after)))


def _affine(weights, x, capture, stage):
    products, partials, output = [None] * 6, [None] * 6, []
    for column in range(2):
        running = 0.0
        for row in range(3):
            previous = running
            weight = weights[2 * row + column]
            product = _finite(x[row] * weight, "affine product")
            running = _finite(previous + product, "affine partial")
            products[2 * row + column] = product
            partials[2 * row + column] = running
            capture.add(stage, dict(row=row, column=column, x=x[row], weight=weight, previous=previous),
                        dict(product=product, running=running))
        output.append(running)
    return dict(products=products, partials=partials, output=output)


def _error_family(reference, measured, capture, stage):
    differences, squares, absolutes, partials, maxima, underflows = [], [], [], [], [], []
    sse, max_abs = 0.0, 0.0
    for index in range(len(reference)):
        difference = _finite(measured[index] - reference[index], "error difference")
        square = _finite(difference * difference, "error square")
        absolute = abs(difference)
        previous, previous_max = sse, max_abs
        sse = _finite(previous + square, "error SSE")
        max_abs = _maximum(previous_max, absolute)
        underflow = int(difference != 0.0 and square == 0.0)
        differences.append(difference)
        squares.append(square)
        absolutes.append(absolute)
        partials.append(sse)
        maxima.append(max_abs)
        underflows.append(underflow)
        capture.add(stage, dict(index=index, reference=reference[index], measured=measured[index],
                                previous=previous, previousMax=previous_max),
                    dict(difference=difference, square=square, absolute=absolute, sse=sse,
                         maxAbs=max_abs, squareUnderflow=underflow))
    return dict(differences=differences, squares=squares, absolutes=absolutes,
                partials=partials, maxima=maxima, squareUnderflows=underflows, sse=sse, maxAbs=max_abs)


def _capture_quantization(value, prefix, capture=None):
    """All private arithmetic, storage and saved copies precede any observer."""
    state = quantization_state(value)
    _support._prefix(prefix)
    if capture is None:
        capture = _Capture()
    weights = [state[key] for key in _FIELDS[3:9]]
    x = [state[key] for key in _FIELDS[9:]]
    qmax = 2 ** state["bits"] - 1
    groups = (tuple(range(6)),) if state["mode"] == 0 else ((0, 2, 4), (1, 3, 5))
    counts = [0, 0, 0, 0, 0]
    capture.add("inputs", state, dict(Q=qmax, groups=len(groups)))
    clipped, clipping = [], []
    for index, weight in enumerate(weights):
        inner = _minimum(state["clip"], weight)
        result = _maximum(-state["clip"], inner)
        changed = int(weight < -state["clip"] or weight > state["clip"])
        clipped.append(result)
        clipping.append(changed)
        capture.add("clip", dict(index=index, weight=weight, clip=state["clip"], inner=inner),
                    dict(clipped=result, clipping=changed))
    fits, cells = [], [None] * 6
    codes, reconstructed = [None] * 6, [None] * 6
    for group, indices in enumerate(groups):
        group_counts = [0, 0, 0, 0, 0]
        lower, upper = 0.0, 0.0
        for index in indices:
            previous_lower, previous_upper = lower, upper
            lower = _minimum(lower, clipped[index])
            upper = _maximum(upper, clipped[index])
            capture.add("fit", dict(group=group, index=index, clipped=clipped[index],
                                    previousLower=previous_lower, previousUpper=previous_upper),
                        dict(lower=lower, upper=upper))
        span = _finite(upper - lower, "calibration span")
        capture.add("span", dict(group=group, lower=lower, upper=upper), dict(span=span, zeroGroup=int(span == 0.0)))
        if span == 0.0:
            fits.append(dict(group=group, indices=indices, lower=lower, upper=upper, span=span,
                             zeroGroup=1, scale=1.0, zeroPoint=0, counts=group_counts,
                             omitted="No scale division, zero-ratio rounding, cell division or arithmetic dequantization in the all-zero policy branch."))
            capture.add("zero_policy", dict(group=group, lower=lower, upper=upper, span=span), dict(scale=1.0, zeroPoint=0))
            for index in indices:
                codes[index], reconstructed[index] = 0, 0.0
                cells[index] = dict(group=group, index=index, clipped=clipped[index],
                                    zeroGroup=1, code=0, reconstructed=0.0, saturation=0,
                                    lowEndpoint=1, highEndpoint=0, zeroPointCode=1)
                capture.add("zero_cell_policy", dict(group=group, index=index, clipped=clipped[index]),
                            dict(code=0, reconstructed=0.0, saturation=0,
                                 lowEndpoint=1, highEndpoint=0, zeroPointCode=1))
                for k, decision in enumerate((clipping[index], 0, 1, 0, 1)):
                    group_counts[k] += decision
                    counts[k] += decision
            capture.add("group_counts", dict(group=group, cells=len(indices)), dict(zip(_COUNT_FIELDS, group_counts)))
            continue
        scale = _finite(span / qmax, "calibration scale")
        capture.add("scale", dict(group=group, span=span, qmax=qmax), dict(scale=scale))
        if scale == 0.0:
            capture.fault = NumericalFault("UNAVAILABLE", _SCALE_UNDERFLOW)
            raise capture.fault
        negative_lower = -lower
        ratio = _finite(negative_lower / scale, "zero-point quotient")
        zero_round = _round_details(ratio)
        rounded_zero = zero_round["rounded"]
        zero_point = max(0, min(qmax, rounded_zero))
        fits.append(dict(group=group, indices=indices, lower=lower, upper=upper, span=span,
                         zeroGroup=0, scale=scale, negativeLower=negative_lower, zeroRatio=ratio,
                         zeroFloor=zero_round["lower"], zeroFraction=zero_round["fraction"],
                         zeroHalfway=zero_round["halfway"], roundedZero=rounded_zero, zeroPoint=zero_point,
                         counts=group_counts))
        capture.add("zero_point", dict(group=group, lower=lower, negativeLower=negative_lower,
                                       scale=scale, qmax=qmax),
                    dict(ratio=ratio, floor=zero_round["lower"], fraction=zero_round["fraction"],
                         halfway=zero_round["halfway"], rounded=rounded_zero, zeroPoint=zero_point))
        for index in indices:
            scaled = _finite(clipped[index] / scale, "weight quotient")
            cell_round = _round_details(scaled)
            rounded = cell_round["rounded"]
            candidate = rounded + zero_point
            code = max(0, min(qmax, candidate))
            centered = code - zero_point
            result = _finite(centered * scale, "reconstructed weight")
            saturation = int(candidate < 0 or candidate > qmax)
            low_endpoint, high_endpoint, zero_code = int(code == 0), int(code == qmax), int(code == zero_point)
            codes[index], reconstructed[index] = code, result
            cells[index] = dict(group=group, index=index, clipped=clipped[index], zeroGroup=0,
                                scaled=scaled, floor=cell_round["lower"], fraction=cell_round["fraction"],
                                halfway=cell_round["halfway"], rounded=rounded, candidate=candidate, code=code,
                                centered=centered, reconstructed=result, saturation=saturation,
                                lowEndpoint=low_endpoint, highEndpoint=high_endpoint, zeroPointCode=zero_code)
            capture.add("cell", dict(group=group, index=index, clipped=clipped[index], scale=scale,
                                     zeroPoint=zero_point, qmax=qmax),
                        dict(scaled=scaled, floor=cell_round["lower"], fraction=cell_round["fraction"],
                             halfway=cell_round["halfway"], rounded=rounded, candidate=candidate, code=code,
                             centered=centered, reconstructed=result, saturation=saturation,
                             lowEndpoint=low_endpoint, highEndpoint=high_endpoint, zeroPointCode=zero_code))
            for k, decision in enumerate((clipping[index], saturation, low_endpoint, high_endpoint, zero_code)):
                group_counts[k] += decision
                counts[k] += decision
        capture.add("group_counts", dict(group=group, cells=len(indices)), dict(zip(_COUNT_FIELDS, group_counts)))
    capture.add("counts", dict(cells=6, groups=len(groups)), dict(zip(_COUNT_FIELDS, counts)))
    original = _affine(weights, x, capture, "original_affine")
    clipped_path = _affine(clipped, x, capture, "clipped_affine")
    rebuilt = _affine(reconstructed, x, capture, "reconstructed_affine")
    # Ordinary Y is read from actual indexed binary64 storage, not a decorative copy.
    stored = _support._storage(rebuilt["output"], 1, 2)
    rebuilt["output"] = [float(stored[0, 0, column]) for column in range(2)]
    weight_errors, output_errors = {}, {}
    for name, before, after in (("clipping", weights, clipped),
                                ("quantization", clipped, reconstructed),
                                ("total", weights, reconstructed)):
        weight_errors[name] = _error_family(before, after, capture, "weight_" + name)
    for name, before, after in (("clipping", original["output"], clipped_path["output"]),
                                ("quantization", clipped_path["output"], rebuilt["output"]),
                                ("total", original["output"], rebuilt["output"])):
        output_errors[name] = _error_family(before, after, capture, "output_" + name)
    return _freeze(dict(state=state, weights=weights, x=x, qmax=qmax, clipped=clipped,
                        clipping=clipping, fits=fits, cells=cells, codes=codes,
                        reconstructed=reconstructed, counts=counts, original=original, clippedPath=clipped_path,
                        rebuilt=rebuilt, weightErrors=weight_errors, outputErrors=output_errors,
                        operations=capture.operations))


def evaluate_quantization(value, trace, prefix):
    """Capture/storage, then complete saved projection, then public callbacks."""
    capture = _Capture()
    try:
        mechanism = _capture_quantization(value, prefix, capture)
    except NumericalFault as error:
        if type(error) is not NumericalFault or capture.fault is not error:
            raise
        frames = _project_frames(capture.operations, prefix)
        _flush(trace, frames)
        raise
    frames = _project_frames(mechanism["operations"], prefix)
    result = _project_success(mechanism, prefix)
    _flush(trace, frames)
    return result


def _project_frames(operations, prefix):
    """Only names, literal metadata and saved scalar copies; no float replay."""
    frames = []
    for stage, before, after in operations:
        if stage == "inputs":
            identifier = prefix + "_inputs"
            label = "Capture all twelve validated raw controls"
            equation = "Q=2**bits-1; groups=(mode==0?1:2)"
            explanation = "All own data descriptors, then all finite operands, then all domains and finally the ASCII prefix were checked before this first frame. Weights use InputFeature,OutputFeature row storage."
            inputs, outputs = dict(before), dict(after)
        elif stage == "clip":
            cell = before["index"]
            identifier, label = f"{prefix}_clip_{cell}", f"Clip weight cell {cell}"
            equation = "clipped=max(-clip,min(clip,original)); clippedFlag=(original<-clip||original>clip)"
            explanation = "Compare the original operand with the strict symmetric bounds. Equality is not clipping; preserve the original and selected clipped WORD including -0."
            inputs = dict(cell=cell, original=before["weight"], clip=before["clip"])
            outputs = dict(clipped=after["clipped"], clippedFlag=after["clipping"])
        elif stage in ("fit", "span", "scale", "zero_policy", "zero_point", "zero_cell_policy", "cell", "group_counts"):
            group = before["group"]
            gp = f"{prefix}_g{group}"
            if stage == "fit":
                cell = before["index"]
                identifier, label = f"{gp}_fit_{cell}", f"Group {group}: include cell {cell} in calibration"
                equation = "lower=min(previousLower,clipped); upper=max(previousUpper,clipped)"
                explanation = "Both fit bounds start at literal +0 and visit group cells in input/row-major order. The lower bound can retain -0 while the upper is +0."
                inputs = dict(group=group, cell=cell, previousLower=before["previousLower"], previousUpper=before["previousUpper"], clipped=before["clipped"])
                outputs = dict(after)
            elif stage == "span":
                identifier, label = gp + "_span", f"Group {group}: classify the actual span"
                equation = "span=upper-lower; zeroGroup=(span==0)"
                explanation = "Including zero makes span zero exactly for a clipped all-zero group. A positive span whose scale underflows is a different branch."
                inputs, outputs = dict(before), dict(after)
            elif stage == "scale":
                identifier, label = gp + "_scale", f"Group {group}: divide the nonzero span by Q"
                equation = "scale=span/Q"
                explanation = "This is the actual stored binary64 quotient. If it is zero the computation becomes unavailable before any division by this scale; no epsilon or minimum-scale repair is allowed."
                inputs = dict(group=group, span=before["span"], Q=before["qmax"])
                outputs = dict(after)
            elif stage == "zero_policy":
                identifier, label = gp + "_zero_policy", f"Group {group}: assign the explicit all-zero convention"
                equation = "policy: scale=1; zeroPoint=0"
                explanation = "These are assigned policy values, not a division or integer-rounding result. Uncomputed arithmetic tensors are omitted with saved reasons."
                inputs, outputs = dict(before), dict(after)
            elif stage == "zero_point":
                identifier, label = gp + "_zero_point", f"Group {group}: round the stored zero-point quotient"
                equation = "negativeLower=-lower; zeroRatio=negativeLower/scale; roundedZero=RNE(zeroRatio); zeroPoint=max(0,min(Q,roundedZero))"
                explanation = "Integer nearest-even acts on the stored binary64 division result. Zero point and rounding decisions are small exact integers; the operand WORD signs are retained."
                inputs = dict(group=group, lower=before["lower"], scale=before["scale"], Q=before["qmax"])
                outputs = dict(negativeLower=before["negativeLower"], zeroRatio=after["ratio"], roundedZero=after["rounded"], zeroPoint=after["zeroPoint"])
            elif stage == "zero_cell_policy":
                cell = before["index"]
                identifier, label = f"{gp}_policy_{cell}", f"Group {group}: assign zero policy at cell {cell}"
                equation = "policy: code=0; reconstructed=+0; saturated=0; lowEndpoint=1; highEndpoint=0; zeroPointCode=1"
                explanation = "The clipped cell is numerically zero. Code, reconstruction and decisions are assigned by the explicit policy; no scaled quotient, rounded integer, centered subtraction or dequantization product is claimed."
                inputs = dict(group=group, cell=cell, clipped=before["clipped"])
                outputs = dict(code=after["code"], reconstructed=after["reconstructed"], saturated=after["saturation"], lowEndpoint=after["lowEndpoint"], highEndpoint=after["highEndpoint"], zeroPointCode=after["zeroPointCode"])
            elif stage == "cell":
                cell = before["index"]
                identifier, label = f"{gp}_quantize_{cell}", f"Group {group}: quantize cell {cell} using its stored quotient"
                equation = "scaled=clipped/scale; rounded=RNE(scaled); candidate=rounded+zeroPoint; code=max(0,min(Q,candidate)); centered=code-zeroPoint; reconstructed=centered*scale"
                explanation = "Round before adding the zero point, including negative halfway values. Strict candidate saturation differs from code endpoint occupancy. Reconstruction is this actual binary64 product."
                inputs = dict(group=group, cell=cell, clipped=before["clipped"], scale=before["scale"], zeroPoint=before["zeroPoint"], Q=before["qmax"])
                outputs = {key: after[key] for key in ("scaled", "rounded", "candidate", "code", "centered", "reconstructed")}
                outputs.update(saturated=after["saturation"], lowEndpoint=after["lowEndpoint"], highEndpoint=after["highEndpoint"], zeroPointCode=after["zeroPointCode"])
            else:
                identifier, label = gp + "_counts", f"Group {group}: save the five decision counts"
                equation = "counts=sum(each actual cell decision in this group)"
                explanation = "Each decision is counted from its actual current cell; clipping, strict saturation and endpoint/zero-point occupancy remain distinct."
                inputs, outputs = dict(before), dict(after)
        elif stage == "counts":
            identifier, label = prefix + "_counts", "Save whole-tensor decision counts"
            equation = "counts=sum(each actual cell decision across groups)"
            explanation = "These exact source decisions describe this quantizer, not measured hardware or model quality."
            inputs, outputs = dict(before), dict(after)
        elif stage in ("original_affine", "clipped_affine", "reconstructed_affine"):
            path, row, column = stage.removesuffix("_affine"), before["row"], before["column"]
            identifier, label = f"{prefix}_{path}_{row}_{column}", f"{path}: input {row} contributes to output {column}"
            equation = "product=x*weight; partial=previous+product"
            explanation = "Compute this binary64 product, then add to the saved running sum. Visit output features 0,1 and input features 0,1,2; include every zero product."
            inputs = dict(inputFeature=row, outputFeature=column, x=before["x"], weight=before["weight"], previous=before["previous"])
            outputs = dict(product=after["product"], partial=after["running"])
        elif stage in ("weight_clipping", "weight_quantization", "weight_total", "output_clipping", "output_quantization", "output_total"):
            cell = before["index"]
            identifier, label = f"{prefix}_{stage}_{cell}", f"Error cell {cell}: direct difference and independent reductions"
            equation = "difference=actual-reference; square=difference*difference; SSE=previousSSE+square; maxAbs=max(previousMaxAbs,abs(difference))"
            explanation = "Retain the original signed residual even if its square underflows. Every error family has its own subtraction, square, ordered +0 SSE fold and +0 maximum fold; no component sums manufacture total error."
            inputs = dict(cell=cell, reference=before["reference"], actual=before["measured"], previousSSE=before["previous"], previousMaxAbs=before["previousMax"])
            outputs = dict(difference=after["difference"], square=after["square"], absolute=after["absolute"], squaredUnderflow=after["squareUnderflow"], sse=after["sse"], maxAbs=after["maxAbs"])
        else:
            raise RuntimeError("Unknown private IV63 capture stage.")
        frames.append(dict(id=identifier, label=label, equation=equation, explanation=explanation, inputs=inputs, outputs=outputs))
    return _freeze(frames)


def _flush(trace, frames):
    for frame in frames:
        trace.add(frame["id"], frame["label"], frame["equation"], frame["explanation"], frame["inputs"], frame["outputs"])


def _tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    # Only fixed internal shapes and already guarded captures reach this copier.
    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 _project_success(mechanism, prefix):
    """Complete tensor/text projection uses saved operands, never arithmetic."""
    state, x = mechanism["state"], mechanism["x"]
    axes = ["InputFeature", "OutputFeature"]
    tensors = [
        _tensor(prefix + "_Raw", [12], ["RawField"], [state[key] for key in _FIELDS], "Captured raw12 in declared order: bits,mode VALUE; clip,all six weights,all three inputs WORD including -0."),
        _tensor(prefix + "_X", [3], ["InputFeature"], x, "Actual captured x0,x1,x2 words; one row-feature input, no bias."),
        _tensor(prefix + "_WOriginal", [3, 2], axes, mechanism["weights"], "All six captured original weight words in w00,w01,w10,w11,w20,w21 row-major order; explicit transpose of column-weight notation."),
        _tensor(prefix + "_WClipped", [3, 2], axes, mechanism["clipped"], "Actual max(-clip,min(clip,w)) selections before calibration; original W remains unchanged."),
        _tensor(prefix + "_ClipFlags", [3, 2], axes, mechanism["clipping"], "Strict original<-clip or original>clip decisions; endpoints equal to clip are not clipped.", "int32"),
        _tensor(prefix + "_CellGroups", [3, 2], axes, [cell["group"] for cell in mechanism["cells"]], "Global mode maps all cells to group0; per-output mode maps output feature j to group j.", "int32"),
    ]
    policies, uncomputed = [], []
    for fit in mechanism["fits"]:
        group, members = fit["group"], fit["indices"]
        gp, count = f"{prefix}_g{group}", len(members)
        fit_steps = [(before, after) for stage, before, after in mechanism["operations"] if stage == "fit" and before["group"] == group]
        tensors.extend([
            _tensor(gp + "_Members", [count], ["GroupCell"], members, "Actual row-major weight-cell indices in this calibration group, in fit and quantization visit order.", "int32"),
            _tensor(gp + "_FitOperands", [count + 1], ["FitOperand"], [fit_steps[0][0]["previousLower"]] + [mechanism["clipped"][cell] for cell in members], "Literal +0 followed by the actual clipped group words used by both ordered fit folds."),
            _tensor(gp + "_FitPartials", [count, 2], ["GroupCell", "FitBound"], [after[key] for before, after in fit_steps for key in ("lower", "upper")], "Actual lower,upper after each group member; retain lower -0 and upper +0 as produced."),
            _tensor(gp + "_Calibration", [4], ["CalibrationField"], [fit[key] for key in ("lower", "upper", "span", "scale")], "Saved lower,upper,span,scale WORDs. For a zero group scale=1 is an explicit assigned policy, not a division result."),
            _tensor(gp + "_ZeroGroup", [1], ["Scalar"], [fit["zeroGroup"]], "Decision 1 for span==0, otherwise 0; this does not classify a positive-span zero-scale fault as a zero group.", "int32"),
            _tensor(gp + "_ZeroPoint", [1], ["Scalar"], [fit["zeroPoint"]], "Saved integer zero point; assigned 0 for a zero group, otherwise clamped actual RNE((-lower)/scale).", "int32"),
        ])
        if fit["zeroGroup"] == 1:
            policies.append(gp + ": all-zero policy; scale=1, zeroPoint=0, codes=0, reconstructed=+0 assigned; no scale division, zero-point division/RNE, cell division/RNE or arithmetic dequantization executed.")
            for suffix in ("ZeroPointOperands", "RoundedZero", "Scaled", "IntegerStages"):
                uncomputed.append(f"{gp}_{suffix}: omitted because this all-zero group assigns policy values without the corresponding arithmetic.")
        else:
            policies.append(gp + ": nonzero calibration; actual span/Q, (-lower)/scale, integer nearest-even then zero-point clamp; every cell divides by the stored scale, rounds before adding zeroPoint, clamps, centers and multiplies.")
            tensors.extend([
                _tensor(gp + "_ZeroPointOperands", [2], ["ZeroPointOperand"], [fit["negativeLower"], fit["zeroRatio"]], "Actual unary -lower and stored (-lower)/scale operands; no ideal rational quotient substitution."),
                _tensor(gp + "_RoundedZero", [1], ["Scalar"], [fit["roundedZero"]], "Actual nearest-even integer decision on the stored zero-point quotient, before clamping.", "int32"),
                _tensor(gp + "_Scaled", [count], ["GroupCell"], [mechanism["cells"][cell]["scaled"] for cell in members], "Actual clipped/scale binary64 quotient for each listed group member, before integer RNE."),
                _tensor(gp + "_IntegerStages", [count, 4], ["GroupCell", "IntegerStage"], [mechanism["cells"][cell][key] for cell in members for key in ("rounded", "candidate", "code", "centered")], "Actual rounded,candidate,code,centered integer decisions for each listed group member; RNE precedes zero-point addition.", "int32"),
            ])
        tensors.append(_tensor(gp + "_Counts", [5], ["CountField"], fit["counts"], "Independently accumulated group counts: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode; occupancy does not imply saturation.", "int32"))
    tensors.extend([
        _tensor(prefix + "_Codes", [3, 2], axes, mechanism["codes"], "Actual code integers restored to original row-major weight order; ordinary int32 records, not packed b-bit allocations.", "int32"),
        _tensor(prefix + "_WReconstructed", [3, 2], axes, mechanism["reconstructed"], "Actual centered*scale words for nonzero groups; explicit policy +0 for zero groups, restored to original weight order."),
        _tensor(prefix + "_CodeFlags", [3, 2, 4], axes + ["CodeDecision"], [cell[key] for cell in mechanism["cells"] for key in ("saturation", "lowEndpoint", "highEndpoint", "zeroPointCode")], "Per-cell saturated,lowEndpoint,highEndpoint,zeroPointCode flags; zero policy assigns 0,1,0,1.", "int32"),
        _tensor(prefix + "_Counts", [5], ["CountField"], mechanism["counts"], "Actual whole-tensor counts independently accumulated from cell decisions: clipped,saturated,lowEndpoint,highEndpoint,zeroPointCode.", "int32"),
    ])
    for path, key in (("original", "original"), ("clipped", "clippedPath"), ("reconstructed", "rebuilt")):
        saved = mechanism[key]
        pp = f"{prefix}_{path}"
        tensors.extend([
            _tensor(pp + "_Products", [3, 2], axes, saved["products"], "Actual x_i*weight_ij products, stored row-major; computation visits output feature then input feature."),
            _tensor(pp + "_Partials", [3, 2], axes, saved["partials"], "Actual running binary64 sums after each product; each output starts from literal +0."),
            _tensor(pp + "_Y", [2], ["OutputFeature"], saved["output"], "Actual independently accumulated xW output for this path; no bias, FMA, reassociation or error-based reconstruction."),
        ])
    output_index = len(tensors) - 1
    for kind, families, shape, names in (("weight", mechanism["weightErrors"], [3, 2], axes), ("output", mechanism["outputErrors"], [2], ["OutputFeature"])):
        for family in ("clipping", "quantization", "total"):
            saved, ep = families[family], f"{prefix}_{kind}_{family}"
            partials = [entry for pair in zip(saved["partials"], saved["maxima"]) for entry in pair]
            tensors.extend([
                _tensor(ep + "_Difference", shape, names, saved["differences"], "Actual direct actual-reference binary64 differences, preserving signed zero; not a sum of rounded component differences."),
                _tensor(ep + "_Squares", shape, names, saved["squares"], "Actual difference*difference binary64 products; zero squares can conceal nonzero residuals."),
                _tensor(ep + "_Absolute", shape, names, saved["absolutes"], "Actual Math.abs of each saved difference, in the original weight or output units."),
                _tensor(ep + "_SquaredUnderflow", shape, names, saved["squareUnderflows"], "Flag 1 exactly when difference!=0 and its actual rounded square==0; otherwise 0.", "int32"),
                _tensor(ep + "_ReductionPartials", [len(saved["differences"]), 2], ["ErrorCell", "ReductionField"], partials, "Actual running SSE,maxAbs after each cell in row-major weight or increasing output-feature order, from literal +0,+0."),
                _tensor(ep + "_Summary", [2], ["ReductionField"], [saved["sse"], saved["maxAbs"]], "Saved SSE,maxAbs; SSE has squared weight/output units and maxAbs has the original corresponding units. No square root or relative-error denominator."),
            ])
    texts = dict(
        rawFields=list(_FIELDS), weightFields=list(_FIELDS[3:9]), modeNames=["perTensor", "perOutputChannel"],
        fitBoundFields=["lower", "upper"], calibrationFields=["lower", "upper", "span", "scale"], zeroPointOperandFields=["negativeLower", "zeroRatio"],
        integerStageFields=["rounded", "candidate", "code", "centered"], codeDecisionFields=["saturated", "lowEndpoint", "highEndpoint", "zeroPointCode"], countFields=list(_COUNT_FIELDS),
        affinePaths=["original", "clipped", "reconstructed"], errorFamilies=["clipping", "quantization", "total"], reductionFields=["sse", "maxAbs"], groupPolicies=policies, uncomputed=uncomputed,
        rawPolicy="Exactly twelve own data descriptors are captured before all finite guards, all finite guards before any domains, then prefix last; no coercion, getters, merge or reread. bits/mode are VALUE; all ten remaining raw floats and their copies are WORD including -0.",
        roundingPolicy="Actual stored binary64 quotient first; nearest represented integer with exact ties to even, including negative halves; integer zero canonical +0. Never Math.round, epsilon, decimal preprocessing or RNE(scaled+zeroPoint). Public RNE input bound [-512,512].",
        zeroPolicy="Zero span assigns scale1,zeroPoint0,codes0,reconstructed+0 without fictitious division/RNE/dequantization arithmetic. Per-group absent tensors and reasons are saved in uncomputed. A nonzero span producing scale0 throws UNAVAILABLE before division by that scale.",
        arithmeticPolicy="All floating arithmetic is separately binary64 RN-even with gradual underflow. Three complete affine paths independently compute every product then ordered +0 accumulation; all cell/feature orders and WORD signs are retained. No native elementary calls.",
        errorPolicy="Three direct weight differences and three direct output differences each own their squares, absolutes, underflow flags and ordered SSE/maxAbs reductions. SSE uses squared units, maxAbs original units. No sqrt, relative norm, tolerance or inferred total from components; SSE0 is numeric zero, not WORD identity.",
        limitsPolicy="Isolated authored weight-only affine xW toy, not a quantized transformer, training run, integer hardware kernel or packed allocation. No speed, RAM, latency, throughput, quality, perplexity or deployment claim. No model/API/download or hidden computation.",
    )
    saved = _freeze(dict(state=state, tensors=tensors, texts=texts))
    return _support._FrozenDict(dict(state=saved["state"], output=saved["tensors"][output_index], tensors=saved["tensors"], texts=saved["texts"]))


def check_mechanism():
    if not __debug__:
        raise RuntimeError("Explicit IV63 mechanism check refuses optimized Python (-O).")
    import struct
    for value, expected in ((-2.5, -2), (-1.5, -2), (-0.5, 0), (0.5, 0), (1.5, 2), (2.5, 2),
                            (-0.5000000000000001, -1), (-0.49999999999999994, 0),
                            (0.49999999999999994, 0), (0.5000000000000001, 1), (-512, -512), (512, 512)):
        assert round_ties_to_even(value) == expected
    assert type(round_ties_to_even(-0.5)) is int
    default = dict(DEFAULT_IV63)
    result = _capture_quantization(default, "first")
    assert result["codes"] == [0, 1, 1, 1, 3, 2]
    assert result["reconstructed"] == [-1, 0, 0, 0, 2, 1]
    assert result["original"]["output"] == [-3, 0.5]
    assert result["rebuilt"]["output"] == [-3, -1]
    assert result["weightErrors"]["total"]["sse"] == 0.375
    assert result["outputErrors"]["total"]["sse"] == 2.25
    assert result["weightErrors"]["total"]["maxAbs"] == 0.5
    assert result["outputErrors"]["total"]["maxAbs"] == 1.5
    channel = _capture_quantization(dict(default, mode=1), "channel")
    assert channel["weightErrors"]["total"]["sse"] == 0.0
    assert channel["rebuilt"]["output"] == [-3, 0.5]
    zero = dict(default, mode=1, **{key: -0.0 for key in _FIELDS[3:9]})
    result = _capture_quantization(zero, "zero")
    assert all(fit["zeroGroup"] == 1 for fit in result["fits"])
    assert all("zeroRatio" not in fit for fit in result["fits"])
    assert all("scaled" not in cell for cell in result["cells"])
    assert struct.pack(">d", result["fits"][0]["lower"]) == struct.pack(">d", -0.0)
    assert struct.pack(">d", result["fits"][0]["upper"]) == struct.pack(">d", 0.0)
    assert all(struct.pack(">d", value) == struct.pack(">d", 0.0) for value in result["reconstructed"])
    saturation = dict(default, mode=1, w00=-1.5, w10=0.0, w20=1.5,
                      w01=0.0, w11=0.0, w21=0.0, x0=1.0, x1=1.0, x2=1.0)
    result = _capture_quantization(saturation, "saturation")
    assert result["reconstructed"] == [-2, 0, 0, 0, 1, 0]
    assert [cell["saturation"] for cell in result["cells"]] == [0, 0, 0, 0, 1, 0]
    assert result["rebuilt"]["output"] == [-1, 0]
    assert result["fits"][1]["zeroGroup"] == 1
    clipped = _capture_quantization(dict(saturation, clip=1.5, w20=2.0), "clipped")
    assert clipped["clipping"] == [0, 0, 0, 0, 1, 0]
    assert clipped["original"]["output"] == [0.5, 0]
    assert clipped["clippedPath"]["output"] == [0, 0]
    assert clipped["rebuilt"]["output"] == [-1, 0]
    assert clipped["outputErrors"]["clipping"]["differences"] == [-0.5, 0]
    assert clipped["outputErrors"]["quantization"]["differences"] == [-1, 0]
    assert clipped["outputErrors"]["total"]["differences"] == [-1.5, 0]
    cancellation = dict(default, w00=-1.0, w01=-0.5, w10=0.5, w11=0.25, w20=2.0, w21=1.0)
    global_result = _capture_quantization(cancellation, "global")
    channel_result = _capture_quantization(dict(cancellation, mode=1), "channels")
    assert global_result["weightErrors"]["total"]["sse"] == 0.5625
    assert channel_result["weightErrors"]["total"]["sse"] == 0.3125
    assert global_result["outputErrors"]["total"]["sse"] == 1.0
    assert channel_result["outputErrors"]["total"]["sse"] == 1.25
    boundary = dict(default, w00=0.0, w01=0.0, w10=0.9999999999999999,
                    w11=0.0, w20=2.0, w21=0.0, x0=0.0, x1=1.0, x2=0.0)
    result = _capture_quantization(boundary, "boundary")
    assert result["cells"][2]["scaled"] == 1.5
    assert result["codes"][2] == 2
    tiny = float.fromhex("0x0.0000000000001p-1022")
    try:
        _capture_quantization(dict(zero, w20=tiny), "underflow")
    except NumericalFault as error:
        assert type(error) is NumericalFault and error.code == "UNAVAILABLE" and error.reason == _SCALE_UNDERFLOW
    else:
        raise AssertionError("Nonzero scale underflow must not take the zero policy.")
    capture = _Capture()
    residual = _error_family([0.0], [tiny], capture, "tiny_error")
    assert residual["differences"] == [tiny] and residual["squares"] == [0.0]
    assert residual["squareUnderflows"] == [1]


def check_guards():
    if not __debug__:
        raise RuntimeError("Explicit IV63 guard check refuses optimized Python (-O).")
    default = dict(DEFAULT_IV63)
    for invalid in (True, "0", None, [], float("nan"), float("inf"), 10**400):
        try:
            round_ties_to_even(invalid)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == "NONFINITE" and error.reason == "roundTiesToEven input must be finite."
        else:
            raise AssertionError("RNE rejects non-numeric/nonfinite input before its domain.")
    for invalid in (-513, 513):
        try:
            round_ties_to_even(invalid)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT" and error.reason == "roundTiesToEven input must be between -512 and 512."
        else:
            raise AssertionError("RNE has an explicit bounded domain.")
    for value, code in ((dict(default, bits=0, x2=True), "NONFINITE"),
                        (dict(default, bits=0, x2=10**400), "NONFINITE"),
                        (dict(default, w21=5), "INVALID_INPUT"), ({}, "INVALID_INPUT")):
        try:
            quantization_state(value)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == code
        else:
            raise AssertionError("Expected a raw boundary fault.")
    try:
        _capture_quantization(dict(default, x2=False), "bad-prefix")
    except NumericalFault as error:
        assert error.code == "NONFINITE"
    else:
        raise AssertionError("All raw finite checks precede prefix.")
    for field in _FIELDS:
        for item in (True, "0", None, float("nan"), float("inf"), 10**400):
            try:
                quantization_state(dict(default, **{field: item}))
            except NumericalFault as error:
                assert error.code == "NONFINITE" and error.reason == f"state.{field} must be finite."
            else:
                raise AssertionError("All raw fields have actual finite guards.")
    for field, item, reason in (("bits", 2.5, "bits must be an integer in {2,3,4,8}."),
                                ("mode", 2, "mode must be an integer in {0,1}."),
                                ("clip", 0, "clip must be between 0.25 and 4."),
                                ("w00", 5, "w00 must be between -4 and 4."),
                                ("x2", -5, "x2 must be between -4 and 4.")):
        try:
            evaluate_quantization(dict(default, **{field: item}), object(), "bad-prefix")
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT" and error.reason == reason
        else:
            raise AssertionError("All domains precede prefix or observer access.")
    for prefix in ("", "0bad", "bad-prefix", "a\n", "é", None, 1):
        try:
            evaluate_quantization(default, object(), prefix)
        except NumericalFault as error:
            assert error.reason == "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores."
        else:
            raise AssertionError("ASCII prefix guard precedes capture and observer access.")


def check_public():
    if not __debug__:
        raise RuntimeError("Explicit IV63 public check refuses optimized Python (-O).")
    import struct
    default = dict(DEFAULT_IV63)
    zero = dict(default, **{key: -0.0 for key in _FIELDS[3:9]})
    mixed = dict(default, mode=1, w01=0.0, w11=0.0, w21=0.0)
    for value, frames, tensors, cells, aliases, omissions in (
            (default, 66, 66, 347, 283, 0), (zero, 65, 62, 314, 256, 4),
            (dict(default, mode=1), 70, 77, 362, 295, 0),
            (mixed, 69, 73, 344, 280, 4), (dict(zero, mode=1), 68, 69, 326, 265, 8)):
        trace = quantization_trace()
        result = evaluate_quantization(value, trace, "p")
        assert list(result) == ["state", "output", "tensors", "texts"]
        assert result["output"] is result["tensors"][-37]
        assert result["output"]["id"] == "p_reconstructed_Y"
        assert len(trace.steps) == frames and len(trace.outputs) == aliases
        assert len(result["tensors"]) == tensors
        assert sum(len(tensor["values"]) for tensor in result["tensors"]) == cells
        assert len(result["texts"]) == 20 and len(result["texts"]["uncomputed"]) == omissions
        for step in trace.steps:
            assert list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"]
            for key, item in step["outputs"].items():
                assert struct.pack(">d", trace.outputs[step["id"] + "_" + key]) == struct.pack(">d", item)
        for tensor in result["tensors"]:
            assert list(tensor) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
            assert tensor["values"] and tensor["provenance"]
            assert tensor["precision"] == (0 if tensor["dtype"] == "int32" else 8)
            if tensor["dtype"] == "int32":
                assert all(type(item) is int for item in tensor["values"])
        ids = [tensor["id"] for tensor in result["tensors"]]
        for fit in result["texts"]["uncomputed"]:
            assert fit.split(":", 1)[0] not in ids
        try:
            result["tensors"][0]["values"][0] = 8
        except TypeError:
            pass
        else:
            raise AssertionError("Saved public tensor values must be immutable.")
        try:
            result["state"]["x0"] = 4
        except TypeError:
            pass
        else:
            raise AssertionError("Saved public state must be immutable.")
    signed = dict(default, mode=-0.0, w10=-0.0, x0=-0.0)
    result = evaluate_quantization(signed, quantization_trace(), "s")
    indexed = {tensor["id"]: tensor for tensor in result["tensors"]}
    assert struct.pack(">d", result["state"]["w10"]) == struct.pack(">d", -0.0)
    assert struct.pack(">d", indexed["s_Raw"]["values"][5]) == struct.pack(">d", -0.0)
    assert struct.pack(">d", indexed["s_WClipped"]["values"][2]) == struct.pack(">d", -0.0)
    assert struct.pack(">d", indexed["s_X"]["values"][0]) == struct.pack(">d", -0.0)
    default["w00"] = 4.0
    assert result["state"]["w00"] == -1.0


def check_trace():
    if not __debug__:
        raise RuntimeError("Explicit IV63 trace check refuses optimized Python (-O).")
    import struct
    assert quantization_trace is _support.decoder_trace
    trace = quantization_trace()
    before, after = {"b": -0.0, "2": 2, "0": -0.0, "01": 1}, {"v": -0.0}
    trace.add("a", "l", "e", "why", before, after)
    before["b"], after["v"] = 8, 8
    assert list(trace.steps[0]["inputs"]) == ["0", "2", "b", "01"]
    assert struct.pack(">d", trace.outputs["a_v"]) == struct.pack(">d", -0.0)
    for identifier in ("", "a"):
        try:
            trace.add(identifier, "", "", "", {"bad": float("nan")}, {})
        except NumericalFault as error:
            assert error.reason == "Trace IDs must be nonempty and unique."
        else:
            raise AssertionError("IDs are checked before operands.")
    for index in range(1, 512):
        trace.add(str(index), "", "", "", {}, {})
    try:
        trace.add("full", "", "", "", {"bad": float("nan")}, {})
    except NumericalFault as error:
        assert error.code == "NONFINITE" and error.reason == "full.inputs.bad must be an actual finite number."
    else:
        raise AssertionError("Operands precede the frame cap.")
    try:
        trace.add("full", "", "", "", {}, {})
    except NumericalFault as error:
        assert error.code == "UNSUPPORTED_SIZE" and len(trace.steps) == 512
    else:
        raise AssertionError("The unchanged collector caps frames at512.")
    proto = quantization_trace()
    proto.add("_", "", "", "", {"__proto__": -0.0}, {"proto__": 1})
    assert "__proto__" not in proto.outputs and "__proto__" in proto.steps[0]["inputs"]
    unknown = ValueError("foreign operand observer")

    class UnknownItems:
        def items(self):
            if not __debug__:
                raise RuntimeError("Explicit IV63 operand hook refuses optimized Python (-O).")
            raise unknown

    try:
        quantization_trace().add("foreign", "", "", "", UnknownItems(), {})
    except ValueError as error:
        assert error is unknown
    else:
        raise AssertionError("Unknown trusted operand exceptions retain identity.")


def check_capture_storage_callbacks():
    if not __debug__:
        raise RuntimeError("Explicit IV63 capture/storage/callback check refuses optimized Python (-O).")
    import struct
    global _error_family, _project_success
    saved_storage, saved_errors, saved_project = _support._storage, _error_family, _project_success
    events, stored_words, output_operand_words = [], [], []
    source, trace = dict(DEFAULT_IV63), quantization_trace()

    def storage(values, rows, cols):
        if not __debug__:
            raise RuntimeError("Explicit IV63 storage hook refuses optimized Python (-O).")
        assert (rows, cols) == (1, 2) and not events
        stored = saved_storage(values, rows, cols)
        stored_words.extend(struct.pack(">d", stored[0, 0, column]) for column in range(2))
        events.append("storage")
        return stored

    def errors(reference, measured, capture, stage):
        if not __debug__:
            raise RuntimeError("Explicit IV63 error hook refuses optimized Python (-O).")
        assert events[0] == "storage" and "projected" not in events
        if stage in ("output_quantization", "output_total"):
            output_operand_words.append([struct.pack(">d", item) for item in measured])
            assert output_operand_words[-1] == stored_words
        result = saved_errors(reference, measured, capture, stage)
        events.append(stage)
        return result

    def project(mechanism, prefix):
        if not __debug__:
            raise RuntimeError("Explicit IV63 projection hook refuses optimized Python (-O).")
        assert events == ["storage", "weight_clipping", "weight_quantization", "weight_total", "output_clipping", "output_quantization", "output_total"]
        result = saved_project(mechanism, prefix)
        assert [struct.pack(">d", item) for item in result["output"]["values"]] == stored_words
        events.append("projected")
        return result

    class Observer:
        def add(self, identifier, label, equation, explanation, inputs, outputs):
            if not __debug__:
                raise RuntimeError("Explicit IV63 public callback hook refuses optimized Python (-O).")
            assert "projected" in events and len(output_operand_words) == 2
            source["w00"] = 4.0
            events.append("callback")
            trace.add(identifier, label, equation, explanation, inputs, outputs)

    try:
        _support._storage, _error_family, _project_success = storage, errors, project
        result = evaluate_quantization(source, Observer(), "saved")
        assert result["state"]["w00"] == -1.0 and source["w00"] == 4.0
        assert result["output"]["values"] == [-3, -1] and len(trace.steps) == 66
    finally:
        _support._storage, _error_family, _project_success = saved_storage, saved_errors, saved_project
    for unknown in (ValueError("callback"), MemoryError("callback resource"), KeyboardInterrupt("callback interrupt")):
        class FailingObserver:
            def add(self, identifier, label, equation, explanation, inputs, outputs):
                if not __debug__:
                    raise RuntimeError("Explicit IV63 failing callback hook refuses optimized Python (-O).")
                raise unknown
        try:
            evaluate_quantization(dict(DEFAULT_IV63), FailingObserver(), "abort")
        except BaseException as error:
            assert error is unknown
        else:
            raise AssertionError("Unknown callbacks retain identity and can abort flushing.")


def check_fault_prefixes():
    if not __debug__:
        raise RuntimeError("Explicit IV63 fault-prefix check refuses optimized Python (-O).")
    import struct
    global _capture_quantization
    saved_capture, saved_storage = _capture_quantization, _support._storage
    caught = []

    def capture(value, prefix, private=None):
        if not __debug__:
            raise RuntimeError("Explicit IV63 stopped capture hook refuses optimized Python (-O).")
        try:
            return saved_capture(value, prefix, private)
        except NumericalFault as error:
            assert private.fault is error
            caught.append((error, private))
            raise

    def no_storage(values, rows, cols):
        if not __debug__:
            raise RuntimeError("Explicit IV63 failure storage hook refuses optimized Python (-O).")
        raise AssertionError("Stopped quantizers must not enter NumPy storage.")

    tiny = float.fromhex("0x0.0000000000001p-1022")
    zero = dict(DEFAULT_IV63, **{key: 0.0 for key in _FIELDS[3:9]})
    cases = ((dict(zero, w20=tiny), 15, 29, 0, (0, 1, 2, 3, 4, 5)),
             (dict(zero, mode=1, w20=tiny), 12, 23, 0, (0, 2, 4)),
             (dict(zero, mode=1, w00=-1.0, w20=2.0, w21=tiny), 22, 71, 1, (1, 3, 5)),
             (dict(zero, mode=1, w21=tiny), 21, 56, 1, (1, 3, 5)))
    try:
        _capture_quantization, _support._storage = capture, no_storage
        for value, frame_count, alias_count, group, members in cases:
            trace = quantization_trace()
            caught.clear()
            try:
                evaluate_quantization(value, trace, "p")
            except NumericalFault as error:
                assert error is caught[0][0] and error.code == "UNAVAILABLE" and error.reason == _SCALE_UNDERFLOW
                assert caught[0][1].operations[-1][0] == "scale"
            else:
                raise AssertionError("Nonzero positive-span scale underflow must throw.")
            assert len(trace.steps) == frame_count and len(trace.outputs) == alias_count
            assert [step["id"] for step in trace.steps[:7]] == ["p_inputs"] + [f"p_clip_{cell}" for cell in range(6)]
            suffix = [f"p_g{group}_fit_{cell}" for cell in members] + [f"p_g{group}_span", f"p_g{group}_scale"]
            assert [step["id"] for step in trace.steps[-len(suffix):]] == suffix
            final = trace.steps[-1]
            assert list(final["inputs"]) == ["group", "span", "Q"] and list(final["outputs"]) == ["scale"]
            assert final["inputs"]["span"] == tiny
            assert struct.pack(">d", final["outputs"]["scale"]) == struct.pack(">d", 0.0)
            assert all(not step["id"].startswith((f"p_g{group}_zero_point", f"p_g{group}_quantize", "p_original", "p_output", "finish")) for step in trace.steps)
            if group == 1:
                assert trace.steps[7]["id"] == "p_g0_fit_0" and trace.steps[-len(suffix) - 1]["id"] == "p_g0_counts"
                assert any(step["id"] == "p_g0_zero_policy" for step in trace.steps) == (frame_count == 21)
        unknown = MemoryError("abort failure-prefix flush")
        forwarded = []

        class FailingObserver:
            def add(self, identifier, label, equation, explanation, inputs, outputs):
                if not __debug__:
                    raise RuntimeError("Explicit IV63 stopped-prefix callback hook refuses optimized Python (-O).")
                assert caught and caught[-1][1].fault is caught[-1][0]
                forwarded.append(identifier)
                if len(forwarded) == 2:
                    raise unknown

        try:
            evaluate_quantization(cases[0][0], FailingObserver(), "p")
        except MemoryError as error:
            assert error is unknown and forwarded == ["p_inputs", "p_clip_0"]
        else:
            raise AssertionError("Unknown observer failure can abort known-fault flushing.")
    finally:
        _capture_quantization, _support._storage = saved_capture, saved_storage

3. Canonical entry and explicit checks: iv63.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.

"""IV63 canonical actual producer, bound to owner-adopted A public inventory.

Producer only: no --verify, replay, RN authority or implicit checks. All UNRUN.
"""
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import FunctionType, ModuleType


def _load_reference():
    name = "_book_iv63_quantization"
    path = str(Path(__file__).resolve().with_name("quantization_reference.py"))
    if name in sys.modules:
        incumbent = sys.modules[name]
        if type(incumbent) is not ModuleType:
            raise ImportError("Unknown IV63 reference cache identity.")
        namespace = incumbent.__dict__
        certificate = namespace.get("_IV63_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 str(Path(certificate[5].origin).resolve()) != path):
            raise ImportError("Unknown or incomplete IV63 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("IV63 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("IV63 reference dependency cache changed.")
        for key, owned_object in certificate[4]:
            if namespace.get(key) is not owned_object:
                raise ImportError("IV63 reference dependency alias changed.")
        support = namespace["_support"]
        incumbent._module_identity(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("IV63 reference identity appeared during specification creation.")
    if spec is None or spec.loader is None:
        raise ImportError("Cannot load adjacent IV63 reference.")
    staged = importlib.util.module_from_spec(spec)
    if name in sys.modules:
        raise ImportError("IV63 reference identity appeared during module creation.")
    transaction = [(name, staged)]
    staged._IV63_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("IV63 reference identity 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"))
        dependencies = (("_book_iv63_generic59", staged._support),)
        aliases = tuple((key, staged.__dict__[key]) for key in
                        ("_support", "NumericalFault", "_freeze", "quantization_trace",
                         "DEFAULT_IV63", "_Capture", "_FIELDS", "_COUNT_FIELDS", "_SCALE_UNDERFLOW"))
        staged._IV63_CERTIFICATE = (staged, path, functions, dependencies, aliases, spec)
        staged._module_identity(staged, path)
        staged.__dict__.pop("_IV63_TRANSACTION", None)
        return staged
    except BaseException:
        # Roll back only identities created here that are STILL ours, in reverse.
        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_IV63 = _reference.DEFAULT_IV63
quantization_state = _reference.quantization_state
quantization_trace = _reference.quantization_trace
round_ties_to_even = _reference.round_ties_to_even
evaluate_quantization = _reference.evaluate_quantization


class _JsonInputError(ValueError):
    """Only local parser admission failures are declared known errors."""


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_PARSE_CODES = (json.JSONDecoder.decode.__code__, json.JSONDecoder.raw_decode.__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 as error:
        if type(error) is not _JsonInputError:
            raise
        raise NumericalFault("INVALID_INPUT", str(error)) from error
    except json.JSONDecodeError as error:
        # Only errors raised by the captured ACTUAL parser are syntax faults.
        origin = error.__traceback__
        while origin.tb_next is not None:
            origin = origin.tb_next
        if type(error) is not json.JSONDecodeError or origin.tb_frame.f_code not in _JSON_PARSE_CODES:
            raise
        raise NumericalFault("INVALID_INPUT", "Expected one finite strict JSON value.") from error


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


def derive_iv63(value):
    """Full replacement input; complete adopted root or owned unavailable3."""
    try:
        trace = quantization_trace()
        evaluated = evaluate_quantization(value, trace, "quantization")
        state, tensors = evaluated["state"], evaluated["tensors"]
        code_max, groups = trace.steps[0]["outputs"]["Q"], trace.steps[0]["outputs"]["groups"]
        indexed = {tensor["id"]: tensor for tensor in tensors}
        counts = indexed["quantization_Counts"]["values"]
        summary = dict(bits=state["bits"], mode=state["mode"], inputFeatures=3, outputFeatures=2,
                       groups=groups, codeMax=code_max, clipped=counts[0], saturated=counts[1],
                       lowEndpoint=counts[2], highEndpoint=counts[3], zeroPointCode=counts[4],
                       expCalls=0, sqrtCalls=0, nativeElementaryCalls=0,
                       frames=len(trace.steps) + 1, tensorCount=len(tensors))
        trace.add("finish", "Save the actual quantizer source graph counts", "output=quantization_reconstructed_Y; counts=quantization_Counts; nativeElementaryCalls=0",
                  "Copy the saved whole-tensor decisions and source graph sizes after all three actual affine paths and all six direct error reductions. Source counts do not measure hardware speed, storage or model quality.",
                  dict(bits=state["bits"], mode=state["mode"], groups=groups, codeMax=code_max), summary)
        texts = dict(evaluated["texts"])
        texts.update(
            tracePolicy="Exact unchanged decoderTrace alias. Empty/duplicate IDs fail before finite operands; the 512-frame cap follows operand capture. Frames are detached finite six-field snapshots. Full raw/domain/prefix preflight precedes the first frame; a positive-span zero-scale fault retains only the actual collector prefix. Every saved frame output is copied to root outputs as frameId_key.",
            summaryPolicy="All sixteen primary summary fields and their finish aliases use VALUE choices, dimensions, decisions or source counts. Raw tensor fields0,1 use VALUE and fields2..11 WORD. Other floating operands/results/copies use WORD including -0; explicitly structural integers use VALUE. Helper output is the very same saved reconstructed_Y TensorRecord in its tensors list. No natives field or empty-native tensor.",
            validationPolicy="SOURCE IMPLEMENTATION ONLY. All checks UNRUN under the human FluxGeo hold: imports, numerical references/oracles, fixture generation, tests, typecheck, build, browser, accessibility, offline and performance. Source inventory requires owner adoption; runtime validation and chapter acceptance remain pending.",
        )
        outputs = dict(summary)
        for step in trace.steps:
            for key, entry in step["outputs"].items():
                alias = step["id"] + "_" + key
                if alias in outputs:
                    raise RuntimeError("IV63 output aliases must be unique.")
                outputs[alias] = entry
        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 selects default, full JSON, stdin or check."""
    args = sys.argv[1:]
    if args == ["--self-check"]:
        source_self_check()
        print("IV63 explicit source checks completed.")
        return 0
    if len(args) > 1 or (args and args[0].startswith("--")):
        print("Usage: iv63.py [JSON|-|--self-check]", file=sys.stderr)
        return 2
    try:
        value = dict(DEFAULT_IV63) if not args else strict_json(sys.stdin.read() if args[0] == "-" else args[0])
        result = derive_iv63(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 IV63 parser check refuses optimized Python (-O).")
    import struct
    for spelling in ("-0", "-0.0", "-0e0"):
        assert struct.pack(">d", strict_json(spelling)) == struct.pack(">d", -0.0)
    assert strict_json("1" + "0" * 308) == 1e308
    assert strict_json('{"bits":2}') == {"bits": 2.0}
    for source in ("1" + "0" * 309, "9" * 309, "1e309", "NaN", "Infinity", "-Infinity",
                   '{"a":1,"a":2}', '{"a":{"z":0,"z":1}}', "{} {}", "", '{"a":01}'):
        try:
            strict_json(source)
        except NumericalFault as error:
            assert type(error) is NumericalFault and error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Expected local strict JSON fault.")
    global _JSON_DECODE
    saved = _JSON_DECODE
    for unknown in (ValueError("foreign value"), json.JSONDecodeError("foreign JSON", "", 0),
                    MemoryError("resource"), KeyboardInterrupt("interrupt")):
        def injected(text):
            if not __debug__:
                raise RuntimeError("Explicit IV63 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("Unknown parser failures must retain identity.")
        finally:
            _JSON_DECODE = saved


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

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

    try:
        derive_iv63 = producer
        for args, source, expected in (([], "", dict(DEFAULT_IV63)),
                                        (["{}"], "", {}), (["-"], '{"bits":2}', {"bits": 2.0})):
            sys.argv, sys.stdin = ["iv63.py"] + args, io.StringIO(source)
            output = io.StringIO()
            with contextlib.redirect_stdout(output):
                assert run() == 0
            assert seen[-1] == expected
            assert json.loads(output.getvalue())["reason"] == "CLI plumbing check only"
        for args in (["--verify"], ["{}", "{}"], ["--unknown"]):
            sys.argv = ["iv63.py"] + args
            with contextlib.redirect_stderr(io.StringIO()):
                assert run() == 2
        for args in (["NaN"], ['{"bits":2,"bits":4}']):
            sys.argv = ["iv63.py"] + args
            with contextlib.redirect_stdout(io.StringIO()):
                assert run() == 0
        unknown = ValueError("foreign producer value")

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

        derive_iv63, sys.argv = foreign, ["iv63.py", "{}"]
        try:
            run()
        except ValueError as error:
            assert error is unknown
        else:
            raise AssertionError("Unknown CLI failure must escape unchanged.")
    finally:
        derive_iv63, sys.argv, sys.stdin = saved_derive, saved_argv, saved_stdin
    # Actual semantic and default paths, without the plumbing hook.
    assert derive_iv63({})["status"] == "unavailable"
    assert derive_iv63(dict(DEFAULT_IV63))["status"] == "defined"
    for args, source in (([], ""), (["-"], json.dumps(dict(DEFAULT_IV63))),
                         ([json.dumps(dict(DEFAULT_IV63))], ""), (["{}"], ""), (["NaN"], "")):
        output = io.StringIO()
        try:
            sys.argv, sys.stdin = ["iv63.py"] + args, io.StringIO(source)
            with contextlib.redirect_stdout(output):
                assert run() == 0
            actual = json.loads(output.getvalue())
            assert actual["status"] == ("unavailable" if args in (["{}"], ["NaN"]) else "defined")
        finally:
            sys.argv, sys.stdin = saved_argv, saved_stdin


def check_loader():
    if not __debug__:
        raise RuntimeError("Explicit IV63 loader check refuses optimized Python (-O).")
    name = "_book_iv63_quantization"
    original = sys.modules[name]
    support_name = "_book_iv63_generic59"
    support = sys.modules[support_name]
    saved_spec, saved_create = importlib.util.spec_from_file_location, importlib.util.module_from_spec
    try:
        assert _load_reference() is original
        for incumbent in (None, object(), ModuleType(name)):
            sys.modules[name] = incumbent
            try:
                _load_reference()
            except ImportError:
                assert sys.modules[name] is incumbent
            else:
                raise AssertionError("Unknown/preexisting cache value must be preserved.")
        sys.modules[name] = original
        for incumbent in (None, object()):
            sys.modules[support_name] = incumbent
            try:
                _load_reference()
            except ImportError:
                assert sys.modules[support_name] is incumbent
            else:
                raise AssertionError("Dependency replacement must not be adopted.")
        sys.modules[support_name] = support
        del sys.modules[name]

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

        importlib.util.spec_from_file_location = appearing_spec
        try:
            _load_reference()
        except ImportError:
            assert name in sys.modules and sys.modules[name] is None
        else:
            raise AssertionError("Creation-phase incumbent must prevent staging.")
        importlib.util.spec_from_file_location = saved_spec
        del sys.modules[name]

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

        importlib.util.module_from_spec = appearing_module
        try:
            _load_reference()
        except ImportError:
            assert name in sys.modules and sys.modules[name] is None
        else:
            raise AssertionError("Module creation incumbent must prevent staging.")
        importlib.util.module_from_spec = saved_create
        del sys.modules[name]
        # These hooks model our transaction only; no foreign identity is removed.
        for disposition in ("owned", "none", "replacement", "deleted", "preexisting", "root_none", "root_deleted"):
            for unknown in (ValueError("load value"), json.JSONDecodeError("load JSON", "", 0),
                            MemoryError("load resource"), KeyboardInterrupt("load interrupt")):
                sys.modules.pop(name, None)
                if disposition == "preexisting":
                    sys.modules[support_name] = support
                else:
                    sys.modules.pop(support_name, None)
                replacement = object()

                class FailingLoader:
                    def create_module(self, spec):
                        if not __debug__:
                            raise RuntimeError("Explicit IV63 failure creation hook refuses optimized Python (-O).")
                        return None

                    def exec_module(self, module):
                        if not __debug__:
                            raise RuntimeError("Explicit IV63 failure execution hook refuses optimized Python (-O).")
                        if disposition != "preexisting":
                            child = ModuleType(support_name)
                            module._IV63_TRANSACTION.append((support_name, child))
                            sys.modules[support_name] = child
                            if disposition == "none":
                                sys.modules[support_name] = None
                            elif disposition == "replacement":
                                sys.modules[support_name] = replacement
                            elif disposition == "deleted":
                                del sys.modules[support_name]
                        if disposition == "root_none":
                            sys.modules[name] = None
                        elif disposition == "root_deleted":
                            del sys.modules[name]
                        raise unknown

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

                importlib.util.spec_from_file_location = failing_spec
                try:
                    _load_reference()
                except BaseException as error:
                    assert error is unknown
                    if disposition == "root_none":
                        assert name in sys.modules and sys.modules[name] is None
                    else:
                        assert name not in sys.modules
                    if disposition == "none":
                        assert support_name in sys.modules and sys.modules[support_name] is None
                    elif disposition == "replacement":
                        assert sys.modules[support_name] is replacement
                    elif disposition == "preexisting":
                        assert sys.modules[support_name] is support
                    else:
                        assert support_name not in sys.modules
                else:
                    raise AssertionError("Owned transaction must preserve unknown exception identity.")
    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_support():
    if not __debug__:
        raise RuntimeError("Explicit IV63 support-loader check refuses optimized Python (-O).")
    name, support_name = "_book_iv63_quantization", "_book_iv63_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
    saved_capture, saved_capture_code = original._Capture.add, original._Capture.add.__code__
    saved_numeric, saved_file = support._numeric, support.__file__

    def foreign_method(self, stage, inputs, outputs):
        if not __debug__:
            raise RuntimeError("Explicit IV63 code-identity hook refuses optimized Python (-O).")
        raise AssertionError("A substituted capture method must never be invoked.")

    try:
        original._Capture.add = foreign_method
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Class method identities belong to the cache certificate.")
        original._Capture.add = saved_capture
        saved_capture.__code__ = foreign_method.__code__
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("The same function with replaced code must be rejected.")
        saved_capture.__code__ = saved_capture_code
        support._numeric = foreign_method
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Reachable generic trace functions are code-certified.")
        support._numeric = saved_numeric
        support.__file__ = str(Path(saved_file).with_name("iv63.py"))
        try:
            _load_reference()
        except ImportError:
            pass
        else:
            raise AssertionError("Resolved actual source file identity must match.")
        support.__file__ = saved_file
        for phase in ("spec", "creation"):
            sys.modules.pop(support_name, None)

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

            def appearing_module(spec):
                if not __debug__:
                    raise RuntimeError("Explicit IV63 support creation hook refuses optimized Python (-O).")
                result = saved_create(spec)
                sys.modules[support_name] = None
                return result

            if phase == "spec":
                importlib.util.spec_from_file_location = appearing_spec
            else:
                importlib.util.module_from_spec = appearing_module
            try:
                original._load_support()
            except ImportError:
                assert support_name in sys.modules and sys.modules[support_name] is None
            else:
                raise AssertionError("Support-loader incumbents must not be overwritten.")
            importlib.util.spec_from_file_location, importlib.util.module_from_spec = saved_spec, saved_create
        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.evaluate_quantization(dict(cold.DEFAULT_IV63), cold.quantization_trace(), "cold")["output"]["values"] == [-3, -1]
    finally:
        original._Capture.add = saved_capture
        saved_capture.__code__ = saved_capture_code
        support._numeric, support.__file__ = saved_numeric, saved_file
        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_root():
    if not __debug__:
        raise RuntimeError("Explicit IV63 root check refuses optimized Python (-O).")
    import struct
    default = dict(DEFAULT_IV63)
    zero = dict(default, **{key: -0.0 for key in _reference._FIELDS[3:9]})
    for value, frames, tensors, outputs in ((default, 67, 66, 315), (zero, 66, 62, 288),
            (dict(default, mode=1), 71, 77, 327),
            (dict(default, mode=1, w01=0.0, w11=0.0, w21=0.0), 70, 73, 312),
            (dict(zero, mode=1), 69, 69, 297)):
        result = derive_iv63(value)
        assert list(result) == ["status", "outputs", "steps", "tensors", "texts"] and result["status"] == "defined"
        assert len(result["steps"]) == frames and len(result["tensors"]) == tensors and len(result["outputs"]) == outputs
        assert len(result["texts"]) == 23
        summary_keys = ["bits", "mode", "inputFeatures", "outputFeatures", "groups", "codeMax", "clipped", "saturated", "lowEndpoint", "highEndpoint", "zeroPointCode", "expCalls", "sqrtCalls", "nativeElementaryCalls", "frames", "tensorCount"]
        assert list(result["outputs"])[:16] == summary_keys
        assert result["steps"][-1]["id"] == "finish" and list(result["steps"][-1]["outputs"]) == summary_keys
        aliases = [step["id"] + "_" + key for step in result["steps"] for key in step["outputs"]]
        assert list(result["outputs"])[16:] == aliases
        for step in result["steps"]:
            for key, entry in step["outputs"].items():
                assert struct.pack(">d", result["outputs"][step["id"] + "_" + key]) == struct.pack(">d", entry)
        assert result["outputs"]["frames"] == frames and result["outputs"]["tensorCount"] == tensors
        assert [result["outputs"][key] for key in ("expCalls", "sqrtCalls", "nativeElementaryCalls")] == [0, 0, 0]
        assert "natives" not in result
    result = derive_iv63(default)
    indexed = {tensor["id"]: tensor for tensor in result["tensors"]}
    assert indexed["quantization_reconstructed_Y"]["values"] == [-3, -1]
    assert indexed["quantization_weight_total_Summary"]["values"] == [0.375, 0.5]
    assert indexed["quantization_output_total_Summary"]["values"] == [2.25, 1.5]
    tiny = float.fromhex("0x0.0000000000001p-1022")
    for value, code, reason in (({}, "INVALID_INPUT", "state must have exactly bits, mode, clip, w00, w01, w10, w11, w20, w21, x0, x1, x2 as own fields."),
            (dict(default, bits=0, x2=True), "NONFINITE", "state.x2 must be finite."),
            (dict(zero, w20=tiny), "UNAVAILABLE", _reference._SCALE_UNDERFLOW)):
        result = derive_iv63(value)
        assert list(result) == ["status", "code", "reason"] and result == dict(status="unavailable", code=code, reason=reason)


def source_self_check():
    if not __debug__:
        raise RuntimeError("Explicit IV63 aggregate refuses optimized Python (-O).")
    _reference.check_mechanism()
    _reference.check_guards()
    _reference.check_public()
    _reference.check_trace()
    _reference.check_capture_storage_callbacks()
    _reference.check_fault_prefixes()
    check_root()
    check_parser()
    check_cli()
    check_loader()
    check_loader_support()


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

What this experiment can establish

A logical b-bit code alphabet is not a packed allocation. Six codes nominally carry 6b payload bits before scale/zero-point and other metadata. Ordinary integer arrays, binary64 reconstructed weights and scalar arithmetic do not establish actual memory use, native low-bit multiplication, throughput, latency, energy savings or language-model quality. More labels and finer per-column scales are choices to evaluate with actual outputs, not reasons to invent benchmark results.

Connect this limit to Book III III-35, Cross-Validation and Hyperparameter Tuning. When evaluating a real system, use separate examples to assess settings such as bit width, grouping and clipping. An example used to choose a setting is not independent evidence for that choice. This one-input worksheet exposes arithmetic and cancellation; it does not estimate performance on new examples.

Keep four takeaways: reconstruct weights using scale and zero point before multiplying; distinguish clipping, endpoint occupancy and saturation; compute all three output paths and all three error families independently; and inspect residuals and rounding stages before interpreting a zero or a smaller SSE.

The next chapter, IV-64, Inference Systems: Throughput and Latency, asks how prefill, decoding, batching and memory affect systems costs. This arithmetic lesson supplies numerical tradeoffs; systems measurements require their own evidence.