The neural notebook
← All chapters

IV-52 / Part XIII · Training Language Models

Language-Model Training Steps and Batches

Follow isolated toy documents through actual token losses, a masked token mean, all fifteen readout gradients and one simultaneous SGD or Adam update.

Review the ideas this chapter uses

A model can assign probabilities without learning anything. Learning begins when we use known next tokens to calculate a loss, find how that loss changes with each parameter, and actually replace the parameters. Here we follow one small batch all the way through that replacement, including the state an optimizer keeps.

Learning objective: Calculate token losses, reduced gradients and one optimizer update.

Compute it yourself

Language-Model Training Steps and Batches

Give a tiny model one or two short documents, score their actual next-token targets, then update its fifteen readout parameters once. Start with the saved loss before and after; open the controls to compare SGD, Adam or a loss mask. Each edit starts a fresh one-step calculation from the displayed initial weights.

Only the readout learns: the encoder that produces Y stays fixed. Two documents mean two isolated old B=1 forwards, each starting at position zero. A real updated readout reuses that same Y; there is no second full encoder forward or promised loss decrease.

meanNLLBefore2.312099658912116
meanNLLAfter1.9286725179824338
validTargets2
completedUpdates1

Use one or two raw a/b letters per document. Empty text is unavailable; spaces, other letters and overlong text are rejected without trimming or cropping. Both documents and all 26 numeric fields validate even when B, a mask slot, a vocabulary column or Adam controls are unused. The fixed tokenizer corpus is abab, EOS is off inside each tokenizer, and one explicit EOS is appended per document.

Use one or two raw a/b letters per document. Empty text is unavailable; spaces, other letters and overlong text are rejected without trimming or cropping. Both documents and all 26 numeric fields validate even when B, a mask slot, a vocabulary column or Adam controls are unused. The fixed tokenizer corpus is abab, EOS is off inside each tokenizer, and one explicit EOS is appended per document.

Tokenization and isolated batch
Initial readout U [2,5]
Initial bias [5]
One simultaneous optimizer update
Four requested loss masks
Exact starting inputs for this saved calculation

meanNLLBefore 2.312099658912116. meanNLLAfter 1.9286725179824338. validTargets 2. completedUpdates 1. Declare actual isolated readout-only training. All own descriptors precede captured value reads; both string types and every numeric domain precede A then B text semantics. Initial bounds are separate from finite derived weights.

Declare actual isolated readout-only training

two EOS-off tokenizers; one EOS/doc; selected inputs=sequence[:-1]; targets=sequence[1:]; train U[2,5] and bias[5]

All own descriptors precede captured value reads; both string types and every numeric domain precede A then B text semantics. Initial bounds are separate from finite derived weights.

Saved inputs

merges
0
batchSize
2
u00
1
u01
0
u02
0
u03
0
u04
0
u10
0
u11
1
u12
0
u13
0
u14
0
b0
0
b1
0
b2
0
b3
0
b4
0
eta
0.1
optimizer
0
beta1
0.9
beta2
0.999
epsilon
1e-8
mA0
1
mA1
1
mB0
1
mB1
1

Saved outputs

byteBound
2
tokenizerCalls
2
appendedEOS
2
classCount
3
trainableParameters
15
fixedEncoder
1

Two actual token streams → selected real targets

Actual readout-only training of ten U weights and five biases. The old embedding, causal attention, RoPE, normalization and 2x3x2 FFN stay fixed at actual defaults. No full Transformer backpropagation is claimed.

Document A: "a"

Raw UTF-8 bytes [97]; actual content IDs [97]; one-EOS sequence [97,512]. Strict content reconstruction "a".

Selected: true. Its real rows have an initial full forward and updated readout.

Document A: tokenizer evidence

Fixed corpus "abab"; rules []; expansions []; content labels ["ID 97, bytes [97]"]; content expansions ["[97]"]. Zero merges requested: no training round or pair selection occurs.

Document B: "b"

Raw UTF-8 bytes [98]; actual content IDs [98]; one-EOS sequence [98,512]. Strict content reconstruction "b".

Selected: true. Its real rows have an initial full forward and updated readout.

Document B: tokenizer evidence

Fixed corpus "abab"; rules []; expansions []; content labels ["ID 98, bytes [98]"]; content expansions ["[98]"]. Zero merges requested: no training round or pair selection occurs.

Batch size 1 selects A; 2 selects A then B. Both raw documents and all four masks validate and both tokenizers run. Each selected document has its own old B=1 forward with positions restarting at zero; no arbitrary packed-mask decoder is claimed. Active class IDs [97,98,512]. Public IDs label classes; they are not array offsets. U has shape [D,ModelRow]=[2,5], bias [5], and each selected Y has [B,T,D]=[1,T,2].

The first piece is given. Score every selected real shifted target, including EOS, with its requested 0/1 loss mask. Sum mask*NLL in A then B position order and divide once by the total included targets. Unused raw mask slots create no row. A one-token document uses only mask slot 0. An unused slot 1 still validates but contributes no target. If a selected document is wholly loss-masked while N>0 elsewhere, its full real neural evidence remains; loss masking does not change attention permissions.

All saved real rows and before/after target losses
Row / document / positionInput ID → target ID (compact row)Loss mask / includedBefore target PBefore NLLBefore mask×NLLBefore running sumAfter target PAfter NLLAfter mask×NLLAfter running sum
0 / A / 097 → 512 (2)1 / true0.099053055435092062.3120996589121162.3120996589121162.3120996589121160.145341008054297621.92867251798243381.92867251798243381.9286725179824338
1 / B / 098 → 512 (2)1 / true0.099053055435092062.3120996589121162.3120996589121164.6241993178242320.145341008054297621.92867251798243381.92867251798243383.8573450359648676

Before: saved sum 4.624199317824232 / included targets N=2 = 2.312099658912116. After: saved sum 3.8573450359648676 / the same N=2 = 1.9286725179824338. Saved change (after−before)=-0.3834271409296821.

Here N counts included target tokens, not documents or attention cells. Different document lengths require one total-token denominator. N=0 makes the objective unavailable before neural work, with no mean or optimizer state published.

Saved target count and both mean reductions

count: Count selected real target masks before neural work

N starts at 0; visit selected docs A then B and positions ascending; running_r=previous+mask_r

Both documents were tokenized already. Unselected B and unused mask slots create no neural row or denominator term. N=0 is unavailable before any full forward or update.

Saved inputs
batchSize
2
docID0
0
position0
0
inputID0
97
targetID0
512
targetRow0
2
mask0
1
docID1
1
position1
0
inputID1
98
targetID1
512
targetRow1
2
mask1
1
Saved outputs
running0
1
running1
2
predictionRows
2
validTargets
2

before_mean: Reduce the genuine masked objective before the update

meanNLLBefore=lossSumBefore/validTargets

One total token denominator, not a mean of document means. Every selected document was fully evaluated even when all its rows have mask zero.

Saved inputs
lossSumBefore
4.624199317824232
validTargets
2
Saved outputs
meanNLLBefore
2.312099658912116

gradient_count: Count included gradient rows

N starts at 0; running_r=previous+mask_r

Only actual rows, in document then position order, contribute. This repeats the wrapper count on the supplied gradient operands.

Saved inputs
mask0
1
mask1
1
Saved outputs
running0
1
running1
2
validTargets
2

after_mean: Reduce the genuine masked objective after the update

meanNLLAfter=lossSumAfter/validTargets; lossChange=meanNLLAfter-meanNLLBefore

The actual new parameters supply every updated logit. A positive lossChange is a valid result; no decrease is forced.

Saved inputs
lossSumAfter
3.8573450359648676
validTargets
2
meanNLLBefore
2.312099658912116
Saved outputs
meanNLLAfter
1.9286725179824338
lossChange
-0.3834271409296821

Inspecting saved row 0, document A, position 0; parameter u00; class slot 2, active=true. These selectors only inspect the saved record and leave the trace cursor, starting inputs and question cases unchanged.

Trace selection: setup. Matching saved operations below are marked current.

Document A: its one or two actual old forward rows

Only the selected document’s saved initial forward is shown here. Select one of the other document’s prediction rows above to inspect its separate forward. Each row retains all three feed-forward hidden units, including the computed zero unit. Values below are stored without display rounding.

Document A: actual initial encoder features and fixed block intermediates
Position / input IDX [1,T,2]LN1 [1,T,2]R1 [1,T,2]LN2 [1,T,2]Hidden [1,T,3]F [1,T,2]Y [1,T,2]
0 / 97[1,0][0.4472135954999579,-0.4472135954999579][1.4472135954999579,-0.4472135954999579][0.6876854075163181,-0.6876854075163181][0.6876854075163181,0,0][0.6876854075163181,0][2.134899003016276,-0.4472135954999579]
Document A: actual old causal permissions [B,H,Query,Key]=[1,1,T,T]
QueryKey 0
0true
Document A: all saved initial full-forward operations

forwardA_input_0: Gather observed token at position 0

inputRow=compactRow(inputID); X[0,t,:]=E[inputRow,:]

EOS is an ordinary available embedding row in this numeric kernel. There is no implicit stop rule or target lookup.

Saved inputs
t
0
inputID
97
Saved outputs
inputRow
0
x0
1
x1
0

forwardA_ln1_0_statistics: ln1_0: 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.

Saved inputs
x0
1
x1
0
epsilon
1
Saved outputs
sum
1
mean
0.5
centered0
0.5
centered1
-0.5
square0
0.25
square1
0.25
squareSum
0.5
variance
0.25
variancePlusEpsilon
1.25
denominator
1.118033988749895

forwardA_ln1_0_feature_0: ln1_0: affine feature 0

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.

Saved inputs
d
0
source
0.5
denominator
1.118033988749895
gamma
1
beta
0
Saved outputs
normalized
0.4472135954999579
scaled
0.4472135954999579
value
0.4472135954999579

forwardA_ln1_0_feature_1: ln1_0: affine feature 1

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.

Saved inputs
d
1
source
-0.5
denominator
1.118033988749895
gamma
1
beta
0
Saved outputs
normalized
-0.4472135954999579
scaled
-0.4472135954999579
value
-0.4472135954999579

forwardA_heads_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.

Saved inputs
B
1
T
1
H
1
Dk
2
Dv
2
x000
0.4472135954999579
x001
-0.4472135954999579
x010
0
x011
1
x020
1
x021
1
x100
1
x101
1
x110
-1
x111
0
x120
0
x121
2
wq000
1
wq001
0
wq010
0
wq011
1
wq100
0
wq101
1
wq110
1
wq111
0
wk000
1
wk001
0
wk010
0
wk011
1
wk100
0
wk101
1
wk110
1
wk111
0
wv000
1
wv001
0
wv010
0
wv011
1
wv100
0
wv101
1
wv110
1
wv111
0
mode
1
valid0
1
valid1
1
valid2
1
shift
0
wo000
1
wo001
0
wo010
0
wo011
1
wo100
1
wo101
-1
wo110
0
wo111
0.5
Saved outputs
B
1
T
1
D
2
H
1
Dk
2
Dv
2

forwardA_heads_project_Q_0_0_0_0: Q[0,0,head 0,feature 0]: 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.

Saved inputs
b
0
t
0
h
0
f
0
x0
0.4472135954999579
x1
-0.4472135954999579
w0
1
w1
0
Saved outputs
product0
0.4472135954999579
product1
0
value
0.4472135954999579

forwardA_heads_project_Q_0_0_0_1: Q[0,0,head 0,feature 1]: 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.

Saved inputs
b
0
t
0
h
0
f
1
x0
0.4472135954999579
x1
-0.4472135954999579
w0
0
w1
1
Saved outputs
product0
0
product1
-0.4472135954999579
value
-0.4472135954999579

forwardA_heads_project_K_0_0_0_0: K[0,0,head 0,feature 0]: 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.

Saved inputs
b
0
t
0
h
0
f
0
x0
0.4472135954999579
x1
-0.4472135954999579
w0
1
w1
0
Saved outputs
product0
0.4472135954999579
product1
0
value
0.4472135954999579

forwardA_heads_project_K_0_0_0_1: K[0,0,head 0,feature 1]: 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.

Saved inputs
b
0
t
0
h
0
f
1
x0
0.4472135954999579
x1
-0.4472135954999579
w0
0
w1
1
Saved outputs
product0
0
product1
-0.4472135954999579
value
-0.4472135954999579

forwardA_heads_project_V_0_0_0_0: V[0,0,head 0,feature 0]: 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.

Saved inputs
b
0
t
0
h
0
f
0
x0
0.4472135954999579
x1
-0.4472135954999579
w0
1
w1
0
Saved outputs
product0
0.4472135954999579
product1
0
value
0.4472135954999579

forwardA_heads_project_V_0_0_0_1: V[0,0,head 0,feature 1]: 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.

Saved inputs
b
0
t
0
h
0
f
1
x0
0.4472135954999579
x1
-0.4472135954999579
w0
0
w1
1
Saved outputs
product0
0
product1
-0.4472135954999579
value
-0.4472135954999579

forwardA_heads_reshape_Q: Q: 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.

Saved inputs
B
1
T
1
H
1
F
2
features
2
elements
2
Saved outputs
elements
2

forwardA_heads_permute_Q_0_0_0_0: Q: copy [0,0,0,0] to [0,0,0,0]

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.

Saved inputs
b
0
h
0
t
0
f
0
feature
0
sourceOffset
0
destinationOffset
0
sourceValue
0.4472135954999579
Saved outputs
value
0.4472135954999579

forwardA_heads_permute_Q_0_0_0_1: Q: copy [0,0,0,1] to [0,0,0,1]

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.

Saved inputs
b
0
h
0
t
0
f
1
feature
1
sourceOffset
1
destinationOffset
1
sourceValue
-0.4472135954999579
Saved outputs
value
-0.4472135954999579

forwardA_heads_reshape_K: K: 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.

Saved inputs
B
1
T
1
H
1
F
2
features
2
elements
2
Saved outputs
elements
2

forwardA_heads_permute_K_0_0_0_0: K: copy [0,0,0,0] to [0,0,0,0]

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.

Saved inputs
b
0
h
0
t
0
f
0
feature
0
sourceOffset
0
destinationOffset
0
sourceValue
0.4472135954999579
Saved outputs
value
0.4472135954999579

forwardA_heads_permute_K_0_0_0_1: K: copy [0,0,0,1] to [0,0,0,1]

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.

Saved inputs
b
0
h
0
t
0
f
1
feature
1
sourceOffset
1
destinationOffset
1
sourceValue
-0.4472135954999579
Saved outputs
value
-0.4472135954999579

forwardA_heads_reshape_V: V: 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.

Saved inputs
B
1
T
1
H
1
F
2
features
2
elements
2
Saved outputs
elements
2

forwardA_heads_permute_V_0_0_0_0: V: copy [0,0,0,0] to [0,0,0,0]

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.

Saved inputs
b
0
h
0
t
0
f
0
feature
0
sourceOffset
0
destinationOffset
0
sourceValue
0.4472135954999579
Saved outputs
value
0.4472135954999579

forwardA_heads_permute_V_0_0_0_1: V: copy [0,0,0,1] to [0,0,0,1]

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.

Saved inputs
b
0
h
0
t
0
f
1
feature
1
sourceOffset
1
destinationOffset
1
sourceValue
-0.4472135954999579
Saved outputs
value
-0.4472135954999579

forwardA_rope_Q_0: Rotate Q pair at absolute position 0

frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos

The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved.

Saved inputs
t
0
x0
0.4472135954999579
x1
-0.4472135954999579
base
10000
exponent
0
Saved outputs
frequency
1
angle
0
cos
1
sin
0
product0
0.4472135954999579
product1
0
product2
0
product3
-0.4472135954999579
rotated0
0.4472135954999579
rotated1
-0.4472135954999579

forwardA_rope_K_0: Rotate K pair at absolute position 0

frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos

The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved.

Saved inputs
t
0
x0
0.4472135954999579
x1
-0.4472135954999579
base
10000
exponent
0
Saved outputs
frequency
1
angle
0
cos
1
sin
0
product0
0.4472135954999579
product1
0
product2
0
product3
-0.4472135954999579
rotated0
0.4472135954999579
rotated1
-0.4472135954999579

forwardA_heads_score_0_0_0_0: Batch 0, head 0: query 0 against key 0

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.

Saved inputs
b
0
h
0
i
0
j
0
Dk
2
divisor
1.4142135623730951
q0
0.4472135954999579
k0
0.4472135954999579
q1
-0.4472135954999579
k1
-0.4472135954999579
Saved outputs
product0
0.19999999999999998
product1
0.19999999999999998
raw
0.39999999999999997
score
0.28284271247461895

forwardA_heads_row_0_0_0: Batch 0, head 0, query 0: 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.

Saved inputs
b
0
h
0
i
0
mode
1
shift
0
score0
0.28284271247461895
allowed0
1
Saved outputs
max
0.28284271247461895
denominator
1
shifted0
0
term0
1
p0
1

forwardA_heads_head_mix_0_0_0_0: OHeads[0,0,0,0]: 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.

Saved inputs
b
0
h
0
i
0
f
0
p0
1
v0
0.4472135954999579
Saved outputs
product0
0.4472135954999579
running0
0.4472135954999579
value
0.4472135954999579

forwardA_heads_head_mix_0_0_0_1: OHeads[0,0,0,1]: 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.

Saved inputs
b
0
h
0
i
0
f
1
p0
1
v0
-0.4472135954999579
Saved outputs
product0
-0.4472135954999579
running0
-0.4472135954999579
value
-0.4472135954999579

forwardA_heads_concat_0_0_0_0: Join head 0, feature 0 into C[0,0,0]

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.

Saved inputs
b
0
t
0
h
0
f
0
concatFeature
0
sourceOffset
0
destinationOffset
0
sourceValue
0.4472135954999579
Saved outputs
value
0.4472135954999579

forwardA_heads_concat_0_0_0_1: Join head 0, feature 1 into C[0,0,1]

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.

Saved inputs
b
0
t
0
h
0
f
1
concatFeature
1
sourceOffset
1
destinationOffset
1
sourceValue
-0.4472135954999579
Saved outputs
value
-0.4472135954999579

forwardA_heads_output_0_0_0: Y[0,0,0]: 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.

Saved inputs
b
0
t
0
d
0
c0
0.4472135954999579
w0
1
c1
-0.4472135954999579
w1
0
Saved outputs
product0
0.4472135954999579
product1
0
running0
0.4472135954999579
running1
0.4472135954999579
value
0.4472135954999579

forwardA_heads_output_0_0_1: Y[0,0,1]: 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.

Saved inputs
b
0
t
0
d
1
c0
0.4472135954999579
w0
0
c1
-0.4472135954999579
w1
1
Saved outputs
product0
0
product1
-0.4472135954999579
running0
0
running1
-0.4472135954999579
value
-0.4472135954999579

forwardA_residual1_0_0: First residual position 0, feature 0

value=X+AttentionOutput

Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding.

Saved inputs
t
0
d
0
left
1
right
0.4472135954999579
Saved outputs
value
1.4472135954999579

forwardA_residual1_0_1: First residual position 0, feature 1

value=X+AttentionOutput

Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding.

Saved inputs
t
0
d
1
left
0
right
-0.4472135954999579
Saved outputs
value
-0.4472135954999579

forwardA_ln2_0_statistics: ln2_0: 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.

Saved inputs
x0
1.4472135954999579
x1
-0.4472135954999579
epsilon
1
Saved outputs
sum
1
mean
0.5
centered0
0.9472135954999579
centered1
-0.9472135954999579
square0
0.8972135954999578
square1
0.8972135954999578
squareSum
1.7944271909999157
variance
0.8972135954999578
variancePlusEpsilon
1.8972135954999578
denominator
1.3773937692250382

forwardA_ln2_0_feature_0: ln2_0: affine feature 0

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.

Saved inputs
d
0
source
0.9472135954999579
denominator
1.3773937692250382
gamma
1
beta
0
Saved outputs
normalized
0.6876854075163181
scaled
0.6876854075163181
value
0.6876854075163181

forwardA_ln2_0_feature_1: ln2_0: affine feature 1

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.

Saved inputs
d
1
source
-0.9472135954999579
denominator
1.3773937692250382
gamma
1
beta
0
Saved outputs
normalized
-0.6876854075163181
scaled
-0.6876854075163181
value
-0.6876854075163181

forwardA_ffn_hidden_0_0_0: Hidden affine [0,0,0]

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.

Saved inputs
b
0
t
0
m
0
x0
0.6876854075163181
x1
-0.6876854075163181
w0
1
w1
0
bias
0
Saved outputs
product0
0.6876854075163181
product1
0
sum
0.6876854075163181
preactivation
0.6876854075163181

forwardA_ffn_hidden_0_0_1: Hidden affine [0,0,1]

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.

Saved inputs
b
0
t
0
m
1
x0
0.6876854075163181
x1
-0.6876854075163181
w0
0
w1
1
bias
0
Saved outputs
product0
0
product1
-0.6876854075163181
sum
-0.6876854075163181
preactivation
-0.6876854075163181

forwardA_ffn_hidden_0_0_2: Hidden affine [0,0,2]

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.

Saved inputs
b
0
t
0
m
2
x0
0.6876854075163181
x1
-0.6876854075163181
w0
0
w1
0
bias
0
Saved outputs
product0
0
product1
0
sum
0
preactivation
0

forwardA_ffn_relu_0_0_0: ReLU [0,0,0]

activation=max(0,preactivation)

ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.

Saved inputs
b
0
t
0
m
0
preactivation
0.6876854075163181
Saved outputs
activation
0.6876854075163181

forwardA_ffn_relu_0_0_1: ReLU [0,0,1]

activation=max(0,preactivation)

ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.

Saved inputs
b
0
t
0
m
1
preactivation
-0.6876854075163181
Saved outputs
activation
0

forwardA_ffn_relu_0_0_2: ReLU [0,0,2]

activation=max(0,preactivation)

ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.

Saved inputs
b
0
t
0
m
2
preactivation
0
Saved outputs
activation
0

forwardA_ffn_output_0_0_0: FFN output [0,0,0]

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.

Saved inputs
b
0
t
0
d
0
h0
0.6876854075163181
w0
1
h1
0
w1
0
h2
0
w2
0
bias
0
Saved outputs
product0
0.6876854075163181
product1
0
product2
0
running0
0.6876854075163181
running1
0.6876854075163181
running2
0.6876854075163181
sum
0.6876854075163181
value
0.6876854075163181

forwardA_ffn_output_0_0_1: FFN output [0,0,1]

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.

Saved inputs
b
0
t
0
d
1
h0
0.6876854075163181
w0
0
h1
0
w1
1
h2
0
w2
0
bias
0
Saved outputs
product0
0
product1
0
product2
0
running0
0
running1
0
running2
0
sum
0
value
0

forwardA_residual2_0_0: Second residual position 0, feature 0

value=R1+F

The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights.

Saved inputs
t
0
d
0
left
1.4472135954999579
right
0.6876854075163181
Saved outputs
value
2.134899003016276

forwardA_residual2_0_1: Second residual position 0, feature 1

value=R1+F

The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights.

Saved inputs
t
0
d
1
left
-0.4472135954999579
right
0
Saved outputs
value
-0.4472135954999579

forwardA_readout_0_0: Readout position 0, class 0

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

Final decoder features multiply only the active class columns. Bias is added last; targets are not operands.

Saved inputs
t
0
c
0
y0
2.134899003016276
u0
1
y1
-0.4472135954999579
u1
0
bias
0
Saved outputs
product0
2.134899003016276
product1
0
sum
2.134899003016276
logit
2.134899003016276

forwardA_readout_0_1: Readout position 0, class 1

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

Final decoder features multiply only the active class columns. Bias is added last; targets are not operands.

Saved inputs
t
0
c
1
y0
2.134899003016276
u0
0
y1
-0.4472135954999579
u1
1
bias
0
Saved outputs
product0
0
product1
-0.4472135954999579
sum
-0.4472135954999579
logit
-0.4472135954999579

forwardA_readout_0_2: Readout position 0, class 2

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

Final decoder features multiply only the active class columns. Bias is added last; targets are not operands.

Saved inputs
t
0
c
2
y0
2.134899003016276
u0
0
y1
-0.4472135954999579
u1
0
bias
0
Saved outputs
product0
0
product1
0
sum
0
logit
0

forwardA_class_0_max: Position 0: active class maximum

max=max(active logits)

The maximum stabilizes exponentiation; every active class participates before the target is selected.

Saved inputs
z0
2.134899003016276
z1
-0.4472135954999579
z2
0
Saved outputs
max
2.134899003016276

forwardA_class_0_exp_0: Position 0: exponentiate class 0

shifted=logit-max; term=exp(shifted)

At least one term is exp(0)=1. No probability is clipped or rounded for this calculation.

Saved inputs
t
0
c
0
logit
2.134899003016276
max
2.134899003016276
Saved outputs
shifted
0
term
1

forwardA_class_0_exp_1: Position 0: exponentiate class 1

shifted=logit-max; term=exp(shifted)

At least one term is exp(0)=1. No probability is clipped or rounded for this calculation.

Saved inputs
t
0
c
1
logit
-0.4472135954999579
max
2.134899003016276
Saved outputs
shifted
-2.582112598516234
term
0.0756140929478022

forwardA_class_0_exp_2: Position 0: exponentiate class 2

shifted=logit-max; term=exp(shifted)

At least one term is exp(0)=1. No probability is clipped or rounded for this calculation.

Saved inputs
t
0
c
2
logit
0
max
2.134899003016276
Saved outputs
shifted
-2.134899003016276
term
0.11825653332669596

forwardA_class_0_normalize: Position 0: class denominator and logsumexp

running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS

Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE.

Saved inputs
term0
1
term1
0.0756140929478022
term2
0.11825653332669596
max
2.134899003016276
Saved outputs
running0
1
running1
1.0756140929478022
running2
1.1938706262744982
denominator
1.1938706262744982
logS
0.17720065589584005
lse
2.312099658912116

forwardA_class_0_probability_0: Position 0: normalize class 0

probability=term/S

This is the stored binary64 probability for a real active class, before display formatting.

Saved inputs
t
0
c
0
term
1
denominator
1.1938706262744982
Saved outputs
probability
0.8376116959343609

forwardA_class_0_probability_1: Position 0: normalize class 1

probability=term/S

This is the stored binary64 probability for a real active class, before display formatting.

Saved inputs
t
0
c
1
term
0.0756140929478022
denominator
1.1938706262744982
Saved outputs
probability
0.063335248630547

forwardA_class_0_probability_2: Position 0: normalize class 2

probability=term/S

This is the stored binary64 probability for a real active class, before display formatting.

Saved inputs
t
0
c
2
term
0.11825653332669596
denominator
1.1938706262744982
Saved outputs
probability
0.09905305543509206

forwardA_class_0_argmax: Position 0: computed-logit winner

argmax computed logits; exact ties choose smallest compact class

Stored probabilities can appear tied even for different computed logits. This prediction is inspected, never fed back into teacher forcing.

Saved inputs
z0
2.134899003016276
z1
-0.4472135954999579
z2
0
Saved outputs
nextRow
0
nextID
97
nextProbability
0.8376116959343609

Row 0, class slot 2: actual operands and probabilities

Logit z[c]=(Y[t,0]×U[0,c]+Y[t,1]×U[1,c])+bias[c]. A probability P[c] is the saved normalized exponential for an active class. Its target indicator is 1 only for the actual observed target. NLL uses (max−targetLogit)+logS, where logS is the logarithm of the saved shifted exponential sum.

Saved gradient operands for row 0, compact class 2
ActiveActual P beforeTarget indicatorP−indicatorMask×differenceDivide by N: dLogit
true0.099053055435092061-0.900946944564908-0.900946944564908-0.450473472282454
Saved active class 2, ID512: initial and updated distributions
PhaseLogitMax-shifted logitExponential termDenominatorActual P
Initial full forward0-2.1348990030162760.118256533326695961.19387062627449820.09905305543509206
Updated readout on same Y0.2184022442795555-1.67823719675950640.186702806434806521.28458450188440040.14534100805429762
Selected class: initial/updated readout products and distribution steps

forwardA_readout_0_2: Readout position 0, class 2

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

Final decoder features multiply only the active class columns. Bias is added last; targets are not operands.

Saved inputs
t
0
c
2
y0
2.134899003016276
u0
0
y1
-0.4472135954999579
u1
0
bias
0
Saved outputs
product0
0
product1
0
sum
0
logit
0

forwardA_class_0_max: Position 0: active class maximum

max=max(active logits)

The maximum stabilizes exponentiation; every active class participates before the target is selected.

Saved inputs
z0
2.134899003016276
z1
-0.4472135954999579
z2
0
Saved outputs
max
2.134899003016276

forwardA_class_0_exp_2: Position 0: exponentiate class 2

shifted=logit-max; term=exp(shifted)

At least one term is exp(0)=1. No probability is clipped or rounded for this calculation.

Saved inputs
t
0
c
2
logit
0
max
2.134899003016276
Saved outputs
shifted
-2.134899003016276
term
0.11825653332669596

forwardA_class_0_normalize: Position 0: class denominator and logsumexp

running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS

Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE.

Saved inputs
term0
1
term1
0.0756140929478022
term2
0.11825653332669596
max
2.134899003016276
Saved outputs
running0
1
running1
1.0756140929478022
running2
1.1938706262744982
denominator
1.1938706262744982
logS
0.17720065589584005
lse
2.312099658912116

forwardA_class_0_probability_2: Position 0: normalize class 2

probability=term/S

This is the stored binary64 probability for a real active class, before display formatting.

Saved inputs
t
0
c
2
term
0.11825653332669596
denominator
1.1938706262744982
Saved outputs
probability
0.09905305543509206

postA_0_readout_2: Updated readout class 2

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

Two fixed-feature products in feature order, then bias last. Derived finite weights have no initial-editor bounds.

Saved inputs
c
2
y0
2.134899003016276
u0
0.07602575056443042
y1
-0.4472135954999579
u1
0.07602575056443042
bias
0.0900946944564908
Saved outputs
product0
0.1623072990835666
product1
-0.03399974926050189
sum
0.1283075498230647
logit
0.2184022442795555

postA_0_class_max: Find the maximum active computed logit

max=max(z0,...,z[V-1])

All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.

Saved inputs
z0
1.896639441039062
z1
-0.4273562778022991
z2
0.2184022442795555
Saved outputs
max
1.896639441039062

postA_0_class_exp_2: Exponentiate active class 2

shifted=logit-max; term=exp(shifted)

No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.

Saved inputs
c
2
logit
0.2184022442795555
max
1.896639441039062
Saved outputs
shifted
-1.6782371967595064
term
0.18670280643480652

postA_0_class_normalize: Accumulate terms and compute logsumexp

running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS

The denominator adds terms in ascending compact class order. Every actual running sum is saved.

Saved inputs
term0
1
term1
0.09788169544959381
term2
0.18670280643480652
max
1.896639441039062
Saved outputs
running0
1
running1
1.0978816954495938
running2
1.2845845018844004
denominator
1.2845845018844004
logS
0.25043532122292733
lse
2.1470747622619895

postA_0_class_probability_2: Normalize active class 2

probability=term/S

This stored binary64 probability is displayed without feeding its formatting back into arithmetic.

Saved inputs
c
2
term
0.18670280643480652
denominator
1.2845845018844004
Saved outputs
probability
0.14534100805429762
Selected row: actual before/after target loss and all five logit derivatives

forwardA_loss_0: Score document 0, position 0

gap=max-targetLogit; nll=gap+logS; weightedNLL=mask*nll; lossSum=previousSum+weightedNLL

Keep even a masked row’s genuine distribution and NLL. Factored finite NLL avoids probability clipping and rounded LSE subtraction; accumulate A then B in position order.

Saved inputs
docID
0
position
0
targetID
512
targetRow
2
mask
1
max
2.134899003016276
targetLogit
0
logS
0.17720065589584005
probability
0.09905305543509206
previousSum
0
Saved outputs
gap
2.134899003016276
nll
2.312099658912116
weightedNLL
2.312099658912116
lossSum
2.312099658912116

gradient_row_0: All five logit derivatives for row 0

active: difference=P-indicator; masked=mask*difference; gradient=masked/N; inactive: gradient=0

Every active class operand and result is retained. Inactive slots have structural zero derivatives without invented probabilities.

Saved inputs
r
0
targetID
512
targetRow
2
mask
1
validTargets
2
probability0
0.8376116959343609
indicator0
0
probability1
0.063335248630547
indicator1
0
probability2
0.09905305543509206
indicator2
1
Saved outputs
active0
1
difference0
0.8376116959343609
masked0
0.8376116959343609
gradient0
0.41880584796718046
active1
1
difference1
0.063335248630547
masked1
0.063335248630547
gradient1
0.0316676243152735
active2
1
difference2
-0.900946944564908
masked2
-0.900946944564908
gradient2
-0.450473472282454
active3
0
gradient3
0
active4
0
gradient4
0

postA_0_loss: Score document 0, position 0

gap=max-targetLogit; nll=gap+logS; weightedNLL=mask*nll; lossSum=previousSum+weightedNLL

Keep even a masked row’s genuine distribution and NLL. Factored finite NLL avoids probability clipping and rounded LSE subtraction; accumulate A then B in position order.

Saved inputs
docID
0
position
0
targetID
512
targetRow
2
mask
1
max
1.896639441039062
targetLogit
0.2184022442795555
logS
0.25043532122292733
probability
0.14534100805429762
previousSum
0
Saved outputs
gap
1.6782371967595064
nll
1.9286725179824338
weightedNLL
1.9286725179824338
lossSum
1.9286725179824338

Fifteen actual gradients → one simultaneous update

A gradient g is the derivative of this saved masked mean with respect to one initial readout parameter θ. For U[d,c], sum Y[row,d]×dLogit[row,c] in A-then-B position order; for bias[c], sum dLogit directly. Every new θ uses this same old gradient vector. The table includes inactive structural zeros.

One simultaneous SGD update from the same old gradient vector. Unused Adam m/v stay zero and tAdam stays 0; completedUpdates becomes 1. First moments m average signed gradients; second moments v average squared gradients. Each starts at zero here. Adam’s bias-corrected moments are mHat/vHat; its denominator is sqrt(vHat)+ε, with ε outside the square root.

All fifteen saved readout coordinates, gradients, updates and moments
ParameterActive classθ beforeGradient gSubtracted deltaθ afterm beforem afterv beforev after
u00true10.87994599515154430.087994599515154430.91200540048484560000
u01true0-0.11968848950724015-0.0119688489507240160.0119688489507240160000
u02true0-0.7602575056443042-0.076025750564430420.076025750564430420000
u03false00000000
u04false00000000
u10true0-0.11968848950724015-0.0119688489507240160.0119688489507240160000
u11true10.87994599515154430.087994599515154430.91200540048484560000
u12true0-0.7602575056443042-0.076025750564430420.076025750564430420000
u13false00000000
u14false00000000
b0true00.450473472282453940.045047347228245396-0.0450473472282453960000
b1true00.450473472282453940.045047347228245396-0.0450473472282453960000
b2true0-0.900946944564908-0.09009469445649080.09009469445649080000
b3false00000000
b4false00000000
Actual shared optimizer counters for the fifteen-coordinate update
CounterBeforeAfter
Adam-only tAdam00
Global completedUpdates01

Saved optimizer: SGD; η=0.1. A finite step may increase, decrease or preserve the objective. SGD leaves unused m/v and tAdam zero. Inactive Adam controls still validate.

Actual ordered contraction for u00
Prediction rowSaved dLogit gSaved Y featureSaved productSaved running sum
00.418805847967180462.1348990030162760.89410818728251960.8941081872825196
10.0316676243152735-0.4472135954999579-0.0141621921309753560.8799459951515443
Selected parameter: full contraction, common optimizer setup and actual update operands

gradient_parameter_0: Derivative u00

product_r=Y[r,d]*g[r,c]; running starts at 0; running_r=previous+product_r

Immediately accumulate in document then position order. All fifteen parameters remain present, including inactive structural zeros.

Saved inputs
k
0
c
0
d
0
active
1
g0
0.41880584796718046
y0
2.134899003016276
g1
0.0316676243152735
y1
-0.4472135954999579
Saved outputs
product0
0.8941081872825196
running0
0.8941081872825196
product1
-0.014162192130975356
running1
0.8799459951515443
gradient
0.8799459951515443

optimizer_setup: Compute the common optimizer arithmetic once

completedNew=completedUpdates+1; tNew=0

Global completed updates and Adam-only steps are distinct. Every coordinate below uses the same old state and gradient.

Saved inputs
eta
0.1
optimizer
0
beta1
0.9
beta2
0.999
epsilon
1e-8
tAdam
0
completedUpdates
0
Saved outputs
completedNew
1
tNew
0

optimizer_parameter_0: Simultaneously update u00

delta=eta*g; thetaNew=theta-delta; mNew=vNew=0

The old arrays are never mutated. A complete new state is published only after every finite calculation succeeds; epsilon is outside sqrt.

Saved inputs
k
0
theta
1
gradient
0.8799459951515443
eta
0.1
mOld
0
vOld
0
Saved outputs
mNew
0
vNew
0
delta
0.08799459951515443
thetaNew
0.9120054004848456

Updated loss: new readout, same actual Y

Actual old Y is independent of U/bias. Recompute finite updated affine readout, old directDistribution and factored NLL on that same Y. No second full forward or reuse of readout-dependent cache evidence; no raw bound check or clipping of updated weights.

Saved tokenizerCalls=2; initial fullForwardCalls=2; updated postReadoutRows=2. No additional full encoder call occurs after the update. Initial U/bias editor limits describe starting inputs; finite derived weights may lie beyond them and are neither clamped nor put back through that editor. The tokenizer corpus, encoder defaults and tensor metadata are fixed; each edit creates a fresh detached saved record.

A real update can increase, decrease or preserve this masked objective. These values are computed from the supplied authored toy data, not a generated learning curve or a monotonicity promise.

Both actual tokenizer traces, EOS append steps and final call counts

setup: Declare actual isolated readout-only training

two EOS-off tokenizers; one EOS/doc; selected inputs=sequence[:-1]; targets=sequence[1:]; train U[2,5] and bias[5]

All own descriptors precede captured value reads; both string types and every numeric domain precede A then B text semantics. Initial bounds are separate from finite derived weights.

Saved inputs
merges
0
batchSize
2
u00
1
u01
0
u02
0
u03
0
u04
0
u10
0
u11
1
u12
0
u13
0
u14
0
b0
0
b1
0
b2
0
b3
0
b4
0
eta
0.1
optimizer
0
beta1
0.9
beta2
0.999
epsilon
1e-8
mA0
1
mA1
1
mB0
1
mB1
1
Saved outputs
byteBound
2
tokenizerCalls
2
appendedEOS
2
classCount
3
trainableParameters
15
fixedEncoder
1

docA_setup: Declare learned byte-pair encoding and both exact inputs

byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes

Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.

Saved inputs
requestedMerges
0
eos
0
Saved outputs
corpusUnits
4
corpusScalars
4
utf16Units
1
scalarCount
1
byteBound
24
mergeBase
256
mergeBound
4
EOS
512

docA_corpus_scalar_0: Encode scalar 0: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
0
byteWidth
1
payload0
97
byte0
97

docA_corpus_scalar_1: Encode scalar 1: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
1
utf16Offset
1
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
1
byteWidth
1
payload0
98
byte0
98

docA_corpus_scalar_2: Encode scalar 2: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
2
utf16Offset
2
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
2
byteWidth
1
payload0
97
byte0
97

docA_corpus_scalar_3: Encode scalar 3: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
3
utf16Offset
3
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
3
byteWidth
1
payload0
98
byte0
98

docA_source_scalar_0: Encode scalar 0: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
0
byteWidth
1
payload0
97
byte0
97

docA_corpus_expand_0: corpus: expand ID at token 0

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
0
id
97
Saved outputs
byteOffset
0
byteWidth
1
byte0
97

docA_corpus_expand_1: corpus: expand ID at token 1

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
1
id
98
Saved outputs
byteOffset
1
byteWidth
1
byte0
98

docA_corpus_expand_2: corpus: expand ID at token 2

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
2
id
97
Saved outputs
byteOffset
2
byteWidth
1
byte0
97

docA_corpus_expand_3: corpus: expand ID at token 3

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
3
id
98
Saved outputs
byteOffset
3
byteWidth
1
byte0
98

docA_corpus_decode_0: Decode UTF-8 scalar 0

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docA_corpus_decode_1: Decode UTF-8 scalar 1

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
1
byteOffset
1
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docA_corpus_decode_2: Decode UTF-8 scalar 2

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
2
byteOffset
2
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docA_corpus_decode_3: Decode UTF-8 scalar 3

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
3
byteOffset
3
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docA_target_expand_0: target: expand ID at token 0

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
0
id
97
Saved outputs
byteOffset
0
byteWidth
1
byte0
97

docA_target_decode_0: Decode UTF-8 scalar 0

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docA_roundtrip: Compare both actual strict reconstructions with the original strings

corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)

Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.

Saved inputs
corpusOriginalUnits
4
corpusDecodedUnits
4
corpusDecodedByteCount
4
originalUnits
1
decodedUnits
1
decodedByteCount
1
Saved outputs
corpusTokens
4
tokenCount
1
corpusEqual
1
equal
1

docA_append_eos: docA: append exactly one EOS

sequenceIDs=[...actual EOS-off TargetIDs,512]

The helper returned these genuine content IDs and this one appended EOS. This frame records that actual append; no second append is performed.

Saved inputs
docID
0
contentTokens
1
tokenizerEOS
0
Saved outputs
eosPosition
1
eosID
512
sequenceTokens
2

docB_setup: Declare learned byte-pair encoding and both exact inputs

byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes

Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.

Saved inputs
requestedMerges
0
eos
0
Saved outputs
corpusUnits
4
corpusScalars
4
utf16Units
1
scalarCount
1
byteBound
24
mergeBase
256
mergeBound
4
EOS
512

docB_corpus_scalar_0: Encode scalar 0: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
0
byteWidth
1
payload0
97
byte0
97

docB_corpus_scalar_1: Encode scalar 1: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
1
utf16Offset
1
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
1
byteWidth
1
payload0
98
byte0
98

docB_corpus_scalar_2: Encode scalar 2: U+0061

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
2
utf16Offset
2
utf16Width
1
codePoint
97
unit0
97
Saved outputs
byteOffset
2
byteWidth
1
payload0
97
byte0
97

docB_corpus_scalar_3: Encode scalar 3: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
3
utf16Offset
3
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
3
byteWidth
1
payload0
98
byte0
98

docB_source_scalar_0: Encode scalar 0: U+0062

supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits

A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.

Saved inputs
scalarIndex
0
utf16Offset
0
utf16Width
1
codePoint
98
unit0
98
Saved outputs
byteOffset
0
byteWidth
1
payload0
98
byte0
98

docB_corpus_expand_0: corpus: expand ID at token 0

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
0
id
97
Saved outputs
byteOffset
0
byteWidth
1
byte0
97

docB_corpus_expand_1: corpus: expand ID at token 1

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
1
id
98
Saved outputs
byteOffset
1
byteWidth
1
byte0
98

docB_corpus_expand_2: corpus: expand ID at token 2

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
2
id
97
Saved outputs
byteOffset
2
byteWidth
1
byte0
97

docB_corpus_expand_3: corpus: expand ID at token 3

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
3
id
98
Saved outputs
byteOffset
3
byteWidth
1
byte0
98

docB_corpus_decode_0: Decode UTF-8 scalar 0

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docB_corpus_decode_1: Decode UTF-8 scalar 1

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
1
byteOffset
1
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docB_corpus_decode_2: Decode UTF-8 scalar 2

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
2
byteOffset
2
byteWidth
1
byte0
97
Saved outputs
payload0
97
accumulator0
97
codePoint
97
utf16Width
1
unit0
97

docB_corpus_decode_3: Decode UTF-8 scalar 3

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
3
byteOffset
3
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docB_target_expand_0: target: expand ID at token 0

ID → validated byte expansion

Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.

Saved inputs
index
0
id
98
Saved outputs
byteOffset
0
byteWidth
1
byte0
98

docB_target_decode_0: Decode UTF-8 scalar 0

accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar

Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.

Saved inputs
scalarIndex
0
byteOffset
0
byteWidth
1
byte0
98
Saved outputs
payload0
98
accumulator0
98
codePoint
98
utf16Width
1
unit0
98

docB_roundtrip: Compare both actual strict reconstructions with the original strings

corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)

Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.

Saved inputs
corpusOriginalUnits
4
corpusDecodedUnits
4
corpusDecodedByteCount
4
originalUnits
1
decodedUnits
1
decodedByteCount
1
Saved outputs
corpusTokens
4
tokenCount
1
corpusEqual
1
equal
1

docB_append_eos: docB: append exactly one EOS

sequenceIDs=[...actual EOS-off TargetIDs,512]

The helper returned these genuine content IDs and this one appended EOS. This frame records that actual append; no second append is performed.

Saved inputs
docID
1
contentTokens
1
tokenizerEOS
0
Saved outputs
eosPosition
1
eosID
512
sequenceTokens
2

finish: Disclose actual calls and state counters

fullForwardCalls=batchSize; postReadoutRows=predictionRows; completedUpdates=1

Both complete tokenizer records, every selected full forward and every updated direct distribution are preserved. No hidden cache, fabricated inactive probability, full-model gradient or second full-forward claim.

Saved inputs
tokenizerFrames
34
forwardFrames
114
predictionRows
2
optimizer
0
Saved outputs
tokenizerCalls
2
appendedEOS
2
fullForwardCalls
2
postReadoutRows
2
validTargets
2
completedUpdates
1
tAdam
0
Saved model and computation policies
tokenizerPolicy
Two actual IV51 document-helper calls reuse the full old EOS-off IV39 records with fixed corpus abab. Append exactly one explicit EOS per document; no normalization, lookup substitute or retokenization.
gradientPolicy
Active logit derivatives are mask*(P-indicator)/N. Inactive five-class slots have structural zero gradients without invented probabilities. Contract all fifteen parameter gradients from the actual saved old Y and probabilities.
numericCoherence
Public helpers validate numeric structure and finite domains, not encoder origin or objective identity. The wrapper supplies actual old Y and same-evaluation probabilities/classes/targets/masks and retains their complete witnesses.
provenance
Authored raw a/b documents, fixed authored tokenizer corpus abab, deterministic old model defaults; no random stream, external corpus, pretrained model or hidden history.

All tables copy the same saved record. Scrollable tables are named and keyboard-focusable; permissions use true/false words. The complete inspector below retains each tensor’s actual dtype, rank, axes, shape, precision and provenance. Inspection performs storage indexing only; displayed operands never feed another model calculation.

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.

docA_CorpusCodePoints

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198
297
398

docA_CorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docA_CorpusUTF16Widths

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11
21
31

docA_CorpusByteOffsets

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docA_CorpusByteWidths

Scalars=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11
21
31

docA_CorpusBytes

Bytes=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198
297
398

docA_SourceCodePoints

Scalars=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097

docA_SourceUTF16Offsets

Scalars=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00

docA_SourceUTF16Widths

Scalars=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01

docA_SourceByteOffsets

Scalars=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00

docA_SourceByteWidths

Scalars=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01

docA_SourceBytes

Bytes=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097

docA_TrainInitialIDs

Tokens=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexStored value
097
198
297
398

docA_CorpusIDs

Tokens=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexStored value
097
198
297
398

docA_EncodeInitialIDs

Tokens=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Initial target byte IDs before any ranked application.

Zero-based storage indexStored value
097

docA_TargetIDs

Tokens=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexStored value
097

docA_CorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198
297
398

docA_TargetDecodedBytes

Bytes=1 · int32 · precision 0 · Actual docA IV39 call; fixed corpus abab, EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097

docA_ContentIDs

ContentPosition=1 · int32 · precision 0 · Actual old EOS-off TargetIDs, copied without lookup or retokenization.

Zero-based storage indexStored value
097

docA_SequenceIDs

DocumentPosition=2 · int32 · precision 0 · Actual content IDs followed by exactly one explicit EOS512.

Zero-based storage indexStored value
097
1512

docB_CorpusCodePoints

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198
297
398

docB_CorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docB_CorpusUTF16Widths

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11
21
31

docB_CorpusByteOffsets

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

docB_CorpusByteWidths

Scalars=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11
21
31

docB_CorpusBytes

Bytes=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198
297
398

docB_SourceCodePoints

Scalars=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
098

docB_SourceUTF16Offsets

Scalars=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00

docB_SourceUTF16Widths

Scalars=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01

docB_SourceByteOffsets

Scalars=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00

docB_SourceByteWidths

Scalars=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01

docB_SourceBytes

Bytes=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
098

docB_TrainInitialIDs

Tokens=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexStored value
097
198
297
398

docB_CorpusIDs

Tokens=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexStored value
097
198
297
398

docB_EncodeInitialIDs

Tokens=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Initial target byte IDs before any ranked application.

Zero-based storage indexStored value
098

docB_TargetIDs

Tokens=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexStored value
098

docB_CorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198
297
398

docB_TargetDecodedBytes

Bytes=1 · int32 · precision 0 · Actual docB IV39 call; fixed corpus abab, EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
098

docB_ContentIDs

ContentPosition=1 · int32 · precision 0 · Actual old EOS-off TargetIDs, copied without lookup or retokenization.

Zero-based storage indexStored value
098

docB_SequenceIDs

DocumentPosition=2 · int32 · precision 0 · Actual content IDs followed by exactly one explicit EOS512.

Zero-based storage indexStored value
098
1512

ActiveIDs

Class=3 · int32 · precision 0 · Restricted active prediction classes, not the full tokenizer vocabulary; public IDs are labels.

Zero-based storage indexStored value
097
198
2512

RowDocIDs

PredictionRow=2 · int32 · precision 0 · Selected real shifted rows in document then ascending position order; no padding or unselected document rows.

Zero-based storage indexStored value
00
11

RowPositions

PredictionRow=2 · int32 · precision 0 · Selected real shifted rows in document then ascending position order; no padding or unselected document rows.

Zero-based storage indexStored value
00
10

InputIDs

PredictionRow=2 · int32 · precision 0 · Selected real shifted rows in document then ascending position order; no padding or unselected document rows.

Zero-based storage indexStored value
097
198

TargetIDs

PredictionRow=2 · int32 · precision 0 · Selected real shifted rows in document then ascending position order; no padding or unselected document rows.

Zero-based storage indexStored value
0512
1512

TargetRows

PredictionRow=2 · int32 · precision 0 · Selected real shifted rows in document then ascending position order; no padding or unselected document rows.

Zero-based storage indexStored value
02
12

RequestedMask

PredictionRow=2 · int32 · precision 0 · Selected real shifted rows in document then ascending position order; no padding or unselected document rows.

Zero-based storage indexStored value
01
11

forwardA_AllClassIDs

ModelRow=5 · int32 · precision 0 · Actual isolated forwardA at initial weights; positions restart at zero. Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets.

Zero-based storage indexStored value
097
198
2512
3256
4257

forwardA_ClassIDs

Class=3 · int32 · precision 0 · Actual isolated forwardA at initial weights; positions restart at zero. Active prefix of the full model row map; V=3+merges.

Zero-based storage indexStored value
097
198
2512

forwardA_E

ModelRow=5 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. All ten validated editable embeddings, including EOS and inactive learned pieces.

Zero-based storage indexStored value
01
10
20
31
40
50
60.5
70.5
81
91

forwardA_U

D=2 × ModelRow=5 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. All ten validated editable readout weights; only the first V columns contribute logits.

Zero-based storage indexStored value
01
10
20
30
40
50
61
70
80
90

forwardA_Bias

ModelRow=5 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. All five validated editable biases; inactive columns have no objective dependency.

Zero-based storage indexStored value
00
10
20
30
40

forwardA_InputIDs

Position=1 · int32 · precision 0 · Actual isolated forwardA at initial weights; positions restart at zero. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.

Zero-based storage indexStored value
097

forwardA_InputRows

Position=1 · int32 · precision 0 · Actual isolated forwardA at initial weights; positions restart at zero. Compact model row gathered for each observed ID; never index by public ID512.

Zero-based storage indexStored value
00

forwardA_X

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Actual gathered E rows; B=1, token-major storage and D=2.

Zero-based storage indexStored value
01
10

forwardA_LN1

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Per-token feature layer norm of X; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionX

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Active token rows; D=2 input features always retained. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Query columns packed by h*Dk+f from wq{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

forwardA_ProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Key columns packed by h*Dk+f from wk{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

forwardA_ProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Value columns packed by h*Dv+f from wv{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

forwardA_ProjectionQConcat

B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. XWQ; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionKConcat

B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. XWK; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionVConcat

B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. XWV; values are projected separately from queries and keys. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionQSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. QConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionQHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionKSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. KConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionKHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionVSplit

B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. VConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_ProjectionVHeads

B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_RotatedQHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_RotatedKHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_RoPEAngles

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Absolute position t times the single-pair frequency1, in radians.

Zero-based storage indexStored value
00

forwardA_RoPECos

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Stored cos(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
01

forwardA_RoPESin

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Stored sin(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
00

forwardA_Attentionraw

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Separate QHeads KHeads transpose products within every batch and head. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.39999999999999997

forwardA_Attentionscores

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895

forwardA_Attentionallowed

B=1 × H=1 × Query=1 × Key=1 · bool · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Causal and/or valid-key mask; shared validity across B and H; every query retained. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
0true

forwardA_Attentionlogits

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Finite score+shift, including forbidden cells; mask applied separately. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895

forwardA_Attentionprobabilities

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
01

forwardA_AttentionOHeads

B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Actual per-head P times VHeads; every product and running sum is traced. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_AttentionC

B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_AttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. wo{h}{f}{d} packed in h,f,d order, preserving parameter identity. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
01
10
20
31

forwardA_AttentionOutput

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Y=C WO, summing products in ascending joined-feature order from zero; no normalization. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

forwardA_R1

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Exact named-shape addition of X and AttentionOutput; no broadcasting.

Zero-based storage indexStored value
01.4472135954999579
1-0.4472135954999579

forwardA_LN2

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Per-token feature layer norm of R1; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
00.6876854075163181
1-0.6876854075163181

forwardA_W1

D=2 × HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

Zero-based storage indexStored value
01
10
20
30
41
50

forwardA_b1

HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

forwardA_Z

B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Hidden preactivations X W1+b1; no batch or token mixing.

Zero-based storage indexStored value
00.6876854075163181
1-0.6876854075163181
20

forwardA_Hidden

B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. ReLU(Z)=max(0,Z), before the second affine layer.

Zero-based storage indexStored value
00.6876854075163181
10
20

forwardA_W2

HiddenFeature=3 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Shared hidden-to-output weights, f2{m}{d}.

Zero-based storage indexStored value
01
10
20
31
40
50

forwardA_b2

D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

forwardA_F

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Zero-based storage indexStored value
00.6876854075163181
10

forwardA_Y

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Exact named-shape addition of R1 and F; no broadcasting.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579

forwardA_Logits

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Final Y times the active U prefix, then active Bias; targets are not operands.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20

forwardA_Max

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Maximum computed active class logit at each position.

Zero-based storage indexStored value
02.134899003016276

forwardA_Shifted

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Computed class logit minus its saved row maximum.

Zero-based storage indexStored value
00
1-2.582112598516234
2-2.134899003016276

forwardA_Terms

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Actual exp(Shifted) before left-to-right class summation.

Zero-based storage indexStored value
01
10.0756140929478022
20.11825653332669596

forwardA_Denominator

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Shifted exponential sum from zero in ascending compact class order.

Zero-based storage indexStored value
01.1938706262744982

forwardA_LogS

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. ln(Denominator), saved for factored NLL.

Zero-based storage indexStored value
00.17720065589584005

forwardA_LSE

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.

Zero-based storage indexStored value
02.312099658912116

forwardA_P

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Terms/Denominator for real active classes only; no inactive-class probabilities.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
20.09905305543509206

forwardA_NextRows

Position=1 · int32 · precision 0 · Actual isolated forwardA at initial weights; positions restart at zero. Highest computed logit; exact ties keep the smallest compact class.

Zero-based storage indexStored value
00

forwardA_NextIDs

Position=1 · int32 · precision 0 · Actual isolated forwardA at initial weights; positions restart at zero. Public ID mapped from each computed-logit winner.

Zero-based storage indexStored value
097

forwardA_NextProbability

Position=1 · float64 · precision 8 · Actual isolated forwardA at initial weights; positions restart at zero. Stored class probability of the computed-logit winner; never fed back as an observed input.

Zero-based storage indexStored value
00.8376116959343609

forwardB_AllClassIDs

ModelRow=5 · int32 · precision 0 · Actual isolated forwardB at initial weights; positions restart at zero. Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets.

Zero-based storage indexStored value
097
198
2512
3256
4257

forwardB_ClassIDs

Class=3 · int32 · precision 0 · Actual isolated forwardB at initial weights; positions restart at zero. Active prefix of the full model row map; V=3+merges.

Zero-based storage indexStored value
097
198
2512

forwardB_E

ModelRow=5 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. All ten validated editable embeddings, including EOS and inactive learned pieces.

Zero-based storage indexStored value
01
10
20
31
40
50
60.5
70.5
81
91

forwardB_U

D=2 × ModelRow=5 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. All ten validated editable readout weights; only the first V columns contribute logits.

Zero-based storage indexStored value
01
10
20
30
40
50
61
70
80
90

forwardB_Bias

ModelRow=5 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. All five validated editable biases; inactive columns have no objective dependency.

Zero-based storage indexStored value
00
10
20
30
40

forwardB_InputIDs

Position=1 · int32 · precision 0 · Actual isolated forwardB at initial weights; positions restart at zero. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.

Zero-based storage indexStored value
098

forwardB_InputRows

Position=1 · int32 · precision 0 · Actual isolated forwardB at initial weights; positions restart at zero. Compact model row gathered for each observed ID; never index by public ID512.

Zero-based storage indexStored value
01

forwardB_X

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Actual gathered E rows; B=1, token-major storage and D=2.

Zero-based storage indexStored value
00
11

forwardB_LN1

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Per-token feature layer norm of X; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionX

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Active token rows; D=2 input features always retained. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Query columns packed by h*Dk+f from wq{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

forwardB_ProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Key columns packed by h*Dk+f from wk{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

forwardB_ProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Value columns packed by h*Dv+f from wv{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

forwardB_ProjectionQConcat

B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. XWQ; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionKConcat

B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. XWK; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionVConcat

B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. XWV; values are projected separately from queries and keys. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionQSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. QConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionQHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionKSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. KConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionKHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionVSplit

B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. VConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_ProjectionVHeads

B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_RotatedQHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_RotatedKHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_RoPEAngles

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Absolute position t times the single-pair frequency1, in radians.

Zero-based storage indexStored value
00

forwardB_RoPECos

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Stored cos(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
01

forwardB_RoPESin

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Stored sin(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
00

forwardB_Attentionraw

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Separate QHeads KHeads transpose products within every batch and head. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.39999999999999997

forwardB_Attentionscores

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895

forwardB_Attentionallowed

B=1 × H=1 × Query=1 × Key=1 · bool · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Causal and/or valid-key mask; shared validity across B and H; every query retained. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
0true

forwardB_Attentionlogits

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Finite score+shift, including forbidden cells; mask applied separately. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895

forwardB_Attentionprobabilities

B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
01

forwardB_AttentionOHeads

B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Actual per-head P times VHeads; every product and running sum is traced. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_AttentionC

B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_AttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. wo{h}{f}{d} packed in h,f,d order, preserving parameter identity. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
01
10
20
31

forwardB_AttentionOutput

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Y=C WO, summing products in ascending joined-feature order from zero; no normalization. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
0-0.4472135954999579
10.4472135954999579

forwardB_R1

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Exact named-shape addition of X and AttentionOutput; no broadcasting.

Zero-based storage indexStored value
0-0.4472135954999579
11.4472135954999579

forwardB_LN2

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Per-token feature layer norm of R1; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
0-0.6876854075163181
10.6876854075163181

forwardB_W1

D=2 × HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

Zero-based storage indexStored value
01
10
20
30
41
50

forwardB_b1

HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

forwardB_Z

B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Hidden preactivations X W1+b1; no batch or token mixing.

Zero-based storage indexStored value
0-0.6876854075163181
10.6876854075163181
20

forwardB_Hidden

B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. ReLU(Z)=max(0,Z), before the second affine layer.

Zero-based storage indexStored value
00
10.6876854075163181
20

forwardB_W2

HiddenFeature=3 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Shared hidden-to-output weights, f2{m}{d}.

Zero-based storage indexStored value
01
10
20
31
40
50

forwardB_b2

D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

forwardB_F

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Zero-based storage indexStored value
00
10.6876854075163181

forwardB_Y

B=1 × T=1 × D=2 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Exact named-shape addition of R1 and F; no broadcasting.

Zero-based storage indexStored value
0-0.4472135954999579
12.134899003016276

forwardB_Logits

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Final Y times the active U prefix, then active Bias; targets are not operands.

Zero-based storage indexStored value
0-0.4472135954999579
12.134899003016276
20

forwardB_Max

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Maximum computed active class logit at each position.

Zero-based storage indexStored value
02.134899003016276

forwardB_Shifted

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Computed class logit minus its saved row maximum.

Zero-based storage indexStored value
0-2.582112598516234
10
2-2.134899003016276

forwardB_Terms

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Actual exp(Shifted) before left-to-right class summation.

Zero-based storage indexStored value
00.0756140929478022
11
20.11825653332669596

forwardB_Denominator

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Shifted exponential sum from zero in ascending compact class order.

Zero-based storage indexStored value
01.1938706262744982

forwardB_LogS

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. ln(Denominator), saved for factored NLL.

Zero-based storage indexStored value
00.17720065589584005

forwardB_LSE

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.

Zero-based storage indexStored value
02.312099658912116

forwardB_P

Position=1 × Class=3 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Terms/Denominator for real active classes only; no inactive-class probabilities.

Zero-based storage indexStored value
00.063335248630547
10.8376116959343609
20.09905305543509206

forwardB_NextRows

Position=1 · int32 · precision 0 · Actual isolated forwardB at initial weights; positions restart at zero. Highest computed logit; exact ties keep the smallest compact class.

Zero-based storage indexStored value
01

forwardB_NextIDs

Position=1 · int32 · precision 0 · Actual isolated forwardB at initial weights; positions restart at zero. Public ID mapped from each computed-logit winner.

Zero-based storage indexStored value
098

forwardB_NextProbability

Position=1 · float64 · precision 8 · Actual isolated forwardB at initial weights; positions restart at zero. Stored class probability of the computed-logit winner; never fed back as an observed input.

Zero-based storage indexStored value
00.8376116959343609

postA_0_ClassIDs

Class=3 · int32 · precision 0 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.

Zero-based storage indexStored value
097
198
2512

postA_0_Z

Class=3 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Actual finite computed input logits; no derived-input clipping.

Zero-based storage indexStored value
01.896639441039062
1-0.4273562778022991
20.2184022442795555

postA_0_Shifted

Class=3 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Z minus the saved active maximum.

Zero-based storage indexStored value
00
1-2.323995718841361
2-1.6782371967595064

postA_0_Terms

Class=3 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Actual exp(Shifted), before normalization.

Zero-based storage indexStored value
01
10.09788169544959381
20.18670280643480652

postA_0_Denominator

Scalar=1 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Actual left-to-right sum of active shifted terms.

Zero-based storage indexStored value
01.2845845018844004

postA_0_LogS

Scalar=1 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Natural logarithm of Denominator.

Zero-based storage indexStored value
00.25043532122292733

postA_0_LSE

Scalar=1 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Saved max+LogS in binary64.

Zero-based storage indexStored value
02.1470747622619895

postA_0_P

Class=3 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Terms/Denominator for active classes only, without clipping or padding.

Zero-based storage indexStored value
00.7784618283445474
10.07619716360115496
20.14534100805429762

postA_0_NextRow

Decision=1 · int32 · precision 0 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Lowest compact index among highest computed logits.

Zero-based storage indexStored value
00

postA_0_NextID

Decision=1 · int32 · precision 0 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Public class ID gathered at NextRow.

Zero-based storage indexStored value
097

postA_0_NextProbability

Decision=1 · float64 · precision 8 · Actual postA_0 updated readout on saved initial Y, not another encoder forward. Stored P gathered at the computed-logit winner.

Zero-based storage indexStored value
00.7784618283445474

postB_0_ClassIDs

Class=3 · int32 · precision 0 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.

Zero-based storage indexStored value
097
198
2512

postB_0_Z

Class=3 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Actual finite computed input logits; no derived-input clipping.

Zero-based storage indexStored value
0-0.4273562778022991
11.896639441039062
20.2184022442795555

postB_0_Shifted

Class=3 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Z minus the saved active maximum.

Zero-based storage indexStored value
0-2.323995718841361
10
2-1.6782371967595064

postB_0_Terms

Class=3 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Actual exp(Shifted), before normalization.

Zero-based storage indexStored value
00.09788169544959381
11
20.18670280643480652

postB_0_Denominator

Scalar=1 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Actual left-to-right sum of active shifted terms.

Zero-based storage indexStored value
01.2845845018844004

postB_0_LogS

Scalar=1 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Natural logarithm of Denominator.

Zero-based storage indexStored value
00.25043532122292733

postB_0_LSE

Scalar=1 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Saved max+LogS in binary64.

Zero-based storage indexStored value
02.1470747622619895

postB_0_P

Class=3 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Terms/Denominator for active classes only, without clipping or padding.

Zero-based storage indexStored value
00.07619716360115496
10.7784618283445474
20.14534100805429762

postB_0_NextRow

Decision=1 · int32 · precision 0 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Lowest compact index among highest computed logits.

Zero-based storage indexStored value
01

postB_0_NextID

Decision=1 · int32 · precision 0 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Public class ID gathered at NextRow.

Zero-based storage indexStored value
098

postB_0_NextProbability

Decision=1 · float64 · precision 8 · Actual postB_0 updated readout on saved initial Y, not another encoder forward. Stored P gathered at the computed-logit winner.

Zero-based storage indexStored value
00.7784618283445474

BeforeMax

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
02.134899003016276
12.134899003016276

BeforeTargetLogits

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
00
10

BeforeTargetProbability

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
00.09905305543509206
10.09905305543509206

BeforeGap

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
02.134899003016276
12.134899003016276

BeforeNLL

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
02.312099658912116
12.312099658912116

BeforeWeightedNLL

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
02.312099658912116
12.312099658912116

BeforeLossRunning

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
02.312099658912116
14.624199317824232

AfterMax

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
01.896639441039062
11.896639441039062

AfterTargetLogits

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
00.2184022442795555
10.2184022442795555

AfterTargetProbability

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
00.14534100805429762
10.14534100805429762

AfterGap

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
01.6782371967595064
11.6782371967595064

AfterNLL

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
01.9286725179824338
11.9286725179824338

AfterWeightedNLL

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
01.9286725179824338
11.9286725179824338

AfterLossRunning

PredictionRow=2 · float64 · precision 8 · Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.

Zero-based storage indexStored value
01.9286725179824338
13.8573450359648676

dLogits

PredictionRow=2 × ModelRow=5 · float64 · precision 8 · Active mask*(P-indicator)/N from actual initial distributions; inactive structural zeros, no inactive P.

Zero-based storage indexStored value
00.41880584796718046
10.0316676243152735
2-0.450473472282454
30
40
50.0316676243152735
60.41880584796718046
7-0.450473472282454
80
90

dU

D=2 × ModelRow=5 · float64 · precision 8 · Immediate document/position-ascending sums of actual fixed Y times dLogits.

Zero-based storage indexStored value
00.8799459951515443
1-0.11968848950724015
2-0.7602575056443042
30
40
5-0.11968848950724015
60.8799459951515443
7-0.7602575056443042
80
90

db

ModelRow=5 · float64 · precision 8 · Document/position-ascending sums of actual dLogits, including inactive zeros.

Zero-based storage indexStored value
00.45047347228245394
10.45047347228245394
2-0.900946944564908
30
40

Gradient

Parameter=15 · float64 · precision 8 · Ordered u00..u04,u10..u14,b0..b4 analytic readout-only gradient.

Zero-based storage indexStored value
00.8799459951515443
1-0.11968848950724015
2-0.7602575056443042
30
40
5-0.11968848950724015
60.8799459951515443
7-0.7602575056443042
80
90
100.45047347228245394
110.45047347228245394
12-0.900946944564908
130
140

ThetaBefore

Parameter=15 · float64 · precision 8 · Detached simultaneous optimizer parameters in TRAINABLE_KEYS order.

Zero-based storage indexStored value
01
10
20
30
40
50
61
70
80
90
100
110
120
130
140

MBefore

Parameter=15 · float64 · precision 8 · Actual first moments; unused SGD moments are zero.

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

VBefore

Parameter=15 · float64 · precision 8 · Actual nonnegative second moments; unused SGD moments are zero.

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

CountersBefore

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; no update on an unavailable objective.

Zero-based storage indexStored value
00
10

ThetaAfter

Parameter=15 · float64 · precision 8 · Detached simultaneous optimizer parameters in TRAINABLE_KEYS order.

Zero-based storage indexStored value
00.9120054004848456
10.011968848950724016
20.07602575056443042
30
40
50.011968848950724016
60.9120054004848456
70.07602575056443042
80
90
10-0.045047347228245396
11-0.045047347228245396
120.0900946944564908
130
140

MAfter

Parameter=15 · float64 · precision 8 · Actual first moments; unused SGD moments are zero.

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

VAfter

Parameter=15 · float64 · precision 8 · Actual nonnegative second moments; unused SGD moments are zero.

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

CountersAfter

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; no update on an unavailable objective.

Zero-based storage indexStored value
00
11

UAfter

D=2 × ModelRow=5 · float64 · precision 8 · Actual updated finite readout matrix; no raw-editor clamp.

Zero-based storage indexStored value
00.9120054004848456
10.011968848950724016
20.07602575056443042
30
40
50.011968848950724016
60.9120054004848456
70.07602575056443042
80
90

BiasAfter

ModelRow=5 · float64 · precision 8 · Actual updated finite biases; may exceed initial raw bounds.

Zero-based storage indexStored value
0-0.045047347228245396
1-0.045047347228245396
20.0900946944564908
30
40

Check your understanding

Use the inputs stated in each question. Live questions use the current calculation. Each option pairs a value or conclusion with its mechanism. Editing a raw input, resetting or selecting a trace step clears graded answers; local inspection selectors preserve them.

1. What is actually trained in this lab’s one language-model training step?
2. At reset (A=a, B=b, merges=0, batch=2, all masks=1), let α=1/√5, d=1/2+α, r=d/√(1+d²), A*=1+α+r and Z=exp(A*)+exp(−α)+1. Which hand calculation matches the actual starting case?
3. For the current saved starting case (all selected real rows, independent of inspection selectors), lossSumBefore=4.624199317824232, N=2, predictionRows=2, and meanNLLBefore=2.312099658912116. Which rule produced this mean?
4. For the current saved starting case, optimizer=SGD (0), η=0.1, tAdam after=0, completedUpdates=1. Which update mechanism and state claim is correct, independently of the inspected parameter?
5. Transfer: set A=a, B=aa, merges=0, batch=2; mA0=mA1=mB0=1, mB1=0; all U=0; biases=[1,−4,−1,0,0]; η=1, SGD. Which conclusion follows from the fixed-feature counterexample?

The five graded cases above are the only graded set. Their prompts name either reset, the current saved starting case, or the fixed transfer case. Inspection selectors leave those cases and graded answers unchanged; input edits, reset and trace navigation clear answers.

This is readout-only training: ten output weights and five output biases can change. The embeddings, attention, normalization and feed-forward network stay at the tiny decoder’s actual defaults. An embedding looks up a feature vector for a token ID. Attention mixes permitted context values using computed weights; normalization rescales a token’s features; the feed-forward network applies the same small nonlinear calculation at each position. Rotary position encoding (RoPE) rotates query/key feature pairs by position; this kernel adds no position embedding. Review IV-43 — End-to-End Tiny Language-Model Objective for the decoder and its loss derivatives, IV-51 — Training Data, Packing and Causal Boundaries for data boundaries, and IV-13 — Momentum, Adam and Optimizer State for Adam. IV-08 — One Training Step: Hand-Derived Backpropagation remains the complete manual-backpropagation example through earlier layers.

The data are two authored strings, initially A=a and B=b. Their tokenizer trains on the authored corpus abab. These are teaching inputs, not measured language data. We give each document’s first piece, predict its following pieces including one end marker, and combine the included predictions into one loss. No generated token replaces a known training input.

Use the one-step lab

Start with the four summaries: loss before, loss after, included targets N and completed updates. At reset the inputs are A=a, B=b, merges=0, batch size 2, U00=U11=1 with all other U entries and biases zero, eta=.1, SGD and four requested masks equal to 1. Each edit starts a fresh calculation from the displayed initial weights and zero moments; editing again does not train for a second step or continue from the previous after-state.

The two text areas are Document A — authored toy text and Document B — authored toy text. Open Tokenization and isolated batch to change BPE merge budget (fixed corpus abab) or Selected isolated documents. The merge choices activate a/b/EOS, then ab, then abab; the batch choices select A only or A then B. B is still validated and tokenized at batch size 1. The Initial readout U [2,5] and Initial bias [5] groups expose all fifteen starting coordinates, including inactive vocabulary slots.

Open One simultaneous optimizer update for eta, the SGD/Adam choice, beta1, beta2 and epsilon. The beta controls exclude 1 and epsilon is outside sqrt. All these fields validate even for SGD. In Four requested loss masks, each mA0/mA1/mB0/mB1 chooses 0 to exclude a real row’s loss while retaining its evidence, or 1 to include the row if it exists and its document is selected. Try eta=0 with Adam: compare unchanged weights with the saved moments and counters. Try a one-row A-only batch with mA0=0: an unused mA1 or unselected B cannot supply a denominator.

Below the row-loss table, Saved prediction row (inspection only) selects the row and its document’s actual forward. Saved parameter contraction and update selects one of the fifteen coordinates; choose b2 to follow the worked bias example. Saved compact vocabulary slot selects one of all five model slots, initially EOS slot 2. At merges=0, choosing slot 3 or 4 shows “Absent: inactive class” and structural zero derivative rather than a fabricated probability. These selectors change which saved evidence is displayed; they preserve inputs, trace cursor and graded answers. When a changed input leaves fewer rows, the displayed row is bounded to the remaining real rows. Selectors do not run a separate model calculation.

The before/after row table preserves a masked row’s actual probability and NLL alongside its zero weighted contribution. The selected document table shows X, LN1, R1, LN2, all three hidden FFN coordinates, F and Y; a separate true/false table shows its causal permissions. The class table shows actual readout/distribution operands. The fifteen-coordinate table shows old/new theta, gradient, subtracted delta and old/new moments; its counter table distinguishes Adam steps from completed updates. Open the saved-operation disclosures to read the products, running sums and bias corrections used by those tables.

Previous step, Next step and Calculation step select the saved trace operation. A matching operation in the projection is marked current, and its saved equation/operands remain visible. Input edits, trace navigation and Reset example clear graded answers; reset restores the starting raw controls and trace cursor. An already mounted inspection selector can retain its selection. Invalid input shows its reason and removes unavailable results and questions. The complete inspector retains all scalar aliases, text, tensor values, axes, dtypes, precision and provenance. Displayed values never feed back into arithmetic.

The lab contains the chapter’s only five graded questions, with immediate reasoning after either answer. They distinguish the fifteen-coordinate readout scope, the exact reset features/two EOS losses, the current saved token-mean arithmetic, the current saved optimizer state, and the fixed loss-increase/derived-bias counterexample. The live mean uses all selected real rows, regardless of inspection choices. The optimizer question branches on SGD versus Adam and separately on eta=0, so unchanged weights are never mistaken for a cancelled update. Reset and transfer questions name their own fixed cases; moving an inspection selector does not change those cases. Work through the derivations below, then use the saved operands to explain each choice.

Words and shapes before arithmetic

A parameter is a model number that training may replace. A logit is a real-valued class score before normalization. Softmax converts the active logits into probabilities summing to one in exact arithmetic. A target is the known next token. Its negative log-likelihood, or NLL, is minus the natural logarithm of its probability: lower means the model assigned that known answer more probability. Natural-log losses have units called nats.

A batch is the selected group of examples used for one update. A gradient contains one derivative per trainable parameter: each derivative describes the local change of loss per small change in that parameter. An optimizer turns the gradient, a learning rate and possibly saved state into new parameter values. Reduction means combining many row losses or derivatives, here by summing included rows and dividing once by their count.

A tensor is an array whose axes name the roles of its indices. Document index j means A or B; position t starts at zero separately in each document. Feature index d is 0 or 1. Compact class index c is a small array offset, not a public token ID. Write Tj for the number of prediction rows in document j, V for the number of active classes, and R for the sum of selected Tj values, including loss-masked rows.

QuantityShape and axesMeaning
InputIDs, TargetIDs for j[Tj], PositionPublic IDs of observed inputs and known next pieces; Tj is 1 or 2
Saved decoder Y for j[1,Tj,2], B,T,DOne isolated decoder call, two features per position
Row notation Yj[Tj,2], Position,DSame features with the singleton B axis explicitly removed
U[2,5], D,ModelRowTen trainable readout weights, including inactive columns
b[5], ModelRowFive trainable biases
Logits and probabilities for j[Tj,V], Position,ClassOnly actual active classes, V=3+merges
Row logit gradients[R,5], PredictionRow,ModelRowReal selected rows; inactive columns have structural zero derivatives
dU and db[2,5] and [5]Derivatives in the same orientation as U and b
Optimizer vectors[15], ParameterU00…U04, U10…U14, b0…b4, in that order

The letter B in the old decoder’s axis names is a singleton batch axis. Selecting two documents here makes two isolated B=1 calls; it does not secretly assemble one padded B=2 tensor. Multiplication Yj U is legal because Yj has two feature columns and U has two feature rows. The full storage has five output columns; the calculation visits only the first V active columns and creates no inactive logits or probabilities. Adding b means explicitly adding the same active class bias to every position.

For Book II’s orientation and derivatives, see II.9 — Matrix × vector, III.7 — Multivariable functions and partial derivatives and III.8 — Gradient and directional derivatives. We use feature-last row storage here; a single Book II column-vector readout uses the transpose of U. Book III’s III-05 — Parameters, Hyperparameters, Loss and Optimization separates parameters from optimizer settings; III-16 — Multiclass Classification and Softmax Regression explains multiclass prediction.

Tokenize actual documents, then isolate their calculations

Each document uses the accepted tokenizePackingDocument helper, which makes a real EOS-off tokenizer call on that string. Its actual content IDs, sequence IDs, active IDs and complete tokenizer record are retained. The sequence adds exactly one EOS, end-of-sequence ID 512. At reset the sequences are [97,512] and [98,512]; a is ID 97 and b is ID 98. Taking all but the final sequence entry gives the inputs; taking all but the first gives the targets. Thus each document has one input and one EOS target.

Active classes are the first V entries of [97,98,512,256,257]: a, b, EOS, ab and abab. At zero merges V=3 even if a particular document contains only a. EOS occupies compact class 2; the public ID 512 must never be used as an array offset. With merges=1, ab becomes content [256], so its input is that merged token and its one target is EOS. Changing tokenization can change the number and meaning of prediction rows.

Raw documents are nonempty a/b strings of at most two UTF-8 bytes. Positions restart at zero for each separate forward. Within a document, causal attention can read earlier positions and itself; it cannot read a later input. Between documents there is no shared attention calculation. This is a real isolated batch. The triangular-only old decoder does not implement IV51’s arbitrary packed document/chunk permission grid.

A loss mask m_jt is numeric 0 or 1: it excludes or includes one existing target’s loss. It does not remove that input from earlier context or alter an attention permission. The four raw requests mA0, mA1, mB0, mB1 all validate. An unused second request for a one-row document creates no extra row. Batch size 1 selects only A; batch size 2 selects A and B. Both source documents still validate and tokenize even when B is unselected. Unselected B has tokenizer evidence, but no claimed neural output.

Compute a stable loss and a nonempty mean

For one row, the readout visits active c in order. It computes product0=Y[t,0]×U[0,c], product1=Y[t,1]×U[1,c], their sum, then adds b[c] last to obtain z[c]. Let M be the maximum active z. Form each shifted term exp(z[c]−M), left-add them from zero into S, and save logS=ln(S). The probability P[c] is that class term divided by S. Here exp is the exponential function and ln its inverse.

Let k be the target’s compact class. Save targetLogit=z[k] and gap=M−targetLogit, then NLL=gap+logS. This is exactly ln(sum exp(z))−z[k] over real numbers, but avoids subtracting the target from an already rounded M+logS. It also avoids taking ln of a target probability that might underflow to zero. There is no probability clipping.

Count N by adding the requested masks on selected real rows, A before B and positions in ascending order. Only when N is positive define

weightedNLL[j,t] = m[j,t] * NLL[j,t]
lossSum = left-to-right sum of weightedNLL, starting from 0
L = lossSum / N

L denotes the batch mean loss. N counts included targets, not documents, classes or attention cells. If N=0, the result is unavailable after both tokenizations and before neural work. There is no empty mean 0, perplexity 1, parameter update or counter advance. If N is positive elsewhere, a selected document whose masks are all zero still receives its full promised forward and row evidence.

Why averaging document means gives the wrong weights

Use A=a, B=ab, merges=0 and all real masks on. There is one A target and two B targets. Call their losses x, y and z; these are names for actual row losses, not invented numeric outputs. The token mean is (x+y+z)/3. The mean of document means is (x+(y+z)/2)/2, giving half the total influence to A’s single target.

Writing muA=x and muB=(y+z)/2, the document-mean expression minus the token mean is (muA−muB)/6. They agree only when the two document means happen to agree. The reset case has equal lengths, so it cannot reveal this weighting error. If a document has no included targets, its own mean is undefined; assigning it mean zero adds a second error.

For an explicit valid counterexample, use A=a, B=aa, merges=0, batchSize=2, all real masks on, all ten U entries zero and biases (1,0,0,0,0). Every row then has logits (1,0,0), irrespective of its fixed features. Let Z0=exp(1)+2. The A target is EOS, with loss ln(Z0). The B targets are a then EOS, with losses ln(Z0)−1 and ln(Z0). The token mean is ln(Z0)−1/3, while averaging document means gives ln(Z0)−1/4: an exact difference of 1/12. These are exact-real expressions for allowed data and weights, not fabricated observed row values.

Derive the one-byte reset by hand

Everything in this section is an exact-real expression, not an executed binary64 result. The implementations use binary64, a 64-bit floating-point number format that rounds arithmetic results; displayed decimals must come from their records. In particular the raw learning-rate default .1 is a binary64 number, while 1/10 below describes its ideal decimal value.

Here sqrt(x) means the nonnegative square root of x. A residual adds the incoming features back to a computed branch; feature normalization rescales a token using its own feature statistics.

At one input a, the embedding is (1,0). Feature normalization subtracts the mean 1/2. Its population variance is ((1/2)²+(−1/2)²)/2=1/4; adding the fixed normalization epsilon 1 gives 5/4. Division by sqrt(5/4) gives (alpha,−alpha), where alpha (α)=1/sqrt(5). This epsilon belongs to normalization; it is separate from Adam’s epsilon.

At position zero the query/key rotary angle is zero. The sole allowed key has attention probability one, and identity value/output projections return the normalized pair. The first residual adds the original embedding, giving (1+alpha,−alpha). Its mean is again 1/2. For this hand calculation only, d is a scalar abbreviation, distinct from the feature index d. Define d=1/2+alpha; centered coordinates are (d,−d), variance d², and the second normalization gives (r,−r), where r=d/sqrt(1+d²).

The actual feed-forward matrices have shapes [2,3] then [3,2]. They produce hidden preactivations (r,−r,0), ReLU outputs (r,0,0), and output (r,0). ReLU replaces a negative number with zero. The third hidden unit is actually computed; this is not an omitted two-unit network. The second residual therefore gives Ya=(A,−alpha), where A=1+alpha+r. This capital A is a scalar feature value; document A remains the name of the first example. Starting from b swaps the coordinates and gives Yb=(−alpha,A). No derivative through those fixed operations is needed for readout training.

Reset U has U00=U11=1 and every other entry zero; all biases are zero. The active readout logits are therefore (A,−alpha,0) for a and (−alpha,A,0) for b. Both targets are EOS. Define

Z = exp(A) + exp(-alpha) + 1
p = exp(A)/Z; q = exp(-alpha)/Z; s = 1/Z

Z is the unshifted exact-real normalizer. It differs from the stable shifted S. The probabilities are (p,q,s) and (q,p,s); p+q+s=1. Each target has probability s and NLL=−ln(s)=ln(Z). With N=2, the mean is (ln(Z)+ln(Z))/2=ln(Z).

From row derivatives to all fifteen parameter gradients

The indicator I(c=k) is 1 when c is the target and 0 otherwise. Differentiating the log-normalizer gives P[c]; differentiating the subtracted target logit gives I(c=k). Multiplication by the loss mask and division by N therefore give

difference = P[c] - I(c == k)
masked = m[j,t] * difference
gLogit[j,t,c] = masked / N

For inactive c≥V the derivative is explicitly zero, without inventing an inactive probability. For reset the row gradients on the three active classes are (p/2,q/2,(s−1)/2) for A and (q/2,p/2,(s−1)/2) for B. Multiplying by each saved feature and adding rows gives dU[d,c]; adding row logit gradients alone gives db[c]. Every reduction starts at zero and visits A then B, position by position.

For example dU00 = A×(p/2) + (−alpha)×(q/2) = (A p−alpha q)/2. The same parameter influences both examples, so both contributions belong in its derivative. Define G=(A p−alpha q)/2, H=(A q−alpha p)/2, K=(A−alpha)(s−1)/2 and J=(p+q)/2 to keep the complete table readable. These letters are exact expressions, not rounded helper results.

CoordinateOld valueExact-real gradientSGD at ideal eta=1/10
U001G=(A p−alpha q)/21−G/10
U010H=(A q−alpha p)/2−H/10
U020K=(A−alpha)(s−1)/2−K/10
U03000
U04000
U100H−H/10
U111G1−G/10
U120K−K/10
U13000
U14000
b00J=(p+q)/2−J/10
b10J−J/10
b20s−1(1−s)/10
b3000
b4000

Here dU/db name derivatives, not proposed weight changes. The learning rate converts them into changes. Each whole parameter contraction retains all its row products and running sums. Neither greedy predictions nor generated samples occur in this differentiation; known targets and all active probabilities do.

Make one simultaneous SGD or Adam update

Write theta (θ) for any one of the fifteen old coordinates and g for its saved batch derivative. SGD, stochastic gradient descent, computes delta=eta×g, then thetaNew=theta−delta. Eta, written η in mathematics, is the learning rate. For default b2, g=s−1, delta=(s−1)/10 and the new bias is (1−s)/10 in ideal real arithmetic. The table applies the same rule to every coordinate from the same old gradient vector. Recomputing gradients after changing each coordinate would define a different algorithm.

For Adam, m is the first-moment state, a weighted gradient average; v is the second-moment state, a weighted average of squared gradients. Beta1 and beta2 choose how much old state to retain. They are less than one. The Adam counter tAdam counts Adam updates; it is separate from completedUpdates, which counts updates of either optimizer. Initially every moment and both counters are zero.

Compute and save the common setup once, then reuse it for all fifteen coordinate updates. In the coordinate lines, mOld and vOld are that coordinate’s old m and v:

completedNew = completedUpdates + 1
tNew = tAdam + 1
oneMinusBeta1 = 1 - beta1; oneMinusBeta2 = 1 - beta2
power1 = beta1**tNew; power2 = beta2**tNew
correction1 = 1 - power1; correction2 = 1 - power2

mDecay = beta1*mOld; mProduct = oneMinusBeta1*g
mNew = mDecay + mProduct
square = g*g
vDecay = beta2*vOld; vProduct = oneMinusBeta2*square
vNew = vDecay + vProduct
mHat = mNew/correction1; vHat = vNew/correction2
root = sqrt(vHat); denominator = root + epsilon
normalized = mHat/denominator
delta = eta*normalized; thetaNew = theta - delta

Hat means bias-corrected: starting the moving averages at zero otherwise shrinks the early averages. Epsilon is a positive small stabilizer outside the square root. From zero moments, ideal beta1=9/10, beta2=999/1000 and tNew=1 give decays 0, contributions g/10 and g²/1000, corrections 1/10 and 1/1000, mHat=g, vHat=g², root=abs(g), denominator=abs(g)+epsilon. Here abs means absolute value. Thus the first ideal Adam update is theta−eta g/(abs(g)+epsilon), not theta−eta g.

For b2 specifically, put g=s−1. Since 0<s<1, abs(g)=1−s. Its ideal moments become (s−1)/10 and (s−1)²/1000; normalized=(s−1)/(1−s+epsilon); with ideal eta=1/10 the new bias is (1−s)/(10×(1−s+epsilon)). This differs from SGD’s (1−s)/10. For each of G,H,K,J in the table, substituting that expression for g gives all the corresponding Adam intermediates. A zero derivative gives zero moments and update, including every inactive coordinate. The implementation must retain the unsimplified products, powers, divisions and stored results: ideal cancellations are not a license to fabricate binary64 intermediates.

After available SGD, the unused Adam moment vectors stay all zero, tAdam stays 0 and completedUpdates becomes 1. After available Adam, both counters become 1 and all new moments are retained. At eta=0 both methods preserve weights; Adam can still change moments and its counter. Unavailable N=0 performs neither kind of update. New arrays are detached from old arrays, so inspecting old state must not mutate it.

Why updated loss can reuse Y, and what it must recompute

U and b first enter the decoder at its readout. Consequently the actual saved Y is independent of all fifteen trainable coordinates. Compute the updated readout on that Y using the same two products and bias-last association, then compute a new stable distribution and target NLL. Reducing these new row losses with the same masks/N gives the real after loss. This is justified for every allowed document, not only the symmetric reset.

There is one initial full forward per selected document, including fully loss-masked selected documents when N>0. Afterwards there are R new readout rows. Reusing Y is a dependency argument, not a second full forward or reuse of arbitrary cached model evidence. If embeddings or block weights changed, this justification would fail. A KV cache from a different model identity cannot silently survive a parameter update.

Initial editor bounds and derived-state validity answer different questions. The initial controls restrict U to [−2,2] and b to [−4,4] for a bounded teaching experiment. A finite optimizer result may lie outside those intervals. It must be checked for valid finite arithmetic and state, not clamped or passed into the old raw-input validator to obtain after loss. Likewise updated finite logits use the derived distribution path without the old raw logit editor’s [−40,40] restriction.

For completeness, the ideal SGD reset update in the table gives A’s new active logits

z0New = A - (A*G - alpha*H + J)/10
z1New = -alpha - (A*H - alpha*G + J)/10
z2New = (-(A-alpha)*K + (1-s))/10

B swaps the first two and shares z2New. Both targets remain EOS, so the exact-real new mean is ln(exp(z0New)+exp(z1New)+exp(z2New))−z2New. The maintained calculation uses the stable shifted form above, with actual updated parameters; this expression supplies a hand comparison, not invented stored after-loss digits.

A valid step that increases the loss

A gradient describes local behavior. A finite jump can overshoot, even within the permitted learning-rate range. Here is a constructive exact-real example; no training curve or computed decimal is assumed.

Choose A=a, B=aa, merges=0, batchSize=2, mA0=1, mA1=1, mB0=1, mB1=0. All ten U entries are zero. Set biases (b0,b1,b2,b3,b4)=(1,−4,−1,0,0), eta=1 and SGD; retain valid default Adam settings. The unused mA1 still validates. A contributes a→EOS; B contributes its first a→a, while its second a→EOS row is evaluated but loss-masked. Both included rows have the same position-zero feature y=(A,−alpha), because the causal first position cannot read the later a.

Let P_a, P_b and P_E be the probabilities of logits (1,−4,−1), with E meaning EOS. The two targets have frequencies f=(1/2,0,1/2). Put C=1+A²+alpha² and D=P_a−P_E. The mean gradients are y[d]×(P[c]−f[c]) for U and P[c]−f[c] for b. Applying eta=1 therefore changes the logits on either included row to zNew[c]=z[c]−C×(P[c]−f[c]).

Subtract the a/EOS midpoint from every updated logit; this common shift leaves probabilities unchanged. The centered logits become (xNew,wNew,−xNew), where xNew=1−CD/2 and wNew=−4−3C P_b/2. Define cosh(x)=(exp(x)+exp(−x))/2 and sinh(x)=(exp(x)−exp(−x))/2. The old and new means are

LBefore = ln(2*cosh(1) + exp(-4))
LAfter  = ln(2*cosh(xNew) + exp(wNew))

The following rational bounds establish the direction without manufactured decimals. Alpha>4/9 gives d>17/18, r>2/3 and A>19/9, hence C>2291/405>11/2. Writing e=exp(1), its positive series gives e>65/24>27/10. Then e³(e²−7)>3, which implies D>3/4 by multiplying out the positive softmax denominator. Therefore xNew<1−(11/2)×(3/4)/2=−17/16.

Since sinh(1)>1, the increase from 2cosh(1) to 2cosh(17/16) is greater than 1/8: its derivative 2sinh(x) exceeds 2 throughout an interval of length 1/16. Also exp(−4)<1/16 because e>2. Thus 2cosh(xNew)>2cosh(1)+exp(−4). Adding the positive exp(wNew) and taking the increasing ln function proves LAfter>LBefore.

This same example produces b1New=−4−P_b<−4. Clipping it at −4 would change the optimizer, and rejecting it through the initial bias bounds would discard a valid derived update. The inequalities concern the exact-real model. A floating-point verdict also needs the independent error analysis and actual records; this proof is not an executed numerical pass.

Follow the saved training record

The entry deriveIV52 returns a defined record with exactly status, outputs, steps, tensors and texts, in that order. An unavailable result has only status, code and reason; it is not a partly completed update. The first four output summaries are meanNLLBefore, meanNLLAfter, validTargets and completedUpdates. Read them together: an available eta=0 calculation can leave both losses unchanged while recording one completed update.

There are 45 summary entries before the step-output aliases. Those summaries include fullForwardCalls, postReadoutRows, predictionRows, tAdam, frames and tensorCount, plus eleven actual tokenizer summaries for each document. Every saved step output is then copied once into outputs under stepID_outputName, in step order. For example, gradient_parameter_12_gradient names the b2 derivative, and optimizer_parameter_12_thetaNew names its updated value. These aliases refer to saved arithmetic; they do not run it again. The 35 text entries retain the scope and reduction policies, actual model vocabulary and both complete tokenizer reconstructions/labels.

Each step has six fields: id, label, equation, explanation, inputs, outputs. Begin at setup, follow all docA_ tokenizer steps and docA_append_eos, then the corresponding docB_ steps. count identifies the selected real rows and counts their masks. The complete forwardA_ steps, followed by forwardB_ at batch size 2, precede the row losses and before_mean. gradient_count explicitly counts the supplied gradient masks again; gradient_row_0 onward records every active subtraction/mask/division and inactive zero. gradient_parameter_0 through gradient_parameter_14 retain the row contributions to every parameter. optimizer_setup saves common counter/Adam arithmetic once; its fifteen coordinate steps retain the simultaneous updates. Finally postA_0_readout_0 and the other actual post-row/class steps lead to new losses, after_mean and finish.

Use tensors to see the same calculation by shape. RowDocIDs, RowPositions, InputIDs, TargetIDs, TargetRows and RequestedMask share the real PredictionRow axis. forwardA_Y and, when selected, forwardB_Y retain the genuine old encoder features; the full old tensors and provenance accompany them. BeforeNLL/AfterNLL, their WeightedNLL and LossRunning companions, and the phase-specific target probabilities distinguish a real row loss from its masked contribution. dLogits, dU, db and Gradient retain every derivative. ThetaBefore/ThetaAfter, MBefore/MAfter, VBefore/VAfter and CountersBefore/CountersAfter retain optimizer state. Counters are ordered [tAdam,completedUpdates]: after SGD [0,1], after Adam [1,1]. UAfter and BiasAfter are slices of the actual new parameters.

A tensor records id, shape, axes, dtype (data type), flat row-major values, provenance (where the values came from) and precision. Precision describes display, not arithmetic rounding. A post-row tensor such as postA_0_P contains only the V actual probabilities. The five-column dLogits instead includes inactive structural zeros. Both tokenizer records are retained even at batch size 1; unselected B has no forwardB_ or postB_ neural evidence. Unique document and phase prefixes keep old and new values separate.

The manual source inventory gives reset batch size 2 exactly 217 frames and 211 tensors; batch size 1 gives 145 and 143. The reachable maximum is 441 frames and 271 tensors for two two-byte non-ab documents at merges=2 with N positive. These are counts from the source loops, not observations from an executed lesson. More tensors than frames is legitimate: saving a tensor need not add an arithmetic step.

The shared numeric helpers have distinct jobs. trainingState(state) validates the initial raw record; finiteReadout(y,theta,classIDs,trace,prefix) computes the derived readout and full distribution; readoutGradients(rows,classIDs,trace,prefix) contracts the saved row derivatives; optimizerUpdate(state,gradient,config,trace,prefix) creates detached new parameters, moments and counters. Their finite arrays validate numerical structure and domains. They cannot prove that caller-supplied Y came from an encoder or that supplied probabilities belong to that same objective. The chapter wrapper supplies actual saved Y and probabilities from the same old forward, with the same classes, targets, masks and row order, and retains their full witness. An arbitrary finite feature array is not certified model evidence.

Boundaries and what this experiment cannot establish

The raw record has exactly 28 fields. Own names and data descriptors precede captured value reads; accessors, symbols and extras are rejected. Both actual string types validate A then B. All 26 numeric fields validate before either document’s Unicode/content semantics, including inactive fields. Non-number/nonfinite numeric input gives NONFINITE; finite numbers outside their domains give INVALID_INPUT. There is no string/boolean coercion.

Numeric domains are merges integer 0…2, batchSize 1 or 2, U in [−2,2], b in [−4,4], eta in [0,1], optimizer numeric 0 for SGD or 1 for Adam, beta1/beta2 in [0,1), epsilon in [1e−8,1], and masks numeric 0 or 1. In particular beta=1 is excluded and epsilon cannot be zero. All fields still validate for SGD and eta=0. Document semantics then follow the accepted helper’s order: outer UTF-16 length bound, strict surrogate handling, actual UTF-8 byte count, a/b alphabet, nonempty; finish A before B. No invalid input is silently repaired.

A check of these gradients must hold Y, classes, tokenization and masks fixed while perturbing one finite U or b coordinate. Differentiating BPE switches, greedy choices, mask switches or an optimizer step would test a different function. The smooth readout extends beyond raw editor bounds, so a central difference at an initial endpoint must not reapply raw limits. Its step must be representable and genuinely change both endpoints.

For the one-byte features, abs(Y)<3 gives the conservative third-derivative bound M3=27/4 for a U coordinate and 1/4 for a bias. The ideal central-difference truncation bound is M3×h²/6 for positive step h. Actual numerical comparison additionally needs independently justified loss-evaluation roundoff, endpoint/subtraction/division allowances and analytic-gradient roundoff. Agreement alone does not determine a tolerance. See Book II’s III.14 — Numerical differentiation and VIII.3 — Error propagation and conditioning.

For the declared one-byte batch-size-2 check only, both actual position-zero masks are 1 and merges is 0 or 2, giving V=3 or V=5 active classes. The independent source budget fixes h=2^-12, u=2^-53, R=8192u and G=32768u before any discrepancy is measured. Here u is binary64 unit roundoff, R bounds one conditional objective evaluation, and G bounds the computed analytic gradient’s roundoff. They are unrelated to the earlier row-count R and gradient abbreviation G in the hand table. The complete allowed comparison error is

M3*h*h/6 + 2*R/h + G

The selected coordinate center is exactly 0 or 1 from reset, or a selected raw boundary ±2 for U / ±4 for bias; other coordinates remain fixed during each perturbation and within their initial raw bounds. The witness requires actual fixed stored features with abs(Y)<3 and exact, distinct endpoints separated by 2h. Inactive coordinates use M3=0. This budget does not cover arbitrary centers, longer documents, changed masks, V=4 or arbitrary updated readouts.

The proof assumes separate round-to-nearest-even binary64 operations, gradual underflow, no fused multiply-add, and deterministic exp/log with at most four units in the last place of absolute error at the represented argument. A unit in the last place is the spacing of nearby representable numbers. The independent witness must bind the actual old features, endpoint elementary results and exact analytic-gradient copies, and justify the endpoint/gradient arithmetic against R and G before comparing derivatives. Those implementation/library premises require runtime evidence. This is a conditional, predeclared error argument, not evidence that a gradient check has run or passed. A complete public-record review also covers step aliases, text, tensor metadata and provenance; agreement of a private numerical projection cannot certify the whole record.

This experiment makes one bounded readout update. It does not train the full Transformer, shuffle a corpus, establish held-out generalization, explain a frontier model or supply a measured scaling curve. A lower training loss, if obtained, concerns the selected known targets. Book III’s III-04 — Training, Validation, Testing and Generalization explains why independent evaluation remains necessary.

Read the actual Python source closure

The eleven panels below load actual maintained project files as raw source. They do not execute Python. Keep their relative directories under code/python; the standard library and NumPy supply the external runtime requirements. Loading a displayed file and running its explicit validation entry points are separate actions.

The entry iv52.py defines derive_iv52(state). It first prepares the real tokenized documents, then selects/counts rows before any neural call. For N positive it copies one initial forward_tiny per selected document, extracts each actual Y row and same-forward probabilities, scores the old losses, calls the gradient and optimizer helpers, and computes each new readout/loss on that Y. Its final five-field record copies only the 45 summaries before appending every saved step-output alias once. A deep copy detaches all returned Python lists/dictionaries. The TypeScript entry additionally freezes its snapshot; Python detachment does not make its lists immutable.

The public Python entry catches only the enumerated known NumericalFault classes. A new unexpected implementation exception propagates. Its main dispatcher is the existing packing_reference.run: no argument copies the defaults, one JSON argument replaces the complete raw28 object, and - reads that complete JSON from standard input (stdin). Missing fields are not filled from reset. The JSON parser rejects duplicate keys, including inside nested objects, and rejects NaN/Infinity constants. Parsing failures have their own unavailable result; the derive call is outside that parsing catch. --self-check cannot be combined with a state query and invokes the local wrapper assertion leaf outside query catches.

The following are command examples. With Python 3 and NumPy already available, use the Book IV project root as the working directory:

python3 code/python/p13/iv52.py

For a complete stdin replacement choosing eta=0 and Adam, retain all 28 fields:

python3 code/python/p13/iv52.py - <<'JSON'
{"docA":"a","docB":"b","merges":0,"batchSize":2,"u00":1,"u01":0,"u02":0,"u03":0,"u04":0,"u10":0,"u11":1,"u12":0,"u13":0,"u14":0,"b0":0,"b1":0,"b2":0,"b3":0,"b4":0,"eta":0,"optimizer":1,"beta1":0.9,"beta2":0.999,"epsilon":1e-8,"mA0":1,"mA1":1,"mB0":1,"mB1":1}
JSON

The same complete JSON may instead be passed as the single quoted positional argument. A fragment such as {"eta":0} is invalid replacement input. The CLI prints the full JSON record, including both tokenizer witnesses and every actual neural/gradient/update step; it does not reduce the answer to a few loss numbers.

python3 code/python/p13/iv52.py --self-check

That explicit flag selects iv52.source_self_check, the local public-record/CLI assertion leaf. It does not call training_reference.source_self_check, iv52.gradient_source_self_check, any old source’s check or an oracle. The mechanics leaf and the separate conditional finite-difference leaf are independently invoked functions for validation. The latter checks the declared inequality with fixed saved Y; it cannot establish the runtime rounding/library premises by itself. None of these leaves runs on module load or an ordinary query. A defined query is a computed record, not a certificate that an independent oracle, parity, gradient, browser or accessibility check passed.

The retained older files declare five additional explicit checks: packing_reference.source_self_check, iv39.source_self_check, bpe_reference.source_self_check, tiny_reference.source_self_check and choice_reference.source_self_check. Only the old explicitly invoked iv39 check calls the old BPE check. None is reached from the new query or its three separate checks. Thus the eleven source paths contain eight check declarations; seven do not call another declared check. File-relative loading can create multiple module instances from one source path, so eleven files does not mean eleven loaded module objects.

Follow training_reference.py in four small stages:

  1. training_state builds a fresh ordered raw record after checking both strings and all numeric domains. It compares arbitrary-size Python integers with their domains before float conversion and rejects booleans. tokenize_training_documents passes an explicit complete IV51 configuration to packing_reference.tokenize_documents; it uses the real EOS-off records and sequences without calling the separate packing-grid calculation.
  2. finite_readout validates a two-feature row, fifteen finite weights/biases and the active class prefix. NumPy arrays store the values; explicit builtin-float products and additions compute feature 0, feature 1, their sum and bias last. It calls choice_reference.direct_distribution, which retains the real shifted exponentials, ascending denominator sums, probabilities and logS. Using an array for storage does not imply a BLAS matrix multiplication or a reordered reduction.
  3. readout_gradients validates every supplied row, counts its masks, and allocates a real [R,5] zero array. The active-class branch fills subtraction, mask multiplication and division by N; the inactive branch records structural zero. Its outer parameter loop visits all fifteen coordinates; the inner row loop immediately adds each feature product, or each bias contribution, to its running sum. .reshape(-1).tolist() serializes the same row-major values; it does not recompute a gradient.
  4. optimizer_update checks exact state/configuration dictionaries, all finite fifteen-entry vectors, nonnegative second moments and consistent safe counters. Zero Adam steps require zero moments, and SGD requires unused zero Adam state. The setup computes common corrections once. The coordinate loop fills new NumPy theta/m/v arrays from the old arrays and saved gradient; it returns detached lists only after every coordinate succeeds. No intermediate result overwrites an old input.

The comments and trace.add calls show where the hand equations enter real saved operands. A source_self_check definition is an explicit assertion leaf, not an operation that runs merely because a function is defined. The numerical helpers’ local leaf checks hand-derived binary-exact gradients/SGD, invalid raw/state inputs, eta=0 Adam state and finite derived values beyond editor bounds; it calls no other file’s check leaf. Independent oracle authority remains separate from this production reference.

Chapter entry — p13/iv52.py: the adjacent training-module loader, full five-field public record, local explicit check leaves and strict CLI entry.

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.

"""IV52 — Language-Model Training Steps and Batches; SOURCE ONLY, UNRUN.

Two genuine EOS-off tokenizers and one initial old forward per selected document
supply every training operand. Only U[2,5] and bias[5] change. Post-update losses
use the actual saved fixed Y, finite readout and old direct distribution.
Keep the eleven-file relative closure listed in B_PYTHON_NOTES.md. No import or
query runs a check. --self-check is an explicit, separately invoked local leaf.
"""
from copy import deepcopy
import importlib.util
from pathlib import Path
import numpy as np

_spec = importlib.util.spec_from_file_location(
    "_p13_iv52_training", Path(__file__).resolve().with_name("training_reference.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent training_reference.py")
_training = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_training)
DEFAULT_IV52 = _training.DEFAULT_IV52


def derive_iv52(state):
    """Full ordered detached IV52 record; complete raw28 replacement, no defaults."""
    try:
        return _derive_iv52(state)
    except _training.KNOWN_FAULTS as error:
        return dict(status="unavailable", code=error.code, reason=str(error))


def _derive_iv52(state):
    tokenized = _training.tokenize_training_documents(state)
    raw, documents = tokenized["state"], (tokenized["docA"], tokenized["docB"])
    trace, tensors, tokenizer_outputs = _training.TrainingTrace(), [], {}
    class_ids = list(_training.ALL_IDS[:3 + raw["merges"]])
    V = len(class_ids)
    texts = dict(
        docA=raw["docA"], docB=raw["docB"],
        trainingScope="Actual readout-only training of ten U weights and five biases. The old embedding, causal attention, RoPE, normalization and 2x3x2 FFN stay fixed at actual defaults. No full Transformer backpropagation is claimed.",
        tokenizerPolicy="Two actual IV51 document-helper calls reuse the full old EOS-off IV39 records with fixed corpus abab. Append exactly one explicit EOS per document; no normalization, lookup substitute or retokenization.",
        batchPolicy="Batch size 1 selects A; 2 selects A then B. Both raw documents and all four masks validate and both tokenizers run. Each selected document has its own old B=1 forward with positions restarting at zero; no arbitrary packed-mask decoder is claimed.",
        objectivePolicy="The first piece is given. Score every selected real shifted target, including EOS, with its requested 0/1 loss mask. Sum mask*NLL in A then B position order and divide once by the total included targets. Unused raw mask slots create no row.",
        gradientPolicy="Active logit derivatives are mask*(P-indicator)/N. Inactive five-class slots have structural zero gradients without invented probabilities. Contract all fifteen parameter gradients from the actual saved old Y and probabilities.",
        updatePolicy="One simultaneous SGD update from the same old gradient vector. Unused Adam m/v stay zero and tAdam stays 0; completedUpdates becomes 1." if raw["optimizer"] == 0 else "One simultaneous Adam update from zero moments; tAdam becomes 1. Bias corrections are computed once; epsilon is outside sqrt. Eta 0 may preserve weights while moments and counters change.",
        postPolicy="Actual old Y is independent of U/bias. Recompute finite updated affine readout, old directDistribution and factored NLL on that same Y. No second full forward or reuse of readout-dependent cache evidence; no raw bound check or clipping of updated weights.",
        numericCoherence="Public helpers validate numeric structure and finite domains, not encoder origin or objective identity. The wrapper supplies actual old Y and same-evaluation probabilities/classes/targets/masks and retains their complete witnesses.",
        lossChangePolicy="A real update can increase, decrease or preserve this masked objective. These values are computed from the supplied authored toy data, not a generated learning curve or a monotonicity promise.",
        provenance="Authored raw a/b documents, fixed authored tokenizer corpus abab, deterministic old model defaults; no random stream, external corpus, pretrained model or hidden history.",
        modelVocabulary=[f"compact row {row}: public ID {identifier}" for row, identifier in enumerate(class_ids)],
    )
    numeric = {key: raw[key] for key in tuple(DEFAULT_IV52)[2:]}
    trace.add("setup", "Declare actual isolated readout-only training", "two EOS-off tokenizers; one EOS/doc; selected inputs=sequence[:-1]; targets=sequence[1:]; train U[2,5] and bias[5]",
              "All own descriptors precede captured value reads; both string types and every numeric domain precede A then B text semantics. Initial bounds are separate from finite derived weights.",
              numeric, dict(byteBound=2, tokenizerCalls=2, appendedEOS=2, classCount=V, trainableParameters=15, fixedEncoder=1))

    def save_integer(identifier, axis, values, provenance):
        tensors.append(_training._packing._token.tensor(identifier, axis, np.array(values, dtype=np.int32), provenance))

    def save_float(identifier, shape, axes, values, provenance):
        tensors.append(_training._tiny._component.tensor(identifier, shape, axes, values, provenance))

    def save_scoped(records, prefix, provenance):
        for original in records:
            record = deepcopy(original)
            record["id"] = f"{prefix}_{original['id']}"
            record["provenance"] = provenance + original["provenance"]
            tensors.append(record)

    def copy_steps(steps, prefix):
        for step in steps:
            trace.add(f"{prefix}_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])

    for d, doc in enumerate(documents):
        prefix = "docA" if d == 0 else "docB"
        old = doc["record"]
        copy_steps(old["steps"], prefix)
        save_scoped(old["tensors"], prefix, f"Actual {prefix} IV39 call; fixed corpus abab, EOS off. ")
        for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"):
            tokenizer_outputs[f"{prefix}_{key}"] = old["outputs"][key]
        for key, value in old["texts"].items():
            texts[f"{prefix}_{key}"] = deepcopy(value)
        trace.add(f"{prefix}_append_eos", f"{prefix}: append exactly one EOS", "sequenceIDs=[...actual EOS-off TargetIDs,512]",
                  "The helper returned these genuine content IDs and this one appended EOS. This frame records that actual append; no second append is performed.",
                  dict(docID=d, contentTokens=len(doc["contentIDs"]), tokenizerEOS=old["outputs"]["eos"]),
                  dict(eosPosition=len(doc["contentIDs"]), eosID=_training._packing.EOS, sequenceTokens=len(doc["sequenceIDs"])))
        save_integer(f"{prefix}_ContentIDs", "ContentPosition", doc["contentIDs"], "Actual old EOS-off TargetIDs, copied without lookup or retokenization.")
        save_integer(f"{prefix}_SequenceIDs", "DocumentPosition", doc["sequenceIDs"], "Actual content IDs followed by exactly one explicit EOS512.")
    save_integer("ActiveIDs", "Class", class_ids, "Restricted active prediction classes, not the full tokenizer vocabulary; public IDs are labels.")
    selected_rows, count_inputs, count_outputs, valid_targets = [], dict(batchSize=raw["batchSize"]), {}, 0
    for d in range(raw["batchSize"]):
        doc = documents[d]
        masks = [raw["mA0"], raw["mA1"]] if d == 0 else [raw["mB0"], raw["mB1"]]
        for t in range(len(doc["contentIDs"])):
            r = len(selected_rows)
            input_id, target_id, mask = int(doc["sequenceIDs"][t]), int(doc["sequenceIDs"][t + 1]), masks[t]
            if target_id not in class_ids:
                raise _training.NumericalFault("INVALID_INPUT", "Every shifted target must be an active model class.")
            target_row = class_ids.index(target_id)
            selected_rows.append(dict(docID=d, position=t, inputID=input_id, targetID=target_id, targetRow=target_row, mask=mask))
            count_inputs.update({f"docID{r}": d, f"position{r}": t, f"inputID{r}": input_id, f"targetID{r}": target_id, f"targetRow{r}": target_row, f"mask{r}": mask})
            valid_targets += mask
            count_outputs[f"running{r}"] = valid_targets
    if valid_targets == 0:
        raise _training.NumericalFault("UNAVAILABLE", "No selected real target has mask 1; the masked mean is undefined.")
    count_outputs.update(predictionRows=len(selected_rows), validTargets=valid_targets)
    trace.add("count", "Count selected real target masks before neural work", "N starts at 0; visit selected docs A then B and positions ascending; running_r=previous+mask_r",
              "Both documents were tokenized already. Unselected B and unused mask slots create no neural row or denominator term. N=0 is unavailable before any full forward or update.", count_inputs, count_outputs)
    for identifier, key in (("RowDocIDs", "docID"), ("RowPositions", "position"), ("InputIDs", "inputID"), ("TargetIDs", "targetID"), ("TargetRows", "targetRow"), ("RequestedMask", "mask")):
        save_integer(identifier, "PredictionRow", [row[key] for row in selected_rows], "Selected real shifted rows in document then ascending position order; no padding or unselected document rows.")
    initial_theta = [numeric[key] for key in _training.PARAMETER_KEYS]
    optimizer_before = dict(theta=initial_theta, m=[0]*15, v=[0]*15, tAdam=0, completedUpdates=0)
    parameters = {**_training._tiny.NUMERIC_DEFAULTS, "merges": raw["merges"], **dict(zip(_training.PARAMETER_KEYS, initial_theta))}
    forwards = []
    for d in range(raw["batchSize"]):
        saved, prefix = _training._tiny.tiny_trace(), "forwardA" if d == 0 else "forwardB"
        result = _training._tiny.forward_tiny(parameters, documents[d]["sequenceIDs"][:-1].tolist(), saved)
        forwards.append(dict(prefix=prefix, result=result, frames=len(saved.steps)))
        for step in saved.steps:
            label, equation, explanation = _training.old_forward_prose(step)
            trace.add(f"{prefix}_{step['id']}", label, equation, explanation, step["inputs"], step["outputs"])
        save_scoped(result["tensors"], prefix, f"Actual isolated {prefix} at initial weights; positions restart at zero. ")
    gradient_rows, before_rows, after_rows = [], [], []

    def loss_row(row, distribution, previous_sum, identifier):
        doc_id, position, target_id, target_row, mask = (row[key] for key in ("docID", "position", "targetID", "targetRow", "mask"))
        maximum, target_logit = distribution["max"], distribution["logits"][target_row]
        probability = distribution["probabilities"][target_row]
        gap = _training.finite(maximum - target_logit, "target gap")
        nll = _training.finite(gap + distribution["logS"], "target NLL")
        weighted_nll = _training.finite(mask * nll, "masked NLL")
        loss_sum = _training.finite(previous_sum + weighted_nll, "masked loss running sum")
        trace.add(identifier, f"Score document {doc_id}, position {position}", "gap=max-targetLogit; nll=gap+logS; weightedNLL=mask*nll; lossSum=previousSum+weightedNLL",
                  "Keep even a masked row’s genuine distribution and NLL. Factored finite NLL avoids probability clipping and rounded LSE subtraction; accumulate A then B in position order.",
                  dict(docID=doc_id, position=position, targetID=target_id, targetRow=target_row, mask=mask, max=maximum, targetLogit=target_logit, logS=distribution["logS"], probability=probability, previousSum=previous_sum),
                  dict(gap=gap, nll=nll, weightedNLL=weighted_nll, lossSum=loss_sum))
        return dict(docID=doc_id, position=position, targetID=target_id, targetRow=target_row, mask=mask, max=maximum, targetLogit=target_logit, probability=probability, gap=gap, nll=nll, weightedNLL=weighted_nll, previousSum=previous_sum, lossSum=loss_sum)

    loss_sum_before = 0.0
    for row in selected_rows:
        forward = forwards[row["docID"]]
        features = next(record["values"] for record in forward["result"]["tensors"] if record["id"] == "Y")
        y = features[row["position"] * 2:row["position"] * 2 + 2]
        distribution = forward["result"]["rows"][row["position"]]
        loss = loss_row(row, distribution, loss_sum_before, f"{forward['prefix']}_loss_{row['position']}")
        before_rows.append(loss)
        loss_sum_before = loss["lossSum"]
        gradient_rows.append(dict(y=y, probabilities=distribution["probabilities"], targetID=row["targetID"], mask=row["mask"]))
    mean_before = _training.finite(loss_sum_before / valid_targets, "mean NLL before")
    trace.add("before_mean", "Reduce the genuine masked objective before the update", "meanNLLBefore=lossSumBefore/validTargets",
              "One total token denominator, not a mean of document means. Every selected document was fully evaluated even when all its rows have mask zero.",
              dict(lossSumBefore=loss_sum_before, validTargets=valid_targets), dict(meanNLLBefore=mean_before))
    gradients = _training.readout_gradients(gradient_rows, class_ids, trace, "gradient")
    optimizer_after = _training.optimizer_update(optimizer_before, gradients["gradient"], {key: raw[key] for key in ("eta", "optimizer", "beta1", "beta2", "epsilon")}, trace, "optimizer")
    loss_sum_after, post_readout_rows = 0.0, 0
    for r, row in enumerate(selected_rows):
        prefix = f"post{'A' if row['docID'] == 0 else 'B'}_{row['position']}"
        result = _training.finite_readout(gradient_rows[r]["y"], optimizer_after["theta"], class_ids, trace, prefix)
        post_readout_rows += 1
        save_scoped(result["tensors"], prefix, f"Actual {prefix} updated readout on saved initial Y, not another encoder forward. ")
        loss = loss_row(row, result, loss_sum_after, f"{prefix}_loss")
        after_rows.append(loss)
        loss_sum_after = loss["lossSum"]
    mean_after = _training.finite(loss_sum_after / valid_targets, "mean NLL after")
    loss_change = _training.finite(mean_after - mean_before, "loss change")
    trace.add("after_mean", "Reduce the genuine masked objective after the update", "meanNLLAfter=lossSumAfter/validTargets; lossChange=meanNLLAfter-meanNLLBefore",
              "The actual new parameters supply every updated logit. A positive lossChange is a valid result; no decrease is forced.",
              dict(lossSumAfter=loss_sum_after, validTargets=valid_targets, meanNLLBefore=mean_before), dict(meanNLLAfter=mean_after, lossChange=loss_change))
    R = len(selected_rows)
    for phase, rows in (("Before", before_rows), ("After", after_rows)):
        for suffix, key in (("Max", "max"), ("TargetLogits", "targetLogit"), ("TargetProbability", "probability"), ("Gap", "gap"), ("NLL", "nll"), ("WeightedNLL", "weightedNLL"), ("LossRunning", "lossSum")):
            save_float(f"{phase}{suffix}", [R], ["PredictionRow"], [row[key] for row in rows], "Actual saved phase-specific target/loss operands and ascending masked reduction; no display rounding.")
    save_float("dLogits", [R, 5], ["PredictionRow", "ModelRow"], gradients["rowGradients"], "Active mask*(P-indicator)/N from actual initial distributions; inactive structural zeros, no inactive P.")
    save_float("dU", [2, 5], ["D", "ModelRow"], gradients["dU"], "Immediate document/position-ascending sums of actual fixed Y times dLogits.")
    save_float("db", [5], ["ModelRow"], gradients["db"], "Document/position-ascending sums of actual dLogits, including inactive zeros.")
    save_float("Gradient", [15], ["Parameter"], gradients["gradient"], "Ordered u00..u04,u10..u14,b0..b4 analytic readout-only gradient.")
    for phase, saved_state in (("Before", optimizer_before), ("After", optimizer_after)):
        save_float(f"Theta{phase}", [15], ["Parameter"], saved_state["theta"], "Detached simultaneous optimizer parameters in TRAINABLE_KEYS order.")
        save_float(f"M{phase}", [15], ["Parameter"], saved_state["m"], "Actual first moments; unused SGD moments are zero.")
        save_float(f"V{phase}", [15], ["Parameter"], saved_state["v"], "Actual nonnegative second moments; unused SGD moments are zero.")
        save_integer(f"Counters{phase}", "Counter", [saved_state["tAdam"], saved_state["completedUpdates"]], "Ordered Adam-only tAdam, global completedUpdates; no update on an unavailable objective.")
    save_float("UAfter", [2, 5], ["D", "ModelRow"], optimizer_after["theta"][:10], "Actual updated finite readout matrix; no raw-editor clamp.")
    save_float("BiasAfter", [5], ["ModelRow"], optimizer_after["theta"][10:], "Actual updated finite biases; may exceed initial raw bounds.")
    trace.add("finish", "Disclose actual calls and state counters", "fullForwardCalls=batchSize; postReadoutRows=predictionRows; completedUpdates=1",
              "Both complete tokenizer records, every selected full forward and every updated direct distribution are preserved. No hidden cache, fabricated inactive probability, full-model gradient or second full-forward claim.",
              dict(tokenizerFrames=sum(len(doc["record"]["steps"]) for doc in documents), forwardFrames=sum(forward["frames"] for forward in forwards), predictionRows=R, optimizer=raw["optimizer"]),
              dict(tokenizerCalls=2, appendedEOS=2, fullForwardCalls=len(forwards), postReadoutRows=post_readout_rows, validTargets=valid_targets, completedUpdates=optimizer_after["completedUpdates"], tAdam=optimizer_after["tAdam"]))
    if len(trace.steps) > 441:
        raise _training.NumericalFault("UNSUPPORTED_SIZE", "IV52 supports at most 441 complete trace frames.")
    outputs = dict(meanNLLBefore=mean_before, meanNLLAfter=mean_after, validTargets=valid_targets, completedUpdates=optimizer_after["completedUpdates"],
                   lossSumBefore=loss_sum_before, lossSumAfter=loss_sum_after, lossChange=loss_change, merges=raw["merges"], batchSize=raw["batchSize"], classCount=V, byteBound=2,
                   tokenizerCalls=2, appendedEOS=2, fullForwardCalls=len(forwards), postReadoutRows=post_readout_rows, predictionRows=R, trainableParameters=15, fixedEncoder=1,
                   tAdam=optimizer_after["tAdam"], frames=len(trace.steps), tensorCount=len(tensors), docAContentTokens=len(documents[0]["contentIDs"]), docBContentTokens=len(documents[1]["contentIDs"]))
    outputs.update(tokenizer_outputs)
    for step in trace.steps:
        for key, value in step["outputs"].items():
            outputs[f"{step['id']}_{key}"] = value
    return deepcopy(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))


def source_self_check():
    """DEFERRED public-record/CLI leaf; no other source check leaf is called."""
    assert __debug__, "Deferred checks require assertions enabled."
    default = derive_iv52(dict(DEFAULT_IV52))
    assert list(default) == ["status", "outputs", "steps", "tensors", "texts"]
    summary_keys = ["meanNLLBefore", "meanNLLAfter", "validTargets", "completedUpdates", "lossSumBefore", "lossSumAfter", "lossChange", "merges", "batchSize", "classCount", "byteBound", "tokenizerCalls", "appendedEOS", "fullForwardCalls", "postReadoutRows", "predictionRows", "trainableParameters", "fixedEncoder", "tAdam", "frames", "tensorCount", "docAContentTokens", "docBContentTokens"]
    tokenizer_keys = ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal")
    for prefix in ("docA", "docB"):
        summary_keys.extend(f"{prefix}_{key}" for key in tokenizer_keys)
    text_keys = ["docA", "docB", "trainingScope", "tokenizerPolicy", "batchPolicy", "objectivePolicy", "gradientPolicy", "updatePolicy", "postPolicy", "numericCoherence", "lossChangePolicy", "provenance", "modelVocabulary"]
    old_text_keys = ("corpus", "input", "corpusDecoded", "decoded", "corpusLabels", "corpusExpansions", "targetLabels", "targetExpansions", "ruleLabels", "ruleExpansions", "trainingStop")
    for prefix in ("docA", "docB"):
        text_keys.extend(f"{prefix}_{key}" for key in old_text_keys)
    assert len(summary_keys) == 45 and list(default["texts"]) == text_keys and len(text_keys) == 35
    for patch, frames, tensor_count, output_count in (
        ({}, 217, 211, 817),
        (dict(optimizer=1), 217, 211, 973),
        (dict(batchSize=1), 145, 143, 554),
        (dict(docA="aa", docB="bb", merges=2), 441, 271, 1683),
        (dict(docA="aa", docB="bb", merges=2, optimizer=1), 441, 271, 1839),
    ):
        record = derive_iv52({**DEFAULT_IV52, **patch})
        assert record["status"] == "defined" and list(record) == list(default)
        assert list(record["outputs"])[:45] == summary_keys and list(record["texts"]) == text_keys
        assert len(record["steps"]) == record["outputs"]["frames"] == frames
        assert len(record["tensors"]) == record["outputs"]["tensorCount"] == tensor_count
        if output_count is not None:
            assert len(record["outputs"]) == output_count
        assert record["outputs"]["fullForwardCalls"] == patch.get("batchSize", 2)
        assert record["outputs"]["postReadoutRows"] == record["outputs"]["predictionRows"]
        assert record["outputs"]["completedUpdates"] == 1
        aliases = []
        assert len({step["id"] for step in record["steps"]}) == frames
        for step in record["steps"]:
            assert list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"]
            for key, value in step["outputs"].items():
                alias = f"{step['id']}_{key}"
                aliases.append(alias)
                assert record["outputs"][alias] == value
        assert len(aliases) == len(set(aliases)) and list(record["outputs"])[45:] == aliases
        assert len({item["id"] for item in record["tensors"]}) == tensor_count
        for item in record["tensors"]:
            assert list(item) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
            assert len(item["shape"]) == len(item["axes"]) and len(set(item["axes"])) == len(item["axes"])
            assert all(type(d) is int and 1 <= d <= 64 for d in item["shape"])
            assert _training.math.prod(item["shape"]) == len(item["values"]) <= 4096
            assert item["provenance"] and item["dtype"] in ("int32", "float64", "bool")
            assert item["precision"] == (0 if item["dtype"] == "int32" else 8)
            assert all(type(value) is (int if item["dtype"] == "int32" else bool if item["dtype"] == "bool" else float) for value in item["values"])
        cells = {item["id"]: item for item in record["tensors"]}
        for phase in ("Before", "After"):
            assert cells[f"Counters{phase}"]["dtype"] == "int32"
            assert cells[f"Counters{phase}"]["shape"] == [2] and cells[f"Counters{phase}"]["axes"] == ["Counter"]
        assert cells["CountersBefore"]["values"] == [0, 0]
        assert cells["CountersAfter"]["values"] == [patch.get("optimizer", 0), 1]
        theta, gradient = cells["ThetaBefore"]["values"], cells["Gradient"]["values"]
        assert cells["UAfter"]["values"] + cells["BiasAfter"]["values"] == cells["ThetaAfter"]["values"]
        if patch.get("optimizer", 0) == 0:
            assert cells["ThetaAfter"]["values"] == [old - 0.1*g for old, g in zip(theta, gradient)]
            assert cells["MAfter"]["values"] == cells["VAfter"]["values"] == [0]*15
        if patch.get("merges", 0) == 0:
            for k in (3, 4, 8, 9, 13, 14):
                assert gradient[k] == cells["MAfter"]["values"][k] == cells["VAfter"]["values"][k] == 0
            for r in range(record["outputs"]["predictionRows"]):
                assert cells["dLogits"]["values"][5*r+3:5*r+5] == [0, 0]
        if patch.get("batchSize", 2) == 1:
            assert not any(item["id"].startswith(("forwardB_", "postB_")) for item in record["tensors"])
            assert cells["RowDocIDs"]["values"] == [0]
        # Recompare complete retained old records, not just three-field projections.
        tokenized = _training.tokenize_training_documents({**DEFAULT_IV52, **patch})
        for prefix in ("docA", "docB"):
            old = tokenized[prefix]["record"]
            scoped = [step for step in record["steps"] if step["id"].startswith(prefix + "_") and step["id"] != prefix + "_append_eos"]
            assert scoped == [{**deepcopy(step), "id": f"{prefix}_{step['id']}"} for step in old["steps"]]
            expected_tensors = [{**deepcopy(item), "id": f"{prefix}_{item['id']}", "provenance": f"Actual {prefix} IV39 call; fixed corpus abab, EOS off. {item['provenance']}"} for item in old["tensors"]]
            assert [cells[item["id"]] for item in expected_tensors] == expected_tensors
            assert cells[f"{prefix}_SequenceIDs"]["values"] == tokenized[prefix]["contentIDs"].tolist() + [512]
            assert record["outputs"][f"{prefix}_eos"] == 0 and record["outputs"][f"{prefix}_byteBound"] == 24
            for key in old_text_keys:
                assert record["texts"][f"{prefix}_{key}"] == old["texts"][key]
            d = 0 if prefix == "docA" else 1
            if d >= patch.get("batchSize", 2):
                continue
            forward_prefix = "forwardB" if d else "forwardA"
            parameters = {**_training._tiny.NUMERIC_DEFAULTS, "merges": patch.get("merges", 0),
                          **{key: patch.get(key, DEFAULT_IV52[key]) for key in _training.PARAMETER_KEYS}}
            saved = _training._tiny.tiny_trace()
            forward = _training._tiny.forward_tiny(parameters, tokenized[prefix]["contentIDs"].tolist(), saved)
            inherited = deepcopy(saved.steps)
            expected_steps = []
            for step in saved.steps:
                label, equation, explanation = _training.old_forward_prose(step)
                expected_steps.append(dict(id=f"{forward_prefix}_{step['id']}", label=label, equation=equation,
                                           explanation=explanation, inputs=deepcopy(step["inputs"]), outputs=deepcopy(step["outputs"])))
            actual_steps = [step for step in record["steps"] if step["id"].startswith(forward_prefix + "_") and not step["id"].startswith(forward_prefix + "_loss_")]
            assert actual_steps == expected_steps and saved.steps == inherited
            assert expected_steps[0]["label"] == "Gather observed token at position 0"
            assert inherited[0]["label"] == "Gather embedding for observed token 0"
            # All 57 tensors retain every field, including axes/precision/provenance.
            expected_tensors = [{**deepcopy(item), "id": f"{forward_prefix}_{item['id']}",
                                 "provenance": f"Actual isolated {forward_prefix} at initial weights; positions restart at zero. {item['provenance']}"}
                                for item in forward["tensors"]]
            assert len(expected_tensors) == 57
            assert [item for item in record["tensors"] if item["id"].startswith(forward_prefix + "_")] == expected_tensors
            features = next(item["values"] for item in forward["tensors"] if item["id"] == "Y")
            for t in range(forward["T"]):
                post_prefix = f"post{'B' if d else 'A'}_{t}"
                post_trace = _training.TrainingTrace()
                post = _training.finite_readout(features[2*t:2*t+2], cells["ThetaAfter"]["values"], forward["classIDs"], post_trace, post_prefix)
                assert [step for step in record["steps"] if step["id"].startswith(post_prefix + "_") and step["id"] != post_prefix + "_loss"] == post_trace.steps
                expected_post = [{**deepcopy(item), "id": f"{post_prefix}_{item['id']}",
                                  "provenance": f"Actual {post_prefix} updated readout on saved initial Y, not another encoder forward. {item['provenance']}"}
                                 for item in post["tensors"]]
                assert len(expected_post) == 11
                assert [item for item in record["tensors"] if item["id"].startswith(post_prefix + "_")] == expected_post

    # Token mean at unequal lengths: reconstruct the same scalar-ordered loss sum.
    unequal = derive_iv52({**DEFAULT_IV52, "docB": "aa"})
    cells = {item["id"]: item for item in unequal["tensors"]}
    assert cells["RowDocIDs"]["values"] == [0, 1, 1] and cells["RowPositions"]["values"] == [0, 0, 1]
    assert unequal["outputs"]["validTargets"] == 3
    for phase in ("Before", "After"):
        running = 0.0
        for value in cells[f"{phase}WeightedNLL"]["values"]:
            running = running + value
        assert unequal["outputs"][f"lossSum{phase}"] == running
        assert unequal["outputs"][f"meanNLL{phase}"] == running / 3
    masked = derive_iv52({**DEFAULT_IV52, "docB": "aa", "mB0": 0, "mB1": 0})
    masked_cells = {item["id"]: item for item in masked["tensors"]}
    assert masked["outputs"]["fullForwardCalls"] == 2 and masked["outputs"]["postReadoutRows"] == 3
    assert masked_cells["BeforeWeightedNLL"]["values"][1:] == [0, 0]
    assert all(value == 0 for value in masked_cells["dLogits"]["values"][5:])
    assert masked["outputs"]["meanNLLBefore"] == derive_iv52({**DEFAULT_IV52, "batchSize": 1})["outputs"]["meanNLLBefore"]

    # Preserved independent paper's valid SGD counterexample; no monotonicity rule.
    counterexample = {**DEFAULT_IV52, "docB": "aa", "eta": 1, "mB1": 0,
                      **{key: 0 for key in _training.PARAMETER_KEYS}, "b0": 1, "b1": -4, "b2": -1}
    increased = derive_iv52(counterexample)
    assert increased["status"] == "defined" and increased["outputs"]["meanNLLAfter"] > increased["outputs"]["meanNLLBefore"]
    increased_cells = {item["id"]: item for item in increased["tensors"]}
    assert increased_cells["BiasAfter"]["values"][1] < -4
    assert increased_cells["BeforeWeightedNLL"]["values"][2] == 0
    assert increased["outputs"]["fullForwardCalls"] == 2 and increased["outputs"]["postReadoutRows"] == 3
    zero_eta = derive_iv52({**DEFAULT_IV52, "optimizer": 1, "eta": 0})
    cells = {item["id"]: item for item in zero_eta["tensors"]}
    assert cells["ThetaBefore"]["values"] == cells["ThetaAfter"]["values"]
    assert any(cells["MAfter"]["values"]) and any(cells["VAfter"]["values"])
    assert cells["CountersAfter"]["values"] == [1, 1]
    assert zero_eta["outputs"]["meanNLLBefore"] == zero_eta["outputs"]["meanNLLAfter"]

    raw = dict(DEFAULT_IV52)
    fresh = derive_iv52(raw)
    default["tensors"][0]["values"][0] = -999
    default["steps"][0]["inputs"]["eta"] = -999
    default["texts"]["modelVocabulary"][0] = "changed"
    assert raw == dict(DEFAULT_IV52) and derive_iv52(raw) == fresh
    for value in (None, [], {**DEFAULT_IV52, "extra": 0}, {key: value for key, value in DEFAULT_IV52.items() if key != "mB1"}):
        assert derive_iv52(value)["code"] == "INVALID_INPUT"
    for patch, code, reason in (
        (dict(docA="", docB=None, eta=float("nan")), "INVALID_INPUT", "docB must be an actual string, without coercion."),
        (dict(docA="\ud800", mB1=2), "INVALID_INPUT", "mB1 must be numeric 0 or 1."),
        (dict(batchSize=1, docB="é"), "UNAVAILABLE", "docB: only raw a/b letters are supported; no trimming or normalization is performed."),
        (dict(merges=10**1000), "INVALID_INPUT", "merges must be an integer from 0 to 2."),
        (dict(batchSize=3), "INVALID_INPUT", "batchSize must be 1 or 2."),
        (dict(b0=-5), "INVALID_INPUT", "b0 must be between -4 and 4."),
        (dict(beta1=1), "INVALID_INPUT", "beta1 must be at least 0 and less than 1."),
        (dict(mA0=True), "NONFINITE", "mA0 must be an actual finite number."),
        (dict(docA="aaa\ud800"), "UNSUPPORTED_SIZE", "docA: more than 2 UTF-16 units necessarily exceeds this 2-byte field."),
        (dict(docA="\ud800"), "INVALID_INPUT", "docA: Unpaired high surrogate at UTF-16 offset 0."),
        (dict(docA="🦊"), "UNSUPPORTED_SIZE", "docA: the actual UTF-8 encoding exceeds 2 bytes; shorten this field explicitly."),
        (dict(docA="€"), "UNSUPPORTED_SIZE", "docA: the actual UTF-8 encoding exceeds 2 bytes; shorten this field explicitly."),
        (dict(docA="é"), "UNAVAILABLE", "docA: only raw a/b letters are supported; no trimming or normalization is performed."),
        (dict(docA="", docB="aaa"), "UNAVAILABLE", "docA: provide a nonempty document; its first content piece is given."),
        (dict(mA0=0, mB0=0), "UNAVAILABLE", "No selected real target has mask 1; the masked mean is undefined."),
        (dict(batchSize=1, mA0=0), "UNAVAILABLE", "No selected real target has mask 1; the masked mean is undefined."),
    ):
        result = derive_iv52({**DEFAULT_IV52, **patch})
        assert list(result) == ["status", "code", "reason"] and result == dict(status="unavailable", code=code, reason=reason)

    # N=0 must precede any neural call, even with unused A1/unselected B masks1.
    original_forward = _training._tiny.forward_tiny
    def unexpected_forward(*args):
        raise RuntimeError("unknown IV52 forward sentinel")
    try:
        _training._tiny.forward_tiny = unexpected_forward
        assert derive_iv52({**DEFAULT_IV52, "batchSize": 1, "mA0": 0})["code"] == "UNAVAILABLE"
        try:
            derive_iv52(dict(DEFAULT_IV52))
        except RuntimeError as error:
            assert str(error) == "unknown IV52 forward sentinel"
        else:
            raise AssertionError("Unknown implementation failure became an unavailable record")
    finally:
        _training._tiny.forward_tiny = original_forward

    # Exercise the actual CLI dispatcher without a subprocess or another check leaf.
    from contextlib import redirect_stdout
    from io import StringIO
    import sys
    cli = _training._packing
    saved_argv, saved_stdin = sys.argv, sys.stdin
    default_json = cli.json.dumps(dict(DEFAULT_IV52))
    queries = [(None, None, fresh), ("-", default_json, fresh), (default_json, None, fresh), ("{}", None, derive_iv52({}))]
    queries.extend(("-", bad, None) for bad in ('{"docA":"a","docA":"b"}', '{"extra":{"x":1,"x":2}}', 'NaN', 'Infinity', '-Infinity', '{', '9' * 5000))
    def forbidden_check():
        raise AssertionError("Query invoked a check leaf")
    check_modules = (_training, cli, cli._iv39, cli._iv39._bpe, _training._tiny, _training._tiny._bpe, _training._choice)
    saved_checks = [(module, module.source_self_check) for module in check_modules]
    try:
        for module, _ in saved_checks:
            module.source_self_check = forbidden_check
        for query, stdin_json, expected in queries:
            sys.argv = ["iv52.py"] + ([] if query is None else [query])
            sys.stdin = StringIO(default_json if stdin_json is None else stdin_json)
            stream = StringIO()
            with redirect_stdout(stream):
                cli.run(derive_iv52, DEFAULT_IV52, forbidden_check)
            result = cli.json.loads(stream.getvalue())
            if expected is None:
                assert result["status"] == "unavailable" and result["code"] == "INVALID_INPUT"
            else:
                assert result == expected
        def unexpected_query(_):
            raise ValueError("Unknown query ValueError must escape parser catches")
        sys.argv = ["iv52.py"]
        try:
            cli.run(unexpected_query, DEFAULT_IV52, forbidden_check)
        except ValueError as error:
            assert str(error) == "Unknown query ValueError must escape parser catches"
        else:
            raise AssertionError("Query failure was converted by parsing catches")
        def explicit_sentinel():
            raise AssertionError("Explicit check sentinel must escape query catches")
        sys.argv = ["iv52.py", "--self-check"]
        try:
            cli.run(derive_iv52, DEFAULT_IV52, explicit_sentinel)
        except AssertionError as error:
            assert str(error) == "Explicit check sentinel must escape query catches"
        else:
            raise AssertionError("Explicit leaf failure was swallowed")
    finally:
        for module, check in saved_checks:
            module.source_self_check = check
        sys.argv, sys.stdin = saved_argv, saved_stdin


def gradient_source_self_check():
    """DEFERRED conditional V3 leaf; same finite readout, never raw perturb guards.

    Fixed prior RN/4ULP premises and budgets: B_GRADIENT_DERIVATION.md and the
    independent D source witness. This checks their conditional inequality; it
    does not certify those premises or call any other source's check leaf.
    """
    assert __debug__, "Deferred checks require assertions enabled."
    u, h = 2**-53, 2**-12
    R, G = 8192*u, 32768*u
    for patch in ({}, dict(merges=2), dict(u00=2, u11=-2, b0=4, b2=-4)):
        record = derive_iv52({**DEFAULT_IV52, **patch})
        cells = {item["id"]: item["values"] for item in record["tensors"]}
        features = [cells["forwardA_Y"], cells["forwardB_Y"]]
        theta, ids, gradient = cells["ThetaBefore"], cells["ActiveIDs"], cells["Gradient"]
        assert record["outputs"]["validTargets"] == 2 and len(gradient) == 15
        assert all(len(y) == 2 and all(_training.math.isfinite(value) and abs(value) < 3 for value in y) for y in features)
        target_row = ids.index(512)
        assert target_row == 2
        def objective(weights):
            total = 0.0
            for d, y in enumerate(features):
                distribution = _training.finite_readout(y, weights, ids, _training.TrainingTrace(), f"fd{d}")
                gap = _training.finite(distribution["max"] - distribution["logits"][target_row], "target gap")
                nll = _training.finite(gap + distribution["logS"], "target NLL")
                total = _training.finite(total + nll, "masked loss running sum")
            return _training.finite(total / 2, "mean NLL")
        assert objective(theta[:]) == record["outputs"]["meanNLLBefore"]
        for k in range(15):
            plus, minus = theta[:], theta[:]
            plus[k], minus[k] = theta[k] + h, theta[k] - h
            assert plus[k] != theta[k] and minus[k] != theta[k]
            assert plus[k] - theta[k] == theta[k] - minus[k] == h and plus[k] - minus[k] == 2*h
            central = (objective(plus) - objective(minus)) / (2*h)
            active = k % 5 < len(ids)
            M3 = (27/4 if k < 10 else 1/4) if active else 0
            budget = M3*h*h/6 + 2*R/h + G
            assert _training.math.isfinite(central) and abs(gradient[k] - central) <= budget
            if not active:
                assert gradient[k] == central == 0


if __name__ == "__main__":
    _training._packing.run(derive_iv52, DEFAULT_IV52, source_self_check)

Training mechanics — p13/training_reference.py: raw28 validation, two-document preparation, real NumPy storage, scalar-ordered readout and gradient calculations. Follow the comments and saved operands alongside the hand derivations.

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.

"""IV52 readout-only training mechanics; SOURCE ONLY, execution deferred.

Real NumPy storage, scalar-ordered products and sums. The fixed encoder is the
accepted old tiny decoder, not a reimplementation or a packed-mask simulator.
Public helpers accept numerical operands, not proof of encoder provenance; the
chapter wrapper must retain the actual old forward that supplied each Y row.
No import, ordinary query or helper invokes a self-check.
"""
import importlib.util
import math
from pathlib import Path
from types import MappingProxyType
import numpy as np

_ROOT = Path(__file__).resolve().parents[1]


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


_packing = _load("_iv52_packing", _ROOT / "p13" / "packing_reference.py")
_tiny = _load("_iv52_tiny", _ROOT / "p10" / "tiny_reference.py")
_choice = _load("_iv52_choice", _ROOT / "p11" / "choice_reference.py")
NumericalFault = _packing.NumericalFault
KNOWN_FAULTS = (NumericalFault, *_tiny._DEPENDENCY_FAULTS, _choice.NumericalFault)
ALL_IDS = (97, 98, 512, 256, 257)
PARAMETER_KEYS = tuple(f"u{d}{c}" for d in range(2) for c in range(5)) + tuple(f"b{c}" for c in range(5))
DEFAULT_IV52 = MappingProxyType(dict(
    docA="a", docB="b", merges=0, batchSize=2,
    u00=1, u01=0, u02=0, u03=0, u04=0,
    u10=0, u11=1, u12=0, u13=0, u14=0,
    b0=0, b1=0, b2=0, b3=0, b4=0,
    eta=0.1, optimizer=0, beta1=0.9, beta2=0.999, epsilon=1e-8,
    mA0=1, mA1=1, mB0=1, mB1=1,
))


def _numeric(value, label):
    """Finite derived binary64 numbers; initial editor bounds are separate."""
    if type(value) not in (int, float):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    if type(value) is int and abs(value) > int(float.fromhex("0x1.fffffffffffffp+1023")):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    result = float(value)
    if not math.isfinite(result):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    return result


def finite(value, label):
    """Derived arithmetic follows the shared finite-result fault literal."""
    try:
        return _numeric(value, label)
    except NumericalFault as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error


def training_state(state):
    """Exact raw28: names, both string types, all26 numerics, then tokenization.

    Exact built-in dict avoids invoking subclass accessors. Domain comparisons
    precede float conversion so arbitrary-precision finite ints fail domain.
    """
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV52):
        raise NumericalFault("INVALID_INPUT", "state must have exactly " + ", ".join(DEFAULT_IV52) + " as own fields.")
    for key in ("docA", "docB"):
        if type(state[key]) is not str:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an actual string, without coercion.")
    checked = dict(docA=state["docA"], docB=state["docB"])
    for key in tuple(DEFAULT_IV52)[2:]:
        value = state[key]
        if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)):
            raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
        if key == "merges":
            valid, reason = value in (0, 1, 2), "merges must be an integer from 0 to 2."
        elif key == "batchSize":
            valid, reason = value in (1, 2), "batchSize must be 1 or 2."
        elif key in PARAMETER_KEYS[:10]:
            valid, reason = -2 <= value <= 2, f"{key} must be between -2 and 2."
        elif key in PARAMETER_KEYS[10:]:
            valid, reason = -4 <= value <= 4, f"{key} must be between -4 and 4."
        elif key == "eta":
            valid, reason = 0 <= value <= 1, "eta must be between 0 and 1."
        elif key == "optimizer":
            valid, reason = value in (0, 1), "optimizer must be numeric 0 or 1."
        elif key in ("beta1", "beta2"):
            valid, reason = 0 <= value < 1, f"{key} must be at least 0 and less than 1."
        elif key == "epsilon":
            valid, reason = 1e-8 <= value <= 1, "epsilon must be between 1e-8 and 1."
        else:
            valid, reason = value in (0, 1), f"{key} must be numeric 0 or 1."
        if not valid:
            raise NumericalFault("INVALID_INPUT", reason)
        checked[key] = int(value) if key in ("merges", "batchSize", "optimizer", "mA0", "mA1", "mB0", "mB1") else float(value)
    return checked


def tokenize_training_documents(state):
    """Raw28 first, then TWO actual accepted EOS-off records plus explicit EOS.

    The full ten-field IV51 configuration is derived explicitly. No packing
    grid is evaluated; old tokenize_documents itself appends each EOS once.
    """
    checked = training_state(state)
    configuration = dict(docA=checked["docA"], docB=checked["docB"], merges=checked["merges"],
                         blockSize=6, isolate=1, m0=1, m1=1, m2=1, m3=1, m4=1)
    tokenized = _packing.tokenize_documents(configuration)
    return dict(state=checked, packingConfiguration=configuration,
                docA=tokenized["docA"], docB=tokenized["docB"])


class TrainingTrace:
    """Six-field scalar snapshots, with every actual grouped operand retained."""
    def __init__(self):
        self.steps = []

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


def _prefix(prefix):
    if type(prefix) is not str or not prefix:
        raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")


def _object(value, names, label):
    if type(value) is not dict:
        raise NumericalFault("INVALID_INPUT", f"{label} must be a plain object.")
    if any(type(key) is not str for key in value) or set(value) != set(names):
        raise NumericalFault("INVALID_INPUT", f"{label} must have exactly {', '.join(names)} as own fields.")
    return {key: value[key] for key in names}


def _dense(value, minimum, maximum, label):
    if type(value) is not list:
        raise NumericalFault("INVALID_INPUT", f"{label} must be a dense ordinary array.")
    if not minimum <= len(value) <= maximum:
        size = str(minimum) if minimum == maximum else f"{minimum} to {maximum}"
        raise NumericalFault("SHAPE_MISMATCH", f"{label} requires {size} entries.")
    return value[:]


def _vector(value, minimum, maximum, label):
    return [_numeric(entry, f"{label}[{i}]") for i, entry in enumerate(_dense(value, minimum, maximum, label))]


def _classes(value):
    ids = _vector(value, 3, 5, "classIDs")
    if ids != list(ALL_IDS[:len(ids)]):
        raise NumericalFault("INVALID_INPUT", "classIDs must be the declared compact model prefix.")
    return [int(identifier) for identifier in ids]


def old_forward_prose(step):
    """Adopt complete TS tiny/component/head/FFN literals on new IV52 copies only."""
    identifier, x = step["id"], step["inputs"]
    if identifier.startswith(("ln1_", "ln2_")):
        stem = identifier.removesuffix("_statistics") if identifier.endswith("_statistics") else identifier.rsplit("_feature_", 1)[0]
        if identifier.endswith("_statistics"):
            return (f"{stem}: 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.")
        return (f"{stem}: affine feature {int(x['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.")
    if identifier == "heads_setup":
        return ("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.")
    if identifier.startswith("heads_project_"):
        role = identifier.split("_")[2]
        return (f"{role}[{int(x['b'])},{int(x['t'])},head {int(x['h'])},feature {int(x['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.")
    if identifier.startswith("heads_reshape_"):
        role = identifier.split("_")[2]
        return (f"{role}: 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.")
    if identifier.startswith("heads_permute_"):
        role = identifier.split("_")[2]
        b, t, h, f = (int(x[key]) for key in ("b", "t", "h", "f"))
        return (f"{role}: copy [{b},{t},{h},{f}] to [{b},{h},{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.")
    if identifier.startswith("heads_score_"):
        return (f"Batch {int(x['b'])}, head {int(x['h'])}: query {int(x['i'])} against key {int(x['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.")
    if identifier.startswith("heads_row_"):
        return (f"Batch {int(x['b'])}, head {int(x['h'])}, query {int(x['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.")
    if identifier.startswith("heads_head_mix_"):
        return (f"OHeads[{int(x['b'])},{int(x['h'])},{int(x['i'])},{int(x['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.")
    if identifier.startswith("heads_concat_"):
        return (f"Join head {int(x['h'])}, feature {int(x['f'])} into C[{int(x['b'])},{int(x['t'])},{int(x['concatFeature'])}]",
                "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.")
    if identifier.startswith("heads_output_"):
        return (f"Y[{int(x['b'])},{int(x['t'])},{int(x['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.")
    if identifier.startswith("ffn_hidden_"):
        return (f"Hidden affine [{int(x['b'])},{int(x['t'])},{int(x['m'])}]",
                "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.")
    if identifier.startswith("ffn_relu_"):
        return (f"ReLU [{int(x['b'])},{int(x['t'])},{int(x['m'])}]", "activation=max(0,preactivation)",
                "ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.")
    if identifier.startswith("ffn_output_"):
        return (f"FFN output [{int(x['b'])},{int(x['t'])},{int(x['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.")
    if identifier.startswith("input_"):
        return (f"Gather observed token at position {int(x['t'])}", "inputRow=compactRow(inputID); X[0,t,:]=E[inputRow,:]",
                "EOS is an ordinary available embedding row in this numeric kernel. There is no implicit stop rule or target lookup.")
    if identifier.startswith("rope_"):
        role = identifier.split("_")[1]
        return (f"Rotate {role} pair at absolute position {int(x['t'])}",
                "frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
                "The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved.")
    if identifier.startswith("residual1_"):
        return (f"First residual position {int(x['t'])}, feature {int(x['d'])}", "value=X+AttentionOutput",
                "Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding.")
    if identifier.startswith("residual2_"):
        return (f"Second residual position {int(x['t'])}, feature {int(x['d'])}", "value=R1+F",
                "The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights.")
    if identifier.startswith("readout_"):
        return (f"Readout position {int(x['t'])}, class {int(x['c'])}",
                "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
                "Final decoder features multiply only the active class columns. Bias is added last; targets are not operands.")
    if identifier.startswith("class_"):
        t, kind = int(identifier.split("_")[1]), identifier.split("_")[2]
        if kind == "max":
            return (f"Position {t}: active class maximum", "max=max(active logits)",
                    "The maximum stabilizes exponentiation; every active class participates before the target is selected.")
        if kind == "exp":
            return (f"Position {t}: exponentiate class {int(x['c'])}", "shifted=logit-max; term=exp(shifted)",
                    "At least one term is exp(0)=1. No probability is clipped or rounded for this calculation.")
        if kind == "normalize":
            return (f"Position {t}: class denominator and logsumexp", "running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS",
                    "Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE.")
        if kind == "probability":
            return (f"Position {t}: normalize class {int(x['c'])}", "probability=term/S",
                    "This is the stored binary64 probability for a real active class, before display formatting.")
        if kind == "argmax":
            return (f"Position {t}: computed-logit winner", "argmax computed logits; exact ties choose smallest compact class",
                    "Stored probabilities can appear tied even for different computed logits. This prediction is inspected, never fed back into teacher forcing.")
    raise AssertionError(f"Undeclared IV52 old-forward metadata family: {identifier}")


def finite_readout(y, theta, class_ids, trace, prefix):
    """Actual [2] feature row, [15] finite-derived readout, active classes3..5.

    Numeric coherence precondition: y is the actual fixed encoder row. Finite
    arrays do not certify origin. Return the full old direct_distribution record.
    """
    _prefix(prefix)
    features, weights = _vector(y, 2, 2, "y"), _vector(theta, 15, 15, "theta")
    ids = _classes(class_ids)
    Y, W = np.array(features, dtype=np.float64), np.array(weights, dtype=np.float64)
    logits = np.empty(len(ids), dtype=np.float64)
    for c in range(len(ids)):
        y0, y1, u0, u1, bias = float(Y[0]), float(Y[1]), float(W[c]), float(W[5+c]), float(W[10+c])
        product0, product1 = finite(y0 * u0, "readout product0"), finite(y1 * u1, "readout product1")
        summed = finite(product0 + product1, "readout sum")
        logit = finite(summed + bias, "readout logit")
        logits[c] = logit
        trace.add(f"{prefix}_readout_{c}", f"Updated readout class {c}",
                  "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
                  "Two fixed-feature products in feature order, then bias last. Derived finite weights have no initial-editor bounds.",
                  dict(c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=bias),
                  dict(product0=product0, product1=product1, sum=summed, logit=logit))
    return _choice.direct_distribution(logits, ids, trace, f"{prefix}_class")


def readout_gradients(rows, class_ids, trace, prefix):
    """Rows: exact dict(y,probabilities,targetID,mask), in A/B-position order.

    Coherence precondition: each distribution belongs to this y and the same
    initial readout/classes. Bounds cannot prove normalization or model origin.
    NumPy holds the real [R,5] derivatives and [15] contractions; scalar floats
    perform each ordered subtraction, product, division and immediate addition.
    """
    _prefix(prefix)
    ids = _classes(class_ids)
    captured = [_object(row, ("y", "probabilities", "targetID", "mask"), f"rows[{r}]")
                for r, row in enumerate(_dense(rows, 1, 4, "rows"))]
    checked = []
    for r, row in enumerate(captured):
        y = _vector(row["y"], 2, 2, f"rows[{r}].y")
        probabilities = _vector(row["probabilities"], len(ids), len(ids), f"rows[{r}].probabilities")
        target_id = _numeric(row["targetID"], f"rows[{r}].targetID")
        mask = _numeric(row["mask"], f"rows[{r}].mask")
        if target_id not in ids:
            raise NumericalFault("INVALID_INPUT", f"rows[{r}].targetID must be an active class ID.")
        if mask not in (0, 1):
            raise NumericalFault("INVALID_INPUT", f"rows[{r}].mask must be numeric 0 or 1.")
        if any(p < 0 or p > 1 for p in probabilities) or not any(p > 0 for p in probabilities):
            raise NumericalFault("INVALID_INPUT", f"rows[{r}].probabilities must be nonnegative probabilities at most 1 with at least one positive entry.")
        checked.append(dict(y=y, probabilities=probabilities, targetID=target_id,
                            targetRow=ids.index(target_id), mask=mask))
    n, count_inputs, count_outputs = 0, {}, {}
    for r, row in enumerate(checked):
        count_inputs[f"mask{r}"] = row["mask"]
        n += row["mask"]
        count_outputs[f"running{r}"] = n
    if n == 0:
        raise NumericalFault("UNAVAILABLE", "No selected real target has mask 1; the masked mean is undefined.")
    trace.add(f"{prefix}_count", "Count included gradient rows", "N starts at 0; running_r=previous+mask_r",
              "Only actual rows, in document then position order, contribute. This repeats the wrapper count on the supplied gradient operands.",
              count_inputs, {**count_outputs, "validTargets": n})
    row_gradients = np.zeros((len(checked), 5), dtype=np.float64)
    for r, row in enumerate(checked):
        inputs = dict(r=r, targetID=row["targetID"], targetRow=row["targetRow"], mask=row["mask"], validTargets=n)
        outputs = {}
        for c in range(5):
            outputs[f"active{c}"] = int(c < len(ids))
            if c < len(ids):
                probability, indicator = row["probabilities"][c], int(c == row["targetRow"])
                difference = finite(probability - indicator, "probability minus indicator")
                masked = finite(row["mask"] * difference, "masked difference")
                gradient = finite(masked / n, "mean logit gradient")
                inputs.update({f"probability{c}": probability, f"indicator{c}": indicator})
                outputs.update({f"difference{c}": difference, f"masked{c}": masked, f"gradient{c}": gradient})
            else:
                gradient = 0.0
                outputs[f"gradient{c}"] = gradient
            row_gradients[r, c] = gradient
        trace.add(f"{prefix}_row_{r}", f"All five logit derivatives for row {r}",
                  "active: difference=P-indicator; masked=mask*difference; gradient=masked/N; inactive: gradient=0",
                  "Every active class operand and result is retained. Inactive slots have structural zero derivatives without invented probabilities.", inputs, outputs)
    gradient_array = np.empty(15, dtype=np.float64)
    for k in range(15):
        c, d = k % 5, k // 5 if k < 10 else -1
        inputs, outputs, running = dict(k=k, c=c, d=d, active=int(c < len(ids))), {}, 0.0
        for r, row in enumerate(checked):
            g = float(row_gradients[r, c])
            inputs[f"g{r}"] = g
            if d >= 0:
                feature = row["y"][d]
                product = finite(feature * g, "parameter gradient product")
                inputs[f"y{r}"] = feature
                running = finite(running + product, "parameter gradient sum")
                outputs[f"product{r}"] = product
            else:
                running = finite(running + g, "bias gradient sum")
            outputs[f"running{r}"] = running
        gradient_array[k] = running
        trace.add(f"{prefix}_parameter_{k}", f"Derivative {PARAMETER_KEYS[k]}",
                  "product_r=Y[r,d]*g[r,c]; running starts at 0; running_r=previous+product_r" if d >= 0 else "running starts at 0; running_r=previous+g[r,c]",
                  "Immediately accumulate in document then position order. All fifteen parameters remain present, including inactive structural zeros.",
                  inputs, {**outputs, "gradient": running})
    return dict(validTargets=n, rowGradients=row_gradients.reshape(-1).tolist(),
                dU=gradient_array[:10].tolist(), db=gradient_array[10:].tolist(), gradient=gradient_array.tolist())


def optimizer_update(state, gradient, config, trace, prefix):
    """Detached finite-derived SGD/Adam state; exact state/config dictionaries.

    All15 new coordinates use the same old operands. No initial-editor bounds
    are applied to theta. IV52 supplies zero m/v/counters, and this pure helper
    validates explicit moment/counter inputs for later bounded callers.
    """
    _prefix(prefix)
    raw = _object(state, ("theta", "m", "v", "tAdam", "completedUpdates"), "optimizerState")
    cfg = _object(config, ("eta", "optimizer", "beta1", "beta2", "epsilon"), "optimizerConfig")
    theta, m, v, g = (_vector(value, 15, 15, label) for value, label in
                      ((raw["theta"], "theta"), (raw["m"], "m"), (raw["v"], "v"), (gradient, "gradient")))
    counters = {}
    for key in ("tAdam", "completedUpdates"):
        value = raw[key]
        if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)):
            raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
    for key in ("tAdam", "completedUpdates"):
        value = raw[key]
        if value < 0 or value >= 9007199254740991 or int(value) != value:
            raise NumericalFault("INVALID_INPUT", f"{key} must be a nonnegative safe counter with room for one update.")
        counters[key] = int(value)
    t_adam, completed = counters["tAdam"], counters["completedUpdates"]
    if t_adam > completed:
        raise NumericalFault("INVALID_INPUT", "tAdam cannot exceed completedUpdates.")
    if any(value < 0 for value in v):
        raise NumericalFault("INVALID_INPUT", "Every second moment v must be nonnegative.")
    if t_adam == 0 and (any(m) or any(v)):
        raise NumericalFault("INVALID_INPUT", "Zero Adam steps require zero m and v.")
    # Reuse the raw26 domain order without applying raw weight bounds to theta.
    validated = training_state({**DEFAULT_IV52, **cfg})
    eta, optimizer, beta1, beta2, epsilon = (validated[key] for key in cfg)
    if optimizer == 0 and (t_adam != 0 or any(m) or any(v)):
        raise NumericalFault("INVALID_INPUT", "SGD requires unused zero Adam moments and tAdam=0.")
    completed_new, t_new = completed + 1, t_adam + 1 if optimizer == 1 else 0
    setup_inputs = dict(eta=eta, optimizer=optimizer, beta1=beta1, beta2=beta2, epsilon=epsilon,
                        tAdam=t_adam, completedUpdates=completed)
    setup_outputs = dict(completedNew=completed_new, tNew=t_new)
    one_minus_beta1, one_minus_beta2, correction1, correction2 = 0.0, 0.0, 1.0, 1.0
    if optimizer == 1:
        one_minus_beta1, one_minus_beta2 = finite(1 - beta1, "one minus beta1"), finite(1 - beta2, "one minus beta2")
        power1, power2 = finite(beta1 ** t_new, "beta1 power"), finite(beta2 ** t_new, "beta2 power")
        correction1, correction2 = finite(1 - power1, "first bias correction"), finite(1 - power2, "second bias correction")
        if not (correction1 > 0 and correction2 > 0):
            raise NumericalFault("UNAVAILABLE", "Adam bias corrections must be positive.")
        setup_outputs.update(oneMinusBeta1=one_minus_beta1, oneMinusBeta2=one_minus_beta2,
                             power1=power1, power2=power2, correction1=correction1, correction2=correction2)
    trace.add(f"{prefix}_setup", "Compute the common optimizer arithmetic once",
              "completedNew=completedUpdates+1; tNew=tAdam+1; oneMinusBeta=1-beta; power=beta**tNew; correction=1-power" if optimizer == 1 else "completedNew=completedUpdates+1; tNew=0",
              "Global completed updates and Adam-only steps are distinct. Every coordinate below uses the same old state and gradient.", setup_inputs, setup_outputs)
    next_theta, next_m, next_v = (np.empty(15, dtype=np.float64) for _ in range(3))
    for k in range(15):
        inputs = dict(k=k, theta=theta[k], gradient=g[k], eta=eta, mOld=m[k], vOld=v[k])
        outputs, m_new, v_new = {}, 0.0, 0.0
        if optimizer == 1:
            inputs.update(beta1=beta1, beta2=beta2, oneMinusBeta1=one_minus_beta1,
                          oneMinusBeta2=one_minus_beta2, correction1=correction1, correction2=correction2, epsilon=epsilon, tNew=t_new)
            m_decay, m_product = finite(beta1 * m[k], "m decay"), finite(one_minus_beta1 * g[k], "m gradient product")
            m_new = finite(m_decay + m_product, "new first moment")
            square = finite(g[k] * g[k], "gradient square")
            v_decay, v_product = finite(beta2 * v[k], "v decay"), finite(one_minus_beta2 * square, "v gradient product")
            v_new = finite(v_decay + v_product, "new second moment")
            m_hat, v_hat = finite(m_new / correction1, "corrected first moment"), finite(v_new / correction2, "corrected second moment")
            root = finite(math.sqrt(v_hat), "Adam square root")
            denominator = finite(root + epsilon, "Adam denominator")
            normalized = finite(m_hat / denominator, "normalized Adam gradient")
            delta = finite(eta * normalized, "Adam delta")
            outputs.update(mDecay=m_decay, mProduct=m_product, mNew=m_new, square=square,
                           vDecay=v_decay, vProduct=v_product, vNew=v_new, mHat=m_hat, vHat=v_hat,
                           root=root, denominator=denominator, normalized=normalized)
        else:
            delta = finite(eta * g[k], "SGD delta")
        theta_new = finite(theta[k] - delta, "updated parameter")
        outputs.update(mNew=m_new, vNew=v_new, delta=delta, thetaNew=theta_new)
        next_theta[k], next_m[k], next_v[k] = theta_new, m_new, v_new
        trace.add(f"{prefix}_parameter_{k}", f"Simultaneously update {PARAMETER_KEYS[k]}",
                  "mDecay=beta1*mOld; mProduct=(1-beta1)*g; mNew=mDecay+mProduct; square=g*g; vDecay=beta2*vOld; vProduct=(1-beta2)*square; vNew=vDecay+vProduct; mHat=mNew/correction1; vHat=vNew/correction2; root=sqrt(vHat); denominator=root+epsilon; normalized=mHat/denominator; delta=eta*normalized; thetaNew=theta-delta" if optimizer == 1 else "delta=eta*g; thetaNew=theta-delta; mNew=vNew=0",
                  "The old arrays are never mutated. A complete new state is published only after every finite calculation succeeds; epsilon is outside sqrt.", inputs, outputs)
    return dict(theta=next_theta.tolist(), m=next_m.tolist(), v=next_v.tolist(),
                tAdam=t_new, completedUpdates=completed_new)


def source_self_check():
    """DEFERRED explicit local leaf; never calls another source's check leaf."""
    assert __debug__, "Deferred checks require assertions enabled."
    # Literal public metadata regressions: all 24 branches, independent of inherited prose.
    prose_cases = (
        ("ln1_1_statistics", "ln1_1: 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."),
        ("ln2_1_feature_1", "ln2_1: affine feature 1",
         "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."),
        ("heads_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."),
        ("heads_project_K_0_1_0_1", "K[0,1,head 0,feature 1]: 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."),
        ("heads_reshape_V", "V: 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."),
        ("heads_permute_Q_0_0_1_1", "Q: copy [0,1,0,1] to [0,0,1,1]", "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."),
        ("heads_score_0_0_1_0", "Batch 0, head 0: query 1 against key 0", "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."),
        ("heads_row_0_0_1", "Batch 0, head 0, query 1: 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."),
        ("heads_head_mix_0_0_1_1", "OHeads[0,0,1,1]: 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."),
        ("heads_concat_0_1_0_1", "Join head 0, feature 1 into C[0,1,1]", "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."),
        ("heads_output_0_1_1", "Y[0,1,1]: 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."),
        ("ffn_hidden_0_1_2", "Hidden affine [0,1,2]", "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."),
        ("ffn_relu_0_1_2", "ReLU [0,1,2]", "activation=max(0,preactivation)",
         "ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself."),
        ("ffn_output_0_1_1", "FFN output [0,1,1]", "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."),
        ("input_1", "Gather observed token at position 1", "inputRow=compactRow(inputID); X[0,t,:]=E[inputRow,:]",
         "EOS is an ordinary available embedding row in this numeric kernel. There is no implicit stop rule or target lookup."),
        ("rope_K_1", "Rotate K pair at absolute position 1", "frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
         "The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved."),
        ("residual1_1_1", "First residual position 1, feature 1", "value=X+AttentionOutput",
         "Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding."),
        ("residual2_1_1", "Second residual position 1, feature 1", "value=R1+F",
         "The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights."),
        ("readout_1_4", "Readout position 1, class 4", "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
         "Final decoder features multiply only the active class columns. Bias is added last; targets are not operands."),
        ("class_1_max", "Position 1: active class maximum", "max=max(active logits)",
         "The maximum stabilizes exponentiation; every active class participates before the target is selected."),
        ("class_1_exp_4", "Position 1: exponentiate class 4", "shifted=logit-max; term=exp(shifted)",
         "At least one term is exp(0)=1. No probability is clipped or rounded for this calculation."),
        ("class_1_normalize", "Position 1: class denominator and logsumexp", "running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS",
         "Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE."),
        ("class_1_probability_4", "Position 1: normalize class 4", "probability=term/S",
         "This is the stored binary64 probability for a real active class, before display formatting."),
        ("class_1_argmax", "Position 1: computed-logit winner", "argmax computed logits; exact ties choose smallest compact class",
         "Stored probabilities can appear tied even for different computed logits. This prediction is inspected, never fed back into teacher forcing."),
    )
    assert len(prose_cases) == 24
    for identifier, label, equation, explanation in prose_cases:
        inherited = dict(id=identifier, label="inherited label", equation="inherited equation", explanation="inherited explanation",
                         inputs=dict(b=0, t=1, h=0, f=1, d=1, c=4, i=1, j=0, m=2, concatFeature=1), outputs=dict(value=7))
        assert old_forward_prose(inherited) == (label, equation, explanation), identifier
        assert inherited["label"] == "inherited label" and inherited["outputs"] == dict(value=7)
    try:
        old_forward_prose(dict(id="unknown", inputs={}))
    except AssertionError as error:
        assert str(error) == "Undeclared IV52 old-forward metadata family: unknown"
    else:
        raise AssertionError("Unknown old metadata was silently inherited")
    assert len(DEFAULT_IV52) == 28 and len(PARAMETER_KEYS) == 15
    default = training_state(dict(DEFAULT_IV52))
    assert tuple(default) == tuple(DEFAULT_IV52)
    for key in tuple(DEFAULT_IV52)[2:]:
        for value, code in ((True, "NONFINITE"), (float("nan"), "NONFINITE"),
                            (float("inf"), "NONFINITE"), (10**1000, "INVALID_INPUT")):
            try:
                training_state({**DEFAULT_IV52, key: value})
            except NumericalFault as error:
                assert error.code == code, (key, error.code)
            else:
                raise AssertionError(f"Invalid {key} was accepted")
    class HostileDict(dict):
        def __iter__(self):
            raise AssertionError("Subclass iteration must not run")
        def __getitem__(self, key):
            raise AssertionError("Subclass indexing must not run")
    for value in (HostileDict(DEFAULT_IV52), MappingProxyType(dict(DEFAULT_IV52))):
        try:
            training_state(value)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT" and str(error) == "state must be a plain object."
        else:
            raise AssertionError("Non-dict raw input was accepted")
    try:
        training_state({**DEFAULT_IV52, "docA": "", "docB": None, "mB1": float("nan")})
    except NumericalFault as error:
        assert str(error) == "docB must be an actual string, without coercion."
    else:
        raise AssertionError("Both string types must precede numeric checks")
    rows = [dict(y=[2, -1], probabilities=[0.25, 0.25, 0.5], targetID=512, mask=1)]
    trace = TrainingTrace()
    actual = readout_gradients(rows, list(ALL_IDS[:3]), trace, "check")
    expected = [0.5, 0.5, -1, 0, 0, -0.25, -0.25, 0.5, 0, 0, 0.25, 0.25, -0.5, 0, 0]
    assert actual["gradient"] == expected
    assert actual["rowGradients"] == [0.25, 0.25, -0.5, 0, 0]
    assert len(trace.steps) == 17 and rows[0]["y"] == [2, -1]
    state = dict(theta=[0]*15, m=[0]*15, v=[0]*15, tAdam=0, completedUpdates=0)
    cfg = dict(eta=0.5, optimizer=0, beta1=0.9, beta2=0.999, epsilon=1e-8)
    updated = optimizer_update(state, expected, cfg, TrainingTrace(), "sgd")
    assert updated["theta"] == [-0.5*g for g in expected]
    assert updated["m"] == [0]*15 and updated["v"] == [0]*15
    assert updated["completedUpdates"] == 1 and updated["tAdam"] == 0
    adam_trace = TrainingTrace()
    zero_eta = optimizer_update(state, expected, {**cfg, "eta": 0, "optimizer": 1, "beta1": 0, "beta2": 0}, adam_trace, "adam")
    assert zero_eta["theta"] == state["theta"] and zero_eta["m"] == expected
    assert zero_eta["v"] == [g*g for g in expected]
    assert zero_eta["tAdam"] == zero_eta["completedUpdates"] == 1
    assert len(adam_trace.steps) == 16
    assert state == dict(theta=[0]*15, m=[0]*15, v=[0]*15, tAdam=0, completedUpdates=0)
    # Derived finite weights deliberately exceed old editor bounds.
    readout_trace = TrainingTrace()
    readout = finite_readout([1, 0], [101, 100, 100]+[0]*12, list(ALL_IDS[:3]), readout_trace, "derived")
    post_prose = (
        ("derived_readout_0", "Updated readout class 0", "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
         "Two fixed-feature products in feature order, then bias last. Derived finite weights have no initial-editor bounds."),
        ("derived_class_max", "Find the maximum active computed logit", "max=max(z0,...,z[V-1])",
         "All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability."),
        ("derived_class_exp_0", "Exponentiate active class 0", "shifted=logit-max; term=exp(shifted)",
         "No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it."),
        ("derived_class_normalize", "Accumulate terms and compute logsumexp", "running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS",
         "The denominator adds terms in ascending compact class order. Every actual running sum is saved."),
        ("derived_class_probability_0", "Normalize active class 0", "probability=term/S",
         "This stored binary64 probability is displayed without feeding its formatting back into arithmetic."),
        ("derived_class_argmax", "Choose the highest computed input logit", "strict greater-than updates the winner; exact ties retain lowest compact index",
         "Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order."),
    )
    for identifier, label, equation, explanation in post_prose:
        step = next(step for step in readout_trace.steps if step["id"] == identifier)
        assert (step["label"], step["equation"], step["explanation"]) == (label, equation, explanation)
    assert readout["logits"] == [101, 100, 100] and readout["nextID"] == 97
    for change in (dict(v=[-1]+[0]*14), dict(tAdam=1), dict(m=[1]+[0]*14), dict(completedUpdates=10**1000)):
        try:
            optimizer_update({**state, **change}, expected, cfg, TrainingTrace(), "invalid")
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Invalid optimizer state was accepted")
    for bad_rows in ([{**rows[0], "mask": 0}], [{**rows[0], "probabilities": [0, 0, 0]}]):
        try:
            readout_gradients(bad_rows, list(ALL_IDS[:3]), TrainingTrace(), "invalid")
        except NumericalFault as error:
            assert error.code in ("UNAVAILABLE", "INVALID_INPUT")
        else:
            raise AssertionError("Undefined derivative was accepted")
    # Helper boundary order and detached copies are independent of raw bounds.
    ids = list(ALL_IDS[:3])
    class HostileList(list):
        def __len__(self):
            raise AssertionError("Subclass length must not run")
        def __getitem__(self, key):
            raise AssertionError("Subclass indexing must not run")
    for y, theta, class_ids, prefix, code, reason in (
        ([float("nan"), 0], [0]*15, ids, "", "INVALID_INPUT", "prefix must be an actual nonempty string."),
        (HostileList([1, 0]), [0]*15, ids, "guard", "INVALID_INPUT", "y must be a dense ordinary array."),
        ([1], [0]*15, ids, "guard", "SHAPE_MISMATCH", "y requires 2 entries."),
        ([1, 0], [0]*14, ids, "guard", "SHAPE_MISMATCH", "theta requires 15 entries."),
        ([1, 0], [0]*15, [97, 512, 98], "guard", "INVALID_INPUT", "classIDs must be the declared compact model prefix."),
        ([float("nan"), 0], [0]*14, ids, "guard", "NONFINITE", "y[0] must be an actual finite number."),
    ):
        observed = TrainingTrace()
        try:
            finite_readout(y, theta, class_ids, observed, prefix)
        except NumericalFault as error:
            assert error.code == code and str(error) == reason
            assert observed.steps == []
        else:
            raise AssertionError("Invalid finite readout operand was accepted")
    for patch, code, reason in (
        (dict(targetID=256), "INVALID_INPUT", "rows[0].targetID must be an active class ID."),
        (dict(mask=True), "NONFINITE", "rows[0].mask must be an actual finite number."),
        (dict(mask=2), "INVALID_INPUT", "rows[0].mask must be numeric 0 or 1."),
        (dict(probabilities=[0, 0, 0]), "INVALID_INPUT", "rows[0].probabilities must be nonnegative probabilities at most 1 with at least one positive entry."),
        (dict(probabilities=[float("inf"), 0, 0]), "NONFINITE", "rows[0].probabilities[0] must be an actual finite number."),
        (dict(probabilities=[0.5, 0.5]), "SHAPE_MISMATCH", "rows[0].probabilities requires 3 entries."),
    ):
        observed = TrainingTrace()
        try:
            readout_gradients([{**rows[0], **patch}], ids, observed, "guard")
        except NumericalFault as error:
            assert error.code == code and str(error) == reason and observed.steps == []
        else:
            raise AssertionError("Invalid gradient operand was accepted")
    # All row object structures are captured before any row's numeric operands.
    try:
        readout_gradients([{**rows[0], "y": [float("nan"), 0]}, {**rows[0], "extra": 0}], ids, TrainingTrace(), "guard")
    except NumericalFault as error:
        assert str(error) == "rows[1] must have exactly y, probabilities, targetID, mask as own fields."
    else:
        raise AssertionError("Gradient row structure did not precede numeric work")
    for patch, code, reason in (
        (dict(tAdam=1, completedUpdates=0), "INVALID_INPUT", "tAdam cannot exceed completedUpdates."),
        (dict(tAdam=9007199254740991), "INVALID_INPUT", "tAdam must be a nonnegative safe counter with room for one update."),
        (dict(tAdam=-1, completedUpdates=float("nan")), "NONFINITE", "completedUpdates must be an actual finite number."),
        (dict(v=[-1]+[0]*14), "INVALID_INPUT", "Every second moment v must be nonnegative."),
        (dict(m=[1]+[0]*14), "INVALID_INPUT", "Zero Adam steps require zero m and v."),
    ):
        observed = TrainingTrace()
        try:
            optimizer_update({**state, **patch}, expected, cfg, observed, "guard")
        except NumericalFault as error:
            assert error.code == code and str(error) == reason and observed.steps == []
        else:
            raise AssertionError("Invalid optimizer state was accepted")
    for key, value in (("eta", -1), ("optimizer", 2), ("beta1", 1), ("beta2", 1), ("epsilon", 0)):
        observed = TrainingTrace()
        try:
            optimizer_update(state, expected, {**cfg, key: value}, observed, "guard")
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT" and observed.steps == []
        else:
            raise AssertionError("Inactive optimizer configuration escaped validation")
    real_adam = optimizer_update(state, [1]*15, dict(eta=0.5, optimizer=1, beta1=0.5, beta2=0.5, epsilon=1), TrainingTrace(), "adam")
    assert real_adam["m"] == real_adam["v"] == [0.5]*15
    assert real_adam["theta"] == [-0.25]*15  # sqrt(1)+1, epsilon outside sqrt.
    updated["theta"][0] = -999
    actual["gradient"][0] = -999
    assert state["theta"] == [0]*15 and rows[0]["y"] == [2, -1]
    assert readout_gradients(rows, ids, TrainingTrace(), "copy")["gradient"] == expected
    class ThrowingTrace:
        def add(self, *args):
            raise RuntimeError("unknown helper observer sentinel")
    try:
        finite_readout([1, 0], [0]*15, ids, ThrowingTrace(), "unknown")
    except RuntimeError as error:
        assert str(error) == "unknown helper observer sentinel"
    else:
        raise AssertionError("Unknown observer failure was converted")

Accepted data helper — p13/packing_reference.py: tokenize_documents validates its explicit ten-field data configuration and calls the actual EOS-off tokenizer for each document, appending one EOS per sequence. The packing-grid function is separate from tokenization and is not an isolated decoder.

Read the complete executable Python / NumPy source

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

"""IV-51 integer/bool packing mechanics; authored under the execution hold.

Reuse TWO actual IV-39 EOS-off calls. The old manual UTF codec, BPE decisions,
integer traces, tensors and prose remain available in each returned old record.
No neural model, native-codec answer, objective or training is computed here.
"""
import argparse
from copy import deepcopy
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np

_path = Path(__file__).resolve().parents[1] / "p09" / "iv39.py"
_spec = importlib.util.spec_from_file_location("_p13_packing_iv39", _path)
if _spec is None or _spec.loader is None:
    raise ImportError(f"Cannot load IV-39 source: {_path}")
_iv39 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_iv39)
_token = _iv39._bpe._token
NumericalFault = _token.NumericalFault
guarded = _token.guarded
EOS = _token.EOS
PAD = 768
DEFAULT_IV51 = MappingProxyType(dict(docA="ab", docB="ba", merges=0, blockSize=6,
                                    isolate=1, m0=1, m1=1, m2=1, m3=1, m4=1))


def integer(value, low, high, label):
    """Actual JSON-number types only; finite huge ints fail domain, not finiteness."""
    if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    # Compare Python ints before int/float conversion, including arbitrary precision.
    if value < low or value > high or int(value) != value:
        reason = ("merges must be an integer from 0 to 2." if label == "merges" else
                  "blockSize must be 3 or 6." if label == "blockSize" else
                  f"{label} must be numeric 0 or 1.")
        raise NumericalFault("INVALID_INPUT", reason)
    return int(value)


def packing_state(state):
    """Own field names first, BOTH string types, ALL numeric fields, then semantics."""
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV51):
        raise NumericalFault("INVALID_INPUT", "state must have exactly docA, docB, merges, blockSize, isolate, m0, m1, m2, m3, m4 as own fields.")
    for field in ("docA", "docB"):
        if type(state[field]) is not str:
            raise NumericalFault("INVALID_INPUT", f"{field} must be an actual string, without coercion.")
    result = dict(docA=state["docA"], docB=state["docB"])
    for field in tuple(DEFAULT_IV51)[2:]:
        low, high = (0, 2) if field == "merges" else (3, 6) if field == "blockSize" else (0, 1)
        value = integer(state[field], low, high, field)
        if field == "blockSize" and value not in (3, 6):
            raise NumericalFault("INVALID_INPUT", "blockSize must be 3 or 6.")
        result[field] = value
    return result


def _tokenize_document(text, merges, field):
    """Outer two-unit bound precedes strict old codec; inspect actual old bytes/IDs."""
    if _token.utf16_length(text) > 2:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: more than 2 UTF-16 units necessarily exceeds this 2-byte field.")
    record = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=merges, eos=0))
    if record["status"] == "unavailable":
        raise NumericalFault(record["code"], f"{field}: {record['reason']}")
    source_bytes = next(tensor["values"] for tensor in record["tensors"] if tensor["id"] == "SourceBytes") if text else []
    if len(source_bytes) > 2:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: the actual UTF-8 encoding exceeds 2 bytes; shorten this field explicitly.")
    if any(character not in "ab" for character in text):
        raise NumericalFault("UNAVAILABLE", f"{field}: only raw a/b letters are supported; no trimming or normalization is performed.")
    if not text:
        raise NumericalFault("UNAVAILABLE", f"{field}: provide a nonempty document; its first content piece is given.")
    ids = next(tensor["values"] for tensor in record["tensors"] if tensor["id"] == "TargetIDs")
    content = np.array(ids, dtype=np.int32)
    # EOS was disabled in the actual tokenizer and is appended exactly once here.
    sequence = np.concatenate((content, np.array([EOS], dtype=np.int32)))
    return dict(record=deepcopy(record), contentIDs=content, sequenceIDs=sequence)


def tokenize_documents(state):
    """Validate raw10, then A and B; return real old records and int32 sequences."""
    state = packing_state(state)
    doc_a = _tokenize_document(state["docA"], state["merges"], "docA")
    doc_b = _tokenize_document(state["docB"], state["merges"], "docB")
    return dict(state=state, docA=doc_a, docB=doc_b)


def pack_arrays(tokenized):
    """Build six physical slots, chunk permissions and five shifted target rows.

    Private input is the actual tokenize_documents result, not untrusted IDs.
    Every new counter/ID array is int32; permission and loss gates are bool.
    """
    state = tokenized["state"]
    width, isolate = state["blockSize"], state["isolate"]
    chunks = 6 // width
    sequences = (tokenized["docA"]["sequenceIDs"], tokenized["docB"]["sequenceIDs"])
    count = sum(len(sequence) for sequence in sequences)
    slots = np.full(6, PAD, dtype=np.int32)
    doc_ids = np.full(6, -1, dtype=np.int32)
    doc_positions = np.full(6, -1, dtype=np.int32)
    global_indices = np.arange(6, dtype=np.int32)
    chunk_ids = np.array([index // width for index in range(6)], dtype=np.int32)
    chunk_positions = np.array([index % width for index in range(6)], dtype=np.int32)
    valid = np.zeros(6, dtype=np.bool_)
    offset = 0
    for doc_id, sequence in enumerate(sequences):
        for position, identifier in enumerate(sequence):
            slots[offset] = identifier
            doc_ids[offset], doc_positions[offset], valid[offset] = doc_id, position, True
            offset += 1
    positions = np.full(6, -1, dtype=np.int32)
    for index in range(6):
        if valid[index]:
            positions[index] = doc_positions[index] if isolate else chunk_positions[index]
    allowed = np.zeros((chunks, width, width), dtype=np.bool_)
    for chunk in range(chunks):
        for query in range(width):
            q = chunk * width + query
            for key in range(width):
                k = chunk * width + key
                allowed[chunk, query, key] = bool(valid[q] and valid[k] and key <= query
                                                 and (not isolate or doc_ids[q] == doc_ids[k]))
    requested = np.array([state[f"m{index}"] for index in range(5)], dtype=np.int32)
    input_valid, target_valid = valid[:-1].copy(), valid[1:].copy()
    same_chunk = np.array([chunk_ids[i] == chunk_ids[i + 1] for i in range(5)], dtype=np.bool_)
    same_doc = np.array([doc_ids[i] == doc_ids[i + 1] for i in range(5)], dtype=np.bool_)
    isolation_gate = np.array([not isolate or value for value in same_doc], dtype=np.bool_)
    valid_targets_running = np.zeros(5, dtype=np.int32)
    structural = np.zeros(5, dtype=np.bool_)
    effective = np.zeros(5, dtype=np.bool_)
    active_ids = np.array([97, 98, EOS, 256, 257][:3 + state["merges"]], dtype=np.int32)
    target_rows = np.full(5, -1, dtype=np.int32)
    allowed_cells, valid_targets = 0, 0
    # Both reductions preserve the declared ascending row-major order.
    for chunk in range(chunks):
        for query in range(width):
            for key in range(width):
                allowed_cells += int(allowed[chunk, query, key])
    for i in range(5):
        structural[i] = bool(input_valid[i] and target_valid[i] and same_chunk[i]
                             and (isolation_gate[i]))
        effective[i] = bool(requested[i] and structural[i])
        valid_targets += int(effective[i])
        valid_targets_running[i] = valid_targets
        if target_valid[i]:
            target_rows[i] = active_ids.tolist().index(int(slots[i + 1]))
    return dict(slots=slots.reshape(chunks, width).copy(), globalIndices=global_indices,
                docIDs=doc_ids, docPositions=doc_positions, chunkIDs=chunk_ids,
                chunkPositions=chunk_positions, positionIDs=positions, valid=valid,
                allowed=allowed, activeIDs=active_ids, requestedMask=requested,
                inputValid=input_valid, targetValid=target_valid, sameChunk=same_chunk,
                sameDoc=same_doc, isolationGate=isolation_gate, structuralMask=structural, effectiveMask=effective,
                targetRows=target_rows, validTargetsRunning=valid_targets_running, packedTokens=count, paddingSlots=6-count,
                allowedCells=allowed_cells, validTargets=valid_targets)


def _json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate JSON key: {key}")
        result[key] = value
    return result


def _json_constant(value):
    raise ValueError(f"Invalid JSON constant: {value}")


_JSON_INT = int


def _json_integer(token):
    return -0.0 if token == "-0" else _JSON_INT(token)


def run(derive, defaults, self_check):
    """No args/defaults, complete JSON replacement or '-' stdin; checks explicit."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    parser.add_argument("--self-check", action="store_true")
    args = parser.parse_args()
    if args.self_check:
        if args.state is not None:
            parser.error("--self-check cannot be combined with a state query")
        self_check()  # Outside query handling: assertion/unknown errors propagate.
        return
    try:
        if args.state is None:
            state = dict(defaults)
        else:
            raw = sys.stdin.read() if args.state == "-" else args.state
            state = json.loads(raw, object_pairs_hook=_json_object,
                               parse_constant=_json_constant, parse_int=_json_integer)
    except (ValueError, OSError) as error:
        result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
    else:
        # Parsing alone is caught above; unknown implementation failures stay errors.
        result = derive(state)
    print(json.dumps(result, allow_nan=False, ensure_ascii=False, separators=(",", ":")))


def source_self_check():
    """DEFERRED explicit mechanics leaf; never calls an old or new check leaf."""
    assert __debug__, "Run later checks with assertions enabled."
    for merges, width, isolate, expected_slots, allowed, mask in (
        (0, 6, 1, [97, 98, 512, 98, 97, 512], 12, [1, 1, 0, 1, 1]),
        (0, 6, 0, [97, 98, 512, 98, 97, 512], 21, [1, 1, 1, 1, 1]),
        (0, 3, 0, [97, 98, 512, 98, 97, 512], 12, [1, 1, 0, 1, 1]),
        (1, 6, 1, [256, 512, 98, 97, 512, 768], 9, [1, 0, 1, 1, 0]),
        (2, 6, 0, [256, 512, 98, 97, 512, 768], 15, [1, 1, 1, 1, 0]),
        (2, 3, 1, [256, 512, 98, 97, 512, 768], 7, [1, 0, 0, 1, 0]),
        (1, 3, 0, [256, 512, 98, 97, 512, 768], 9, [1, 1, 0, 1, 0]),
    ):
        actual = pack_arrays(tokenize_documents({**DEFAULT_IV51, "merges": merges, "blockSize": width, "isolate": isolate}))
        assert actual["slots"].reshape(6).tolist() == expected_slots
        assert actual["allowedCells"] == allowed and actual["effectiveMask"].tolist() == mask
        assert actual["validTargets"] == sum(mask)
        for value in actual.values():
            if type(value) is np.ndarray:
                assert value.dtype in (np.dtype(np.int32), np.dtype(np.bool_))
    for patch, code in ((dict(merges=10**1000), "INVALID_INPUT"),
                        (dict(m4=True), "NONFINITE"), (dict(docB=None, merges=float("nan")), "INVALID_INPUT"),
                        (dict(docA="\ud800", m4=2), "INVALID_INPUT"),
                        (dict(docA="aaa\ud800"), "UNSUPPORTED_SIZE"),
                        (dict(docA="\ud800"), "INVALID_INPUT"), (dict(docA="🦊"), "UNSUPPORTED_SIZE"),
                        (dict(docA="é"), "UNAVAILABLE"), (dict(docA=""), "UNAVAILABLE")):
        result = guarded(tokenize_documents)({**DEFAULT_IV51, **patch})
        assert result["status"] == "unavailable" and result["code"] == code
    zero = pack_arrays(tokenize_documents({**DEFAULT_IV51, **{f"m{i}": 0 for i in range(5)}}))
    assert zero["validTargets"] == 0

    class HostileDict(dict):
        def __iter__(self):
            raise AssertionError("Raw guard must reject before iteration")

        def __getitem__(self, key):
            raise AssertionError("Raw guard must reject before item access")

    # A proxy may wrap hostile user code; only an exact dict is public raw state.
    for raw in (HostileDict(DEFAULT_IV51), MappingProxyType(HostileDict(DEFAULT_IV51)),
                MappingProxyType(dict(DEFAULT_IV51))):
        rejected = guarded(tokenize_documents)(raw)
        assert rejected == dict(status="unavailable", code="INVALID_INPUT",
                                reason="state must be a plain object.")

Tokenizer composition — p09/iv39.py: the actual two calls retain the complete corpus/target encoding, ranked rules and reconstructed strings.

Read the complete executable Python / NumPy source

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

"""IV-39 — Byte-Pair Encoding: A Full Merge Trace.

Train adjacent byte-ID pairs on a separate, literal training corpus. Count
ALL adjacent occurrences, including overlaps, choose the greatest count,
then the lexicographically smallest NUMERIC (left ID, right ID) on ties.
Replace matches left to right without overlap. Recount after every rule.
Encode the target with the learned rules in increasing rank, not by taking
the longest dictionary prefix. Only the target can receive explicit EOS512.

Hand default: corpus abab starts [97,98,97,98]. Counts ab2,ba1 select ab256,
so [256,256] becomes rule257=[97,98,97,98]. Target ababab becomes
[256,256,256] then [257,256]; expanding BOTH IDs reconstructs six bytes.
Corpus aaaa has three adjacent aa occurrences but only two replacements.
Corpus bbaa encounters bb,ba,aa once each; numeric order chooses the LAST
encountered aa=(97,97), producing [98,98,256], not insertion-order bb.
Corpus 'bc bc ab' learns bc256,bc-space257,ab258. In its third round
(97,98) beats pairs starting257 numerically, not by decimal string keys.
Target abc becomes [97,256]; greedy longest-prefix ab258 would differ.

All source is authored without imports, execution, fixtures generation or
runtime validation. Keep bpe_reference.py AND token_reference.py beside this
wrapper. File-relative loading supports an arbitrary caller working directory.
"""
import importlib.util
from pathlib import Path

_bpe_spec = importlib.util.spec_from_file_location(
    "_p09_bpe_reference", Path(__file__).resolve().with_name("bpe_reference.py"))
_bpe = importlib.util.module_from_spec(_bpe_spec)
_bpe_spec.loader.exec_module(_bpe)

DEFAULT_IV39 = _bpe.DEFAULT_IV39


@_bpe._token.guarded
def derive_iv39(state):
    """Train a real corpus, encode a separate target, and decode both actual IDs."""
    token = _bpe._token
    s = _bpe.bpe_state(state)
    encoding_trace = token.TokenTrace()
    corpus = _bpe.encode_bounded(s["corpus"], "corpus", "corpus", encoding_trace)
    source = _bpe.encode_bounded(s["text"], "text", "source", encoding_trace)
    trace = token.TokenTrace()
    corpus_units, units = token.utf16_length(s["corpus"]), token.utf16_length(s["text"])
    trace.add("setup", "Declare learned byte-pair encoding and both exact inputs",
              "byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
              "Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.",
              dict(requestedMerges=s["merges"], eos=s["eos"]),
              dict(corpusUnits=corpus_units, corpusScalars=len(corpus["codePoints"]), utf16Units=units,
                   scalarCount=len(source["codePoints"]), byteBound=_bpe.BYTE_BOUND,
                   mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=_bpe.EOS))
    # Scalar records were prepared during validation; keep their actual order.
    trace.steps.extend(encoding_trace.steps)
    tensors = []
    for stem, encoded in (("Corpus", corpus), ("Source", source)):
        for suffix, key, axis, provenance in (
            ("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
            ("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
            ("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
            ("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
            ("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
            ("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
        ):
            _bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
    trained = _bpe.train_bpe(corpus["bytes"], s["merges"], trace, tensors)
    ids = _bpe.encode_bpe(source["bytes"], trained["rules"], s["eos"], trace, tensors)
    # Corpus is NEVER EOS-trained. Both inverse paths expand real saved IDs.
    corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)
    target_decoded = _bpe.decode_bpe_ids(ids, trained["rules"], s["eos"], "target", trace)
    corpus_equal = int(corpus_decoded["decoded"] == s["corpus"])
    equal = int(target_decoded["decoded"] == s["text"])
    if not (corpus_equal and equal):
        raise _bpe.NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
    trace.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
              "corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
              "Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.",
              dict(corpusOriginalUnits=corpus_units, corpusDecodedUnits=token.utf16_length(corpus_decoded["decoded"]),
                   corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=units,
                   decodedUnits=token.utf16_length(target_decoded["decoded"]), decodedByteCount=len(target_decoded["bytes"])),
              dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
    _bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"],
                     "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
    _bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", target_decoded["bytes"],
                     "Actual final target ID expansions passed to strict UTF-8 decoding.")
    expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}

    def expansion(identifier):
        return [] if identifier == _bpe.EOS else [identifier] if identifier <= 255 else expansions[identifier]

    def labels(token_ids):
        return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == _bpe.EOS else
                f"ID {int(identifier)}, bytes {token.json_text(expansion(int(identifier)))}" for identifier in token_ids]

    def expansion_labels(token_ids):
        return [token.json_text(expansion(int(identifier))) for identifier in token_ids]

    summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]),
                   actualMerges=len(trained["rules"]), tokenCount=len(ids), requestedMerges=s["merges"],
                   corpusTokens=len(trained["ids"]), eos=s["eos"], byteBound=_bpe.BYTE_BOUND,
                   vocabularyItems=256 + len(trained["rules"]) + 1, corpusEqual=corpus_equal, equal=equal)
    texts = dict(corpus=s["corpus"], input=s["text"], corpusDecoded=corpus_decoded["decoded"],
                 decoded=target_decoded["decoded"], corpusLabels=labels(trained["ids"]),
                 corpusExpansions=expansion_labels(trained["ids"]), targetLabels=labels(ids),
                 targetExpansions=expansion_labels(ids),
                 ruleLabels=[f"ID {rule['id']}, bytes {token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
                 ruleExpansions=[token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
                 trainingStop="Zero merges requested: no training round or pair selection occurs." if s["merges"] == 0 else
                 "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < s["merges"] else
                 "Requested merge budget completed.")
    return trace.result(summary, tensors, texts)


def source_self_check():
    """Deferred hand-literal record checks; never part of the normal CLI path."""
    assert __debug__, "Run later checks with assertions enabled."
    _bpe.source_self_check()
    result = derive_iv39(dict(DEFAULT_IV39))
    assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
    assert list(result["outputs"])[:11] == ["corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"]
    assert [result["outputs"][key] for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount")] == [4, 6, 2, 2]
    assert len(result["steps"]) == 44 and len(result["tensors"]) == 37
    assert result["texts"]["corpusDecoded"] == "abab" and result["texts"]["decoded"] == "ababab"
    assert result["texts"]["targetLabels"] == ["ID 257, bytes [97,98,97,98]", "ID 256, bytes [97,98]"]
    # Tensor count:12source+1initial+10round+1corpus+3rules+2expansions+
    # 1targetinitial+4targetpasses+1targetfinal+2decoded=37. No program counted it.
    tensor_ids = [record["id"] for record in result["tensors"]]
    for merges, eos, steps in ((2, 1, 46), (3, 0, 45), (3, 1, 47), (4, 0, 45), (4, 1, 47)):
        case = derive_iv39(dict(corpus="abab", text="ababab", merges=merges, eos=eos))
        assert len(case["steps"]) == steps
        assert [record["id"] for record in case["tensors"]] == tensor_ids
    for eos in (0, 1):
        empty = derive_iv39(dict(corpus="", text="", merges=0, eos=eos))
        assert empty["outputs"]["tokenCount"] == eos
        assert len(empty["steps"]) == 2 + 2 * eos
        assert empty["texts"]["decoded"] == empty["texts"]["corpusDecoded"] == ""
    for patch, code in (
        (dict(corpus="\ud800", merges=float("nan")), "NONFINITE"),
        (dict(corpus="a" * 25, text="\ud800"), "UNSUPPORTED_SIZE"),
        (dict(corpus="\ud800", text="a" * 25), "INVALID_INPUT"),
        (dict(text="🦊" * 7), "UNSUPPORTED_SIZE"),
        (dict(text="🦊" * 9), "UNSUPPORTED_SIZE"),
    ):
        bad = derive_iv39({**DEFAULT_IV39, **patch})
        assert list(bad) == ["status", "code", "reason"] and bad["code"] == code


if __name__ == "__main__":
    # No args: defaults; one complete JSON state: replacement; '-': stdin JSON.
    _bpe._token.run(derive_iv39, DEFAULT_IV39)

BPE operations — p09/bpe_reference.py: overlapping pair counts, numeric tie order, disjoint replacements, ranked encoding and inverse expansions.

Read the complete executable Python / NumPy source

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

"""IV-39: complete learned byte-pair encoding, authored without execution.

NumPy int32 arrays hold actual bytes, code points, offsets, IDs and rule
expansions. Python integers do scalar comparisons, counts and index arithmetic.
The unchanged token_reference.py supplies the manual UTF-8 codec and record
storage. No native codec supplies a production answer. A byte piece need not
be valid Unicode alone: concatenate all expansions before strict decoding.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
import numpy as np

# File-relative loading works even when the caller has an unrelated cwd.
_token_spec = importlib.util.spec_from_file_location(
    "_p09_bpe_token_reference", Path(__file__).resolve().with_name("token_reference.py"))
_token = importlib.util.module_from_spec(_token_spec)
_token_spec.loader.exec_module(_token)

NumericalFault = _token.NumericalFault
BPE_BYTE_BOUND = 24
BYTE_BOUND = BPE_BYTE_BOUND
MERGE_BASE = 256
MERGE_BOUND = 4
EOS = 512
DEFAULT_IV39 = MappingProxyType(dict(corpus="abab", text="ababab", merges=2, eos=0))


def data_object(value, fields, label):
    """Exact built-in mappings have own data entries, never property getters."""
    if type(value) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", f"{label} must be a plain object.")
    if any(type(key) is not str for key in value) or set(value) != set(fields):
        raise NumericalFault("INVALID_INPUT", f"{label} must have exactly {', '.join(fields)} as own fields.")


def dense_data(values, limit, label, numeric=True):
    """Reject custom indexing BEFORE reading entries; never narrow invalid data."""
    if type(values) is np.ndarray and numeric:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
    if len(values) > limit:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")


def budget(merges):
    if type(merges) not in (int, float):
        raise NumericalFault("NONFINITE", "merges must be an actual finite number.")
    # The reused integer validator catches finiteness OverflowError on huge ints.
    return _token.integer(merges, 0, MERGE_BOUND, "merges")


def eos_flag(eos):
    _token._flag(eos)
    return int(eos)


def bpe_state(state):
    """ALL raw strings/numbers precede corpus, then target Unicode semantics."""
    data_object(state, DEFAULT_IV39, "state")
    for key in ("corpus", "text"):
        if type(state[key]) is not str:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an actual string, without coercion.")
    merges = budget(state["merges"])
    if type(state["eos"]) not in (int, float):
        raise NumericalFault("NONFINITE", "eos must be an actual finite number.")
    # Check finite before the flag domain, preserving NONFINITE error precedence.
    eos = _token.integer(state["eos"], 0, 1, "eos")
    return dict(corpus=state["corpus"], text=state["text"], merges=merges, eos=eos)


def encode_bounded(text, field, prefix, trace):
    """Early UTF-16 bound, all surrogate checks, then actual UTF-8 byte bound."""
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", f"{field} must be an actual string, without coercion.")
    if _token.utf16_length(text) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: more than 24 UTF-16 units necessarily exceeds this 24-byte field.")
    reason = f"{field}: the actual UTF-8 encoding exceeds 24 bytes; shorten this field explicitly."
    try:
        encoded = _token.utf8_encode(text, prefix, trace)
    except NumericalFault as error:
        # Nine foxes hit the inherited32-byte bound before this24-byte postcheck.
        if error.code == "UNSUPPORTED_SIZE":
            raise NumericalFault("UNSUPPORTED_SIZE", reason) from error
        raise
    if len(encoded["bytes"]) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", reason)
    return encoded


def bytes_input(values):
    dense_data(values, BYTE_BOUND, "BPE bytes")
    return _token.int_array(values, high=255, label="BPE bytes", limit=BYTE_BOUND)


def rule_table(rules):
    """Validate a lossless, acyclic rule namespace before expanding caller IDs."""
    dense_data(rules, MERGE_BOUND, "BPE rules", numeric=False)
    # Inspect every object/container first; no arbitrary mapping/index getter runs.
    for rule in rules:
        data_object(rule, ("id", "left", "right", "bytes"), "rule")
        dense_data(rule["bytes"], BYTE_BOUND, "Rule bytes")
    expansions, pairs = {}, set()
    for rank, rule in enumerate(rules):
        expected_id = MERGE_BASE + rank
        identifier = int(_token.int_array([rule["id"]], high=259, label="Rule ID")[0])
        if identifier != expected_id:
            raise NumericalFault("INVALID_INPUT", f"Rule {rank} must have ID {expected_id}.")
        operands = _token.int_array([rule["left"], rule["right"]], high=expected_id - 1, label="Rule operands")
        left, right = int(operands[0]), int(operands[1])
        # IDs between255 and this ID must already be present, never forward/cyclic.
        if any(operand > 255 and operand not in expansions for operand in (left, right)):
            raise NumericalFault("INVALID_INPUT", "Each rule operand must be a byte ID or an earlier merge ID.")
        if (left, right) in pairs:
            raise NumericalFault("INVALID_INPUT", "Duplicate BPE rule pairs are not allowed.")
        pairs.add((left, right))
        stored = _token.int_array(rule["bytes"], high=255, label="Rule bytes", limit=BYTE_BOUND)
        left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
        right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
        expected = np.concatenate((left_bytes, right_bytes))
        if len(expected) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "A rule expansion exceeds 24 bytes.")
        if len(expected) != len(stored) or any(int(a) != int(b) for a, b in zip(expected, stored)):
            raise NumericalFault("INVALID_INPUT", "Rule bytes must equal the left expansion followed by the right expansion.")
        expansions[identifier] = expected
    return expansions


def save_tensor(tensors, identifier, axis, values, provenance):
    """Keep actual int32 storage; an empty stream has no fabricated tensor."""
    if len(values):
        tensors.append(_token.tensor(identifier, axis, values, provenance))


def replace_pass(ids, rule, rank, stage, trace, tensors):
    """Count positions in CURRENT input tokens, not original UTF-8 bytes."""
    stem = f"{'Train' if stage == 'train' else 'Encode'}R{rank}"
    save_tensor(tensors, f"{stem}Before", "Tokens", ids,
                "Complete current token list before this nonoverlapping left-to-right pass.")
    result, position = [], 0
    while position < len(ids):
        current_id = int(ids[position])
        next_id = int(ids[position + 1]) if position + 1 < len(ids) else -1
        matched = int(current_id == rule["left"] and next_id == rule["right"])
        consumed = 2 if matched else 1
        identifier = rule["id"] if matched else current_id
        next_position = position + consumed
        inputs = dict(rank=rank, position=position, inputLength=len(ids), left=rule["left"],
                      right=rule["right"], newID=rule["id"], currentID=current_id,
                      nextID=next_id, outputLength=len(result))
        result.append(identifier)
        trace.add(f"{stage}_replace_{rank}_{position}", f"{stage}: rank {rank}, current-token position {position}",
                  "matched=(currentID=left and nextID=right); emit matched?newID:currentID; consumed=matched?2:1; nextPosition=position+consumed",
                  "Positions index the current token list, not original bytes. A match consumes two tokens and emits one; a nonmatch copies one token. Advancing past both matched operands prevents overlapping replacements. The complete pass snapshots and position/consumed/nextPosition retain every scan; nextID -1 means no next token, never a token or padding item.",
                  inputs, dict(matched=matched, id=identifier, consumed=consumed,
                               nextPosition=next_position, outputLength=len(result)))
        position = next_position
    values = np.array(result, dtype=np.int32)
    save_tensor(tensors, f"{stem}After", "Tokens", values,
                "Complete actual output token list after this rank; no padding or truncation.")
    return values


def train_bpe(values, merges, trace, tensors):
    """Count overlaps, select numeric ties, concatenate bytes, replace disjointly."""
    merges = budget(merges)
    ids = bytes_input(values).copy()
    rules, expansions = [], {}
    save_tensor(tensors, "TrainInitialIDs", "Tokens", ids,
                "Initial training byte IDs, one ID for each actual corpus byte.")
    for rank in range(merges):
        if len(ids) < 2:
            trace.add("train_stop", "Stop: fewer than two training tokens remain", "length<2 means no adjacent pair exists",
                      "This is one real early stop, not a fabricated merge. A zero requested budget does not enter training at all.",
                      dict(rank=rank, length=len(ids), requestedMerges=merges), dict(actualMerges=len(rules)))
            break
        counts = {}
        # Advance by ONE here: unlike replacement, counting includes overlaps.
        for position in range(len(ids) - 1):
            left, right = int(ids[position]), int(ids[position + 1])
            count_before = counts.get((left, right), 0)
            counts[(left, right)] = count_before + 1
            trace.add(f"train_count_{rank}_{position}", f"Count round {rank} pair at current-token position {position}",
                      "frequency(left,right)=previous frequency+1; next counting position=position+1",
                      "Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.",
                      dict(rank=rank, position=position, left=left, right=right, countBefore=count_before),
                      dict(countAfter=counts[(left, right)], distinctPairs=len(counts)))
        # Sort NUMERIC tuples, never string keys or insertion order (bbaa anchor).
        candidates = sorted(counts)
        for suffix, entries, provenance in (
            ("Left", [pair[0] for pair in candidates], "Numeric tuple order: left ID, then right ID; aligned candidate columns."),
            ("Right", [pair[1] for pair in candidates], "Right ID in the same sorted candidate order."),
            ("Frequency", [counts[pair] for pair in candidates], "Actual adjacent-pair frequency, including overlapping occurrences."),
        ):
            save_tensor(tensors, f"TrainR{rank}Candidate{suffix}", "Candidates",
                        np.array(entries, dtype=np.int32), provenance)
        best = None
        best_frequency = 0
        for candidate_index, (left, right) in enumerate(candidates):
            frequency = counts[(left, right)]
            best_left, best_right = best if best is not None else (-1, -1)
            inputs = dict(candidateIndex=candidate_index, left=left, right=right, frequency=frequency,
                          bestLeft=best_left, bestRight=best_right, bestFrequency=best_frequency)
            frequency_greater = int(frequency > best_frequency)
            frequency_equal = int(frequency == best_frequency)
            lex_smaller = int(best is not None and (left, right) < best)
            take = int(best is None or frequency_greater or (frequency_equal and lex_smaller))
            if take:
                best, best_frequency = (left, right), frequency
            trace.add(f"train_compare_{rank}_{candidate_index}", f"Compare round {rank} candidate {candidate_index}",
                      "take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))",
                      "Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.",
                      inputs, dict(take=take, frequencyGreater=frequency_greater, frequencyEqual=frequency_equal,
                                   lexSmaller=lex_smaller, bestLeft=best[0], bestRight=best[1], bestFrequency=best_frequency))
        left, right = best
        identifier = MERGE_BASE + rank
        trace.add(f"train_select_{rank}", f"Select round {rank} winning pair",
                  "newID=256+rank; select greatest frequency, then smallest numeric pair",
                  "Frequency 1 is eligible. Requested merges are a budget; actual merges stop early only when no adjacent pair remains.",
                  dict(rank=rank, currentLength=len(ids), candidateCount=len(candidates)),
                  dict(id=identifier, left=left, right=right, frequency=best_frequency))
        left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
        right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
        expansion = np.concatenate((left_bytes, right_bytes))
        rule = dict(id=identifier, left=left, right=right, bytes=expansion)
        inputs = dict(id=identifier, left=left, right=right, leftWidth=len(left_bytes), rightWidth=len(right_bytes))
        inputs.update({f"leftByte{i}": int(byte) for i, byte in enumerate(left_bytes)})
        inputs.update({f"rightByte{i}": int(byte) for i, byte in enumerate(right_bytes)})
        outputs = dict(byteWidth=len(expansion))
        outputs.update({f"byte{i}": int(byte) for i, byte in enumerate(expansion)})
        trace.add(f"train_rule_{rank}", f"Build rule {rank} byte expansion", "new bytes=left bytes followed by right bytes",
                  "Both operands are bytes or earlier merge IDs. Their complete concatenation defines the new ID and cannot create a cycle. A piece may end inside a UTF-8 scalar, so its label uses ID and exact JSON bytes.",
                  inputs, outputs)
        rules.append(rule)
        expansions[identifier] = expansion.copy()
        ids = replace_pass(ids, rule, rank, "train", trace, tensors)
    save_tensor(tensors, "CorpusIDs", "Tokens", ids,
                "Final learned corpus token IDs; corpus training never contains EOS.")
    for identifier, key, provenance in (
        ("RuleIDs", "id", "Learned IDs in ascending rank, ID=256+rank."),
        ("RuleLeft", "left", "Left operand ID for each learned rank."),
        ("RuleRight", "right", "Right operand ID for each learned rank."),
    ):
        save_tensor(tensors, identifier, "Rules", np.array([rule[key] for rule in rules], dtype=np.int32), provenance)
    for rule in rules:
        save_tensor(tensors, f"Rule{rule['id']}Bytes", "Bytes", rule["bytes"],
                    "Actual concatenated operand bytes; the piece alone need not be valid UTF-8.")
    return dict(ids=ids, rules=rules)


def encode_bpe(values, rules, eos, trace, tensors):
    """Apply each learned rank once; only then append optional target EOS512.

    A later rule emits a higher ID and leaves a replacement token between any
    untouched neighbors, so it cannot create an earlier rule's lower-ID pair.
    """
    rule_table(rules)
    eos = eos_flag(eos)
    ids = bytes_input(values).copy()
    save_tensor(tensors, "EncodeInitialIDs", "Tokens", ids,
                "Initial target byte IDs before any ranked application.")
    for rank, rule in enumerate(rules):
        # Public rule fields may be integral floats; scalar trace fields are ints.
        actual = dict(id=int(rule["id"]), left=int(rule["left"]), right=int(rule["right"]))
        ids = replace_pass(ids, actual, rank, "encode", trace, tensors)
    ids = _token.append_eos(ids, eos, "target", trace)
    save_tensor(tensors, "TargetIDs", "Tokens", ids,
                "Final target token IDs after all learned ranks, then optional unique EOS tail.")
    return ids


def decode_bpe_ids(values, rules, eos, prefix, trace):
    """Expand the ACTUAL validated IDs, then strictly reconstruct Unicode."""
    expansions = rule_table(rules)
    eos = eos_flag(eos)
    dense_data(values, BYTE_BOUND + 1, "BPE token IDs")
    ids = _token.int_array(values, high=EOS, label="BPE token IDs", limit=BYTE_BOUND + 1)
    has_tail = len(ids) > 0 and int(ids[-1]) == EOS
    content = ids[:-1] if has_tail else ids
    if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
        raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
    for stored in content:
        identifier = int(stored)
        if identifier > 255 and identifier not in expansions:
            raise NumericalFault("INVALID_INPUT", f"Unknown or inactive BPE ID {identifier}.")
    byte_values = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        expansion = [identifier] if identifier <= 255 else expansions[identifier].tolist()
        byte_offset = len(byte_values)
        byte_values.extend(expansion)
        if len(byte_values) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "Decoded BPE expansions exceed 24 bytes.")
        outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
        outputs.update({f"byte{i}": byte for i, byte in enumerate(expansion)})
        trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → validated byte expansion",
                  "Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.",
                  dict(index=index, id=identifier), outputs)
    if eos == 1:
        trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
                  "The decoder has validated the unique required tail marker. Its empty expansion is a control convention, not a lost source character.",
                  dict(index=len(ids) - 1, id=EOS), dict(stripped=1))
    actual_bytes = np.array(byte_values, dtype=np.int32)
    return dict(bytes=actual_bytes, decoded=_token.utf8_decode(actual_bytes, prefix, trace))


def source_self_check():
    """Hand-derived deferred assertions: NEVER called by import or normal CLI.

    The human resource hold forbids invoking this function now. These are
    source checks for later owner validation, not generated expected answers.
    """
    assert __debug__, "Run later checks with assertions enabled."

    def rejects(call, code="INVALID_INPUT"):
        try:
            call()
        except NumericalFault as error:
            assert error.code == code, (error.code, code)
            return error
        raise AssertionError("Invalid boundary was accepted")

    def train(values, merges):
        trace, tensors = _token.TokenTrace(), []
        result = train_bpe(values, merges, trace, tensors)
        return result, trace, tensors

    # Default: abab -> ab/ab -> abab; target ababab -> abab/ab.
    trained, trace, tensors = train([97, 98, 97, 98], 2)
    assert trained["ids"].tolist() == [257]
    assert [(rule["id"], rule["left"], rule["right"]) for rule in trained["rules"]] == [(256, 97, 98), (257, 256, 256)]
    assert [rule["bytes"].tolist() for rule in trained["rules"]] == [[97, 98], [97, 98, 97, 98]]
    ids = encode_bpe([97, 98, 97, 98, 97, 98], trained["rules"], 1, trace, tensors)
    assert ids.tolist() == [257, 256, 512]
    assert decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)["decoded"] == "abab"
    assert decode_bpe_ids(ids, trained["rules"], 1, "target", trace)["decoded"] == "ababab"
    assert ids.dtype == np.dtype(np.int32) and trained["ids"].dtype == np.dtype(np.int32)
    assert all(rule["bytes"].dtype == np.dtype(np.int32) for rule in trained["rules"])
    assert all(record["dtype"] == "int32" and record["precision"] == 0 for record in tensors)
    concat = next(step for step in trace.steps if step["id"] == "train_rule_1")
    assert list(concat["inputs"]) == ["id", "left", "right", "leftWidth", "rightWidth", "leftByte0", "leftByte1", "rightByte0", "rightByte1"]
    tail = next(step for step in trace.steps if step["id"] == "encode_replace_1_2")
    assert tail["inputs"]["nextID"] == -1
    assert tail["outputs"] == dict(matched=0, id=256, consumed=1, nextPosition=3, outputLength=2)

    # Count overlaps3, replace disjointly2; every emitted token remains lossless.
    overlap, overlap_trace, _ = train([97, 97, 97, 97], 1)
    assert overlap["ids"].tolist() == [256, 256]
    assert next(step for step in overlap_trace.steps if step["id"] == "train_count_0_2")["outputs"]["countAfter"] == 3
    assert len([step for step in overlap_trace.steps if step["id"].startswith("train_replace_")]) == 2
    last_tie, _, _ = train([98, 98, 97, 97], 1)
    assert (last_tie["rules"][0]["left"], last_tie["rules"][0]["right"]) == (97, 97)
    assert last_tie["ids"].tolist() == [98, 98, 256]

    # Numeric97 precedes257; rank application differs from greedy prefix ab.
    ranked, rank_trace, rank_tensors = train([98, 99, 32, 98, 99, 32, 97, 98], 3)
    assert [(rule["left"], rule["right"]) for rule in ranked["rules"]] == [(98, 99), (256, 32), (97, 98)]
    assert ranked["ids"].tolist() == [257, 257, 258]
    assert encode_bpe([97, 98, 99], ranked["rules"], 0, rank_trace, rank_tensors).tolist() == [97, 256]
    empty, empty_trace, empty_tensors = train([], 4)
    assert not empty["rules"] and empty["ids"].tolist() == []
    assert [step["id"] for step in empty_trace.steps] == ["train_stop"] and empty_tensors == []
    _, zero_trace, _ = train([97, 98], 0)
    assert zero_trace.steps == []
    assert encode_bpe([], [], 1, _token.TokenTrace(), []).tolist() == [512]

    # Malformed IDs/EOS/rules fail before any guessed/replacement decoding.
    for values, eos in (([], 1), ([512], 0), ([512, 65], 1), ([65, 512, 512], 1), ([256], 0), ([384], 0), ([1024], 0), ([True], 0), ([10**1000], 0)):
        rejects(lambda: decode_bpe_ids(values, [], eos, "target", _token.TokenTrace()))
    rejects(lambda: decode_bpe_ids([65] * 25, [], 0, "target", _token.TokenTrace()), "UNSUPPORTED_SIZE")
    for values in ([195], [192, 128], [237, 160, 128], [244, 144, 128, 128]):
        rejects(lambda: decode_bpe_ids(values, [], 0, "target", _token.TokenTrace()))
    assert decode_bpe_ids([239, 187, 191, 0], [], 0, "target", _token.TokenTrace())["decoded"] == "\ufeff\0"
    for bad in (
        [dict(id=257, left=97, right=98, bytes=[97, 98])],
        [dict(id=256, left=256, right=98, bytes=[97, 98])],
        [dict(id=256, left=97, right=98, bytes=[98, 97])],
        [dict(id=256, left=97, right=98, bytes=[97, 98]), dict(id=257, left=97, right=98, bytes=[97, 98])],
    ):
        rejects(lambda: rule_table(bad))

    # Both 7fox/28byte postcheck and 9fox/36byte inherited32 rejection say24.
    for text in ("🦊" * 7, "🦊" * 9):
        error = rejects(lambda: encode_bounded(text, "corpus", "corpus", _token.TokenTrace()), "UNSUPPORTED_SIZE")
        assert "24" in str(error) and "32" not in str(error)
    rejects(lambda: encode_bounded("🦊" * 7 + "\ud800", "corpus", "corpus", _token.TokenTrace()))
    rejects(lambda: bpe_state(dict(corpus=None, text="", merges=0, eos=float("nan"))))
    rejects(lambda: bpe_state(dict(corpus="\ud800", text="", merges=float("nan"), eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=10**1000, eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=10**1000)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=True, eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=0, extra=0)))
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0)))

    class AccessorState:
        @property
        def corpus(self):
            raise AssertionError("Getter must never run")

    class AccessorList(list):
        def __getitem__(self, index):
            raise AssertionError("Custom indexing must never run")

    rejects(lambda: bpe_state(AccessorState()))
    rejects(lambda: decode_bpe_ids(AccessorList([65]), [], 0, "target", _token.TokenTrace()))
    rejects(lambda: rule_table([dict(id=256, left=97, right=98, bytes=AccessorList([97, 98]))]))

Codec and integer trace — p09/token_reference.py: strict explicit UTF-8 encoding/decoding, public token IDs and integer tensor records.

Read the complete executable Python / NumPy source

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

"""Part IX: bounded integer tokenization, authored without execution.

NumPy int32 arrays store actual code points, offsets, bytes and IDs. Arithmetic
uses Python integers, so bit shifts never depend on NumPy scalar promotion.
UTF-8 is implemented below; no native codec supplies an encoded/decoded answer.
Empty streams, BOMs, noncharacters, spaces and NULs are ordinary valid data.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np

EOS = 512
BYTE_BOUND = 32
CHARACTER_BASE = 1024
IV37_DEFAULTS = MappingProxyType(dict(text="Aé🦊", eos=0))
IV38_DEFAULTS = MappingProxyType(dict(text="lower low", vocabLimit=8, eos=0))
# Fixed active-prefix dictionary: these pieces are authored, not trained.
SUBWORDS = (
    (384, "low", (108, 111, 119)),
    (385, "lower", (108, 111, 119, 101, 114)),
    (386, "lowest", (108, 111, 119, 101, 115, 116)),
    (387, "er", (101, 114)),
    (388, "est", (101, 115, 116)),
    (389, "ing", (105, 110, 103)),
    (390, "a", (97,)),
    (391, "ab", (97, 98)),
)


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


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


def integer(value, low, high, label):
    """Validate before conversion; Python bool is not a mathematical number here."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    try:
        finite = math.isfinite(value)
    except OverflowError:
        finite = False
    if not finite:
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    if value < low or value > high or int(value) != value:
        raise NumericalFault("INVALID_INPUT", f"{label} must be an integer from {low} to {high}.")
    return int(value)


def scalar_valid(cp):
    return 0 <= cp <= 0x10FFFF and not 0xD800 <= cp <= 0xDFFF


def utf16_units(cp):
    """Reconstruct the actual high/low units from a validated supplementary scalar."""
    if cp <= 0xFFFF:
        return [cp]
    return [0xD800 + ((cp - 0x10000) >> 10), 0xDC00 + ((cp - 0x10000) & 1023)]


def utf16_length(text):
    return sum(2 if ord(character) > 0xFFFF else 1 for character in text)


def text_state(state, chapter):
    """Exact raw fields and numeric domains precede ALL Unicode/size semantics."""
    if type(chapter) is not int or chapter not in (37, 38):
        raise NumericalFault("INVALID_INPUT", "Use token chapter 37 or 38.")
    defaults = IV37_DEFAULTS if chapter == 37 else IV38_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields.")
    if type(state["text"]) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    result = dict(text=state["text"])
    for key in defaults:
        if key != "text":
            if type(state[key]) not in (int, float):
                raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
            result[key] = integer(state[key], 0, 8 if key == "vocabLimit" else 1, key)
    return result


def int_array(values, low=0, high=0x7FFFFFFF, label="integer array", limit=BYTE_BOUND):
    """Check dense numeric storage BEFORE narrowing; integral-valued floats are legal."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
    if len(values) > limit:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")
    checked = []
    for index, value in enumerate(values):
        if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
            raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
        try:
            finite = math.isfinite(value)
        except OverflowError:
            finite = False
        if not finite or value < low or value > high or int(value) != value:
            raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
        checked.append(int(value))
    return np.array(checked, dtype=np.int32)


def utf8_encode(text, prefix="source", trace=None):
    """Scan valid scalars first; then split each into explicit UTF-8 payload groups."""
    if trace is None:
        trace = TokenTrace()
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", "UTF-8 input must be an actual string.")
    if utf16_length(text) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", "More than 32 UTF-16 units necessarily exceeds this 32-byte lab.")
    code_points, offsets, widths = [], [], []
    offset = 0
    # Python strings store scalars directly; explicit surrogate values are invalid.
    for character in text:
        cp = ord(character)
        if 0xD800 <= cp <= 0xDBFF:
            raise NumericalFault("INVALID_INPUT", f"Unpaired high surrogate at UTF-16 offset {offset}.")
        if 0xDC00 <= cp <= 0xDFFF:
            raise NumericalFault("INVALID_INPUT", f"Unpaired low surrogate at UTF-16 offset {offset}.")
        width = len(utf16_units(cp))
        code_points.append(cp)
        offsets.append(offset)
        widths.append(width)
        offset += width
    byte_values, byte_offsets, byte_widths = [], [], []
    for index, cp in enumerate(code_points):
        if cp <= 0x7F:
            expansion = [cp]
        elif cp <= 0x7FF:
            expansion = [0xC0 | (cp >> 6), 0x80 | (cp & 63)]
        elif cp <= 0xFFFF:
            expansion = [0xE0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
        else:
            expansion = [0xF0 | (cp >> 18), 0x80 | ((cp >> 12) & 63),
                         0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
        units = utf16_units(cp)
        inputs = dict(scalarIndex=index, utf16Offset=offsets[index], utf16Width=widths[index], codePoint=cp, unit0=units[0])
        if len(units) == 2:
            inputs["unit1"] = units[1]
        outputs = dict(byteOffset=len(byte_values), byteWidth=len(expansion))
        for j, byte in enumerate(expansion):
            mask = (31 if len(expansion) == 2 else 15 if len(expansion) == 3 else 7) if j == 0 else 63
            outputs[f"payload{j}"] = byte if len(expansion) == 1 else byte & mask
        outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
        trace.add(f"{prefix}_scalar_{index}", f"Encode scalar {index}: U+{cp:04X}",
                  "supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits",
                  "A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.",
                  inputs, outputs)
        byte_offsets.append(len(byte_values))
        byte_widths.append(len(expansion))
        byte_values.extend(expansion)
    if len(byte_values) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 encoding exceeds 32 bytes; shorten the input explicitly.")
    return dict(bytes=int_array(byte_values, high=255, label="UTF-8 bytes"), codePoints=int_array(code_points),
                offsets=int_array(offsets), widths=int_array(widths), byteOffsets=int_array(byte_offsets), byteWidths=int_array(byte_widths))


def utf8_decode(values, prefix="utf8", trace=None):
    """Remove prefixes, accumulate radix-64 digits, validate, then rebuild the text."""
    if trace is None:
        trace = TokenTrace()
    values = int_array(values, high=255, label="UTF-8 bytes")
    characters, offset = [], 0
    while offset < len(values):
        lead = int(values[offset])
        width = 1 if lead <= 0x7F else 2 if 0xC2 <= lead <= 0xDF else 3 if 0xE0 <= lead <= 0xEF else 4 if 0xF0 <= lead <= 0xF4 else 0
        if not width:
            raise NumericalFault("INVALID_INPUT", f"Invalid UTF-8 lead at byte {offset}.")
        if offset + width > len(values):
            raise NumericalFault("INVALID_INPUT", f"Truncated UTF-8 sequence at byte {offset}.")
        inputs = dict(scalarIndex=len(characters), byteOffset=offset, byteWidth=width)
        outputs, cp = {}, 0
        for j in range(width):
            byte = int(values[offset + j])
            if j > 0 and not 0x80 <= byte <= 0xBF:
                raise NumericalFault("INVALID_INPUT", f"Invalid continuation byte at {offset + j}.")
            inputs[f"byte{j}"] = byte
            mask = (31 if width == 2 else 15 if width == 3 else 7) if j == 0 else 63
            payload = byte if width == 1 else byte & mask
            outputs[f"payload{j}"] = payload
            cp = cp * 64 + payload
            outputs[f"accumulator{j}"] = cp
        minimum = 0 if width == 1 else 0x80 if width == 2 else 0x800 if width == 3 else 0x10000
        if cp < minimum or not scalar_valid(cp):
            raise NumericalFault("INVALID_INPUT", f"Overlong, surrogate or out-of-range scalar at byte {offset}.")
        units = utf16_units(cp)
        outputs.update(codePoint=cp, utf16Width=len(units))
        outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
        # chr uses the validated scalar; no source text is available to copy here.
        characters.append(chr(cp))
        trace.add(f"{prefix}_decode_{len(characters) - 1}", f"Decode UTF-8 scalar {len(characters) - 1}",
                  "accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar",
                  "Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.",
                  inputs, outputs)
        offset += width
    return "".join(characters)


def _flag(eos):
    if type(eos) not in (int, float) or eos not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "eos must be numeric 0 or 1.")


def _vocabulary(limit):
    try:
        if type(limit) not in (int, float):
            raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.")
        return integer(limit, 0, 8, "vocabLimit")
    except NumericalFault as error:
        raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.") from error


def _strip_eos(ids, eos):
    _flag(eos)
    ids = int_array(ids, high=CHARACTER_BASE + 0x10FFFF, label="Token IDs", limit=BYTE_BOUND + 1)
    has_tail = len(ids) > 0 and int(ids[-1]) == EOS
    content = ids[:-1].copy() if has_tail else ids.copy()
    if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
        raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
    return ids, content


def append_eos(ids, eos, prefix, trace):
    """Return actual int32 storage with the optional reserved tail, never text matching."""
    _flag(eos)
    if eos == 1:
        index = len(ids)
        ids = np.concatenate((ids, np.array([EOS], dtype=np.int32)))
        trace.add(f"{prefix}_eos", f"{prefix}: append explicit EOS", "id=512",
                  "Only this flag appends EOS; literal text such as <eos> remains ordinary input.",
                  dict(index=index, eos=eos), dict(id=EOS))
    return ids


def _eos_record(ids, eos, prefix, trace):
    if eos == 1:
        trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
                  "The decoder has validated the whole ID stream and the required unique tail marker.",
                  dict(index=len(ids) - 1, id=EOS), dict(stripped=1))


def decode_byte_ids(ids, eos, prefix="byte", trace=None):
    return _decode_pieces(ids, eos, 0, False, prefix, TokenTrace() if trace is None else trace)


def decode_subword_ids(ids, eos, limit, prefix="subword", trace=None):
    limit = _vocabulary(limit)
    return _decode_pieces(ids, eos, limit, True, prefix, TokenTrace() if trace is None else trace)


def _decode_pieces(ids, eos, limit, subwords, prefix, trace):
    ids, content = _strip_eos(ids, eos)
    active = {identifier: expansion for identifier, _, expansion in SUBWORDS[:limit]} if subwords else {}
    byte_values = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        if identifier <= 255:
            expansion = (identifier,)
        elif identifier in active:
            expansion = active[identifier]
        else:
            raise NumericalFault("INVALID_INPUT", f"Unknown or inactive {prefix} ID {identifier}.")
        byte_offset = len(byte_values)
        byte_values.extend(expansion)
        if len(byte_values) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "Decoded token expansions exceed 32 bytes.")
        outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
        outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
        trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → declared byte expansion",
                  "Fallback byte IDs equal their byte value; active subword IDs expand to their full declared bytes. A single fallback byte may be only part of a Unicode scalar.",
                  dict(index=index, id=identifier), outputs)
    _eos_record(ids, eos, prefix, trace)
    values = int_array(byte_values, high=255, label="UTF-8 bytes")
    return dict(bytes=values, decoded=utf8_decode(values, prefix, trace))


def decode_character_ids(ids, eos, prefix="char", trace=None):
    if trace is None:
        trace = TokenTrace()
    ids, content = _strip_eos(ids, eos)
    characters = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        cp = identifier - CHARACTER_BASE
        if not scalar_valid(cp):
            raise NumericalFault("INVALID_INPUT", f"Character ID {identifier} does not name a Unicode scalar.")
        units = utf16_units(cp)
        outputs = dict(codePoint=cp, utf16Width=len(units))
        outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
        characters.append(chr(cp))
        trace.add(f"{prefix}_inverse_{index}", f"Character ID {index}: inverse mapping",
                  "codePoint=id−1024; reconstruct UTF-16 units",
                  "The scalar range excludes surrogate code points but includes noncharacters. The comparison vocabulary is algorithmic; no million-row matrix is allocated.",
                  dict(index=index, id=identifier), outputs)
    _eos_record(ids, eos, prefix, trace)
    decoded = "".join(characters)
    # External ID streams obey the same text bound; this private trace is omitted.
    utf8_encode(decoded)
    return decoded


def greedy_ids(values, limit, trace):
    """Choose longest matching byte expansion, then lowest ID; no match keeps a byte."""
    values = int_array(values, high=255, label="Greedy source bytes")
    limit = _vocabulary(limit)
    ids, offset = [], 0
    while offset < len(values):
        matches = []
        for identifier, _, expansion in SUBWORDS[:limit]:
            if offset + len(expansion) <= len(values) and all(int(values[offset + j]) == byte for j, byte in enumerate(expansion)):
                matches.append((identifier, len(expansion)))
        chosen, width = int(values[offset]), 1
        if matches:
            chosen, width = min(matches, key=lambda candidate: (-candidate[1], candidate[0]))
        inputs = dict(byteOffset=offset, remaining=len(values) - offset, candidateMatches=len(matches))
        for index, (identifier, match_width) in enumerate(matches):
            inputs[f"candidate{index}ID"] = identifier
            inputs[f"candidate{index}Width"] = match_width
        trace.add(f"subword_decision_{len(ids)}", f"Choose subword at byte offset {offset}",
                  "choose longest matching active byte expansion; tie: lowest subword ID; no match: current byte",
                  "Matched candidates are listed in fixed vocabulary order. An active one-byte entry is preferred to fallback when it matches. Advance by the actual chosen byte width; spaces and unmatched Unicode bytes remain in the stream.",
                  inputs, dict(id=chosen, byteWidth=width, nextByteOffset=offset + width))
        ids.append(chosen)
        offset += width
    return int_array(ids)


def json_text(value):
    """Match JSON string/array metadata without ASCII escaping or added spaces."""
    return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))


def byte_labels(ids):
    return ["EOS (explicit control)" if int(value) == EOS else f"byte {int(value)}" for value in ids]


def byte_expansions(ids):
    return [json_text([] if int(value) == EOS else [int(value)]) for value in ids]


def numbers(values):
    return {key: integer(value, -0x80000000, 0x7FFFFFFF, key) for key, value in values.items()}


class TokenTrace:
    def __init__(self):
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        inputs, outputs = numbers(inputs), numbers(outputs)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
                               inputs=inputs, outputs=outputs))

    def result(self, summary, tensors, texts):
        # Include copied encoding steps too, after the signed first summary aliases.
        outputs = numbers(summary)
        for step in self.steps:
            outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
        return dict(status="defined", outputs=outputs, steps=self.steps, tensors=tensors, texts=texts)


def tensor(identifier, axis, values, provenance):
    """Serialize actual nonempty int32 storage; empty streams yield no fake tensor."""
    if type(values) is not np.ndarray or values.dtype != np.dtype(np.int32) or values.ndim != 1:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: require one-dimensional int32 storage.")
    if not 1 <= len(values) <= 64:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions must be 1–64.")
    if type(axis) is not str or not axis:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name the axis.")
    return dict(id=identifier, shape=[len(values)], axes=[axis], dtype="int32", values=values.tolist(),
                provenance=provenance, precision=0)


_JSON_INT = int


def run(derive, defaults):
    """No args: defaults; one JSON arg: full replacement; '-': JSON from stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

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

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

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

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

Actual fixed decoder — p10/tiny_reference.py: forward_tiny calculates the old features, readout and distributions with all its saved steps and tensors. Its own text-tokenization/objective path is distinct from calling the observed-ID kernel on our prepared inputs.

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.

"""IV43 tiny decoder: actual NumPy arrays and scalar-ordered arithmetic.

Text -> learned BPE -> E gather -> LN1 -> Q/K/V -> Q/K RoPE -> causal
attention -> identity WO -> residual -> LN2 -> M3 ReLU FFN -> residual
-> U/bias logits -> stable conditional objective and readout derivatives.
The first token is given. No optimizer, embedding/full-block gradient,
pretrained model or trained capability is supplied. All execution DEFERRED.

Keep the original p06, p07 and p09 files at their relative locations. The
chapter displays this exact dependency closure, rather than a rewritten demo.
"""
import argparse
from functools import wraps
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np


_ROOT = Path(__file__).resolve().parent.parent


def _load(name, path):
    """Resolve an explicit source file; never search cwd or sys.path for helpers."""
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load canonical dependency: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


_component = _load("_iv43_component_reference", _ROOT / "p07" / "component_reference.py")
# The unchanged FFN imports this bare name. Force OUR canonical dependency,
# even when an unrelated module already occupies the name, then restore it.
_missing = object()
_previous_component = sys.modules.get("component_reference", _missing)
sys.modules["component_reference"] = _component
try:
    _ffn = _load("_iv43_ffn_reference", _ROOT / "p07" / "ffn_reference.py")
finally:
    if _previous_component is _missing:
        del sys.modules["component_reference"]
    else:
        sys.modules["component_reference"] = _previous_component
del _previous_component, _missing
_head = _load("_iv43_head_reference", _ROOT / "p06" / "head_reference.py")
_bpe = _load("_iv43_bpe_reference", _ROOT / "p09" / "bpe_reference.py")
_token = _bpe._token  # BPE itself loads this exact adjacent token file.
NumericalFault = _component.NumericalFault
_DEPENDENCY_FAULTS = (NumericalFault, _head.NumericalFault, _bpe.NumericalFault, _ffn.NumericalFault)

ALL_IDS = (97, 98, 512, 256, 257)
PARAMETER_DEFAULTS = MappingProxyType(dict(
    e00=1, e01=0, e10=0, e11=1, e20=0, e21=0, e30=0.5, e31=0.5, e40=1, e41=1,
    u00=1, u01=0, u02=0, u03=0, u04=0, u10=0, u11=1, u12=0, u13=0, u14=0,
    b0=0, b1=0, b2=0, b3=0, b4=0,
))
NUMERIC_DEFAULTS = MappingProxyType(dict(merges=0, **PARAMETER_DEFAULTS))
DEFAULT_IV43 = MappingProxyType(dict(text="ab", **NUMERIC_DEFAULTS))


def finite(value, label):
    """Own numbers only: booleans, coercion and overflowing integers are faults."""
    if type(value) not in (int, float):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def _object(value, fields, label):
    # Exact dict rejects inherited/overridden indexing without invoking a getter.
    if type(value) is not dict:
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named data fields.")
    if any(type(key) is not str for key in value) or set(value) != set(fields):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive parameters.")


def numeric_parameters(state):
    """Check all26 numeric fields, including unused rows/columns, in raw order."""
    _object(state, NUMERIC_DEFAULTS, "numeric parameters")
    checked = {}
    for key in NUMERIC_DEFAULTS:
        value = finite(state[key], key)
        low, high = (0, 2) if key == "merges" else (-4, 4) if key.startswith("b") else (-2, 2)
        if key == "merges" and (not value.is_integer() or not low <= value <= high):
            raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
        if not low <= value <= high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        checked[key] = int(value) if key == "merges" else value
    return checked


def tiny_state(state):
    """String type first, then EVERY numeric field, then text semantics later."""
    _object(state, DEFAULT_IV43, "state")
    if type(state["text"]) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    return dict(text=state["text"], numeric=numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS}))


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


def _ids(values, active):
    """Validate original public IDs before narrowing to real int32 storage."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", "inputIDs must be a dense one-dimensional numeric array.")
        entries = values.tolist()
    elif type(values) in (list, tuple):
        entries = values
    else:
        raise NumericalFault("INVALID_INPUT", "inputIDs must be an actual dense array.")
    if len(entries) > 3:
        raise NumericalFault("UNSUPPORTED_SIZE", "Numeric inputIDs must contain at most 3 observed tokens.")
    if not entries:
        raise NumericalFault("UNAVAILABLE", "Numeric forward requires at least one observed input token.")
    result = []
    for t, value in enumerate(entries):
        if type(value) not in (int, float):
            raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
        try:
            value = float(value)
        except (ValueError, OverflowError) as error:
            raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.") from error
        if not math.isfinite(value) or not value.is_integer() or value not in active:
            raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
        result.append(int(value))
    return np.array(result, dtype=np.int32)


def _float_tensor(identifier, shape, axes, values, provenance):
    """Serialize an actual float64 array into detached row-major JSON storage."""
    if type(values) is not np.ndarray or values.dtype != np.dtype(np.float64) or tuple(shape) != values.shape:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64 storage of the declared shape.")
    return _component.tensor(identifier, shape, axes, values.reshape(-1).tolist(), provenance)


def _norm(name, x, trace):
    """Keep normalization statistics in real scalar steps, without extra tensors."""
    T = x["shape"][1]
    X = np.array(x["values"], dtype=np.float64).reshape(1, T, 2)
    output = np.empty((1, T, 2), dtype=np.float64)
    for t in range(T):
        row = _component.feature_norm("layer", f"{name.lower()}_{t}", X[0, t].tolist(),
                                      [1, 1], [0, 0], 1, trace)
        output[0, t] = row["values"]
    source = "X" if name == "LN1" else "R1"
    return _float_tensor(name, [1, T, 2], ["B", "T", "D"], output,
                         f"Per-token feature layer norm of {source}; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.")


def _residual(name, prefix, left, right, trace):
    result = _component.same_shape_add(name, left, right)
    for t in range(result["shape"][1]):
        for d in range(2):
            index = 2 * t + d
            trace.add(f"{prefix}_{t}_{d}", f"{name} residual [0,{t},{d}]", "value=left+right",
                      "Actual same-shape addition; no broadcasting or second numerical engine.",
                      dict(t=t, d=d, left=left["values"][index], right=right["values"][index]),
                      dict(value=result["values"][index]))
    return result


def _rope(role, values, trace):
    """One adjacent Q/K pair, frequency1, angle=absolute token position radians."""
    T = values.shape[2]
    rotated = np.empty((1, 1, T, 2), dtype=np.float64)
    angles, cosines, sines = (np.empty(T, dtype=np.float64) for _ in range(3))
    for t in range(T):
        frequency = 10000 ** 0
        angle = finite(t * frequency, "RoPE angle")
        cosine, sine = finite(math.cos(angle), "RoPE cosine"), finite(math.sin(angle), "RoPE sine")
        x0, x1 = float(values[0, 0, t, 0]), float(values[0, 0, t, 1])
        product0, product1 = finite(x0 * cosine, "RoPE x0*cos"), finite(x1 * sine, "RoPE x1*sin")
        product2, product3 = finite(x0 * sine, "RoPE x0*sin"), finite(x1 * cosine, "RoPE x1*cos")
        rotated0, rotated1 = finite(product0 - product1, "RoPE first coordinate"), finite(product2 + product3, "RoPE second coordinate")
        rotated[0, 0, t] = [rotated0, rotated1]
        angles[t], cosines[t], sines[t] = angle, cosine, sine
        trace.add(f"rope_{role}_{t}", f"RoPE {role} token {t}",
                  "frequency=10000^0; angle=t*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
                  "Rotate this single adjacent pair at absolute position t. Q and K rotate; V remains unrotated. Every product is saved.",
                  dict(t=t, x0=x0, x1=x1, base=10000, exponent=0),
                  dict(frequency=frequency, angle=angle, cos=cosine, sin=sine, product0=product0, product1=product1,
                       product2=product2, product3=product3, rotated0=rotated0, rotated1=rotated1))
    return rotated, angles, cosines, sines


# Literal metadata adoption is local: unchanged helpers still supply all storage and steps.
_PROJECTION_PROVENANCE = {
    "X": "Active token rows; D=2 input features always retained.",
    "WQ": "Query columns packed by h*Dk+f from wq{d}{h}{f}.",
    "WK": "Key columns packed by h*Dk+f from wk{d}{h}{f}.",
    "WV": "Value columns packed by h*Dv+f from wv{d}{h}{f}.",
    "QConcat": "XWQ; each packed coordinate has two products and one sum.",
    "KConcat": "XWK; each packed coordinate has two products and one sum.",
    "VConcat": "XWV; values are projected separately from queries and keys.",
    "QSplit": "QConcat reshaped without changing flat order; feature=h*F+f.",
    "QHeads": "QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
    "KSplit": "KConcat reshaped without changing flat order; feature=h*F+f.",
    "KHeads": "KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
    "VSplit": "VConcat reshaped without changing flat order; feature=h*F+f.",
    "VHeads": "VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
}
_ATTENTION_PROVENANCE = {
    "raw": "Separate QHeads KHeads transpose products within every batch and head.",
    "scores": "raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.",
    "allowed": "Causal and/or valid-key mask; shared validity across B and H; every query retained.",
    "logits": "Finite score+shift, including forbidden cells; mask applied separately.",
    "probabilities": "Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.",
    "OHeads": "Actual per-head P times VHeads; every product and running sum is traced.",
}
_JOIN_PROVENANCE = {
    "C": "OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged.",
    "WO": "wo{h}{f}{d} packed in h,f,d order, preserving parameter identity.",
    "Y": "Y=C WO, summing products in ascending joined-feature order from zero; no normalization.",
}
_FFN_PROVENANCE = {
    "W1": "Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.",
    "b1": "Shared hidden bias, added after the two products.",
    "Z": "Hidden preactivations X W1+b1; no batch or token mixing.",
    "Hidden": "ReLU(Z)=max(0,Z), before the second affine layer.",
    "W2": "Shared hidden-to-output weights, f2{m}{d}.",
    "b2": "Shared output bias, added after all three running sums.",
    "F": "ReLU(X W1+b1) W2+b2, independently per token with shared parameters.",
}


def _attention(n1, trace):
    """Reuse project/attend/join kernels; explicitly override their old WO."""
    T = n1["shape"][1]
    s = dict(_head.OUTPUT_HEAD_DEFAULTS)
    s.update(B=1, T=T, H=1, Dk=2, Dv=2, mode=1, shift=0)
    for t in range(T):
        for d in range(2):
            s[f"x0{t}{d}"] = n1["values"][2 * t + d]
    for prefix in ("wq", "wk", "wv"):
        for d in range(2):
            for f in range(2):
                s[f"{prefix}{d}0{f}"] = int(d == f)
    for f in range(2):
        for d in range(2):
            s[f"wo0{f}{d}"] = int(f == d)
    child = _head.head_trace()
    try:
        projected = _head.project_heads(s, child)
        for step in child.steps:
            trace.add(f"heads_{step['id']}", step["label"], step["equation"],
                      step["explanation"], step["inputs"], step["outputs"])
        q, angles, cosines, sines = _rope("Q", projected["QHeads"], trace)
        k, _, _, _ = _rope("K", projected["KHeads"], trace)
        rotated = {**projected, "QHeads": q, "KHeads": k}
        child = _head.head_trace()
        attended = _head.attend_heads(s, rotated, child)
        joined = _head.join_heads(s, attended, child)
    except _head.NumericalFault as error:
        raise NumericalFault(error.code, str(error)) from error
    for step in child.steps:
        trace.add(f"heads_{step['id']}", step["label"], step["equation"],
                  step["explanation"], step["inputs"], step["outputs"])
    tensors = [{**record, "id": f"Projection{record['id']}",
                "provenance": _PROJECTION_PROVENANCE[record["id"]] + " Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated."}
               for record in projected["tensors"]]
    tensors.extend([
        _float_tensor("RotatedQHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], q,
                      "Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately."),
        _float_tensor("RotatedKHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], k,
                      "Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately."),
        _float_tensor("RoPEAngles", [T], ["Position"], angles, "Absolute position t times the single-pair frequency1, in radians."),
        _float_tensor("RoPECos", [T], ["Position"], cosines, "Stored cos(angle) used in the Q pair rotation; K uses the same angle."),
        _float_tensor("RoPESin", [T], ["Position"], sines, "Stored sin(angle) used in the Q pair rotation; K uses the same angle."),
    ])
    tensors.extend({**record, "id": f"Attention{record['id']}",
                    "provenance": _ATTENTION_PROVENANCE[record["id"]] + " QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads."}
                   for record in attended["tensors"])
    tensors.extend({**record, "id": "AttentionOutput" if record["id"] == "Y" else f"Attention{record['id']}",
                    "provenance": _JOIN_PROVENANCE[record["id"]] + " Source is AttentionOHeads; active WO is explicitly identity2."}
                   for record in joined["tensors"])
    return tensors[-1], tensors


def tiny_trace():
    """An explicit finite scalar accumulator; forward_tiny never discards one."""
    return _component.component_trace()


def forward_tiny(numeric_state, input_ids, trace):
    """Observed-ID forward with the adopted T,V,classIDs,inputIDs,inputRows,rows,tensors.

    Validate26 parameters first, then dense active public IDs, including EOS.
    Real float64/int32/bool arrays back the computation; the public return is a
    detached JSON snapshot with complete stable distributions, without targets.
    """
    s = numeric_parameters(numeric_state)
    V = 3 + s["merges"]
    ids = _ids(input_ids, ALL_IDS[:V])
    T = len(ids)
    class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
    input_rows = np.array([ALL_IDS.index(int(identifier)) for identifier in ids], dtype=np.int32)
    E = np.array([[s[f"e{r}{d}"] for d in range(2)] for r in range(5)], dtype=np.float64)
    U = np.array([[s[f"u{d}{c}"] for c in range(5)] for d in range(2)], dtype=np.float64)
    bias = np.array([s[f"b{c}"] for c in range(5)], dtype=np.float64)
    X = np.empty((1, T, 2), dtype=np.float64)
    for t, identifier in enumerate(ids):
        row = int(input_rows[t])
        X[0, t] = E[row]
        trace.add(f"input_{t}", f"Gather embedding for observed token {t}", "inputRow=compactRow(inputID); X[0,t,d]=E[inputRow,d]",
                  "The full model has an ordinary EOS embedding row. This kernel does not stop on EOS.",
                  dict(t=t, inputID=int(identifier)), dict(inputRow=row, x0=float(X[0, t, 0]), x1=float(X[0, t, 1])))
    tensors = [
        _token.tensor("AllClassIDs", "ModelRow", np.array(ALL_IDS, dtype=np.int32), "Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets."),
        _token.tensor("ClassIDs", "Class", class_ids, "Active prefix of the full model row map; V=3+merges."),
        _float_tensor("E", [5, 2], ["ModelRow", "D"], E, "All ten validated editable embeddings, including EOS and inactive learned pieces."),
        _float_tensor("U", [2, 5], ["D", "ModelRow"], U, "All ten validated editable readout weights; only the first V columns contribute logits."),
        _float_tensor("Bias", [5], ["ModelRow"], bias, "All five validated editable biases; inactive columns have no objective dependency."),
        _token.tensor("InputIDs", "Position", ids, "Observed public IDs supplied directly to the numeric kernel; active EOS is permitted."),
        _token.tensor("InputRows", "Position", input_rows, "Compact model row gathered for each observed ID; never index by public ID512."),
        _float_tensor("X", [1, T, 2], ["B", "T", "D"], X, "Actual gathered E rows; B=1, token-major storage and D=2."),
    ]
    n1 = _norm("LN1", tensors[-1], trace)
    attention, at = _attention(n1, trace)
    r1 = _residual("R1", "residual1", tensors[-1], attention, trace)
    n2 = _norm("LN2", r1, trace)
    fs = dict(B=1, T=T,
              f100=1, f101=0, f102=0, f110=0, f111=1, f112=0,
              fb10=0, fb11=0, fb12=0,
              f200=1, f201=0, f210=0, f211=1, f220=0, f221=0,
              fb20=0, fb21=0)
    ffn = _ffn.feed_forward(fs, n2, trace, "ffn")
    y = _residual("Y", "residual2", r1, ffn["output"], trace)
    ft = [{**record, "provenance": _FFN_PROVENANCE[record["id"]]} for record in ffn["tensors"]]
    tensors.extend([n1, *at, r1, n2, *ft, y])
    Y = np.array(y["values"], dtype=np.float64).reshape(1, T, 2)
    logits = np.empty((T, V), dtype=np.float64)
    rows = []
    for t in range(T):
        for c in range(V):
            y0, y1, u0, u1, b = float(Y[0, t, 0]), float(Y[0, t, 1]), float(U[0, c]), float(U[1, c]), float(bias[c])
            product0, product1 = finite(y0 * u0, "readout product0"), finite(y1 * u1, "readout product1")
            summed = finite(product0 + product1, "readout sum")
            value = finite(summed + b, "readout logit")
            logits[t, c] = value
            trace.add(f"readout_{t}_{c}", f"Readout row {t}, class {c}",
                      "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
                      "Only the active compact class prefix contributes to logits; targets are not operands.",
                      dict(t=t, c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=b),
                      dict(product0=product0, product1=product1, sum=summed, logit=value))
        rows.append(_class_row(logits[t], t, class_ids, trace))
    tensors.extend([
        _float_tensor("Logits", [T, V], ["Position", "Class"], logits, "Final Y times the active U prefix, then active Bias; targets are not operands."),
        _float_tensor("Max", [T], ["Position"], np.array([row["max"] for row in rows], dtype=np.float64), "Maximum computed active class logit at each position."),
        _float_tensor("Shifted", [T, V], ["Position", "Class"], np.array([row["shifted"] for row in rows], dtype=np.float64), "Computed class logit minus its saved row maximum."),
        _float_tensor("Terms", [T, V], ["Position", "Class"], np.array([row["terms"] for row in rows], dtype=np.float64), "Actual exp(Shifted) before left-to-right class summation."),
        _float_tensor("Denominator", [T], ["Position"], np.array([row["denominator"] for row in rows], dtype=np.float64), "Shifted exponential sum from zero in ascending compact class order."),
        _float_tensor("LogS", [T], ["Position"], np.array([row["logS"] for row in rows], dtype=np.float64), "ln(Denominator), saved for factored NLL."),
        _float_tensor("LSE", [T], ["Position"], np.array([row["lse"] for row in rows], dtype=np.float64), "Max+LogS; saved evidence, not subtracted from target logits to compute NLL."),
        _float_tensor("P", [T, V], ["Position", "Class"], np.array([row["probabilities"] for row in rows], dtype=np.float64), "Terms/Denominator for real active classes only; no inactive-class probabilities."),
        _token.tensor("NextRows", "Position", np.array([row["nextRow"] for row in rows], dtype=np.int32), "Highest computed logit; exact ties keep the smallest compact class."),
        _token.tensor("NextIDs", "Position", np.array([row["nextID"] for row in rows], dtype=np.int32), "Public ID mapped from each computed-logit winner."),
        _float_tensor("NextProbability", [T], ["Position"], np.array([row["nextProbability"] for row in rows], dtype=np.float64), "Stored class probability of the computed-logit winner; never fed back as an observed input."),
    ])
    return json.loads(json.dumps(dict(T=T, V=V, classIDs=class_ids.tolist(), inputIDs=ids.tolist(),
                                     inputRows=input_rows.tolist(), rows=rows, tensors=tensors), allow_nan=False))


def _tokenize(text, merges, trace):
    """Actual IV39 algorithm with the narrower IV43 text/model boundary.

    Prepare encoders before copying any successful record. Size in UTF16 units
    precedes surrogate validation, then actual UTF8 size, then model alphabet.
    The unchanged24/32-byte helper limits remain unchanged in their own files.
    """
    if _token.utf16_length(text) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte model input bound.")
    encoding = _token.TokenTrace()
    try:
        corpus = _bpe.encode_bounded("abab", "corpus", "corpus", encoding)
        source = _bpe.encode_bounded(text, "text", "source", encoding)
        if len(source["bytes"]) > 6:
            raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
        if any(character not in "ab" for character in text):
            raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters; no normalization, unknown token or truncation is applied.")
        if not text:
            raise NumericalFault("UNAVAILABLE", "Empty text has no observed first token and no conditional target.")
        child = _token.TokenTrace()
        child.add("setup", "Declare learned byte-pair encoding and both exact inputs",
                  "byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
                  "The disclosed training corpus is always abab. Encode the separate exact target with learned ranks, then append EOS. No normalization, trimming, unknown token or truncation.",
                  dict(requestedMerges=merges, eos=1),
                  dict(corpusUnits=4, corpusScalars=4, utf16Units=_token.utf16_length(text),
                       scalarCount=len(source["codePoints"]), byteBound=_bpe.BPE_BYTE_BOUND,
                       mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=512))
        child.steps.extend(encoding.steps)
        tensors = []
        for stem, encoded in (("Corpus", corpus), ("Source", source)):
            for suffix, key, axis, provenance in (
                ("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
                ("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
                ("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
                ("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
                ("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
                ("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
            ):
                _bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
        trained = _bpe.train_bpe(corpus["bytes"], merges, child, tensors)
        ids = _bpe.encode_bpe(source["bytes"], trained["rules"], 1, child, tensors)
        corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", child)
        decoded = _bpe.decode_bpe_ids(ids, trained["rules"], 1, "target", child)
        corpus_equal = int(corpus_decoded["decoded"] == "abab")
        equal = int(decoded["decoded"] == text)
        if not corpus_equal or not equal:
            raise NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
        child.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
                  "corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
                  "Expand actual saved IDs, concatenate bytes, strictly reconstruct scalars, then compare complete strings.",
                  dict(corpusOriginalUnits=4, corpusDecodedUnits=_token.utf16_length(corpus_decoded["decoded"]),
                       corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=_token.utf16_length(text),
                       decodedUnits=_token.utf16_length(decoded["decoded"]), decodedByteCount=len(decoded["bytes"])),
                  dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
        _bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"], "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
        _bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", decoded["bytes"], "Actual final target ID expansions passed to strict UTF-8 decoding.")
    except _bpe.NumericalFault as error:
        raise NumericalFault(error.code, str(error)) from error
    if len(ids) - 1 > 3:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE sequence exceeds 3 observed input positions; change text or merges explicitly.")
    for step in child.steps:
        trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"],
                  step["explanation"], step["inputs"], step["outputs"])
    tensors = [{**record, "id": f"Tokenizer{record['id']}"} for record in tensors]
    expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}

    def expansion(identifier):
        return [] if identifier == 512 else [identifier] if identifier <= 255 else expansions[identifier]

    def labels(values):
        return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == 512 else
                f"ID {int(identifier)}, bytes {_token.json_text(expansion(int(identifier)))}" for identifier in values]

    texts = dict(
        corpus="abab", input=text, corpusDecoded=corpus_decoded["decoded"], decoded=decoded["decoded"],
        corpusLabels=labels(trained["ids"]), corpusExpansions=[_token.json_text(expansion(int(identifier))) for identifier in trained["ids"]],
        targetLabels=labels(ids), targetExpansions=[_token.json_text(expansion(int(identifier))) for identifier in ids],
        ruleLabels=[f"ID {rule['id']}, bytes {_token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
        ruleExpansions=[_token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
        trainingStop="Zero merges requested: no training round or pair selection occurs." if merges == 0 else "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < merges else "Requested merge budget completed.",
    )
    summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]), actualMerges=len(trained["rules"]),
                   tokenCount=len(ids), requestedMerges=merges, corpusTokens=len(trained["ids"]), eos=1,
                   byteBound=_bpe.BPE_BYTE_BOUND, vocabularyItems=256 + len(trained["rules"]) + 1,
                   corpusEqual=corpus_equal, equal=equal)
    return dict(ids=ids, tensors=tensors, texts=texts, summary=summary)


def _class_row(logits, t, class_ids, trace):
    """Stable complete row before the next token's readout; strict-logit argmax."""
    V = len(class_ids)
    maximum_inputs = {f"z{c}": float(logits[c]) for c in range(V)}
    maximum = max(maximum_inputs.values())
    trace.add(f"class_{t}_max", f"Class maximum for prediction row {t}", "max=max(active logits)",
              "Only active classes contribute. The maximum term exp(0)=1 prevents a zero normalizer.",
              maximum_inputs, dict(max=maximum))
    shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
    denominator, running = 0.0, {}
    for c in range(V):
        z = float(logits[c])
        shift = finite(z - maximum, "class shifted logit")
        term = finite(math.exp(shift), "class exponential")
        shifted[c], terms[c] = shift, term
        trace.add(f"class_{t}_exp_{c}", f"Class row {t}, exponential {c}", "shifted=logit-max; term=exp(shifted)",
                  "Save each actual shifted exponential; no epsilon, clipping or rounded display operand.",
                  dict(t=t, c=c, logit=z, max=maximum), dict(shifted=shift, term=term))
        denominator = finite(denominator + term, "class denominator")
        running[f"running{c}"] = denominator
    log_s = finite(math.log(denominator), "class logS")
    lse = finite(maximum + log_s, "class logsumexp")
    trace.add(f"class_{t}_normalize", f"Class denominator and logsumexp for row {t}",
              "running starts at 0; running_c=previous+term_c; denominator=last running; logS=ln(denominator); lse=max+logS",
              "Terms accumulate left to right. The objective uses (max-targetLogit)+logS rather than subtraction of rounded LSE.",
              {**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
              {**running, "denominator": denominator, "logS": log_s, "lse": lse})
    for c in range(V):
        term = float(terms[c])
        probability = finite(term / denominator, "class probability")
        probabilities[c] = probability
        trace.add(f"class_{t}_probability_{c}", f"Class row {t}, probability {c}", "probability=term/denominator",
                  "This is an actual stored probability, never a rounded display value used as arithmetic input.",
                  dict(t=t, c=c, term=term, denominator=denominator), dict(probability=probability))
    next_row = 0
    for c in range(1, V):
        if float(logits[c]) > float(logits[next_row]):
            next_row = c
    next_id, next_probability = int(class_ids[next_row]), float(probabilities[next_row])
    trace.add(f"class_{t}_argmax", f"Computed-logit winner for row {t}", "argmax(logits); exact ties use smallest compact class",
              "Probability rounding can make distinct logits appear tied. Compare computed logits; predictions are not observed teacher-forcing inputs.",
              maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
    return dict(logits=logits.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
                denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
                nextRow=next_row, nextID=next_id, nextProbability=next_probability)


def _objective(forward, targets, trace):
    """Mean shifted-target NLL and ONLY the conditional readout derivatives."""
    T, V, rows, class_ids = forward["T"], forward["V"], forward["rows"], forward["classIDs"]
    Y = np.array(next(record["values"] for record in forward["tensors"] if record["id"] == "Y"), dtype=np.float64).reshape(1, T, 2)
    target_rows = np.empty(T, dtype=np.int32)
    nll, gaps, target_logits, target_probabilities = (np.empty(T, dtype=np.float64) for _ in range(4))
    for t in range(T):
        target_id = int(targets[t])
        if target_id not in class_ids:
            raise NumericalFault("INVALID_INPUT", "Every shifted target must be an active model class.")
        c = class_ids.index(target_id)
        target_rows[t] = c
        trace.add(f"target_lookup_{t}", f"Map shifted target at position {t}", "targetRow=compactRow(sequence[t+1])",
                  "Teacher forcing keeps the observed input and its next target distinct. Final EOS contributes one loss.",
                  dict(t=t, targetID=target_id, V=V), dict(targetRow=c))
        row = rows[t]
        target_logit, maximum, log_s, probability = row["logits"][c], row["max"], row["logS"], row["probabilities"][c]
        gaps[t] = finite(maximum - target_logit, "target gap")
        nll[t] = finite(float(gaps[t]) + log_s, "target NLL")
        target_logits[t], target_probabilities[t] = target_logit, probability
        trace.add(f"loss_{t}", f"Shifted target loss at position {t}", "gap=max-targetLogit; nll=gap+logS",
                  "Use the saved stable operands. The first piece is given; every continuation through EOS has weight1.",
                  dict(t=t, targetID=target_id, targetRow=c, max=maximum, targetLogit=target_logit, logS=log_s, probability=probability),
                  dict(gap=float(gaps[t]), nll=float(nll[t])))
    loss_sum = 0.0
    for t in range(T):
        previous = loss_sum
        loss_sum = finite(previous + float(nll[t]), "loss sum")
        trace.add(f"reduce_{t}", f"Accumulate target loss {t}", "lossSum=previousLossSum+nll",
                  "Accumulate every actual shifted target loss in ascending position order, including EOS.",
                  dict(t=t, previousLossSum=previous, nll=float(nll[t])), dict(lossSum=loss_sum))
    mean_nll = finite(loss_sum / T, "mean NLL")
    perplexity = finite(math.exp(mean_nll), "perplexity")
    trace.add("reduction", "Mean conditional objective and perplexity", "validCount=T; meanNLL=lossSum/T; perplexity=exp(meanNLL)",
              "Natural-log loss is in nats per shifted target. Tokenizer changes alter the events and conditioning.",
              dict(T=T, lossSum=loss_sum), dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity))
    d_logits = np.empty((T, V), dtype=np.float64)
    for t in range(T):
        for c in range(V):
            probability, indicator = rows[t]["probabilities"][c], int(c == int(target_rows[t]))
            difference = finite(probability - indicator, "probability minus target")
            gradient = finite(difference / T, "mean logit derivative")
            d_logits[t, c] = gradient
            trace.add(f"gradient_{t}_{c}", f"Mean-loss logit derivative [{t},{c}]", "indicator=(c=targetRow)?1:0; difference=P-indicator; gradient=difference/T",
                      "The analytic sensitivity includes the mean-loss denominator; it is not a gradient check or update.",
                      dict(t=t, c=c, targetRow=int(target_rows[t]), probability=probability, T=T),
                      dict(indicator=indicator, difference=difference, gradient=gradient))
    # Inactive raw columns have zero dependency, not fabricated active probabilities.
    d_u = np.zeros((2, 5), dtype=np.float64)
    d_bias = np.zeros(5, dtype=np.float64)
    for d in range(2):
        for c in range(V):
            inputs, outputs, gradient = dict(d=d, c=c), {}, 0.0
            for t in range(T):
                feature, g = float(Y[0, t, d]), float(d_logits[t, c])
                inputs[f"y{t}"], inputs[f"g{t}"] = feature, g
                product = finite(feature * g, "readout gradient product")
                gradient = finite(gradient + product, "readout gradient sum")
                outputs[f"product{t}"], outputs[f"running{t}"] = product, gradient
            outputs["gradient"] = gradient
            d_u[d, c] = gradient
            trace.add(f"readout_gradient_{d}_{c}", f"Readout weight derivative [{d},{c}]", "product_t=Y[t,d]*dLogits[t,c]; running starts at 0; gradient=sum_t product_t",
                      "Hold final decoder features fixed. Each product immediately enters the sum in ascending position order.", inputs, outputs)
    for c in range(V):
        inputs, outputs, gradient = dict(c=c), {}, 0.0
        for t in range(T):
            g = float(d_logits[t, c])
            inputs[f"g{t}"] = g
            gradient = finite(gradient + g, "bias gradient sum")
            outputs[f"running{t}"] = gradient
        outputs["gradient"] = gradient
        d_bias[c] = gradient
        trace.add(f"bias_gradient_{c}", f"Readout bias derivative [{c}]", "running starts at 0; gradient=sum_t dLogits[t,c]",
                  "Each active bias contributes directly at each position. Inactive raw columns have structural zero dependency.", inputs, outputs)
    tensors = [
        _token.tensor("TargetIDs", "Position", targets, "sequence[1:]; final EOS included exactly once as a scored continuation."),
        _token.tensor("TargetRows", "Position", target_rows, "Active compact class of each observed shifted target."),
        _float_tensor("TargetLogits", [T], ["Position"], target_logits, "Actual class logit gathered after computing the entire causal distribution."),
        _float_tensor("TargetProbability", [T], ["Position"], target_probabilities, "Actual target class probability; never rounded before loss computation."),
        _float_tensor("TargetGap", [T], ["Position"], gaps, "Saved max-targetLogit used in the factored NLL."),
        _float_tensor("NLL", [T], ["Position"], nll, "TargetGap+LogS for every shifted target, including EOS."),
        _float_tensor("dLogits", [T, V], ["Position", "Class"], d_logits, "(P-oneHot(target))/T for the actual mean objective."),
        _float_tensor("dU", [2, 5], ["D", "ModelRow"], d_u, "Conditional readout gradient sum_t Y[t,d]*dLogits[t,c]; inactive raw class columns have structural zero dependency."),
        _float_tensor("db", [5], ["ModelRow"], d_bias, "Conditional readout bias gradient sum_t dLogits[t,c]; inactive raw biases have structural zero dependency."),
    ]
    return dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity, tensors=tensors)


_JSON_INT = int


def run(derive, defaults):
    """No args: default; one JSON argument: COMPLETE replacement; '-': stdin.

    No query calls any self-check. Invalid data returns only status/code/reason.
    No caller cwd supplies a helper; source loading above is file-relative.
    """
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

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

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

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

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


def source_self_check():
    """DEFERRED explicit helper assertions; never called by import or query.

    Source-authored anchors/metamorphics are not independent oracle authority.
    Future V5 separately invokes this, the wrapper check and the old BPE check.
    """
    assert __debug__, "Deferred checks require assertions enabled."
    assert _ffn.NumericalFault is _component.NumericalFault
    assert _ffn.tensor is _component.tensor
    assert _ffn.finite is _component.finite
    assert Path(_component.__file__).resolve() == _ROOT / "p07" / "component_reference.py"
    assert Path(_ffn.__file__).resolve() == _ROOT / "p07" / "ffn_reference.py"
    assert Path(_head.__file__).resolve() == _ROOT / "p06" / "head_reference.py"
    assert Path(_bpe.__file__).resolve() == _ROOT / "p09" / "bpe_reference.py"
    assert Path(_token.__file__).resolve() == _ROOT / "p09" / "token_reference.py"
    assert len(DEFAULT_IV43) == 27 and len(NUMERIC_DEFAULTS) == 26
    assert list(DEFAULT_IV43) == ["text", "merges", *PARAMETER_DEFAULTS]
    assert list(tiny_state(dict(DEFAULT_IV43))) == ["text", "numeric"]

    def rejects(call, code):
        try:
            call()
        except NumericalFault as error:
            assert error.code == code, (error.code, code)
        else:
            raise AssertionError("Invalid helper input was accepted")

    def forward(parameters, ids):
        return forward_tiny(parameters, ids, tiny_trace())

    def saved(record, identifier):
        return next(tensor for tensor in record["tensors"] if tensor["id"] == identifier)

    s = dict(NUMERIC_DEFAULTS)
    trace = tiny_trace()
    f = forward_tiny(s, [97, 98], trace)
    assert list(f) == ["T", "V", "classIDs", "inputIDs", "inputRows", "rows", "tensors"]
    assert list(f["rows"][0]) == ["logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability"]
    assert f["T"] == 2 and f["V"] == 3 and f["inputRows"] == [0, 1]
    assert len(trace.steps) == 112 and len(f["tensors"]) == 57
    assert saved(f, "E")["shape"] == [5, 2] and saved(f, "U")["shape"] == [2, 5]
    assert saved(f, "Bias")["shape"] == [5]
    assert saved(f, "InputIDs")["dtype"] == "int32" and _ids([97, 98], ALL_IDS).dtype == np.dtype(np.int32)
    assert all(saved(f, name)["dtype"] == "float64" for name in ("E", "U", "Bias", "Y", "Logits", "P"))
    for tensor in f["tensors"]:
        assert list(tensor) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
        assert tensor["precision"] == (0 if tensor["dtype"] == "int32" else 8)
    # These constructors require real float64 storage before JSON projection.
    rejects(lambda: _float_tensor("bad", [1], ["D"], np.array([1], dtype=np.int32), "wrong dtype"), "SHAPE_MISMATCH")
    rejects(lambda: _float_tensor("bad", [2], ["D"], np.array([1], dtype=np.float64), "wrong shape"), "SHAPE_MISMATCH")
    alpha = 1 / math.sqrt(5)
    r = math.exp((2 * alpha * alpha / math.sqrt(2)) * (1 + math.cos(1)))
    d = (r - 1) / (r + 1)
    delta0, delta1 = 0.5 + alpha, 0.5 + alpha * d
    rho0, rho1 = delta0 / math.sqrt(delta0 * delta0 + 1), delta1 / math.sqrt(delta1 * delta1 + 1)
    expected = [[1 + alpha + rho0, -alpha], [-alpha * d, 1 + alpha * d + rho1]]
    for t in range(2):
        for coordinate in range(2):
            assert math.isclose(saved(f, "Y")["values"][t * 2 + coordinate], expected[t][coordinate], rel_tol=1e-12, abs_tol=1e-14)
    attention_p, allowed = saved(f, "Attentionprobabilities"), saved(f, "Attentionallowed")
    assert allowed["dtype"] == "bool" and allowed["precision"] == 8 and allowed["values"] == [True, False, True, True]
    assert attention_p["values"][:2] == [1, 0]
    assert math.isclose(attention_p["values"][2], 1 / (1 + r), rel_tol=1e-12)
    assert math.isclose(attention_p["values"][3], r / (1 + r), rel_tol=1e-12)
    # Earlier causal features survive a later ID edit; forbidden raw scores need not.
    later = forward(s, [97, 97])
    assert saved(f, "Y")["values"][:2] == saved(later, "Y")["values"][:2]
    assert f["rows"][0] == later["rows"][0]
    eos_input = forward({**s, "e20": 1, "e21": -1}, [512])
    assert eos_input["inputIDs"] == [512] and eos_input["inputRows"] == [2]
    assert saved(eos_input, "X")["values"] == [1, -1]
    assert forward(s, [97])["rows"][0] == f["rows"][0]
    assert forward(s, [512, 97])["inputRows"] == [2, 0]
    for merges, text, ids in ((0, "ab", [97, 98, 512]), (1, "ab", [256, 512]),
                              (2, "abab", [257, 512]), (1, "ababab", [256, 256, 256, 512]),
                              (2, "ababab", [257, 256, 512])):
        checked = tiny_state({**DEFAULT_IV43, "text": text, "merges": merges})
        tokenized = _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace())
        assert tokenized["ids"].tolist() == ids and tokenized["ids"].dtype == np.dtype(np.int32)
    for ids, code in (([], "UNAVAILABLE"), ([97] * 4, "UNSUPPORTED_SIZE"), ([256], "INVALID_INPUT"),
                      ([True], "INVALID_INPUT"), (["97"], "INVALID_INPUT"), ([None], "INVALID_INPUT"),
                      ([768], "INVALID_INPUT"), ([97.5], "INVALID_INPUT"),
                      ([float("nan")], "INVALID_INPUT"), ([float("inf")], "INVALID_INPUT"), ([10**1000], "INVALID_INPUT")):
        rejects(lambda: forward(s, ids), code)
    rejects(lambda: forward(s, np.array([True])), "INVALID_INPUT")
    rejects(lambda: forward(s, np.array([[97]])), "INVALID_INPUT")
    rejects(lambda: forward(s, {0: 97}), "INVALID_INPUT")
    for field, value, code in (("e40", 3, "INVALID_INPUT"), ("u04", True, "NONFINITE"),
                                ("b4", 10**1000, "NONFINITE"), ("merges", 0.5, "INVALID_INPUT")):
        rejects(lambda: forward({**s, field: value}, [97]), code)
    rejects(lambda: forward({**s, "b4": float("nan")}, []), "NONFINITE")
    rejects(lambda: numeric_parameters({**s, "extra": 1}), "INVALID_INPUT")
    rejects(lambda: numeric_parameters({key: value for key, value in s.items() if key != "u04"}), "INVALID_INPUT")

    class GetterDict(dict):
        def __getitem__(self, key):
            raise AssertionError("Custom getter must not execute")

    rejects(lambda: tiny_state(GetterDict(DEFAULT_IV43)), "INVALID_INPUT")
    rejects(lambda: tiny_state({**DEFAULT_IV43, "text": [], "e40": float("nan")}), "INVALID_INPUT")
    for patch, code in (({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
                        ({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"), ({"text": "ééé"}, "UNAVAILABLE"),
                        ({"text": "c"}, "UNAVAILABLE"), ({"text": ""}, "UNAVAILABLE"),
                        ({"text": "ababab"}, "UNSUPPORTED_SIZE")):
        checked = tiny_state({**DEFAULT_IV43, **patch})
        rejects(lambda: _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace()), code)
    rejects(lambda: tiny_state({**DEFAULT_IV43, "text": "\ud800", "b4": float("nan")}), "NONFINITE")
    # Public records and the explicit trace are detached from state and later calls.
    f["rows"][0]["probabilities"][0] = 99
    saved(f, "Y")["values"][0] = 99
    f["tensors"][0]["values"][0] = 0
    trace.steps[0]["outputs"].clear()
    again = forward(s, [97, 98])
    assert saved(again, "Y")["values"][0] != 99
    assert again["rows"][0]["probabilities"][0] != 99
    assert again["inputIDs"] == [97, 98]
    assert s == dict(NUMERIC_DEFAULTS)


def derive43(state):
    """Compose the owner-adopted complete ordered numerical/text snapshot."""
    checked = tiny_state(state)
    text, numeric = checked["text"], checked["numeric"]
    token_trace = tiny_trace()
    tokenized = _tokenize(text, numeric["merges"], token_trace)
    sequence = tokenized["ids"]
    inputs, targets = sequence[:-1].copy(), sequence[1:].copy()
    T, V = len(inputs), 3 + numeric["merges"]
    trace = tiny_trace()
    trace.add("setup", "Validate all raw fields before interpreting the text",
              "text<=6 UTF-8 bytes; fixed corpus=abab; eos=1; inputs=sequence[:-1]; targets=sequence[1:]",
              "The first encoded piece is given. Score each continuation through EOS; no first-piece probability, cropping or learning update.",
              numeric, dict(utf16Units=_token.utf16_length(text), byteBound=6, eos=1, corpusUnits=4))
    for step in token_trace.steps:
        trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
    token_summary = tokenized["summary"]
    trace.add("class_map", "Map tokenizer IDs to active compact model classes", "V=3+actualMerges; classIDs=prefix([97,98,512,256,257],V)",
              "Tokenizer vocabularyItems=257+merges differs from the model's 3+merges active classes; public IDs never allocate513 rows.",
              dict(actualMerges=token_summary["actualMerges"], vocabularyItems=token_summary["vocabularyItems"]),
              {"classCount": V, **{f"id{c}": int(identifier) for c, identifier in enumerate(class_ids)}})
    forward = forward_tiny(numeric, inputs, trace)
    objective = _objective(forward, targets, trace)
    trace.add("finish", "Keep the objective and conditional readout derivatives together",
              "objective=mean shifted NLL; derivatives=dLogits,dU,db with decoder features fixed",
              "All parameters are hand-set and untrained. No optimizer, embedding/full-block gradient or language-learning claim.",
              dict(contextLength=T, classCount=V),
              dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"]))
    last = forward["rows"][-1]
    summary = dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"],
                   classCount=V, actualMerges=numeric["merges"], contextLength=T,
                   B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
                   nextRow=last["nextRow"], nextID=last["nextID"], nextProbability=last["nextProbability"],
                   **{f"tokenizer_{key}": value for key, value in token_summary.items()})
    tensors = [*tokenized["tensors"], *forward["tensors"],
               _token.tensor("SequenceIDs", "Sequence", sequence, "Actual ranked BPE result with one final EOS; the first piece is given."),
               *objective["tensors"]]
    texts = dict(input=text, decoded=tokenized["texts"]["decoded"],
                 objective="Conditional continuation through EOS given the first encoded piece; no probability for that first piece.",
                 gradientScope="Analytic readout U/bias derivatives with decoder features fixed; no embedding/full-block gradient, optimizer update or training.",
                 modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256", "4: abab / ID257"],
                 **{f"tokenizer_{key}": value for key, value in tokenized["texts"].items()})
    result = trace.result(summary, tensors)
    result["texts"] = texts
    # Python exposes ordinary detached JSON; TS additionally freezes its snapshot.
    return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))


if __name__ == "__main__":
    run(guarded(derive43), DEFAULT_IV43)

Normalization and residual mechanics — p07/component_reference.py: explicit feature statistics, named-shape additions, finite scalar records and float64 tensor serialization.

Read the complete executable Python / NumPy source

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

"""Part VII component kernels: real NumPy storage, explicit float operations.

Keep this file beside iv30.py and iv31.py. NumPy represents actual shaped arrays;
Python floats perform each product/addition/division separately in signed trace
order. No matmul, vector reduction, broadcast, fused multiply-add or hidden norm.
Authored under the resource hold: this source has NOT been executed or validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


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


def finite(value, label):
    """Reject booleans, numeric strings, complex numbers and nonfinite scalars."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


RESIDUAL_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
    w00=0.5, w01=0, w10=0, w11=-0.5, b0=0, b1=0,
    g000=1, g001=2, g010=1, g011=2, g020=1, g021=2,
    g100=1, g101=2, g110=1, g111=2, g120=1, g121=2,
    residual=1,
))
NORM_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=3, x001=1, x010=2, x011=2, x020=-1, x021=1,
    x100=1, x101=-1, x110=0, x111=0, x120=-2, x121=3,
    gamma0=1, gamma1=1, beta0=0, beta1=0, epsilon=3,
))


def component_state(state, stage):
    """Validate all 33/19 own fields, including inactive X/g, before selecting."""
    if type(stage) is not int or stage not in (30, 31):
        raise NumericalFault("INVALID_INPUT", "Use component stage 30 or 31.")
    defaults = RESIDUAL_DEFAULTS if stage == 30 else NORM_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), residual=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (1e-8, 4) if key == "epsilon" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


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


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


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

    def add(self, identifier, label, equation, explanation, inputs, values):
        # Finite clones detach each saved operand/result from mutable arrays/state.
        inputs, values = numbers(inputs), numbers(values)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})

    def result(self, summary, tensors):
        # Aliases first, then ALL flattened step outputs in their insertion order.
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def component_trace():
    return ComponentTrace()


def tensor(identifier, shape, axes, values, provenance):
    """Platform-style float64 boundary: explicit named shape and dense flat list."""
    if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if type(values) is not list or len(values) != math.prod(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
    flat = [finite(value, f"{identifier}[{n}]") for n, value in enumerate(values)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64",
                values=flat, provenance=provenance, precision=8)


def same_shape_add(identifier, left, right):
    """Add validated float64 TensorRecords; equal element count is insufficient."""
    checked = []
    for n, record in enumerate((left, right)):
        if type(record) not in (dict, MappingProxyType) or record.get("dtype") != "float64":
            raise NumericalFault("INVALID_INPUT", f"{identifier}: operand {n} must be a float64 tensor.")
        checked.append(tensor(record.get("id"), record.get("shape"), record.get("axes"),
                              record.get("values"), record.get("provenance")))
    a, b = checked
    if a["shape"] != b["shape"] or a["axes"] != b["axes"]:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: addition needs identical dimensions and named axes; no broadcasting.")
    values = [finite(value + b["values"][n], f"{identifier}[{n}]") for n, value in enumerate(a["values"])]
    return tensor(identifier, a["shape"], a["axes"], values,
                  f"Exact named-shape addition of {left['id']} and {right['id']}; no broadcasting.")


def feature_norm(kind, prefix, x, gamma, beta, epsilon, trace):
    """Normalize one width-two token; no chapter bounds on derived IV33 rows.

    Inputs are dense lists, as in the TS kernel. Validate beta even for RMS,
    then deliberately omit it from RMS arithmetic and feature trace inputs.
    """
    if kind not in ("layer", "rms"):
        raise NumericalFault("INVALID_INPUT", "Use layer or rms normalization.")
    checked = []
    for name, values in (("x", x), ("gamma", gamma), ("beta", beta)):
        if type(values) is not list or len(values) != 2:
            raise NumericalFault("SHAPE_MISMATCH", f"{name} needs exactly two dense features.")
        checked.append([finite(value, f"{name}[{d}]") for d, value in enumerate(values)])
    x, gamma, beta = checked
    epsilon = finite(epsilon, "epsilon")
    if epsilon <= 0:
        raise NumericalFault("INVALID_INPUT", "epsilon must be strictly positive.")
    statistics = {}
    if kind == "layer":
        # Population variance: two centered squares, then sum, then divide by 2.
        statistics["sum"] = finite(x[0] + x[1], "feature sum")
        statistics["mean"] = finite(statistics["sum"] / 2, "feature mean")
        statistics["centered0"] = finite(x[0] - statistics["mean"], "centered0")
        statistics["centered1"] = finite(x[1] - statistics["mean"], "centered1")
        statistics["square0"] = finite(statistics["centered0"] * statistics["centered0"], "centered square0")
        statistics["square1"] = finite(statistics["centered1"] * statistics["centered1"], "centered square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "centered square sum")
        statistics["variance"] = finite(statistics["squareSum"] / 2, "population variance")
        statistics["variancePlusEpsilon"] = finite(statistics["variance"] + epsilon, "variance plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["variancePlusEpsilon"]), "LN denominator")
        source = [statistics["centered0"], statistics["centered1"]]
    else:
        # RMS uses original features, with neither mean subtraction nor beta.
        statistics["square0"] = finite(x[0] * x[0], "square0")
        statistics["square1"] = finite(x[1] * x[1], "square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "square sum")
        statistics["meanSquare"] = finite(statistics["squareSum"] / 2, "mean square")
        statistics["meanSquarePlusEpsilon"] = finite(statistics["meanSquare"] + epsilon, "mean square plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["meanSquarePlusEpsilon"]), "RMS denominator")
        source = list(x)
    trace.add(f"{prefix}_statistics", f"{prefix}: feature-only statistics",
              "mean=(x0+x1)/2; variance=(centered0²+centered1²)/2; denominator=sqrt(variance+epsilon)" if kind == "layer" else
              "meanSquare=(x0²+x1²)/2; denominator=sqrt(meanSquare+epsilon)",
              "Only this token's two features contribute. Epsilon stays inside the square root.",
              dict(x0=x[0], x1=x[1], epsilon=epsilon), statistics)
    normalized, values = [], []
    for d in range(2):
        n = finite(source[d] / statistics["denominator"], "normalized feature")
        scaled = finite(gamma[d] * n, "scaled feature")
        value = finite(scaled + beta[d], "LN affine feature") if kind == "layer" else scaled
        normalized.append(n)
        values.append(value)
        inputs = dict(d=d, source=source[d], denominator=statistics["denominator"], gamma=gamma[d])
        if kind == "layer":
            inputs["beta"] = beta[d]
        trace.add(f"{prefix}_feature_{d}", f"{prefix}: affine feature {d}",
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta" if kind == "layer" else
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled",
                  "LayerNorm uses centered features and beta; scale-only RMS uses original features and no beta.",
                  inputs, dict(normalized=n, scaled=scaled, value=value))
    return dict(values=values, normalized=normalized, statistics=statistics)


_JSON_INT = int


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

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

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

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

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

Feed-forward network — p07/ffn_reference.py: actual two-to-three-to-two arrays and scalar contractions. Tiny supplies its explicit parameter overrides; the standalone FFN defaults are a different example.

Read the complete executable Python / NumPy source

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

"""Part VII position-wise FFN: actual NumPy storage, explicit float order.

D=2 input features -> M=3 hidden features -> D=2 output features. Parameters
are shared across tokens/batches; arithmetic never sums over token positions.
NumPy stores shaped float64 arrays, but every arithmetic operation below uses
Python floats, with finite checks and saved operands/results. No BLAS reduction,
broadcast, fused multiply-add, residual, dropout or output softmax is hidden.
Source only: this program has not been imported, executed or validated.
"""
from types import MappingProxyType
import numpy as np
from component_reference import NORM_DEFAULTS, NumericalFault, finite, tensor


FFN_PARAMETERS = MappingProxyType(dict(
    f100=1, f101=0, f102=1, f110=0, f111=1, f112=-1,
    fb10=0, fb11=0, fb12=0,
    f200=0.5, f201=0, f210=0, f211=-0.5, f220=0.25, f221=0.25,
    fb20=0, fb21=0,
))
FFN_DEFAULTS = MappingProxyType(dict(
    B=NORM_DEFAULTS["B"], T=NORM_DEFAULTS["T"],
    **{key: value for key, value in NORM_DEFAULTS.items() if key.startswith("x")},
    **FFN_PARAMETERS,
))


def ffn_state(state):
    """Validate all 31 exact own scalar fields, including inactive X slots."""
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(FFN_DEFAULTS):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    result = {}
    for key in FFN_DEFAULTS:
        value = finite(state[key], key)
        low, high = (1, 2) if key == "B" else (1, 3) if key == "T" else (-4, 4)
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in ("B", "T") and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in ("B", "T") else value
    return result


def feed_forward(s, input_record, trace, prefix="ffn"):
    """Return seven stage tensors and aliases; the caller owns input_record.

    This reusable kernel accepts finite derived inputs beyond raw [-4,4] bounds.
    It requires exact [B,T,2] dimensions/axes and finite values for all parameters.
    """
    dimensions = []
    for key, maximum in (("B", 2), ("T", 3)):
        value = finite(s.get(key), key)
        if not value.is_integer() or not 1 <= value <= maximum:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer between 1 and {maximum}.")
        dimensions.append(int(value))
    B, T = dimensions
    parameters = {key: finite(s.get(key), key) for key in FFN_PARAMETERS}
    if type(input_record) not in (dict, MappingProxyType) or input_record.get("dtype") != "float64":
        raise NumericalFault("INVALID_INPUT", "FFN input must be a float64 tensor.")
    checked = tensor(input_record.get("id"), input_record.get("shape"), input_record.get("axes"),
                     input_record.get("values"), input_record.get("provenance"))
    shape, axes = [B, T, 2], ["B", "T", "D"]
    if checked["shape"] != shape or checked["axes"] != axes:
        raise NumericalFault("SHAPE_MISMATCH", "FFN input needs exact [B,T,2] dimensions and B,T,D axes.")
    # NumPy holds real shaped storage; scalar float reads prevent reordered reductions.
    X = np.array(checked["values"], dtype=np.float64).reshape(shape)
    W1, b1 = np.empty((2, 3), dtype=np.float64), np.empty(3, dtype=np.float64)
    W2, b2 = np.empty((3, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
    for d in range(2):
        for m in range(3):
            W1[d, m] = parameters[f"f1{d}{m}"]
    for m in range(3):
        b1[m] = parameters[f"fb1{m}"]
        for d in range(2):
            W2[m, d] = parameters[f"f2{m}{d}"]
    for d in range(2):
        b2[d] = parameters[f"fb2{d}"]
    hidden_shape, hidden_axes = [B, T, 3], ["B", "T", "HiddenFeature"]
    Z, Hidden = np.empty(hidden_shape, dtype=np.float64), np.empty(hidden_shape, dtype=np.float64)
    F = np.empty(shape, dtype=np.float64)
    # Save ALL hidden affines before any activation, in ascending b/t/m order.
    for b in range(B):
        for t in range(T):
            for m in range(3):
                x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                w0, w1, bias = float(W1[0, m]), float(W1[1, m]), float(b1[m])
                product0 = finite(x0 * w0, "FFN hidden product0")
                product1 = finite(x1 * w1, "FFN hidden product1")
                summed = finite(product0 + product1, "FFN hidden sum")
                preactivation = finite(summed + bias, "FFN hidden preactivation")
                Z[b, t, m] = preactivation
                trace.add(f"{prefix}_hidden_{b}_{t}_{m}", f"Hidden affine [{b},{t},{m}]",
                          "product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
                          "The same input-to-hidden weights and bias are reused at every token; bias is added last.",
                          dict(b=b, t=t, m=m, x0=x0, x1=x1, w0=w0, w1=w1, bias=bias),
                          dict(product0=product0, product1=product1, sum=summed, preactivation=preactivation))
    for b in range(B):
        for t in range(T):
            for m in range(3):
                preactivation = float(Z[b, t, m])
                activation = finite(max(0.0, preactivation), "FFN ReLU")
                Hidden[b, t, m] = activation
                trace.add(f"{prefix}_relu_{b}_{t}_{m}", f"ReLU [{b},{t},{m}]",
                          "activation=max(0,preactivation)",
                          "ReLU keeps positive values and maps negative values and zero to zero; it is not a softmax.",
                          dict(b=b, t=t, m=m, preactivation=preactivation), dict(activation=activation))
    for b in range(B):
        for t in range(T):
            for d in range(2):
                inputs, products, running = dict(b=b, t=t, d=d), {}, {}
                summed = 0.0
                # Each product is immediately accumulated from zero; bias follows all three.
                for m in range(3):
                    h, w = float(Hidden[b, t, m]), float(W2[m, d])
                    inputs[f"h{m}"], inputs[f"w{m}"] = h, w
                    product = finite(h * w, "FFN output product")
                    products[f"product{m}"] = product
                    summed = finite(summed + product, "FFN output running sum")
                    running[f"running{m}"] = summed
                bias = float(b2[d])
                inputs["bias"] = bias
                value = finite(summed + bias, "FFN output")
                F[b, t, d] = value
                trace.add(f"{prefix}_output_{b}_{t}_{d}", f"FFN output [{b},{t},{d}]",
                          "product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
                          "Three hidden features are contracted in ascending order. No token sum, residual or output softmax is added.",
                          inputs, {**products, **running, "sum": summed, "value": value})
    aliases = {}
    for name, values, width in (("pre", Z, 3), ("h", Hidden, 3), ("f", F, 2)):
        for b in range(B):
            for t in range(T):
                for coordinate in range(width):
                    aliases[f"{name}{b}{t}{coordinate}"] = float(values[b, t, coordinate])
    tensors = [
        tensor("W1", [2, 3], ["D", "HiddenFeature"], W1.reshape(-1).tolist(), "Shared row weights from two input features to three hidden features."),
        tensor("b1", [3], ["HiddenFeature"], b1.tolist(), "Shared hidden-feature biases, added after the two input products."),
        tensor("Z", hidden_shape, hidden_axes, Z.reshape(-1).tolist(), "Hidden affine preactivations before ReLU."),
        tensor("Hidden", hidden_shape, hidden_axes, Hidden.reshape(-1).tolist(), "ReLU applied separately to each preactivation, including zero -> zero."),
        tensor("W2", [3, 2], ["HiddenFeature", "D"], W2.reshape(-1).tolist(), "Shared row weights from three hidden features back to two output features."),
        tensor("b2", [2], ["D"], b2.tolist(), "Shared output-feature biases, added after the three hidden products."),
        tensor("F", shape, axes, F.reshape(-1).tolist(), "Position-wise FFN output; each token uses the same parameters without token mixing."),
    ]
    return dict(output=tensors[-1], tensors=tensors, aliases=aliases)

Attention heads — p06/head_reference.py: projections, reshape and permutation, causal key softmax, weighted values, concatenation and output projection. Tiny supplies the one-head identity projections and the rotary query/key arrays.

Read the complete executable Python / NumPy source

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

"""Part VI: real NumPy head arrays with explicit Python-float arithmetic.

The stages are local: project_heads owns projections and layout, attend_heads
owns scores/probabilities/weighted values, join_heads owns concatenation and WO.
Chapter wrappers combine those records explicitly. No Part V helper is imported.
Keep this file beside iv27.py, iv28.py and iv29.py. Source authored under hold;
none of these numerical programs has been executed or runtime-validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


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


def finite(value, label):
    """Accept numerical scalars, never strings, booleans or nonfinite values."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


# Weight names mean input feature d, head h, feature f WITHIN that head.
_head_defaults = dict(
    B=1, T=3, H=2, Dk=1, Dv=1,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
)
for _prefix in ("wq", "wk", "wv"):
    for _d in range(2):
        for _h in range(2):
            for _f in range(2):
                _head_defaults[f"{_prefix}{_d}{_h}{_f}"] = 1 if _d == (_h + _f) % 2 else 0
HEAD_DEFAULTS = MappingProxyType(_head_defaults)
ATTENTION_HEAD_DEFAULTS = MappingProxyType(dict(
    **HEAD_DEFAULTS, mode=1, valid0=1, valid1=1, valid2=1, shift=0,
))
OUTPUT_HEAD_DEFAULTS = MappingProxyType(dict(
    **ATTENTION_HEAD_DEFAULTS,
    wo000=1, wo001=1, wo010=0.5, wo011=0,
    wo100=1, wo101=-1, wo110=0, wo111=0.5,
))
del _head_defaults, _prefix, _d, _h, _f


def head_state(state, stage):
    """Validate exactly 41/46/54 fields BEFORE selecting any active slots."""
    if type(stage) is not int or stage not in (27, 28, 29):
        raise NumericalFault("INVALID_INPUT", "Use head stage 27, 28 or 29.")
    defaults = {27: HEAD_DEFAULTS, 28: ATTENTION_HEAD_DEFAULTS, 29: OUTPUT_HEAD_DEFAULTS}[stage]
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every named scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), H=(1, 2), Dk=(1, 2), Dv=(1, 2),
                          mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (-10000, 10000) if key == "shift" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


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


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


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

    def add(self, identifier, label, equation, explanation, inputs, values):
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        # New finite dictionaries detach records from the caller's mutable state.
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))

    def result(self, summary, tensors):
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def head_trace():
    return HeadTrace()


def tensor(identifier, shape, axes, values, provenance):
    if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    array = np.asarray(values)
    if array.shape != tuple(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    boolean = array.dtype == np.dtype(np.bool_)
    flat = [bool(value) for value in array.reshape(-1)] if boolean else [finite(value, identifier) for value in array.reshape(-1)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="bool" if boolean else "float64",
                values=flat, provenance=provenance, precision=8)


def split_heads(identifier, values, B, T, H, F, features, trace):
    """Reshape [B,T,H*F] first; then separately permute axes (0,2,1,3)."""
    for name, value, maximum in (("B", B, 2), ("T", T, 3), ("H", H, 2), ("F", F, 2), ("features", features, 4)):
        value = finite(value, name)
        if not value.is_integer() or not 1 <= value <= maximum:
            raise NumericalFault("INVALID_INPUT", f"{name} must be an integer between 1 and {maximum}.")
    B, T, H, F, features = int(B), int(T), int(H), int(F), int(features)
    if features != H * F:
        raise NumericalFault("SHAPE_MISMATCH", "Projection features must equal H*F; no feature may be discarded.")
    if type(values) is not list or len(values) != B * T * features:
        raise NumericalFault("SHAPE_MISMATCH", "Projection storage must be a dense array of B*T*features values.")
    # Shape/storage errors precede traversal of any numerical element.
    flat = [finite(value, f"{identifier}[{index}]") for index, value in enumerate(values)]
    split = np.array(flat, dtype=np.float64).reshape((B, T, H, F))
    trace.add(f"reshape_{identifier}", f"{identifier}: expose the head and within-head feature axes",
              "[B,T,H*F] -> [B,T,H,F]; the flat value order is unchanged",
              "A reshape changes only the coordinate description. It does not move a token or a head value.",
              dict(B=B, T=T, H=H, F=F, features=features, elements=B*T*H*F), dict(elements=B*T*H*F))
    # This declared permutation is a separate copy, not a disguised reshape.
    heads = np.transpose(split, axes=(0, 2, 1, 3)).copy()
    for b in range(B):
        for h in range(H):
            for t in range(T):
                for f in range(F):
                    feature = h * F + f
                    source_offset = (b * T + t) * (H * F) + feature
                    destination_offset = ((b * H + h) * T + t) * F + f
                    source_value = float(split[b, t, h, f])
                    trace.add(f"permute_{identifier}_{b}_{h}_{t}_{f}", f"{identifier}[{b},{h},{t},{f}]: copy to head-major order",
                              "U[b,h,t,f]=R[b,t,h,f]; axes=(0,2,1,3)",
                              "The source and destination flat offsets differ in general; the indexed value is copied unchanged.",
                              dict(b=b, h=h, t=t, f=f, feature=feature, sourceOffset=source_offset,
                                   destinationOffset=destination_offset, sourceValue=source_value),
                              dict(value=float(heads[b, h, t, f])))
    feature_axis = "Dv" if identifier == "V" else "Dk"
    tensors = [tensor(f"{identifier}Split", [B, T, H, F], ["B", "T", "H", feature_axis], split,
                      "Storage-preserving reshape of the concatenated projection; each feature is h*F+f."),
               tensor(f"{identifier}Heads", [B, H, T, F], ["B", "H", "T", feature_axis], heads,
                      "Separate declared axis permutation (0,2,1,3) from token-major to head-major storage.")]
    return dict(split=split, heads=heads, tensors=tensors)


def project_heads(s, trace):
    """Project Q,K,V in role/b/t/h/f order, then expose each head layout."""
    B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
    X = np.empty((B, T, 2), dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                X[b, t, d] = s[f"x{b}{t}{d}"]
    trace.add("setup", "Validate all scalar inputs and select active dimensions",
              "D=2; X[B,T,D]; WQ,WK[D,H*Dk]; WV[D,H*Dv]",
              "Validate even inactive fields, then pack each named head/feature parameter. Both input rows remain active.",
              s, dict(B=B, T=T, D=2, H=H, Dk=Dk, Dv=Dv))
    stage = dict(X=X)
    for name, prefix, width in (("Q", "wq", Dk), ("K", "wk", Dk), ("V", "wv", Dv)):
        weights = np.empty((2, H * width), dtype=np.float64)
        joined = np.empty((B, T, H * width), dtype=np.float64)
        for d in range(2):
            for h in range(H):
                for f in range(width):
                    weights[d, h * width + f] = s[f"{prefix}{d}{h}{f}"]
        for b in range(B):
            for t in range(T):
                for h in range(H):
                    for f in range(width):
                        x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                        w0, w1 = float(weights[0, h * width + f]), float(weights[1, h * width + f])
                        product0 = finite(x0 * w0, "projection product0")
                        product1 = finite(x1 * w1, "projection product1")
                        value = finite(product0 + product1, "projection value")
                        joined[b, t, h * width + f] = value
                        trace.add(f"project_{name}_{b}_{t}_{h}_{f}", f"{name} token {b},{t}, head {h}, feature {f}",
                                  "product0=x0*w0; product1=x1*w1; value=product0+product1",
                                  "Multiply one input row by the column for this head and feature. The two products precede their sum.",
                                  dict(b=b, t=t, h=h, f=f, x0=x0, x1=x1, w0=w0, w1=w1),
                                  dict(product0=product0, product1=product1, value=value))
        stage[f"W{name}"] = weights
        stage[f"{name}Concat"] = joined
    tensors = [tensor("X", [B, T, 2], ["B", "T", "D"], X, "Active input token rows; both input features are retained.")]
    for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
        tensors.append(tensor(f"W{name}", [2, H*width], ["D", axis], stage[f"W{name}"],
                              "Packed named weights: column h*F+f, retaining both input rows."))
    for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
        tensors.append(tensor(f"{name}Concat", [B, T, H*width], ["B", "T", axis], stage[f"{name}Concat"],
                              "Real two-product projections in token-major, packed-head feature order."))
    aliases = {}
    for name, width in (("Q", Dk), ("K", Dk), ("V", Dv)):
        layout = split_heads(name, stage[f"{name}Concat"].reshape(-1).tolist(), B, T, H, width, H*width, trace)
        stage[f"{name}Split"], stage[f"{name}Heads"] = layout["split"], layout["heads"]
        tensors.extend(layout["tensors"])
        for b in range(B):
            for h in range(H):
                for t in range(T):
                    for f in range(width):
                        aliases[f"{name.lower()}{b}{h}{t}{f}"] = float(layout["heads"][b, h, t, f])
    return dict(X=stage["X"], WQ=stage["WQ"], WK=stage["WK"], WV=stage["WV"],
                QConcat=stage["QConcat"], KConcat=stage["KConcat"], VConcat=stage["VConcat"],
                QSplit=stage["QSplit"], QHeads=stage["QHeads"], KSplit=stage["KSplit"],
                KHeads=stage["KHeads"], VSplit=stage["VSplit"], VHeads=stage["VHeads"],
                aliases=aliases, tensors=tensors)


def stable_softmax(logits, allowed):
    """M1 operation order: allowed max, ascending terms/sum, then quotients."""
    if type(logits) is not list or type(allowed) is not list or not 1 <= len(logits) <= 64 or len(logits) != len(allowed):
        raise NumericalFault("SHAPE_MISMATCH", "A boolean allowed mask must match 1–64 logits.")
    logits = [finite(value, f"logit {j}") for j, value in enumerate(logits)]
    if any(type(value) is not bool for value in allowed):
        raise NumericalFault("INVALID_INPUT", "Every mask entry must be boolean.")
    candidates = [value for j, value in enumerate(logits) if allowed[j]]
    if not candidates:
        raise NumericalFault("FULLY_MASKED_ROW", "This query has no allowed keys; no probability distribution exists.")
    maximum = max(candidates)
    # Match Math.max zero ties without erasing an all-negative-zero maximum.
    if maximum == 0.0 and any(value == 0.0 and math.copysign(1.0, value) > 0.0 for value in candidates):
        maximum = 0.0
    terms = []
    for j, logit in enumerate(logits):
        term = finite(math.exp(finite(logit - maximum, "shifted logit")), "softmax term") if allowed[j] else 0.0
        terms.append(term)
    denominator = 0.0
    for term in terms:
        denominator = finite(denominator + term, "softmax denominator")
    probabilities = [finite(term / denominator, "softmax probability") for term in terms]
    return dict(max=maximum, terms=terms, denominator=denominator, probabilities=probabilities)


def attend_heads(s, projected, trace):
    """Each b,h path scores, masks and mixes independently along the key axis."""
    B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
    Q, K, V = projected["QHeads"], projected["KHeads"], projected["VHeads"]
    shape = (B, H, T, T)
    raw, scores = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    aliases = {}
    divisor = finite(math.sqrt(Dk), "score divisor")
    for b in range(B):
        for h in range(H):
            for i in range(T):
                for j in range(T):
                    q0, k0 = float(Q[b, h, i, 0]), float(K[b, h, j, 0])
                    inputs = dict(b=b, h=h, i=i, j=j, Dk=Dk, divisor=divisor, q0=q0, k0=k0)
                    product0 = finite(q0 * k0, "score product0")
                    values, dot = dict(product0=product0), product0
                    if Dk == 2:
                        q1, k1 = float(Q[b, h, i, 1]), float(K[b, h, j, 1])
                        inputs.update(q1=q1, k1=k1)
                        product1 = finite(q1 * k1, "score product1")
                        values["product1"] = product1
                        dot = finite(product0 + product1, "raw score")
                    scaled = finite(dot / divisor, "scaled score")
                    raw[b, h, i, j], scores[b, h, i, j] = dot, scaled
                    values.update(raw=dot, score=scaled)
                    aliases[f"raw{b}{h}{i}{j}"] = dot
                    aliases[f"score{b}{h}{i}{j}"] = scaled
                    trace.add(f"score_{b}_{h}_{i}_{j}", f"Batch {b}, head {h}: query {i} against key {j}",
                              "product0=q0*k0; raw=product0; score=raw/sqrt(Dk)" if Dk == 1 else
                              "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
                              "Only matching features in this batch and head contribute. The divisor is the per-head key width.", inputs, values)
    allowed = np.empty(shape, dtype=np.bool_)
    logits, probabilities = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    causal, padding = s["mode"] in (1, 3), s["mode"] in (2, 3)
    for b in range(B):
        for h in range(H):
            for i in range(T):
                inputs = dict(b=b, h=h, i=i, mode=s["mode"], shift=s["shift"])
                row_logits, row_allowed = [], []
                for j in range(T):
                    score = float(scores[b, h, i, j])
                    inputs[f"score{j}"] = score
                    permit = (not causal or j <= i) and (not padding or s[f"valid{j}"] == 1)
                    allowed[b, h, i, j] = permit
                    logit = finite(score + s["shift"], "shifted score")
                    logits[b, h, i, j] = logit
                    row_logits.append(logit)
                    row_allowed.append(permit)
                for j in range(T):
                    inputs[f"allowed{j}"] = 1 if row_allowed[j] else 0
                if not any(row_allowed):
                    raise NumericalFault("FULLY_MASKED_ROW", f"Batch {b}, head {h}, query {i} has no allowed keys; the entire result is unavailable.")
                row = stable_softmax(row_logits, row_allowed)
                values = dict(max=row["max"], denominator=row["denominator"])
                for j in range(T):
                    if row_allowed[j]:
                        values[f"shifted{j}"] = finite(row_logits[j] - row["max"], "shifted logit")
                for j in range(T):
                    values[f"term{j}"] = row["terms"][j]
                for j in range(T):
                    p = row["probabilities"][j]
                    probabilities[b, h, i, j] = p
                    values[f"p{j}"] = p
                    aliases[f"p{b}{h}{i}{j}"] = p
                trace.add(f"row_{b}_{h}_{i}", f"Batch {b}, head {h}: masked key softmax for query {i}",
                          "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",
                          "Normalize allowed keys only, in ascending key order. Queries remain; masks are shared across heads/batches. Forbidden probabilities are exactly zero; allowed exponential underflow is distinct.", inputs, values)
    OHeads = np.empty((B, H, T, Dv), dtype=np.float64)
    for b in range(B):
        for h in range(H):
            for i in range(T):
                for f in range(Dv):
                    inputs, products, running = dict(b=b, h=h, i=i, f=f), {}, {}
                    value = 0.0
                    for j in range(T):
                        p, v = float(probabilities[b, h, i, j]), float(V[b, h, j, f])
                        inputs[f"p{j}"], inputs[f"v{j}"] = p, v
                        product = finite(p * v, "head value product")
                        products[f"product{j}"] = product
                        value = finite(value + product, "head value running sum")
                        running[f"running{j}"] = value
                    OHeads[b, h, i, f] = value
                    aliases[f"oh{b}{h}{i}{f}"] = value
                    trace.add(f"head_mix_{b}_{h}_{i}_{f}", f"Head output [{b},{h},{i},{f}]",
                              "product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
                              "Use this head's actual probability row and value feature. Every key contributes its product, including masked 0*V, followed immediately by its running sum.",
                              inputs, {**products, **running, "value": value})
    axes = ["B", "H", "Query", "Key"]
    tensors = [tensor("raw", list(shape), axes, raw, "Per-head query-key products, summed before scaling."),
               tensor("scores", list(shape), axes, scores, "Raw dot products divided by sqrt(Dk)."),
               tensor("allowed", list(shape), axes, allowed, "Boolean allowed-key masks; validity is shared across B and H; queries remain."),
               tensor("logits", list(shape), axes, logits, "Finite score+common shift for every key, including forbidden keys; no infinity sentinel."),
               tensor("probabilities", list(shape), axes, probabilities, "Per-batch/head/query stable softmax along allowed keys only."),
               tensor("OHeads", [B, H, T, Dv], ["B", "H", "Query", "Dv"], OHeads,
                      "Actual per-head weighted values: ascending key products and sequential sums from zero.")]
    return dict(raw=raw, scores=scores, allowed=allowed, logits=logits, probabilities=probabilities,
                OHeads=OHeads, aliases=aliases, tensors=tensors)


def join_heads(s, attended, trace):
    """Copy OHeads into C in head/feature order, then compute every C*WO term."""
    B, T, H, Dv = (s[key] for key in ("B", "T", "H", "Dv"))
    OHeads = attended["OHeads"]
    C = np.empty((B, T, H*Dv), dtype=np.float64)
    aliases = {}
    for b in range(B):
        for t in range(T):
            for h in range(H):
                for f in range(Dv):
                    c = h * Dv + f
                    source_offset = ((b * H + h) * T + t) * Dv + f
                    destination_offset = (b * T + t) * (H * Dv) + c
                    value = finite(OHeads[b, h, t, f], "head output to concatenate")
                    C[b, t, c] = value
                    aliases[f"c{b}{t}{c}"] = value
                    trace.add(f"concat_{b}_{t}_{h}_{f}", f"Joined feature [{b},{t},{c}] from head {h}, feature {f}",
                              "C[b,t,h*Dv+f]=OHeads[b,h,t,f]",
                              "Copy the actual head output unchanged; concatenation rearranges coordinates and never averages heads.",
                              dict(b=b, t=t, h=h, f=f, concatFeature=c, sourceOffset=source_offset,
                                   destinationOffset=destination_offset, sourceValue=value), dict(value=value))
    WO = np.empty((H*Dv, 2), dtype=np.float64)
    for h in range(H):
        for f in range(Dv):
            for d in range(2):
                WO[h*Dv+f, d] = s[f"wo{h}{f}{d}"]
    Y = np.empty((B, T, 2), dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                inputs, products, running = dict(b=b, t=t, d=d), {}, {}
                value = 0.0
                for c in range(H*Dv):
                    coordinate, weight = float(C[b, t, c]), float(WO[c, d])
                    inputs[f"c{c}"], inputs[f"w{c}"] = coordinate, weight
                    product = finite(coordinate * weight, "output projection product")
                    products[f"product{c}"] = product
                    value = finite(value + product, "output projection running sum")
                    running[f"running{c}"] = value
                Y[b, t, d] = value
                aliases[f"y{b}{t}{d}"] = value
                trace.add(f"output_{b}_{t}_{d}", f"Output [{b},{t},{d}]: joined values times WO",
                          "product_c=c_c*w_c; running starts at 0; running_c=previous+product_c; value=last running sum",
                          "Pack WO rows by h*Dv+f, retaining parameter identity as Dv changes. Products and immediate running sums follow ascending joined features. Signed output is allowed; no output normalization is added.",
                          inputs, {**products, **running, "value": value})
    tensors = [tensor("C", [B, T, H*Dv], ["B", "T", "JoinedValue"], C, "Head/within-head feature concatenation of actual OHeads, preserving each copied value."),
               tensor("WO", [H*Dv, 2], ["JoinedValue", "D"], WO, "Named output parameters packed in head/feature row order h*Dv+f."),
               tensor("Y", [B, T, 2], ["B", "T", "D"], Y, "C times WO via explicit scalar products and sequential running sums; no output softmax.")]
    return dict(C=C, WO=WO, Y=Y, aliases=aliases, tensors=tensors)


_JSON_INT = int


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

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

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

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

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

Derived distribution — p11/choice_reference.py: direct_distribution accepts finite computed logits without the raw editor bounds and saves every active exponential, denominator, probability and computed-logit decision. The decision is evidence, never a replacement training target.

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.

"""Direct logits -> stable probabilities -> strict-logit greedy choice.

NumPy float64/int32 arrays are the actual storage. Scalar binary64 arithmetic
preserves exp, left-to-right denominator and division order. No neural/tokenizer
import is needed for the literal five-ID model contract. Full ordered chapter
records follow the owner-adopted A inventory. All execution remains DEFERRED.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np

ALL_IDS = (97, 98, 512, 256, 257)
DEFAULT_IV45 = MappingProxyType(dict(V=3, z0=1, z1=0, z2=0, z3=0, z4=0))


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


def finite(value, label):
    """No coercion, bools, custom scalar conversions, infinities or NaNs."""
    if type(value) not in (int, float):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (OverflowError, ValueError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def choice_state(state):
    """Validate all six own fields in raw order, including inactive logits."""
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly V,z0,z1,z2,z3,z4.")
    if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV45):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive logits.")
    checked = {}
    for key in DEFAULT_IV45:
        value = finite(state[key], key)
        if key == "V":
            if not value.is_integer() or not 3 <= value <= 5:
                raise NumericalFault("INVALID_INPUT", "V must be an integer from 3 to 5.")
            checked[key] = int(value)
        else:
            if not -40 <= value <= 40:
                raise NumericalFault("INVALID_INPUT", f"{key} must be between -40 and 40.")
            checked[key] = value
    return checked


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


class ChoiceTrace:
    """Finite detached scalar records; no implicit invocation of self-checks."""
    def __init__(self):
        self.steps = []

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


def _dense(values, label):
    """Inspect both containers before either helper operand is read."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual dense array.")
    if not 3 <= len(values) <= 5:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} must have 3 to 5 entries.")


def _tensor(identifier, axis, values, provenance):
    """Serialize actual internal float64/int32 vectors into detached metadata."""
    if type(values) is not np.ndarray or values.ndim != 1 or values.dtype not in (np.dtype(np.float64), np.dtype(np.int32)):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64/int32 vector storage.")
    if not 1 <= len(values) <= 5:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier} requires 1 to 5 entries.")
    flat = values.tolist()
    for value in flat:
        finite(value, identifier)
    integer = values.dtype == np.dtype(np.int32)
    return dict(id=identifier, shape=[len(flat)], axes=[axis], dtype="int32" if integer else "float64",
                values=flat, provenance=provenance, precision=0 if integer else 8)


def direct_distribution(logits, class_ids, trace, prefix="choice"):
    """Dynamic V3..5 distribution; no slider bound on finite derived logits.

    Prefix precedes both container guards; both descriptors precede entries.
    Highest computed input logit wins; ties keep the lowest compact index.
    """
    if type(prefix) is not str or not prefix:
        raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
    _dense(logits, "logits")
    _dense(class_ids, "classIDs")
    if len(logits) != len(class_ids):
        raise NumericalFault("SHAPE_MISMATCH", "logits and classIDs must have equal lengths.")
    raw_z = logits.tolist() if type(logits) is np.ndarray else logits
    raw_ids = class_ids.tolist() if type(class_ids) is np.ndarray else class_ids
    V = len(raw_z)
    z = np.array([finite(value, f"logits[{c}]") for c, value in enumerate(raw_z)], dtype=np.float64)
    numeric_ids = [finite(value, f"classIDs[{c}]") for c, value in enumerate(raw_ids)]
    checked_ids = []
    for c, identifier in enumerate(numeric_ids):
        if not identifier.is_integer() or identifier != ALL_IDS[c]:
            raise NumericalFault("INVALID_INPUT", "classIDs must be the active prefix of [97,98,512,256,257].")
        checked_ids.append(int(identifier))
    ids = np.array(checked_ids, dtype=np.int32)
    maximum_inputs = {f"z{c}": float(z[c]) for c in range(V)}
    maximum = max(maximum_inputs.values())
    trace.add(f"{prefix}_max", "Find the maximum active computed logit", "max=max(z0,...,z[V-1])",
              "All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.",
              maximum_inputs, dict(max=maximum))
    shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
    denominator, running = 0.0, {}
    for c in range(V):
        logit = float(z[c])
        shift = finite(logit - maximum, "shifted logit")
        term = finite(math.exp(shift), "shifted exponential")
        shifted[c], terms[c] = shift, term
        trace.add(f"{prefix}_exp_{c}", f"Exponentiate active class {c}", "shifted=logit-max; term=exp(shifted)",
                  "No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.",
                  dict(c=c, logit=logit, max=maximum), dict(shifted=shift, term=term))
        denominator = finite(denominator + term, "denominator")
        running[f"running{c}"] = denominator
    if denominator <= 0:
        raise NumericalFault("UNAVAILABLE", "The shifted exponential denominator must be positive.")
    log_s = finite(math.log(denominator), "logS")
    lse = finite(maximum + log_s, "logsumexp")
    trace.add(f"{prefix}_normalize", "Accumulate terms and compute logsumexp",
              "running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS",
              "The denominator adds terms in ascending compact class order. Every actual running sum is saved.",
              {**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
              {**running, "denominator": denominator, "logS": log_s, "lse": lse})
    for c in range(V):
        term = float(terms[c])
        probability = finite(term / denominator, "probability")
        probabilities[c] = probability
        trace.add(f"{prefix}_probability_{c}", f"Normalize active class {c}", "probability=term/S",
                  "This stored binary64 probability is displayed without feeding its formatting back into arithmetic.",
                  dict(c=c, term=term, denominator=denominator), dict(probability=probability))
    next_row = 0
    for c in range(1, V):
        if float(z[c]) > float(z[next_row]):
            next_row = c
    next_id, next_probability = int(ids[next_row]), float(probabilities[next_row])
    trace.add(f"{prefix}_argmax", "Choose the highest computed input logit",
              "strict greater-than updates the winner; exact ties retain lowest compact index",
              "Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.",
              maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
    tensors = [
        _tensor("ClassIDs", "Class", ids, "Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets."),
        _tensor("Z", "Class", z, "Actual finite computed input logits; no derived-input clipping."),
        _tensor("Shifted", "Class", shifted, "Z minus the saved active maximum."),
        _tensor("Terms", "Class", terms, "Actual exp(Shifted), before normalization."),
        _tensor("Denominator", "Scalar", np.array([denominator], dtype=np.float64), "Actual left-to-right sum of active shifted terms."),
        _tensor("LogS", "Scalar", np.array([log_s], dtype=np.float64), "Natural logarithm of Denominator."),
        _tensor("LSE", "Scalar", np.array([lse], dtype=np.float64), "Saved max+LogS in binary64."),
        _tensor("P", "Class", probabilities, "Terms/Denominator for active classes only, without clipping or padding."),
        _tensor("NextRow", "Decision", np.array([next_row], dtype=np.int32), "Lowest compact index among highest computed logits."),
        _tensor("NextID", "Decision", np.array([next_id], dtype=np.int32), "Public class ID gathered at NextRow."),
        _tensor("NextProbability", "Decision", np.array([next_probability], dtype=np.float64), "Stored P gathered at the computed-logit winner."),
    ]
    return dict(classIDs=ids.tolist(), logits=z.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
                denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
                nextRow=next_row, nextID=next_id, nextProbability=next_probability, tensors=tensors)


def compute_choice(state):
    """Full ordered IV45 record, including raw inactive metadata and every step."""
    s = choice_state(state)
    raw_z = np.array([s[f"z{c}"] for c in range(5)], dtype=np.float64)
    class_ids = np.array(ALL_IDS[:s["V"]], dtype=np.int32)
    trace = ChoiceTrace()
    trace.add("setup", "Validate all raw logits before selecting active classes", "V in {3,4,5}; every raw z in [-40,40]; activeZ=rawZ[:V]",
              "Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.",
              s, dict(classCount=s["V"], rawLogitCount=5))
    row = direct_distribution(raw_z[:s["V"]], class_ids, trace)
    trace.add("finish", "Keep the distribution and greedy decision together", "nextID=classIDs[argmax computed activeZ]; nextProbability=P[nextRow]",
              "The selected ID is a deterministic decision. Equal stored probabilities need not mean equal logits.",
              dict(nextRow=row["nextRow"]), dict(nextID=row["nextID"], nextProbability=row["nextProbability"]))
    outputs = dict(nextID=row["nextID"], nextProbability=row["nextProbability"], classCount=s["V"], logsumexp=row["lse"],
                   nextRow=row["nextRow"], max=row["max"], denominator=row["denominator"], logS=row["logS"], rawLogitCount=5)
    for step in trace.steps:
        outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
    tensors = [_tensor("RawZ", "ModelRow", raw_z, "All five validated editable raw logits, including inactive slots."), *row["tensors"]]
    return dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors)


def source_self_check():
    """DEFERRED helper checks; never calls any other file's self-check."""
    assert __debug__, "Deferred checks require assertions enabled."
    state = dict(DEFAULT_IV45)
    trace = ChoiceTrace()
    row = direct_distribution([1, 0, 0], [97, 98, 512], trace)
    assert list(row) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
    ndarray_row = direct_distribution(np.array([1, 0, 0], dtype=np.float64), np.array([97, 98, 512], dtype=np.int32), ChoiceTrace())
    assert ndarray_row == row
    assert direct_distribution((1, 0, 0), (97, 98, 512), ChoiceTrace()) == row
    assert len(trace.steps) == 9 and trace.steps[0]["id"] == "choice_max"
    denominator = math.e + 2
    assert row["nextRow"] == 0 and row["nextID"] == 97
    assert math.isclose(row["probabilities"][0], math.e / denominator, rel_tol=1e-14)
    assert math.isclose(row["probabilities"][1], 1 / denominator, rel_tol=1e-14)
    assert math.isclose(row["lse"], math.log(denominator), rel_tol=1e-14)
    tied = direct_distribution([0, 0, 1, 1, 0], ALL_IDS, ChoiceTrace())
    assert tied["nextRow"] == 2 and tied["nextID"] == 512
    uniform = direct_distribution([0] * 5, ALL_IDS, ChoiceTrace())
    assert uniform["probabilities"] == [0.2] * 5 and uniform["nextID"] == 97
    rounded = direct_distribution([0, math.ulp(0.0), 0], ALL_IDS[:3], ChoiceTrace())
    assert rounded["probabilities"] == [1 / 3] * 3 and rounded["nextID"] == 98
    thin = direct_distribution([-40, 40, -40], ALL_IDS[:3], ChoiceTrace())
    assert thin["probabilities"][0] > 0 and thin["probabilities"][2] > 0
    derived_trace = ChoiceTrace()
    shifted = direct_distribution([101, 100, 100], ALL_IDS[:3], derived_trace, "derived")
    assert shifted["probabilities"] == row["probabilities"] and shifted["nextID"] == row["nextID"]
    assert all(step["id"].startswith("derived_") for step in derived_trace.steps)
    for patch, code in ((dict(V=True), "NONFINITE"), (dict(V=2), "INVALID_INPUT"),
                        (dict(V=3.5), "INVALID_INPUT"), (dict(z4=True), "NONFINITE"),
                        (dict(z4=41), "INVALID_INPUT"), (dict(z4=float("nan")), "NONFINITE"),
                        (dict(z4=10**1000), "NONFINITE")):
        fault = guarded(compute_choice)({**state, **patch})
        assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
    class Hostile(dict):
        def __getitem__(self, key):
            raise AssertionError("Custom indexing must not be read")
    assert guarded(compute_choice)(Hostile(state))["code"] == "INVALID_INPUT"
    class HostileList(list):
        def __getitem__(self, key):
            raise AssertionError("Custom indexing must not be read")
    for logits, ids, code in (([1, 0, 0], HostileList([97, 98, 512]), "INVALID_INPUT"),
                             (HostileList([1, 0, 0]), [97, 98, 512], "INVALID_INPUT"),
                             ([1, 0, 0], [97, 98, 256], "INVALID_INPUT"),
                             ([1, 0, 0], [99, float("nan"), 512], "NONFINITE"),
                             ([1, float("nan"), 0], None, "INVALID_INPUT"),
                             ([1, 0, 0], [97, 98, 512, 256], "SHAPE_MISMATCH"),
                             (np.array([True, False, False]), ALL_IDS[:3], "INVALID_INPUT"),
                             ([1, True, 0], ALL_IDS[:3], "NONFINITE"),
                             ([1, float("inf"), 0], ALL_IDS[:3], "NONFINITE"),
                             ([1e308, -1e308, 0], ALL_IDS[:3], "NONFINITE"),
                             ([1, 0], [97, 98], "UNSUPPORTED_SIZE")):
        try:
            direct_distribution(logits, ids, ChoiceTrace(), "bad")
        except NumericalFault as error:
            assert error.code == code
        else:
            raise AssertionError("Invalid helper boundary was accepted")
    for prefix in (None, "", 0, True):
        rejected_trace = ChoiceTrace()
        try:
            direct_distribution(HostileList(), None, rejected_trace, prefix)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT" and "prefix" in str(error)
            assert not rejected_trace.steps
        else:
            raise AssertionError("Prefix must validate before containers")
    assert _tensor("F", "Class", np.array([1.0], dtype=np.float64), "check")["dtype"] == "float64"
    assert _tensor("I", "Class", np.array([97], dtype=np.int32), "check")["dtype"] == "int32"
    row["tensors"][0]["values"][0] = -1
    row["probabilities"][0] = -1
    trace.steps[0]["outputs"].clear()
    assert direct_distribution([1, 0, 0], ALL_IDS[:3], ChoiceTrace())["tensors"][0]["values"] == [97, 98, 512]
    assert state == dict(DEFAULT_IV45)


_JSON_INT = int


def run(derive, defaults):
    """Default / full replacement JSON / '-' stdin; never invokes self-checks."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

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

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

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

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

The loader graph is iv52 → training_reference → packing_reference, tiny_reference, choice_reference. Packing loads iv39 → bpe_reference → token_reference; tiny loads the component, FFN, head and BPE helpers. Paths resolve from __file__, not a caller-selected working directory. For the unchanged FFN bare import, tiny temporarily binds its canonical component module and then restores the prior binding. No oracle provides the production answer.

Recap and bridge

  • Known next tokens define the targets; generation and greedy choices do not supply training answers.
  • The loss denominator counts included real targets. Zero included targets means no defined update.
  • Every readout gradient sums the saved old row contributions; all fifteen coordinates update simultaneously.
  • Adam’s moments and counters are state even when eta=0 leaves the weights unchanged.
  • Recomputing the updated readout on fixed Y is valid here; a finite step can still increase loss.

Next, IV-53 — Checkpoints and Reproducible Resumption asks what must be saved to stop and reproduce a training computation, including optimizer state rather than weights alone.