The neural notebook
← All chapters

IV-53 / Part XIII · Training Language Models

Checkpoints and Reproducible Resumption

Understand complete training state, lossless binary64 checkpoints and the conditions under which stopping and restoring reproduces a three-update computation.

Review the ideas this chapter uses

Imagine stopping a calculation halfway through a recipe. Keeping the ingredients is not enough: you also need to know which instruction comes next. Training has a similar problem. Its current weights matter, but so do the optimizer’s memory and the position in the data.

Learning objective: Explain exact trainable and RNG state needed to resume.

Compute it yourself

Checkpoints and Reproducible Resumption

Stop a tiny training run, save its complete continuation state, decode it, and finish. Compare it with an uninterrupted three-update baseline. Start with full restore, then deliberately forget optimizer memory, future randomness or the data cursor.

The fixed authored documents are A=a and B=b. Only fifteen readout weights and biases train, using two actual saved encoder feature vectors. Each edit creates a fresh saved experiment with six real updates: three baseline, a prefix, and its resumed suffix. The tables inspect that same record.

seed0
split1
mode0
eta0.1
Exact starting inputs for this saved calculation

seed 0. split 1. mode 0. eta 0.1. Declare the fixed three-update resumption experiment. All five raw finite-number checks precede every finite domain check. Only the fifteen readout parameters train; all old full-forward evidence is retained.

Declare the fixed three-update resumption experiment

baseline3; prefix=split; suffix=3-split; actual updates=6

All five raw finite-number checks precede every finite domain check. Only the fifteen readout parameters train; all old full-forward evidence is retained.

Saved inputs

seed
0
split
1
mode
0
eta
0.1
optimizer
1

Saved outputs

totalUpdates
3
realUpdates
6
tokenizerCalls
2
appendedEOS
2
fullForwardCalls
2
classCount
3
trainableParameters
15
beta1
0.5
beta2
0.5
epsilon
1e-8

Did the saved state survive — and did continuation agree?

Prefix → decoded: all stateequal (1)
Baseline → resumed: final full stateequal (1)
Every corresponding updateequal (1)
Final weights onlyequal (1)

Round-trip compares the original prefix with its unmodified decode. Recovery is applied afterwards. Final-state equality compares all weights, moments, counters, RNG, order, cursor and epoch. Trajectory equality also checks samples, pre-update losses, gradients and every post-update state. Equal weights alone do not settle the other comparisons.

Current saved experiment: seed=0, split=1, mode=0, η=0.1, optimizer=Adam. Decode the valid normal prefix first. Mode0 restores all fields; mode1 changes ONLY m/v to positive zeros; mode2 changes ONLY future RNG to raw seed; mode3 changes ONLY cursor to0. Some interventions coincide with the baseline; no divergence is forced.

Every NLL below is measured BEFORE its associated update. NLL (negative log-likelihood) measures surprise at the known EOS target; lower means more target probability for that sample. There is no objective evaluation after the final update and no training curve of a fixed evaluation set.

Six actual update rows: baseline, interrupted prefix and decoded suffix
Saved row / completed index beforeSample / input → targetPre-update NLLBefore: RNG / order / cursor / epochAfter: RNG / order / cursor / epochAfter: tAdam / completedUpdates
baseline_1 / 0A / 97 → 5122.3120996589121161013904223 / [0,1] / 0 / 01013904223 / [0,1] / 1 / 01 / 1
baseline_2 / 1B / 98 → 5122.6012865817518011013904223 / [0,1] / 1 / 01196435762 / [0,1] / 0 / 12 / 2
baseline_3 / 2A / 97 → 5121.45403858693399271196435762 / [0,1] / 0 / 11196435762 / [0,1] / 1 / 13 / 3
prefix_1 / 0A / 97 → 5122.3120996589121161013904223 / [0,1] / 0 / 01013904223 / [0,1] / 1 / 01 / 1
resume_2 / 1B / 98 → 5122.6012865817518011013904223 / [0,1] / 1 / 01196435762 / [0,1] / 0 / 12 / 2
resume_3 / 2A / 97 → 5121.45403858693399271196435762 / [0,1] / 0 / 11196435762 / [0,1] / 1 / 13 / 3

Six genuine readout-only updates: baseline3 plus interrupted prefix and decoded suffix totaling3. Actual old fixed encoder features; no full Transformer gradients or final diagnostic evaluation. Saved counts: updates=6; initial full forwards=2; current readouts=6; RNG draws=3. A and B each have one input, one EOS target, mask=1 and included-target count N=1.

Inspecting baseline_1, state Prefix, parameter u00, word eta, class slot 2. These selectors index saved evidence only; they preserve the raw inputs, selected trace step and question cases.

Selected trace: setup. Matching saved operations below are marked current. This trace cursor is independent of the inspection selectors.

Complete saved state: Prefix

θ (theta) is a trainable readout coordinate. First moment m averages signed gradients; second moment v averages squared gradients. The fifteen coordinates are ten U weights in feature-major [2,5] storage, then five biases. Adam’s step tAdam controls bias correction; completedUpdates counts successful optimizer transitions for either optimizer.

Prefix: all fifteen parameter and optimizer-memory coordinates
Parameterθmv
u000.90000000055921650.89410818728251961.5988589011312664
u01-0.099999992604336330.067607179578571370.009141461461138397
u020.09999999948009566-0.9617153668610911.849792893713526
u03000
u04000
u100.0999999973304242-0.187295669085811520.07015933531660362
u111.0999999646947436-0.0141621921309753560.0004011353719093206
u12-0.099999997518091470.201457861216786880.08117053969208433
u13000
u14000
b0-0.099999998806129390.418805847967180460.35079667658301816
b1-0.099999984211006310.03166762431527350.002005676859546603
b20.09999999889005673-0.4504734722824540.4058526984604217
b3000
b4000
Important actual continuation boundaries
BoundarytAdam / completedUpdatesFuture RNG (uint32)Prefetched orderCursor / epoch
Prefix1 / 11013904223[0,1]1 / 0
Initial0 / 01013904223[0,1]0 / 0
Decoded1 / 11013904223[0,1]1 / 0
Recovered1 / 11013904223[0,1]1 / 0
BaselineFinal3 / 31196435762[0,1]1 / 1
ResumedFinal3 / 31196435762[0,1]1 / 1

Draw one pedagogical uint32 LCG state to prefetch the initial two-item order. Select order[cursor]. After a successful update advance cursor; cursor2 resets0, increments epoch and immediately draws/prefetches the next order. RNG is the state for the next fresh order; saved current order is independently authoritative. Normal uninterrupted transitions establish completedUpdates=2×epoch+cursor and order matching the current RNG high bit. These relations describe that history; the structural decoder does not authenticate origin or require these relations after an explicit intervention.

Selected boundary: actual tensor axes, dtype, precision and provenance

Prefix_Theta: Parameter=15; float64; display precision 8. Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Prefix_M: Parameter=15; float64; display precision 8. Detached actual first moments, preserving all finite bits including signed zero.

Prefix_V: Parameter=15; float64; display precision 8. Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Prefix_Counters: Counter=2; int32; display precision 0. Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Prefix_RNG: RNGState=1; float64; display precision 0. Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Prefix_Order: OrderPosition=2; int32; display precision 0. Actual independently authoritative current prefetched two-item order.

Prefix_Position: IteratorField=2; int32; display precision 0. Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

One actual readout, loss, gradient and update: baseline_1

The selected document A uses its initial saved encoder Y with shape [batch,position,feature]=[1,1,2]. A feature is one numeric component of that encoder output. U is the trainable [feature,class] weight matrix; bias adds one value per class. Only this readout is repeated. Its logit z (unnormalized score) for active class index c is (Y[0]×U[0,c]+Y[1]×U[1,c])+bias[c]. P is the saved normalized exponential probability over the three active classes. No probability exists for the two inactive slots.

Document A: actual initial fixed encoder features
TensorSaved values
forwardA_X[1, 0]
forwardA_LN1[0.4472135954999579, -0.4472135954999579]
forwardA_R1[1.4472135954999579, -0.4472135954999579]
forwardA_LN2[0.6876854075163181, -0.6876854075163181]
forwardA_Hidden[0.6876854075163181, 0, 0]
forwardA_F[0.6876854075163181, 0]
forwardA_Y[2.134899003016276, -0.4472135954999579]
baseline_1: active class 2 actual distribution operands
Logit zShifted zexp(shifted)DenominatorlogSP
0-2.1348990030162760.118256533326695961.19387062627449820.177200655895840050.09905305543509206

Let max be the largest active logit and logS the logarithm of the sum of their shifted exponentials. For the actual EOS target, NLL=(max−targetLogit)+logS. The loss mask is 1 and N=1 here; the source still performs mask multiplication, accumulation and division.

baseline_1: all actual PRE-update loss operands and reductions
maxtargetLogitlogStarget PgapNLLmask×NLLloss summean NLL
2.13489900301627600.177200655895840050.099053055435092062.1348990030162762.3120996589121162.3120996589121162.3120996589121162.312099658912116
baseline_1: selected class gradient, mask=1 and N=1
SlotActual PTarget indicatorP−indicatorMask×differencedLogit
20.099053055435092061-0.900946944564908-0.900946944564908-0.900946944564908

A gradient g tells how this current loss changes with a parameter. dLogit[c] is the derivative with respect to class c’s logit; its target indicator is 1 for EOS and 0 otherwise. With feature index d equal to 0 or 1, U[d,c] has g=Y[d]×dLogit[c]; a bias uses dLogit directly, with accumulation from zero. All fifteen new coordinates use the same old parameter state and gradient vector.

baseline_1: every actual simultaneous parameter update
Parameterθ beforeGradient gSubtracted deltaθ afterm before / afterv before / after
u0011.78821637456503920.099999999440783570.90000000055921650 / 0.89410818728251960 / 1.5988589011312664
u0100.135214359157142750.09999999260433633-0.099999992604336330 / 0.067607179578571370 / 0.009141461461138397
u020-1.923430733722182-0.099999999480095660.099999999480095660 / -0.9617153668610910 / 1.849792893713526
u0300000 / 00 / 0
u0400000 / 00 / 0
u100-0.37459133817162305-0.09999999733042420.09999999733042420 / -0.187295669085811520 / 0.07015933531660362
u111-0.028324384261950712-0.099999964694743661.09999996469474360 / -0.0141621921309753560 / 0.0004011353719093206
u1200.402915722433573760.09999999751809147-0.099999997518091470 / 0.201457861216786880 / 0.08117053969208433
u1300000 / 00 / 0
u1400000 / 00 / 0
b000.83761169593436090.09999999880612939-0.099999998806129390 / 0.418805847967180460 / 0.35079667658301816
b100.0633352486305470.09999998421100631-0.099999984211006310 / 0.03166762431527350 / 0.002005676859546603
b20-0.900946944564908-0.099999998890056730.099999998890056730 / -0.4504734722824540 / 0.4058526984604217
b300000 / 00 / 0
b400000 / 00 / 0

Fixed beta1=beta2=0.5 and represented epsilon1e-8, outside sqrt. Every coordinate uses the same old theta, moments and gradient; SGD leaves unused Adam moments/tAdam zero. Eta0 still consumes data and advances counters; Adam still updates moments. For Adam, β1=β2=1/2 are decay factors; ε is the represented 1e-8 constant, and η scales the weight change. A prime means the new value: m′=β1 m+(1−β1)g and v′=β2 v+(1−β2)g². At new Adam step t, mHat=m′/(1−β1^t) and vHat=v′/(1−β2^t) are the bias-corrected moments. Subtract η×mHat/(sqrt(vHat)+ε) from θ. SGD instead subtracts ηg and keeps unused m/v and tAdam zero. The saved operations below retain the actual arithmetic order.

The helper computes and retains actual powers, corrections, root and epsilon arithmetic. The conditional operation premise for beta=1/2 at t1,2,3 is exact powers 1/2,1/4,1/8 and corrections 1/2,3/4,7/8; the later independent validation must check this premise. No arbitrary pow accuracy claim.

Why moment memory matters: a fixed hand calculation

This exact-real helper example is separate from the current saved run: take one coordinate, old Adam step 1, gradient g=1, η=1 and β1=β2=1/2. If old m=v=1, then m′=v′=1/2+1/2=1; at new step 2 the correction is 1−1/4=3/4, so mHat=vHat=4/3. Reset only old m/v to 0 and the same calculation gives m′=v′=1/2, hence mHat=vHat=2/3. The subtracted changes are (4/3)/(sqrt(4/3)+ε) and (2/3)/(sqrt(2/3)+ε). These differ even though old θ and the counter agree. This illustrates the dependency; the actual binary64 operands for the selected coordinate are below.

baseline_1, u00: actual contraction, optimizer setup, moment arithmetic and iterator commit

baseline_1_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.8376116959343609
y0
2.134899003016276
Saved outputs
product0
1.7882163745650392
running0
1.7882163745650392
gradient
1.7882163745650392

baseline_1_optimizer_setup: Compute the common optimizer arithmetic once

completedNew=completedUpdates+1; tNew=tAdam+1; oneMinusBeta=1-beta; power=beta**tNew; correction=1-power

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
1
beta1
0.5
beta2
0.5
epsilon
1e-8
tAdam
0
completedUpdates
0
Saved outputs
completedNew
1
tNew
1
oneMinusBeta1
0.5
oneMinusBeta2
0.5
power1
0.5
power2
0.5
correction1
0.5
correction2
0.5

baseline_1_optimizer_parameter_0: Simultaneously update u00

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

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
1.7882163745650392
eta
0.1
mOld
0
vOld
0
beta1
0.5
beta2
0.5
oneMinusBeta1
0.5
oneMinusBeta2
0.5
correction1
0.5
correction2
0.5
epsilon
1e-8
tNew
1
Saved outputs
mDecay
0
mProduct
0.8941081872825196
mNew
0.8941081872825196
square
3.1977178022625328
vDecay
0
vProduct
1.5988589011312664
vNew
1.5988589011312664
mHat
1.7882163745650392
vHat
3.1977178022625328
root
1.7882163745650392
denominator
1.7882163845650392
normalized
0.9999999944078356
delta
0.09999999944078357
thetaNew
0.9000000005592165

baseline_1_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
0
epoch
0
rng
1013904223
order0
0
order1
1
completedNew
1
tNew
1
Saved outputs
cursorIncrement
1
wraps
0
cursor
1
epoch
0
rng
1013904223
order0
0
order1
1
completedUpdates
1
tAdam
1
highBit
0
normalCount
1
normalCountRelation
1
normalOrderRelation
1
Selected sample, loss and class operations with their scope

baseline_1_select: Select the actual current prefetched sample

docID=order[cursor]; inputID=sequence[0]; targetID=sequence[1]; mask=1; N=1

One real current sample, with the known appended EOS target. Neither a prediction nor a fabricated inactive probability selects data.

Saved inputs
completedUpdates
0
rng
1013904223
order0
0
order1
1
cursor
0
epoch
0
Saved outputs
docID
0
inputID
97
targetID
512
targetRow
2
mask
1
position
0
validTargets
1

baseline_1_loss: Score the selected sample BEFORE its update

gap=max-targetLogit; nll=gap+logS; weightedNLL=mask*nll; lossSum=0+weightedNLL; meanNLL=lossSum/N

The current genuine distribution supplies all operands. This is one pre-update loss, not a final-theta objective or a monotonic curve.

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
validTargets
1
Saved outputs
gap
2.134899003016276
nll
2.312099658912116
weightedNLL
2.312099658912116
lossSum
2.312099658912116
meanNLL
2.312099658912116

baseline_1_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
1
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.8376116959343609
active1
1
difference1
0.063335248630547
masked1
0.063335248630547
gradient1
0.063335248630547
active2
1
difference2
-0.900946944564908
masked2
-0.900946944564908
gradient2
-0.900946944564908
active3
0
gradient3
0
active4
0
gradient4
0

baseline_1_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
y1
-0.4472135954999579
u1
0
bias
0
Saved outputs
product0
0
product1
-0
sum
0
logit
0

baseline_1_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
2.134899003016276
z1
-0.4472135954999579
z2
0
Saved outputs
max
2.134899003016276

baseline_1_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
max
2.134899003016276
Saved outputs
shifted
-2.134899003016276
term
0.11825653332669596

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

baseline_1_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.11825653332669596
denominator
1.1938706262744982
Saved outputs
probability
0.09905305543509206

All actual random draws and counter boundaries

The linear congruential generator (LCG) is a small deterministic teaching generator. Each draw computes next=(1664525×rng+1013904223) mod 4294967296, then bit=floor(next/2147483648). Bit 0 gives [A,B]; bit 1 gives [B,A]. Every integer product and sum is below 2^53. This is not cryptographic randomness or a promise of independent shuffles.

Every actual LCG draw: retained integer arithmetic and prefetched order
Draw ID / source RNGProductSumNext uint32High bitOrder
initial_rng / 00101390422310139042230[0,1]
baseline_2_rng / 10139042231687668926789075168766994069329811964357620[0,1]
resume_2_rng / 10139042231687668926789075168766994069329811964357620[0,1]

Fixed hand case, seed 0 before any update: 1664525×0+1013904223=1013904223; reduction modulo 4294967296 leaves that value, and floor(1013904223/2147483648)=0, so prefetch [A,B]. After the second consumed item, the next draw is 1196435762 and again selects [A,B]. Seed 3 instead reaches 1018897798 then 2365144877, selecting [A,B] then [B,A]. These are fixed arithmetic illustrations, not extra draws in the saved trace.

Every actual draw, initial state, recovery and update boundary

initial_rng: Advance the actual future RNG and prefetch an order

product=1664525*rng; sum=product+1013904223; next=sum%4294967296; bit=floor(next/2147483648); order=bit0?[0,1]:[1,0]

All integer operands/results are exact below 2^53. This explicit pedagogical LCG is not cryptographic and does not promise independent shuffles.

Saved inputs
rng
0
multiplier
1664525
increment
1013904223
modulus
4294967296
highDivisor
2147483648
Saved outputs
product
0
sum
1013904223
next
1013904223
bit
0
order0
0
order1
1

initial_state: Detach the common prefetched starting state

theta=default U,bias; m=v=positive zeros; tAdam=completedUpdates=cursor=epoch=0; preserve actual prefetched RNG/order

Baseline and interrupted runs each detach this identical actual starting state. Normal history relations hold here and are not decoder authenticity guards.

Saved inputs
seed
0
rng
1013904223
order0
0
order1
1
Saved outputs
tAdam
0
completedUpdates
0
cursor
0
epoch
0
normalCountRelation
1
normalOrderRelation
1

baseline_1_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
0
epoch
0
rng
1013904223
order0
0
order1
1
completedNew
1
tNew
1
Saved outputs
cursorIncrement
1
wraps
0
cursor
1
epoch
0
rng
1013904223
order0
0
order1
1
completedUpdates
1
tAdam
1
highBit
0
normalCount
1
normalCountRelation
1
normalOrderRelation
1

baseline_2_rng: Advance the actual future RNG and prefetch an order

product=1664525*rng; sum=product+1013904223; next=sum%4294967296; bit=floor(next/2147483648); order=bit0?[0,1]:[1,0]

All integer operands/results are exact below 2^53. This explicit pedagogical LCG is not cryptographic and does not promise independent shuffles.

Saved inputs
rng
1013904223
multiplier
1664525
increment
1013904223
modulus
4294967296
highDivisor
2147483648
Saved outputs
product
1687668926789075
sum
1687669940693298
next
1196435762
bit
0
order0
0
order1
1

baseline_2_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
1
epoch
0
rng
1013904223
order0
0
order1
1
completedNew
2
tNew
2
Saved outputs
cursorIncrement
2
wraps
1
cursor
0
epoch
1
rng
1196435762
order0
0
order1
1
completedUpdates
2
tAdam
2
highBit
0
normalCount
2
normalCountRelation
1
normalOrderRelation
1

baseline_3_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
0
epoch
1
rng
1196435762
order0
0
order1
1
completedNew
3
tNew
3
Saved outputs
cursorIncrement
1
wraps
0
cursor
1
epoch
1
rng
1196435762
order0
0
order1
1
completedUpdates
3
tAdam
3
highBit
0
normalCount
3
normalCountRelation
1
normalOrderRelation
1

prefix_1_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
0
epoch
0
rng
1013904223
order0
0
order1
1
completedNew
1
tNew
1
Saved outputs
cursorIncrement
1
wraps
0
cursor
1
epoch
0
rng
1013904223
order0
0
order1
1
completedUpdates
1
tAdam
1
highBit
0
normalCount
1
normalCountRelation
1
normalOrderRelation
1

recovery: Apply only the declared recovery intervention AFTER valid decode

mode0: complete; mode1: m/v=positive zero; mode2: rng=raw seed; mode3: cursor=0

Retain the original checkpoint text and decoded state. The transformed state passes the same structural guard; legal continuation state does not authenticate historical restoration.

Saved inputs
mode
0
seed
0
decodedRNG
1013904223
decodedCursor
1
Saved outputs
resetMoments
0
resetFutureRNG
0
resetCursor
0
rng
1013904223
cursor
1
epoch
0
tAdam
1
completedUpdates
1

resume_2_rng: Advance the actual future RNG and prefetch an order

product=1664525*rng; sum=product+1013904223; next=sum%4294967296; bit=floor(next/2147483648); order=bit0?[0,1]:[1,0]

All integer operands/results are exact below 2^53. This explicit pedagogical LCG is not cryptographic and does not promise independent shuffles.

Saved inputs
rng
1013904223
multiplier
1664525
increment
1013904223
modulus
4294967296
highDivisor
2147483648
Saved outputs
product
1687668926789075
sum
1687669940693298
next
1196435762
bit
0
order0
0
order1
1

resume_2_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
1
epoch
0
rng
1013904223
order0
0
order1
1
completedNew
2
tNew
2
Saved outputs
cursorIncrement
2
wraps
1
cursor
0
epoch
1
rng
1196435762
order0
0
order1
1
completedUpdates
2
tAdam
2
highBit
0
normalCount
2
normalCountRelation
1
normalOrderRelation
1

resume_3_advance: Commit the optimizer and actual iterator transition

cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch

The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.

Saved inputs
cursor
0
epoch
1
rng
1196435762
order0
0
order1
1
completedNew
3
tNew
3
Saved outputs
cursorIncrement
1
wraps
0
cursor
1
epoch
1
rng
1196435762
order0
0
order1
1
completedUpdates
3
tAdam
3
highBit
0
normalCount
3
normalCountRelation
1
normalOrderRelation
1

The actual checkpoint: ten slots, forty-nine float words

Binary64 is the 64-bit floating-point representation used here. Each float becomes sixteen lowercase hexadecimal digits in big-endian byte order (most significant bytes first). This retains finite bits, including +0 versus −0. The displayed signed high/low integers are two bit halves, not rounded values or unsigned RNG states.

Representation hand example: +0 has word 0000000000000000, whereas −0 has 8000000000000000 with signed high half −2147483648 and low half 0. Sixteen hex digits retain 16×4=64 bits. Ordinary numeric JSON can erase this distinction. This example explains the format; all 49 actual words below are copied from the saved checkpoint texts.

Saved JSON length=1229 UTF-16 code units; cap=8192. Version is 1. The fixed slot names and revision labels below describe the same saved text. They are context identifiers, not hashes or proof of authentic training.

  1. version
  2. modelIdentity
  3. dataIdentity
  4. operationIdentity
  5. config
  6. thetaWords
  7. mWords
  8. vWords
  9. counters
  10. iterator
Actual saved checkpoint JSON (read only)
[1,"iv53:tiny-b1-d2-h1-ffn3-default-encoder-v1","iv53:a,b:abab-bpe-lex-v1:merges0:eos-off+512:position0:classes97,98,512:target512:mask1:b1-v1","iv53:binary64-separate-rn:class-ascending:gradient-feature-order:adam-half-eps1e-8:lcg32-highbit-eager-prefetch-v1",[1,"3fb999999999999a","3fe0000000000000","3fe0000000000000","3e45798ee2308c3a"],["3feccccccd19a87b","bfb9999979d5fb57","3fb99999975df58a","0000000000000000","0000000000000000","3fb999998e225ed0","3ff19999901f70f6","bfb999998ef0b674","0000000000000000","0000000000000000","bfb999999478ece6","bfb9999955c96af8","3fb9999994d53458","0000000000000000","0000000000000000"],["3fec9c88c5eedb42","3fb14eb44143c784","bfeec65f4e175433","0000000000000000","0000000000000000","bfc7f94df2b3f7c4","bf8d0111405670fe","3fc9c95f06b95ed4","0000000000000000","0000000000000000","3fdacdb70b19202a","3fa036bd258d5ed3","bfdcd48eafcacc05","0000000000000000","0000000000000000"],["3ff994ed12346fc4","3f82b8c2301b1a51","3ffd98c06eedf6fb","0000000000000000","0000000000000000","3fb1f5f652b1a41c","3f3a49ef4db9ff11","3fb4c797ad604cd1","0000000000000000","0000000000000000","3fd67373e75e0d24","3f606e3590943f6a","3fd9f97d98b86006","0000000000000000","0000000000000000"],[1,1],[1013904223,0,1,1,0]]
Actual context, config and continuation-field inventory
modelIdentity
iv53:tiny-b1-d2-h1-ffn3-default-encoder-v1
dataIdentity
iv53:a,b:abab-bpe-lex-v1:merges0:eos-off+512:position0:classes97,98,512:target512:mask1:b1-v1
operationIdentity
iv53:binary64-separate-rn:class-ascending:gradient-feature-order:adam-half-eps1e-8:lcg32-highbit-eager-prefetch-v1

Config slots: optimizer, etaWord, beta1Word, beta2Word, epsilonWord. Continuation fields: theta[15], m[15], v[15], tAdam, completedUpdates, rng, order[2], cursor, epoch.

Array-only standard JSON with ten fixed slots. Forty-five state and four config floats use sixteen-digit lowercase big-endian binary64 words. Decode validates structure/config/context, not authentic origin. Saved original text is retained; no editable parser UI or re-encode computation is needed.

All 49 actual encoded/decoded words and signed int32 halves
Word / fieldActual hexadecimal wordEncoded high / lowDecoded high / low
0: eta3fb999999999999a1069128089 / -17179869181069128089 / -1717986918
1: beta13fe00000000000001071644672 / 01071644672 / 0
2: beta23fe00000000000001071644672 / 01071644672 / 0
3: epsilon3e45798ee2308c3a1044740494 / -5001348541044740494 / -500134854
4: theta:u003feccccccd19a87b1072483532 / -8539564851072483532 / -853956485
5: theta:u01bfb9999979d5fb57-1078355559 / 2044066647-1078355559 / 2044066647
6: theta:u023fb99999975df58a1069128089 / -17554499741069128089 / -1755449974
7: theta:u0300000000000000000 / 00 / 0
8: theta:u0400000000000000000 / 00 / 0
9: theta:u103fb999998e225ed01069128089 / -19103501281069128089 / -1910350128
10: theta:u113ff19999901f70f61072798105 / -18769876581072798105 / -1876987658
11: theta:u12bfb999998ef0b674-1078355559 / -1896827276-1078355559 / -1896827276
12: theta:u1300000000000000000 / 00 / 0
13: theta:u1400000000000000000 / 00 / 0
14: theta:b0bfb999999478ece6-1078355559 / -1804014362-1078355559 / -1804014362
15: theta:b1bfb9999955c96af8-1078355559 / 1439263480-1078355559 / 1439263480
16: theta:b23fb9999994d534581069128089 / -17979667601069128089 / -1797966760
17: theta:b300000000000000000 / 00 / 0
18: theta:b400000000000000000 / 00 / 0
19: m:u003fec9c88c5eedb421072471176 / -9742020461072471176 / -974202046
20: m:u013fb14eb44143c7841068584628 / 10949610281068584628 / 1094961028
21: m:u02bfeec65f4e175433-1074870689 / 1310151731-1074870689 / 1310151731
22: m:u0300000000000000000 / 00 / 0
23: m:u0400000000000000000 / 00 / 0
24: m:u10bfc7f94df2b3f7c4-1077413555 / -223086652-1077413555 / -223086652
25: m:u11bf8d0111405670fe-1081278191 / 1079406846-1081278191 / 1079406846
26: m:u123fc9c95f06b95ed41070188895 / 1128117321070188895 / 112811732
27: m:u1300000000000000000 / 00 / 0
28: m:u1400000000000000000 / 00 / 0
29: m:b03fdacdb70b19202a1071304119 / 1861960101071304119 / 186196010
30: m:b13fa036bd258d5ed31067464381 / 6300218431067464381 / 630021843
31: m:b2bfdcd48eafcacc05-1076046706 / -1345663995-1076046706 / -1345663995
32: m:b300000000000000000 / 00 / 0
33: m:b400000000000000000 / 00 / 0
34: v:u003ff994ed12346fc41073321197 / 3054263721073321197 / 305426372
35: v:u013f82b8c2301b1a511065531586 / 8070825771065531586 / 807082577
36: v:u023ffd98c06eedf6fb1073584320 / 18610890191073584320 / 1861089019
37: v:u0300000000000000000 / 00 / 0
38: v:u0400000000000000000 / 00 / 0
39: v:u103fb1f5f652b1a41c1068627446 / 13873735961068627446 / 1387373596
40: v:u113f3a49ef4db9ff111060784623 / 13040350891060784623 / 1304035089
41: v:u123fb4c797ad604cd11068812183 / -13861978071068812183 / -1386197807
42: v:u1300000000000000000 / 00 / 0
43: v:u1400000000000000000 / 00 / 0
44: v:b03fd67373e75e0d241071018867 / -4132666521071018867 / -413266652
45: v:b13f606e3590943f6a1063284277 / -18693326301063284277 / -1869332630
46: v:b23fd9f97d98b860061071249789 / -17327472581071249789 / -1732747258
47: v:b300000000000000000 / 00 / 0
48: v:b400000000000000000 / 00 / 0
Selected word eta: genuine encode/decode operands

Config is grouped in one frame per phase; each parameter frame groups θ/m/v at that coordinate. The frames retain all actual conversions, including the selected word; grouping adds no model or codec computation here.

encode_config: encode: four actual config words

setFloat64(value,bigEndian); high=getInt32(0); low=getInt32(4); word=hex32(high)||hex32(low)

Four genuine conversions in eta,beta1,beta2,epsilon order. Signed int32 halves are bit evidence, not overflowed unsigned tensor values.

Saved inputs
optimizer
1
eta
0.1
beta1
0.5
beta2
0.5
epsilon
1e-8
Saved outputs
etaHigh
1069128089
etaLow
-1717986918
beta1High
1071644672
beta1Low
0
beta2High
1071644672
beta2Low
0
epsilonHigh
1044740494
epsilonLow
-500134854

decode_config: decode: four actual config words

parse high/low hex; setUint32 halves bigEndian; value=getFloat64(0)

Four genuine conversions in eta,beta1,beta2,epsilon order. Signed int32 halves are bit evidence, not overflowed unsigned tensor values.

Saved inputs
optimizer
1
etaHigh
1069128089
etaLow
-1717986918
beta1High
1071644672
beta1Low
0
beta2High
1071644672
beta2Low
0
epsilonHigh
1044740494
epsilonLow
-500134854
Saved outputs
eta
0.1
beta1
0.5
beta2
0.5
epsilon
1e-8

Full coordinate and field comparisons

Float flags use Object.is on actual values, which distinguishes signed zero. Discrete counters, RNG, order entries, cursor and epoch use exact integer value equality. A flag of 1 means equal; 0 means different. The tables preserve every coordinate, including inactive parameters and zero moments.

All 45 float-state equality flags: prefix/decoded and baseline/resumed
ParameterRound-trip θ / m / vFinal θ / m / v
u001 / 1 / 11 / 1 / 1
u011 / 1 / 11 / 1 / 1
u021 / 1 / 11 / 1 / 1
u031 / 1 / 11 / 1 / 1
u041 / 1 / 11 / 1 / 1
u101 / 1 / 11 / 1 / 1
u111 / 1 / 11 / 1 / 1
u121 / 1 / 11 / 1 / 1
u131 / 1 / 11 / 1 / 1
u141 / 1 / 11 / 1 / 1
b01 / 1 / 11 / 1 / 1
b11 / 1 / 11 / 1 / 1
b21 / 1 / 11 / 1 / 1
b31 / 1 / 11 / 1 / 1
b41 / 1 / 11 / 1 / 1
Every discrete continuation coordinate and equality flag
FieldPrefixDecodedRound-trip flagBaseline finalResumed finalFinal flag
tAdam111331
completedUpdates111331
rng101390422310139042231119643576211964357621
order0001001
order1111111
cursor111111
epoch001111
Every paired update: sample/loss flags and all gradient/state/field flags
Update indexSample / PRE-update NLL15 gradient flags15 θ flags15 m flags15 v flags7 discrete field flags
11 / 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1
21 / 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1
31 / 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 1, 1, 1, 1, 1
Selected coordinate and all paired-update comparison operands

compare_parameter_0: Compare actual decoded and final coordinate bits

finite float equality=Object.is, including signed zero; compare theta,m,v separately

Every coordinate is compared. Final differences are allowed for declared interventions; unchanged interventions are also legitimate.

Saved inputs
k
0
prefixtheta
0.9000000005592165
decodedtheta
0.9000000005592165
baselinetheta
0.7605388749226576
resumedtheta
0.7605388749226576
prefixm
0.8941081872825196
decodedm
0.8941081872825196
baselinem
0.9597410168414111
resumedm
0.9597410168414111
prefixv
1.5988589011312664
decodedv
1.5988589011312664
baselinev
1.5054829890144459
resumedv
1.5054829890144459
Saved outputs
roundtriptheta
1
thetaEqual
1
roundtripm
1
mEqual
1
roundtripv
1
vEqual
1

compare_fields: Compare every discrete continuation field

integer fields use exact numeric value equality; order has two separately compared entries

Weights alone cannot certify future RNG, iterator or optimizer-counter restoration. No normal-history relation is substituted for these actual field comparisons.

Saved inputs
prefix_tAdam
1
decoded_tAdam
1
baseline_tAdam
3
resumed_tAdam
3
prefix_completedUpdates
1
decoded_completedUpdates
1
baseline_completedUpdates
3
resumed_completedUpdates
3
prefix_rng
1013904223
decoded_rng
1013904223
baseline_rng
1196435762
resumed_rng
1196435762
prefix_order0
0
decoded_order0
0
baseline_order0
0
resumed_order0
0
prefix_order1
1
decoded_order1
1
baseline_order1
1
resumed_order1
1
prefix_cursor
1
decoded_cursor
1
baseline_cursor
1
resumed_cursor
1
prefix_epoch
0
decoded_epoch
0
baseline_epoch
1
resumed_epoch
1
Saved outputs
roundtrip_tAdam
1
equal_tAdam
1
roundtrip_completedUpdates
1
equal_completedUpdates
1
roundtrip_rng
1
equal_rng
1
roundtrip_order0
1
equal_order0
1
roundtrip_order1
1
equal_order1
1
roundtrip_cursor
1
equal_cursor
1
roundtrip_epoch
1
equal_epoch
1

compare_update_1: Compare corresponding actual update records

compare sample, pre-update loss, all15 gradients, all45 post-update coordinates and all7 discrete fields

Corresponding optimizer-update indices are paired across different trace prefixes. Floating equality preserves zero signs; integer fields have value semantics.

Saved inputs
baselineSample
0
resumedSample
0
baselineLoss
2.312099658912116
resumedLoss
2.312099658912116
baselineGradient0
1.7882163745650392
resumedGradient0
1.7882163745650392
baselinetheta0
0.9000000005592165
resumedtheta0
0.9000000005592165
baselinem0
0.8941081872825196
resumedm0
0.8941081872825196
baselinev0
1.5988589011312664
resumedv0
1.5988589011312664
baselineGradient1
0.13521435915714275
resumedGradient1
0.13521435915714275
baselinetheta1
-0.09999999260433633
resumedtheta1
-0.09999999260433633
baselinem1
0.06760717957857137
resumedm1
0.06760717957857137
baselinev1
0.009141461461138397
resumedv1
0.009141461461138397
baselineGradient2
-1.923430733722182
resumedGradient2
-1.923430733722182
baselinetheta2
0.09999999948009566
resumedtheta2
0.09999999948009566
baselinem2
-0.961715366861091
resumedm2
-0.961715366861091
baselinev2
1.849792893713526
resumedv2
1.849792893713526
baselineGradient3
0
resumedGradient3
0
baselinetheta3
0
resumedtheta3
0
baselinem3
0
resumedm3
0
baselinev3
0
resumedv3
0
baselineGradient4
0
resumedGradient4
0
baselinetheta4
0
resumedtheta4
0
baselinem4
0
resumedm4
0
baselinev4
0
resumedv4
0
baselineGradient5
-0.37459133817162305
resumedGradient5
-0.37459133817162305
baselinetheta5
0.0999999973304242
resumedtheta5
0.0999999973304242
baselinem5
-0.18729566908581152
resumedm5
-0.18729566908581152
baselinev5
0.07015933531660362
resumedv5
0.07015933531660362
baselineGradient6
-0.028324384261950712
resumedGradient6
-0.028324384261950712
baselinetheta6
1.0999999646947436
resumedtheta6
1.0999999646947436
baselinem6
-0.014162192130975356
resumedm6
-0.014162192130975356
baselinev6
0.0004011353719093206
resumedv6
0.0004011353719093206
baselineGradient7
0.40291572243357376
resumedGradient7
0.40291572243357376
baselinetheta7
-0.09999999751809147
resumedtheta7
-0.09999999751809147
baselinem7
0.20145786121678688
resumedm7
0.20145786121678688
baselinev7
0.08117053969208433
resumedv7
0.08117053969208433
baselineGradient8
0
resumedGradient8
0
baselinetheta8
0
resumedtheta8
0
baselinem8
0
resumedm8
0
baselinev8
0
resumedv8
0
baselineGradient9
0
resumedGradient9
0
baselinetheta9
0
resumedtheta9
0
baselinem9
0
resumedm9
0
baselinev9
0
resumedv9
0
baselineGradient10
0.8376116959343609
resumedGradient10
0.8376116959343609
baselinetheta10
-0.09999999880612939
resumedtheta10
-0.09999999880612939
baselinem10
0.41880584796718046
resumedm10
0.41880584796718046
baselinev10
0.35079667658301816
resumedv10
0.35079667658301816
baselineGradient11
0.063335248630547
resumedGradient11
0.063335248630547
baselinetheta11
-0.09999998421100631
resumedtheta11
-0.09999998421100631
baselinem11
0.0316676243152735
resumedm11
0.0316676243152735
baselinev11
0.002005676859546603
resumedv11
0.002005676859546603
baselineGradient12
-0.900946944564908
resumedGradient12
-0.900946944564908
baselinetheta12
0.09999999889005673
resumedtheta12
0.09999999889005673
baselinem12
-0.450473472282454
resumedm12
-0.450473472282454
baselinev12
0.4058526984604217
resumedv12
0.4058526984604217
baselineGradient13
0
resumedGradient13
0
baselinetheta13
0
resumedtheta13
0
baselinem13
0
resumedm13
0
baselinev13
0
resumedv13
0
baselineGradient14
0
resumedGradient14
0
baselinetheta14
0
resumedtheta14
0
baselinem14
0
resumedm14
0
baselinev14
0
resumedv14
0
baseline_tAdam
1
resumed_tAdam
1
baseline_completedUpdates
1
resumed_completedUpdates
1
baseline_rng
1013904223
resumed_rng
1013904223
baseline_order0
0
resumed_order0
0
baseline_order1
1
resumed_order1
1
baseline_cursor
1
resumed_cursor
1
baseline_epoch
0
resumed_epoch
0
Saved outputs
sampleEqual
1
lossEqual
1
gradient0
1
theta0
1
m0
1
v0
1
gradient1
1
theta1
1
m1
1
v1
1
gradient2
1
theta2
1
m2
1
v2
1
gradient3
1
theta3
1
m3
1
v3
1
gradient4
1
theta4
1
m4
1
v4
1
gradient5
1
theta5
1
m5
1
v5
1
gradient6
1
theta6
1
m6
1
v6
1
gradient7
1
theta7
1
m7
1
v7
1
gradient8
1
theta8
1
m8
1
v8
1
gradient9
1
theta9
1
m9
1
v9
1
gradient10
1
theta10
1
m10
1
v10
1
gradient11
1
theta11
1
m11
1
v11
1
gradient12
1
theta12
1
m12
1
v12
1
gradient13
1
theta13
1
m13
1
v13
1
gradient14
1
theta14
1
m14
1
v14
1
equal_tAdam
1
equal_completedUpdates
1
equal_rng
1
equal_order0
1
equal_order1
1
equal_cursor
1
equal_epoch
1

compare_update_2: Compare corresponding actual update records

compare sample, pre-update loss, all15 gradients, all45 post-update coordinates and all7 discrete fields

Corresponding optimizer-update indices are paired across different trace prefixes. Floating equality preserves zero signs; integer fields have value semantics.

Saved inputs
baselineSample
1
resumedSample
1
baselineLoss
2.601286581751801
resumedLoss
2.601286581751801
baselineGradient0
-0.029106416729557414
resumedGradient0
-0.029106416729557414
baselinetheta0
0.8441592477753874
resumedtheta0
0.8441592477753874
baselinem0
0.4325008852764811
resumedm0
0.4325008852764811
baselinev0
0.7998530423130505
resumedv0
0.7998530423130505
baselineGradient1
-0.384933732624635
resumedGradient1
-0.384933732624635
baselinetheta1
-0.03467564265885317
resumedtheta1
-0.03467564265885317
baselinem1
-0.1586632765230318
resumedm1
-0.1586632765230318
baselinev1
0.07865771998673618
resumedv1
0.07865771998673618
baselineGradient2
0.41404014935419237
resumedGradient2
0.41404014935419237
baselinetheta2
0.13145360479317333
resumedtheta2
0.13145360479317333
baselinem2
-0.2738376087534493
resumedm2
-0.2738376087534493
baselinev2
1.010611069495384
resumedv2
1.010611069495384
baselineGradient3
0
resumedGradient3
0
baselinetheta3
0
resumedtheta3
0
baselinem3
0
resumedm3
0
baselinev3
0
resumedv3
0
baselineGradient4
0
resumedGradient4
0
baselinetheta4
0
resumedtheta4
0
baselinem4
0
resumedm4
0
baselinev4
0
resumedv4
0
baselineGradient5
0.13894760955967903
resumedGradient5
0.13894760955967903
baselinetheta5
0.11319790057695953
resumedtheta5
0.11319790057695953
baselinem5
-0.02417402976306625
resumedm5
-0.02417402976306625
baselinev5
0.044732886759476315
resumedv5
0.044732886759476315
baselineGradient6
1.8375886830742476
resumedGradient6
1.8375886830742476
baselinetheta6
1.0189843883800016
resumedtheta6
1.0189843883800016
baselinem6
0.9117132454716361
resumedm6
0.9117132454716361
baselinev6
1.6885666517672284
resumedv6
1.6885666517672284
baselineGradient7
-1.9765362926339265
resumedGradient7
-1.9765362926339265
baselinetheta7
-0.027422561343627833
resumedtheta7
-0.027422561343627833
baselinem7
-0.8875392157085698
resumedm7
-0.8875392157085698
baselinev7
1.9939331278955756
resumedv7
1.9939331278955756
baselineGradient8
0
resumedGradient8
0
baselinetheta8
0
resumedtheta8
0
baselinem8
0
resumedm8
0
baselinev8
0
resumedv8
0
baselineGradient9
0
resumedGradient9
0
baselinetheta9
0
resumedtheta9
0
baselinem9
0
resumedm9
0
baselinev9
0
resumedv9
0
baselineGradient10
0.0650839263887275
resumedGradient10
0.0650839263887275
baselinetheta10
-0.16630811553606428
resumedtheta10
-0.16630811553606428
baselinem10
0.24194488717795398
resumedm10
0.24194488717795398
baselinev10
0.17751629702859573
resumedv10
0.17751629702859573
baselineGradient11
0.8607379929814124
resumedGradient11
0.8607379929814124
baselinetheta11
-0.184539279161325
resumedtheta11
-0.184539279161325
baselinem11
0.44620280864834294
resumedm11
0.44620280864834294
baselinev11
0.37143778471060823
resumedv11
0.37143778471060823
baselineGradient12
-0.9258219193701398
resumedGradient12
-0.9258219193701398
baselinetheta12
0.19999183218723152
resumedtheta12
0.19999183218723152
baselinem12
-0.6881476958262969
resumedm12
-0.6881476958262969
baselinev12
0.6314994624233157
resumedv12
0.6314994624233157
baselineGradient13
0
resumedGradient13
0
baselinetheta13
0
resumedtheta13
0
baselinem13
0
resumedm13
0
baselinev13
0
resumedv13
0
baselineGradient14
0
resumedGradient14
0
baselinetheta14
0
resumedtheta14
0
baselinem14
0
resumedm14
0
baselinev14
0
resumedv14
0
baseline_tAdam
2
resumed_tAdam
2
baseline_completedUpdates
2
resumed_completedUpdates
2
baseline_rng
1196435762
resumed_rng
1196435762
baseline_order0
0
resumed_order0
0
baseline_order1
1
resumed_order1
1
baseline_cursor
0
resumed_cursor
0
baseline_epoch
1
resumed_epoch
1
Saved outputs
sampleEqual
1
lossEqual
1
gradient0
1
theta0
1
m0
1
v0
1
gradient1
1
theta1
1
m1
1
v1
1
gradient2
1
theta2
1
m2
1
v2
1
gradient3
1
theta3
1
m3
1
v3
1
gradient4
1
theta4
1
m4
1
v4
1
gradient5
1
theta5
1
m5
1
v5
1
gradient6
1
theta6
1
m6
1
v6
1
gradient7
1
theta7
1
m7
1
v7
1
gradient8
1
theta8
1
m8
1
v8
1
gradient9
1
theta9
1
m9
1
v9
1
gradient10
1
theta10
1
m10
1
v10
1
gradient11
1
theta11
1
m11
1
v11
1
gradient12
1
theta12
1
m12
1
v12
1
gradient13
1
theta13
1
m13
1
v13
1
gradient14
1
theta14
1
m14
1
v14
1
equal_tAdam
1
equal_completedUpdates
1
equal_rng
1
equal_order0
1
equal_order1
1
equal_cursor
1
equal_epoch
1

compare_update_3: Compare corresponding actual update records

compare sample, pre-update loss, all15 gradients, all45 post-update coordinates and all7 discrete fields

Corresponding optimizer-update indices are paired across different trace prefixes. Floating equality preserves zero signs; integer fields have value semantics.

Saved inputs
baselineSample
0
resumedSample
0
baselineLoss
1.4540385869339927
resumedLoss
1.4540385869339927
baselineGradient0
1.486981148406341
resumedGradient0
1.486981148406341
baselinetheta0
0.7605388749226576
resumedtheta0
0.7605388749226576
baselinem0
0.9597410168414111
resumedm0
0.9597410168414111
baselinev0
1.5054829890144459
resumedv0
1.5054829890144459
baselineGradient1
0.14915236118586062
resumedGradient1
0.14915236118586062
baselinetheta1
-0.032412308041331515
resumedtheta1
-0.032412308041331515
baselinem1
-0.004755457668585594
resumedm1
-0.004755457668585594
baselinev1
0.0504520734170268
resumedv1
0.0504520734170268
baselineGradient2
-1.6361335095922014
resumedGradient2
-1.6361335095922014
baselinetheta2
0.20663998409818538
resumedtheta2
0.20663998409818538
baselinem2
-0.9549855591728253
resumedm2
-0.9549855591728253
baselinev2
1.8437719653529392
resumedv2
1.8437719653529392
baselineGradient3
0
resumedGradient3
0
baselinetheta3
0
resumedtheta3
0
baselinem3
0
resumedm3
0
baselinev3
0
resumedv3
0
baselineGradient4
0
resumedGradient4
0
baselinetheta4
0
resumedtheta4
0
baselinem4
0
resumedm4
0
baselinev4
0
resumedv4
0
baselineGradient5
-0.31148929522189045
resumedGradient5
-0.31148929522189045
baselinetheta5
0.18059021127773017
resumedtheta5
0.18059021127773017
baselinem5
-0.16783166249247836
resumedm5
-0.16783166249247836
baselinev5
0.07087923389865317
resumedv5
0.07087923389865317
baselineGradient6
-0.03124408397258901
resumedGradient6
-0.03124408397258901
baselinetheta6
0.9677796070389142
resumedtheta6
0.9677796070389142
baselinem6
0.44023458074952354
resumedm6
0.44023458074952354
baselinev6
0.8447714222752573
resumedv6
0.8447714222752573
baselineGradient7
0.3427333791944794
resumedGradient7
0.3427333791944794
baselinetheta7
0.000919898299477015
resumedtheta7
0.000919898299477015
baselinem7
-0.2724029182570452
resumedm7
-0.2724029182570452
baselinev7
1.0556996485548211
resumedv7
1.0556996485548211
baselineGradient8
0
resumedGradient8
0
baselinetheta8
0
resumedtheta8
0
baselinem8
0
resumedm8
0
baselinev8
0
resumedv8
0
baselineGradient9
0
resumedGradient9
0
baselinetheta9
0
resumedtheta9
0
baselinem9
0
resumedm9
0
baselinev9
0
resumedv9
0
baselineGradient10
0.6965112383796475
resumedGradient10
0.6965112383796475
baselinetheta10
-0.2534555769595162
resumedtheta10
-0.2534555769595162
baselinem10
0.4692280627788007
resumedm10
0.4692280627788007
baselinev10
0.33132210110887295
resumedv10
0.33132210110887295
baselineGradient11
0.06986389565742071
resumedGradient11
0.06986389565742071
baselinetheta11
-0.24813221548050912
resumedtheta11
-0.24813221548050912
baselinem11
0.2580333521528818
resumedm11
0.2580333521528818
baselinev11
0.1881593743135196
resumedv11
0.1881593743135196
baselineGradient12
-0.766375134037068
resumedGradient12
-0.766375134037068
baselinetheta12
0.29958507880364216
resumedtheta12
0.29958507880364216
baselinem12
-0.7272614149316825
resumedm12
-0.7272614149316825
baselinev12
0.6094151542468249
resumedv12
0.6094151542468249
baselineGradient13
0
resumedGradient13
0
baselinetheta13
0
resumedtheta13
0
baselinem13
0
resumedm13
0
baselinev13
0
resumedv13
0
baselineGradient14
0
resumedGradient14
0
baselinetheta14
0
resumedtheta14
0
baselinem14
0
resumedm14
0
baselinev14
0
resumedv14
0
baseline_tAdam
3
resumed_tAdam
3
baseline_completedUpdates
3
resumed_completedUpdates
3
baseline_rng
1196435762
resumed_rng
1196435762
baseline_order0
0
resumed_order0
0
baseline_order1
1
resumed_order1
1
baseline_cursor
1
resumed_cursor
1
baseline_epoch
1
resumed_epoch
1
Saved outputs
sampleEqual
1
lossEqual
1
gradient0
1
theta0
1
m0
1
v0
1
gradient1
1
theta1
1
m1
1
v1
1
gradient2
1
theta2
1
m2
1
v2
1
gradient3
1
theta3
1
m3
1
v3
1
gradient4
1
theta4
1
m4
1
v4
1
gradient5
1
theta5
1
m5
1
v5
1
gradient6
1
theta6
1
m6
1
v6
1
gradient7
1
theta7
1
m7
1
v7
1
gradient8
1
theta8
1
m8
1
v8
1
gradient9
1
theta9
1
m9
1
v9
1
gradient10
1
theta10
1
m10
1
v10
1
gradient11
1
theta11
1
m11
1
v11
1
gradient12
1
theta12
1
m12
1
v12
1
gradient13
1
theta13
1
m13
1
v13
1
gradient14
1
theta14
1
m14
1
v14
1
equal_tAdam
1
equal_completedUpdates
1
equal_rng
1
equal_order0
1
equal_order1
1
equal_cursor
1
equal_epoch
1

finish: Disclose the actual complete experiment and comparisons

realUpdates=3+split+(3-split); full state/trajectory equality reduce every saved flag

No final objective evaluation, extra encoder calls, dropped no-op updates or truncated helper frames. Bit losslessness and same-backend deterministic continuation are separate from external origin/backend guarantees.

Saved inputs
tokenizerFrames
34
forwardFrames
114
split
1
mode
0
Saved outputs
realUpdates
6
readoutCalls
6
rngDraws
3
roundtripEqual
1
thetaEqual
1
mEqual
1
vEqual
1
stateEqual
1
trajectoryEqual
1
baselineCompleted
3
resumedCompleted
3

Mode 1 under SGD resets moments already zero. Mode 3 at split 2 resets cursor 0 to 0. At η=0 weights can agree while Adam memory still evolves. With seed 0/split 1/mode 2, samples and weight arithmetic can agree while RNG differs; seed 3 changes the third sample, without guaranteeing every weight or loss differs. The tables report the actual case rather than manufacturing divergence.

Actual fixed documents, tokenizer and full initial forward traces

docA: "a"

Content IDs [97]; one-EOS sequence [97,512]; corpus "abab"; reconstruction "a". Zero merges requested: no training round or pair selection occurs.

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

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

docB: "b"

Content IDs [98]; one-EOS sequence [98,512]; corpus "abab"; reconstruction "b". Zero merges requested: no training round or pair selection occurs.

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

forwardB_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
98
Saved outputs
inputRow
1
x0
0
x1
1

forwardB_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
0
x1
1
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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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
0
right
-0.4472135954999579
Saved outputs
value
-0.4472135954999579

forwardB_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
1
right
0.4472135954999579
Saved outputs
value
1.4472135954999579

forwardB_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
-0.4472135954999579
x1
1.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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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

forwardB_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.6876854075163181

forwardB_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

forwardB_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
w0
1
h1
0.6876854075163181
w1
0
h2
0
w2
0
bias
0
Saved outputs
product0
0
product1
0
product2
0
running0
0
running1
0
running2
0
sum
0
value
0

forwardB_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
w0
0
h1
0.6876854075163181
w1
1
h2
0
w2
0
bias
0
Saved outputs
product0
0
product1
0.6876854075163181
product2
0
running0
0
running1
0.6876854075163181
running2
0.6876854075163181
sum
0.6876854075163181
value
0.6876854075163181

forwardB_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
-0.4472135954999579
right
0
Saved outputs
value
-0.4472135954999579

forwardB_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
1.4472135954999579
right
0.6876854075163181
Saved outputs
value
2.134899003016276

forwardB_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
-0.4472135954999579
u0
1
y1
2.134899003016276
u1
0
bias
0
Saved outputs
product0
-0.4472135954999579
product1
0
sum
-0.4472135954999579
logit
-0.4472135954999579

forwardB_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
-0.4472135954999579
u0
0
y1
2.134899003016276
u1
1
bias
0
Saved outputs
product0
-0
product1
2.134899003016276
sum
2.134899003016276
logit
2.134899003016276

forwardB_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
-0.4472135954999579
u0
0
y1
2.134899003016276
u1
0
bias
0
Saved outputs
product0
-0
product1
0
sum
0
logit
0

forwardB_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
-0.4472135954999579
z1
2.134899003016276
z2
0
Saved outputs
max
2.134899003016276

forwardB_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
-0.4472135954999579
max
2.134899003016276
Saved outputs
shifted
-2.582112598516234
term
0.0756140929478022

forwardB_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
2.134899003016276
max
2.134899003016276
Saved outputs
shifted
0
term
1

forwardB_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

forwardB_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
0.0756140929478022
term1
1
term2
0.11825653332669596
max
2.134899003016276
Saved outputs
running0
0.0756140929478022
running1
1.0756140929478022
running2
1.1938706262744982
denominator
1.1938706262744982
logS
0.17720065589584005
lse
2.312099658912116

forwardB_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
0.0756140929478022
denominator
1.1938706262744982
Saved outputs
probability
0.063335248630547

forwardB_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
1
denominator
1.1938706262744982
Saved outputs
probability
0.8376116959343609

forwardB_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

forwardB_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
-0.4472135954999579
z1
2.134899003016276
z2
0
Saved outputs
nextRow
1
nextID
98
nextProbability
0.8376116959343609

Mode0 identity follows from exact decoded state and deterministic transitions on the same operation backend. Word losslessness does not prove cross-language, CPU/GPU, libm, compiler, fusion or nondeterministic backend identity. Changing selected samples means these pre-update losses are not one monotone evaluation curve.

Actual saved Y comes from two complete old forwards. Each readout, NLL and gradient uses the same current-theta evaluation. Finite public helper operands alone do not authenticate encoder origin or historical execution. Normal count/order relations are witnessed facts, never universal decoder guards.

All values and operations above come from the saved public root. The complete inspector below retains every tensor’s axes, shape, dtype, precision, provenance and stored values. Display indexing does not rerun a model, regenerate a checkpoint or create a separate raw state.

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

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

Initial_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

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

Initial_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

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

Initial_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

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

Initial_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
00
10

Initial_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

Initial_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

Initial_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
10

baseline_1_Before_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

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

baseline_1_Before_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

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

baseline_1_Before_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

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

baseline_1_Before_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
00
10

baseline_1_Before_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

baseline_1_Before_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

baseline_1_Before_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
10

baseline_1_ClassIDs

Class=3 · int32 · precision 0 · Actual baseline_1 current 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

baseline_1_Z

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

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20

baseline_1_Shifted

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

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

baseline_1_Terms

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

Zero-based storage indexStored value
01
10.0756140929478022
20.11825653332669596

baseline_1_Denominator

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

Zero-based storage indexStored value
01.1938706262744982

baseline_1_LogS

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

Zero-based storage indexStored value
00.17720065589584005

baseline_1_LSE

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

Zero-based storage indexStored value
02.312099658912116

baseline_1_P

Class=3 · float64 · precision 8 · Actual baseline_1 current 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.8376116959343609
10.063335248630547
20.09905305543509206

baseline_1_NextRow

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

Zero-based storage indexStored value
00

baseline_1_NextID

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

Zero-based storage indexStored value
097

baseline_1_NextProbability

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

Zero-based storage indexStored value
00.8376116959343609

baseline_1_Loss

LossField=9 · float64 · precision 8 · Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.

Zero-based storage indexStored value
02.134899003016276
10
20.17720065589584005
30.09905305543509206
42.134899003016276
52.312099658912116
62.312099658912116
72.312099658912116
82.312099658912116

baseline_1_dLogits

PredictionRow=1 × ModelRow=5 · float64 · precision 8 · Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
2-0.900946944564908
30
40

baseline_1_dU

D=2 × ModelRow=5 · float64 · precision 8 · Actual fixed Y products accumulated from zero in the accepted helper order.

Zero-based storage indexStored value
01.7882163745650392
10.13521435915714275
2-1.923430733722182
30
40
5-0.37459133817162305
6-0.028324384261950712
70.40291572243357376
80
90

baseline_1_db

ModelRow=5 · float64 · precision 8 · Actual same-evaluation logit derivatives accumulated from zero.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
2-0.900946944564908
30
40

baseline_1_Gradient

Parameter=15 · float64 · precision 8 · All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.

Zero-based storage indexStored value
01.7882163745650392
10.13521435915714275
2-1.923430733722182
30
40
5-0.37459133817162305
6-0.028324384261950712
70.40291572243357376
80
90
100.8376116959343609
110.063335248630547
12-0.900946944564908
130
140

baseline_1_After_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

baseline_1_After_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

baseline_1_After_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

baseline_1_After_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

baseline_1_After_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

baseline_1_After_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

baseline_1_After_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

baseline_2_Before_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

baseline_2_Before_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

baseline_2_Before_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

baseline_2_Before_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

baseline_2_Before_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

baseline_2_Before_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

baseline_2_Before_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

baseline_2_ClassIDs

Class=3 · int32 · precision 0 · Actual baseline_2 current 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

baseline_2_Z

Class=3 · float64 · precision 8 · Actual baseline_2 current 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.2890023404038279
12.293110199976295
2-0.15821125543043435

baseline_2_Shifted

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

Zero-based storage indexStored value
0-2.582112540380123
10
2-2.4513214554067293

baseline_2_Terms

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

Zero-based storage indexStored value
00.07561409734371163
11
20.08617962868459328

baseline_2_Denominator

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

Zero-based storage indexStored value
01.1617937260283049

baseline_2_LogS

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

Zero-based storage indexStored value
00.14996512634507148

baseline_2_LSE

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

Zero-based storage indexStored value
02.4430753263213667

baseline_2_P

Class=3 · float64 · precision 8 · Actual baseline_2 current 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.0650839263887275
10.8607379929814124
20.07417808062986017

baseline_2_NextRow

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

Zero-based storage indexStored value
01

baseline_2_NextID

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

Zero-based storage indexStored value
098

baseline_2_NextProbability

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

Zero-based storage indexStored value
00.8607379929814124

baseline_2_Loss

LossField=9 · float64 · precision 8 · Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.

Zero-based storage indexStored value
02.293110199976295
1-0.15821125543043435
20.14996512634507148
30.07417808062986017
42.4513214554067293
52.601286581751801
62.601286581751801
72.601286581751801
82.601286581751801

baseline_2_dLogits

PredictionRow=1 × ModelRow=5 · float64 · precision 8 · Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.

Zero-based storage indexStored value
00.0650839263887275
10.8607379929814124
2-0.9258219193701398
30
40

baseline_2_dU

D=2 × ModelRow=5 · float64 · precision 8 · Actual fixed Y products accumulated from zero in the accepted helper order.

Zero-based storage indexStored value
0-0.029106416729557414
1-0.384933732624635
20.41404014935419237
30
40
50.13894760955967903
61.8375886830742476
7-1.9765362926339265
80
90

baseline_2_db

ModelRow=5 · float64 · precision 8 · Actual same-evaluation logit derivatives accumulated from zero.

Zero-based storage indexStored value
00.0650839263887275
10.8607379929814124
2-0.9258219193701398
30
40

baseline_2_Gradient

Parameter=15 · float64 · precision 8 · All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.

Zero-based storage indexStored value
0-0.029106416729557414
1-0.384933732624635
20.41404014935419237
30
40
50.13894760955967903
61.8375886830742476
7-1.9765362926339265
80
90
100.0650839263887275
110.8607379929814124
12-0.9258219193701398
130
140

baseline_2_After_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.8441592477753874
1-0.03467564265885317
20.13145360479317333
30
40
50.11319790057695953
61.0189843883800016
7-0.027422561343627833
80
90
10-0.16630811553606428
11-0.184539279161325
120.19999183218723152
130
140

baseline_2_After_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.4325008852764811
1-0.1586632765230318
2-0.2738376087534493
30
40
5-0.02417402976306625
60.9117132454716361
7-0.8875392157085698
80
90
100.24194488717795398
110.44620280864834294
12-0.6881476958262969
130
140

baseline_2_After_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
00.7998530423130505
10.07865771998673618
21.010611069495384
30
40
50.044732886759476315
61.6885666517672284
71.9939331278955756
80
90
100.17751629702859573
110.37143778471060823
120.6314994624233157
130
140

baseline_2_After_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
02
12

baseline_2_After_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

baseline_2_After_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

baseline_2_After_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
11

baseline_3_Before_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.8441592477753874
1-0.03467564265885317
20.13145360479317333
30
40
50.11319790057695953
61.0189843883800016
7-0.027422561343627833
80
90
10-0.16630811553606428
11-0.184539279161325
120.19999183218723152
130
140

baseline_3_Before_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.4325008852764811
1-0.1586632765230318
2-0.2738376087534493
30
40
5-0.02417402976306625
60.9117132454716361
7-0.8875392157085698
80
90
100.24194488717795398
110.44620280864834294
12-0.6881476958262969
130
140

baseline_3_Before_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
00.7998530423130505
10.07865771998673618
21.010611069495384
30
40
50.044732886759476315
61.6885666517672284
71.9939331278955756
80
90
100.17751629702859573
110.37143778471060823
120.6314994624233157
130
140

baseline_3_Before_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
02
12

baseline_3_Before_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

baseline_3_Before_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

baseline_3_Before_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
11

baseline_3_ClassIDs

Class=3 · int32 · precision 0 · Actual baseline_3 current 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

baseline_3_Z

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

Zero-based storage indexStored value
01.5852629808065108
1-0.7142719461884053
20.49289574425937477

baseline_3_Shifted

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

Zero-based storage indexStored value
00
1-2.299534926994916
2-1.092367236547136

baseline_3_Terms

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

Zero-based storage indexStored value
01
10.10030548224885925
20.33542153103865646

baseline_3_Denominator

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

Zero-based storage indexStored value
01.4357270132875155

baseline_3_LogS

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

Zero-based storage indexStored value
00.3616713503868567

baseline_3_LSE

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

Zero-based storage indexStored value
01.9469343311933676

baseline_3_P

Class=3 · float64 · precision 8 · Actual baseline_3 current 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.6965112383796475
10.06986389565742071
20.23362486596293197

baseline_3_NextRow

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

Zero-based storage indexStored value
00

baseline_3_NextID

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

Zero-based storage indexStored value
097

baseline_3_NextProbability

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

Zero-based storage indexStored value
00.6965112383796475

baseline_3_Loss

LossField=9 · float64 · precision 8 · Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.

Zero-based storage indexStored value
01.5852629808065108
10.49289574425937477
20.3616713503868567
30.23362486596293197
41.092367236547136
51.4540385869339927
61.4540385869339927
71.4540385869339927
81.4540385869339927

baseline_3_dLogits

PredictionRow=1 × ModelRow=5 · float64 · precision 8 · Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.

Zero-based storage indexStored value
00.6965112383796475
10.06986389565742071
2-0.766375134037068
30
40

baseline_3_dU

D=2 × ModelRow=5 · float64 · precision 8 · Actual fixed Y products accumulated from zero in the accepted helper order.

Zero-based storage indexStored value
01.486981148406341
10.14915236118586062
2-1.6361335095922014
30
40
5-0.31148929522189045
6-0.03124408397258901
70.3427333791944794
80
90

baseline_3_db

ModelRow=5 · float64 · precision 8 · Actual same-evaluation logit derivatives accumulated from zero.

Zero-based storage indexStored value
00.6965112383796475
10.06986389565742071
2-0.766375134037068
30
40

baseline_3_Gradient

Parameter=15 · float64 · precision 8 · All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.

Zero-based storage indexStored value
01.486981148406341
10.14915236118586062
2-1.6361335095922014
30
40
5-0.31148929522189045
6-0.03124408397258901
70.3427333791944794
80
90
100.6965112383796475
110.06986389565742071
12-0.766375134037068
130
140

baseline_3_After_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.7605388749226576
1-0.032412308041331515
20.20663998409818538
30
40
50.18059021127773017
60.9677796070389142
70.000919898299477015
80
90
10-0.2534555769595162
11-0.24813221548050912
120.29958507880364216
130
140

baseline_3_After_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.9597410168414111
1-0.004755457668585594
2-0.9549855591728253
30
40
5-0.16783166249247836
60.44023458074952354
7-0.2724029182570452
80
90
100.4692280627788007
110.2580333521528818
12-0.7272614149316825
130
140

baseline_3_After_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5054829890144459
10.0504520734170268
21.8437719653529392
30
40
50.07087923389865317
60.8447714222752573
71.0556996485548211
80
90
100.33132210110887295
110.1881593743135196
120.6094151542468249
130
140

baseline_3_After_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
03
13

baseline_3_After_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

baseline_3_After_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

baseline_3_After_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
11

BaselineFinal_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.7605388749226576
1-0.032412308041331515
20.20663998409818538
30
40
50.18059021127773017
60.9677796070389142
70.000919898299477015
80
90
10-0.2534555769595162
11-0.24813221548050912
120.29958507880364216
130
140

BaselineFinal_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.9597410168414111
1-0.004755457668585594
2-0.9549855591728253
30
40
5-0.16783166249247836
60.44023458074952354
7-0.2724029182570452
80
90
100.4692280627788007
110.2580333521528818
12-0.7272614149316825
130
140

BaselineFinal_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5054829890144459
10.0504520734170268
21.8437719653529392
30
40
50.07087923389865317
60.8447714222752573
71.0556996485548211
80
90
100.33132210110887295
110.1881593743135196
120.6094151542468249
130
140

BaselineFinal_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
03
13

BaselineFinal_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

BaselineFinal_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

BaselineFinal_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
11

prefix_1_Before_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

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

prefix_1_Before_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

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

prefix_1_Before_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

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

prefix_1_Before_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
00
10

prefix_1_Before_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

prefix_1_Before_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

prefix_1_Before_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
10

prefix_1_ClassIDs

Class=3 · int32 · precision 0 · Actual prefix_1 current 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

prefix_1_Z

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

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20

prefix_1_Shifted

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

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

prefix_1_Terms

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

Zero-based storage indexStored value
01
10.0756140929478022
20.11825653332669596

prefix_1_Denominator

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

Zero-based storage indexStored value
01.1938706262744982

prefix_1_LogS

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

Zero-based storage indexStored value
00.17720065589584005

prefix_1_LSE

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

Zero-based storage indexStored value
02.312099658912116

prefix_1_P

Class=3 · float64 · precision 8 · Actual prefix_1 current 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.8376116959343609
10.063335248630547
20.09905305543509206

prefix_1_NextRow

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

Zero-based storage indexStored value
00

prefix_1_NextID

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

Zero-based storage indexStored value
097

prefix_1_NextProbability

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

Zero-based storage indexStored value
00.8376116959343609

prefix_1_Loss

LossField=9 · float64 · precision 8 · Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.

Zero-based storage indexStored value
02.134899003016276
10
20.17720065589584005
30.09905305543509206
42.134899003016276
52.312099658912116
62.312099658912116
72.312099658912116
82.312099658912116

prefix_1_dLogits

PredictionRow=1 × ModelRow=5 · float64 · precision 8 · Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
2-0.900946944564908
30
40

prefix_1_dU

D=2 × ModelRow=5 · float64 · precision 8 · Actual fixed Y products accumulated from zero in the accepted helper order.

Zero-based storage indexStored value
01.7882163745650392
10.13521435915714275
2-1.923430733722182
30
40
5-0.37459133817162305
6-0.028324384261950712
70.40291572243357376
80
90

prefix_1_db

ModelRow=5 · float64 · precision 8 · Actual same-evaluation logit derivatives accumulated from zero.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
2-0.900946944564908
30
40

prefix_1_Gradient

Parameter=15 · float64 · precision 8 · All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.

Zero-based storage indexStored value
01.7882163745650392
10.13521435915714275
2-1.923430733722182
30
40
5-0.37459133817162305
6-0.028324384261950712
70.40291572243357376
80
90
100.8376116959343609
110.063335248630547
12-0.900946944564908
130
140

prefix_1_After_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

prefix_1_After_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

prefix_1_After_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

prefix_1_After_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

prefix_1_After_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

prefix_1_After_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

prefix_1_After_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

Prefix_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

Prefix_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

Prefix_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

Prefix_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

Prefix_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

Prefix_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

Prefix_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

Decoded_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

Decoded_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

Decoded_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

Decoded_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

Decoded_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

Decoded_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

Decoded_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

Recovered_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

Recovered_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

Recovered_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

Recovered_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

Recovered_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

Recovered_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

Recovered_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

resume_2_Before_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.9000000005592165
1-0.09999999260433633
20.09999999948009566
30
40
50.0999999973304242
61.0999999646947436
7-0.09999999751809147
80
90
10-0.09999999880612939
11-0.09999998421100631
120.09999999889005673
130
140

resume_2_Before_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.8941081872825196
10.06760717957857137
2-0.961715366861091
30
40
5-0.18729566908581152
6-0.014162192130975356
70.20145786121678688
80
90
100.41880584796718046
110.0316676243152735
12-0.450473472282454
130
140

resume_2_Before_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5988589011312664
10.009141461461138397
21.849792893713526
30
40
50.07015933531660362
60.0004011353719093206
70.08117053969208433
80
90
100.35079667658301816
110.002005676859546603
120.4058526984604217
130
140

resume_2_Before_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
01
11

resume_2_Before_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01013904223

resume_2_Before_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

resume_2_Before_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
10

resume_2_ClassIDs

Class=3 · int32 · precision 0 · Actual resume_2 current 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

resume_2_Z

Class=3 · float64 · precision 8 · Actual resume_2 current 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.2890023404038279
12.293110199976295
2-0.15821125543043435

resume_2_Shifted

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

Zero-based storage indexStored value
0-2.582112540380123
10
2-2.4513214554067293

resume_2_Terms

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

Zero-based storage indexStored value
00.07561409734371163
11
20.08617962868459328

resume_2_Denominator

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

Zero-based storage indexStored value
01.1617937260283049

resume_2_LogS

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

Zero-based storage indexStored value
00.14996512634507148

resume_2_LSE

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

Zero-based storage indexStored value
02.4430753263213667

resume_2_P

Class=3 · float64 · precision 8 · Actual resume_2 current 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.0650839263887275
10.8607379929814124
20.07417808062986017

resume_2_NextRow

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

Zero-based storage indexStored value
01

resume_2_NextID

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

Zero-based storage indexStored value
098

resume_2_NextProbability

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

Zero-based storage indexStored value
00.8607379929814124

resume_2_Loss

LossField=9 · float64 · precision 8 · Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.

Zero-based storage indexStored value
02.293110199976295
1-0.15821125543043435
20.14996512634507148
30.07417808062986017
42.4513214554067293
52.601286581751801
62.601286581751801
72.601286581751801
82.601286581751801

resume_2_dLogits

PredictionRow=1 × ModelRow=5 · float64 · precision 8 · Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.

Zero-based storage indexStored value
00.0650839263887275
10.8607379929814124
2-0.9258219193701398
30
40

resume_2_dU

D=2 × ModelRow=5 · float64 · precision 8 · Actual fixed Y products accumulated from zero in the accepted helper order.

Zero-based storage indexStored value
0-0.029106416729557414
1-0.384933732624635
20.41404014935419237
30
40
50.13894760955967903
61.8375886830742476
7-1.9765362926339265
80
90

resume_2_db

ModelRow=5 · float64 · precision 8 · Actual same-evaluation logit derivatives accumulated from zero.

Zero-based storage indexStored value
00.0650839263887275
10.8607379929814124
2-0.9258219193701398
30
40

resume_2_Gradient

Parameter=15 · float64 · precision 8 · All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.

Zero-based storage indexStored value
0-0.029106416729557414
1-0.384933732624635
20.41404014935419237
30
40
50.13894760955967903
61.8375886830742476
7-1.9765362926339265
80
90
100.0650839263887275
110.8607379929814124
12-0.9258219193701398
130
140

resume_2_After_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.8441592477753874
1-0.03467564265885317
20.13145360479317333
30
40
50.11319790057695953
61.0189843883800016
7-0.027422561343627833
80
90
10-0.16630811553606428
11-0.184539279161325
120.19999183218723152
130
140

resume_2_After_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.4325008852764811
1-0.1586632765230318
2-0.2738376087534493
30
40
5-0.02417402976306625
60.9117132454716361
7-0.8875392157085698
80
90
100.24194488717795398
110.44620280864834294
12-0.6881476958262969
130
140

resume_2_After_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
00.7998530423130505
10.07865771998673618
21.010611069495384
30
40
50.044732886759476315
61.6885666517672284
71.9939331278955756
80
90
100.17751629702859573
110.37143778471060823
120.6314994624233157
130
140

resume_2_After_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
02
12

resume_2_After_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

resume_2_After_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

resume_2_After_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
11

resume_3_Before_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.8441592477753874
1-0.03467564265885317
20.13145360479317333
30
40
50.11319790057695953
61.0189843883800016
7-0.027422561343627833
80
90
10-0.16630811553606428
11-0.184539279161325
120.19999183218723152
130
140

resume_3_Before_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.4325008852764811
1-0.1586632765230318
2-0.2738376087534493
30
40
5-0.02417402976306625
60.9117132454716361
7-0.8875392157085698
80
90
100.24194488717795398
110.44620280864834294
12-0.6881476958262969
130
140

resume_3_Before_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
00.7998530423130505
10.07865771998673618
21.010611069495384
30
40
50.044732886759476315
61.6885666517672284
71.9939331278955756
80
90
100.17751629702859573
110.37143778471060823
120.6314994624233157
130
140

resume_3_Before_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
02
12

resume_3_Before_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

resume_3_Before_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

resume_3_Before_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
00
11

resume_3_ClassIDs

Class=3 · int32 · precision 0 · Actual resume_3 current 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

resume_3_Z

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

Zero-based storage indexStored value
01.5852629808065108
1-0.7142719461884053
20.49289574425937477

resume_3_Shifted

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

Zero-based storage indexStored value
00
1-2.299534926994916
2-1.092367236547136

resume_3_Terms

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

Zero-based storage indexStored value
01
10.10030548224885925
20.33542153103865646

resume_3_Denominator

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

Zero-based storage indexStored value
01.4357270132875155

resume_3_LogS

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

Zero-based storage indexStored value
00.3616713503868567

resume_3_LSE

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

Zero-based storage indexStored value
01.9469343311933676

resume_3_P

Class=3 · float64 · precision 8 · Actual resume_3 current 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.6965112383796475
10.06986389565742071
20.23362486596293197

resume_3_NextRow

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

Zero-based storage indexStored value
00

resume_3_NextID

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

Zero-based storage indexStored value
097

resume_3_NextProbability

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

Zero-based storage indexStored value
00.6965112383796475

resume_3_Loss

LossField=9 · float64 · precision 8 · Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.

Zero-based storage indexStored value
01.5852629808065108
10.49289574425937477
20.3616713503868567
30.23362486596293197
41.092367236547136
51.4540385869339927
61.4540385869339927
71.4540385869339927
81.4540385869339927

resume_3_dLogits

PredictionRow=1 × ModelRow=5 · float64 · precision 8 · Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.

Zero-based storage indexStored value
00.6965112383796475
10.06986389565742071
2-0.766375134037068
30
40

resume_3_dU

D=2 × ModelRow=5 · float64 · precision 8 · Actual fixed Y products accumulated from zero in the accepted helper order.

Zero-based storage indexStored value
01.486981148406341
10.14915236118586062
2-1.6361335095922014
30
40
5-0.31148929522189045
6-0.03124408397258901
70.3427333791944794
80
90

resume_3_db

ModelRow=5 · float64 · precision 8 · Actual same-evaluation logit derivatives accumulated from zero.

Zero-based storage indexStored value
00.6965112383796475
10.06986389565742071
2-0.766375134037068
30
40

resume_3_Gradient

Parameter=15 · float64 · precision 8 · All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.

Zero-based storage indexStored value
01.486981148406341
10.14915236118586062
2-1.6361335095922014
30
40
5-0.31148929522189045
6-0.03124408397258901
70.3427333791944794
80
90
100.6965112383796475
110.06986389565742071
12-0.766375134037068
130
140

resume_3_After_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.7605388749226576
1-0.032412308041331515
20.20663998409818538
30
40
50.18059021127773017
60.9677796070389142
70.000919898299477015
80
90
10-0.2534555769595162
11-0.24813221548050912
120.29958507880364216
130
140

resume_3_After_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.9597410168414111
1-0.004755457668585594
2-0.9549855591728253
30
40
5-0.16783166249247836
60.44023458074952354
7-0.2724029182570452
80
90
100.4692280627788007
110.2580333521528818
12-0.7272614149316825
130
140

resume_3_After_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5054829890144459
10.0504520734170268
21.8437719653529392
30
40
50.07087923389865317
60.8447714222752573
71.0556996485548211
80
90
100.33132210110887295
110.1881593743135196
120.6094151542468249
130
140

resume_3_After_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
03
13

resume_3_After_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

resume_3_After_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

resume_3_After_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
11

ResumedFinal_Theta

Parameter=15 · float64 · precision 8 · Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.

Zero-based storage indexStored value
00.7605388749226576
1-0.032412308041331515
20.20663998409818538
30
40
50.18059021127773017
60.9677796070389142
70.000919898299477015
80
90
10-0.2534555769595162
11-0.24813221548050912
120.29958507880364216
130
140

ResumedFinal_M

Parameter=15 · float64 · precision 8 · Detached actual first moments, preserving all finite bits including signed zero.

Zero-based storage indexStored value
00.9597410168414111
1-0.004755457668585594
2-0.9549855591728253
30
40
5-0.16783166249247836
60.44023458074952354
7-0.2724029182570452
80
90
100.4692280627788007
110.2580333521528818
12-0.7272614149316825
130
140

ResumedFinal_V

Parameter=15 · float64 · precision 8 · Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.

Zero-based storage indexStored value
01.5054829890144459
10.0504520734170268
21.8437719653529392
30
40
50.07087923389865317
60.8447714222752573
71.0556996485548211
80
90
100.33132210110887295
110.1881593743135196
120.6094151542468249
130
140

ResumedFinal_Counters

Counter=2 · int32 · precision 0 · Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.

Zero-based storage indexStored value
03
13

ResumedFinal_RNG

RNGState=1 · float64 · precision 0 · Exact uint32 future generator state stored as float64, never overflowed into signed int32.

Zero-based storage indexStored value
01196435762

ResumedFinal_Order

OrderPosition=2 · int32 · precision 0 · Actual independently authoritative current prefetched two-item order.

Zero-based storage indexStored value
00
11

ResumedFinal_Position

IteratorField=2 · int32 · precision 0 · Ordered cursor,epoch; structural state does not certify relation to completedUpdates.

Zero-based storage indexStored value
01
11

CheckpointBits

Word=49 × Half=2 · int32 · precision 0 · All49 actual big-endian binary64 conversions: four config then theta15,m15,v15; signed int32 high/low halves, no flattened oversized axis.

Zero-based storage indexStored value
01069128089
1-1717986918
21071644672
30
41071644672
50
61044740494
7-500134854
81072483532
9-853956485
10-1078355559
112044066647
121069128089
13-1755449974
140
150
160
170
181069128089
19-1910350128
201072798105
21-1876987658
22-1078355559
23-1896827276
240
250
260
270
28-1078355559
29-1804014362
30-1078355559
311439263480
321069128089
33-1797966760
340
350
360
370
381072471176
39-974202046
401068584628
411094961028
42-1074870689
431310151731
440
450
460
470
48-1077413555
49-223086652
50-1081278191
511079406846
521070188895
53112811732
540
550
560
570
581071304119
59186196010
601067464381
61630021843
62-1076046706
63-1345663995
640
650
660
670
681073321197
69305426372
701065531586
71807082577
721073584320
731861089019
740
750
760
770
781068627446
791387373596
801060784623
811304035089
821068812183
83-1386197807
840
850
860
870
881071018867
89-413266652
901063284277
91-1869332630
921071249789
93-1732747258
940
950
960
970

DecodedBits

Word=49 × Half=2 · int32 · precision 0 · All49 actual big-endian binary64 conversions: four config then theta15,m15,v15; signed int32 high/low halves, no flattened oversized axis.

Zero-based storage indexStored value
01069128089
1-1717986918
21071644672
30
41071644672
50
61044740494
7-500134854
81072483532
9-853956485
10-1078355559
112044066647
121069128089
13-1755449974
140
150
160
170
181069128089
19-1910350128
201072798105
21-1876987658
22-1078355559
23-1896827276
240
250
260
270
28-1078355559
29-1804014362
30-1078355559
311439263480
321069128089
33-1797966760
340
350
360
370
381072471176
39-974202046
401068584628
411094961028
42-1074870689
431310151731
440
450
460
470
48-1077413555
49-223086652
50-1081278191
511079406846
521070188895
53112811732
540
550
560
570
581071304119
59186196010
601067464381
61630021843
62-1076046706
63-1345663995
640
650
660
670
681073321197
69305426372
701065531586
71807082577
721073584320
731861089019
740
750
760
770
781068627446
791387373596
801060784623
811304035089
821068812183
83-1386197807
840
850
860
870
881071018867
89-413266652
901063284277
91-1869332630
921071249789
93-1732747258
940
950
960
970

RoundtripCoordinatesEqual

StateVector=3 × Parameter=15 · int32 · precision 0 · Object.is equality for prefix versus decoded theta,m,v, in that vector order.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201
211
221
231
241
251
261
271
281
291
301
311
321
331
341
351
361
371
381
391
401
411
421
431
441

FinalCoordinatesEqual

StateVector=3 × Parameter=15 · int32 · precision 0 · Object.is equality for actual baseline versus resumed final theta,m,v, in that vector order.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201
211
221
231
241
251
261
271
281
291
301
311
321
331
341
351
361
371
381
391
401
411
421
431
441

RoundtripFieldsEqual

ContinuationField=7 · int32 · precision 0 · Exact numeric equality for prefix versus decoded fields in texts.comparisonFields order.

Zero-based storage indexStored value
01
11
21
31
41
51
61

FinalFieldsEqual

ContinuationField=7 · int32 · precision 0 · Exact numeric equality for baseline versus resumed fields in texts.comparisonFields order.

Zero-based storage indexStored value
01
11
21
31
41
51
61

TrajectorySampleLossEqual

Update=3 × Comparison=2 · int32 · precision 0 · Per update: actual sample identity, then Object.is pre-update loss equality.

Zero-based storage indexStored value
01
11
21
31
41
51

TrajectoryGradientEqual

Update=3 × Parameter=15 · int32 · precision 0 · Object.is comparison of corresponding actual baseline/interrupted update records; no tolerance or display rounding.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201
211
221
231
241
251
261
271
281
291
301
311
321
331
341
351
361
371
381
391
401
411
421
431
441

TrajectoryThetaEqual

Update=3 × Parameter=15 · int32 · precision 0 · Object.is comparison of corresponding actual baseline/interrupted update records; no tolerance or display rounding.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201
211
221
231
241
251
261
271
281
291
301
311
321
331
341
351
361
371
381
391
401
411
421
431
441

TrajectoryMEqual

Update=3 × Parameter=15 · int32 · precision 0 · Object.is comparison of corresponding actual baseline/interrupted update records; no tolerance or display rounding.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201
211
221
231
241
251
261
271
281
291
301
311
321
331
341
351
361
371
381
391
401
411
421
431
441

TrajectoryVEqual

Update=3 × Parameter=15 · int32 · precision 0 · Object.is comparison of corresponding actual baseline/interrupted update records; no tolerance or display rounding.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201
211
221
231
241
251
261
271
281
291
301
311
321
331
341
351
361
371
381
391
401
411
421
431
441

TrajectoryFieldsEqual

Update=3 × ContinuationField=7 · int32 · precision 0 · Per-update exact numeric field comparisons in texts.comparisonFields order.

Zero-based storage indexStored value
01
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
201

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. Why does this checkpoint save more than the fifteen trainable weights?
2. Fixed format arithmetic: θ, m and v each contain 15 binary64 values; config adds η, β1, β2 and ε. How many 64-bit float words and signed 32-bit halves must be retained?
3. For the current whole saved root, BEFORE any recovery intervention, Prefix order=[0,1], cursor=1, epoch=0, split=1. Which document is pending in the original checkpoint? Inspection selectors do not change this case.
4. For the current whole saved root: seed=0, split=1, mode=0, η=0.1, optimizer=1; roundtripEqual=1, thetaEqual=1, stateEqual=1, trajectoryEqual=1. Which interpretation uses the complete evidence?
5. Fixed transfer cases: split=1, mode=2, η=0.1, Adam. Compare initial seed 0 with initial seed 3. What follows from the hand-derived high-bit orders, without promising universal weight divergence?

The five graded questions are the only graded set. Fixed cases name their settings; current cases use the whole saved root. Inspection selectors preserve inputs, trace selection and graded answers. Editing a raw control, reset or trace navigation clears answers.

Begin with IV-52 — Language-Model Training Steps and Batches for a real gradient and optimizer update, and III-39 — Reproducibility and Numerical Reliability for reproducibility and numerical reliability. Here we separate three claims: preserving stored numbers exactly, reproducing a computation under a specified backend, and knowing where a checkpoint came from. The first can support the second; neither establishes the third.

Use the saved-state lab

Begin with the default full restore. The comparison panel separates Prefix → decoded: all state, Baseline → resumed: final full state, Every corresponding update, and Final weights only. Equal means flag 1; different means flag 0. Round-trip equality concerns the original checkpoint before any recovery change. The other flags concern what happened after recovery and continuation. The six-row table shows each actual selected sample, its pre-update NLL, and both sides of its iterator transition.

There are exactly five editable experiment controls:

LabelMeaning
Initial seed (unsigned 32-bit integer)IV-53-seed; integer 0…4294967295, default 0
Save after this many updatesIV-53-split; choose 1 or 2, default 1
Recovery after decoding the saved checkpointIV-53-mode; complete restore, reset only m/v, reset only future RNG, or reset only cursor; default mode 0
Learning rate η (eta)IV-53-eta; finite number in [0,1], default .1
Optimizer throughout both runsIV-53-optimizer; SGD or Adam with saved moments, default Adam

An edit creates a fresh complete experiment from initial weights and zero memories. It does not append training to the preceding result. Seed and learning rate are native number inputs; split, mode and optimizer are native selectors. A fractional seed reaches the numerical guard and is invalid even though it lies within the numeric input’s endpoints. Invalid drafts retain their visible reason and remove the unavailable result and graded questions. Reset example restores the five defaults, trace position and unanswered questions. The fixed documents have no text editor, and the actual checkpoint JSON is read only.

The five additional native selectors inspect saved evidence. Actual update row (inspection only) (IV-53-row) starts at baseline_1_select and chooses one of the six actual rows. Saved state boundary (inspection only) (IV-53-state) starts at Prefix and exposes every saved boundary. Parameter coordinate (inspection only) (IV-53-parameter) starts at u00 and chooses all fifteen coordinates. Encoded float word (inspection only) (IV-53-word) starts at eta and chooses all 49 words. Model class slot (inspection only) (IV-53-class) starts at EOS slot 2 and includes inactive slots 3 and 4. Those inactive choices show no computed logit, exponential, P or indicator and retain the structural zero derivative.

Inspection changes neither raw controls nor the trace cursor nor graded answers. A mounted selector can retain its selection across an edit/reset; a state name absent from the new result falls back to Prefix. Previous step, Next step and Calculation step (IV-53-trace) navigate the saved operations independently of inspection. Trace navigation clears answers. A matching operation in an open disclosure is marked current; its equation and operands are saved values, not a new calculation.

For one concrete reading route, keep the initial baseline_1 row, select parameter b2, and retain active class slot 2. The fixed-feature table shows X, LN1, R1, LN2, the three hidden values, F and Y from the selected document’s initial forward. The distribution table shows the current z, shifted z, exponential, denominator, logS and P. Follow the target table through gap, NLL, mask multiplication, loss sum and division by N=1. The gradient row gives P−1 for EOS; the b2 contraction accumulates that one derivative from zero. Open the contraction/optimizer disclosure to follow its actual moments, corrections, root, denominator, delta and new weight. The separate fifteen-coordinate table retains the entire simultaneous update.

Next inspect Prefix, Decoded and Recovered to distinguish lossless decoding from an intervention. Important actual continuation boundaries retains every counter, unsigned RNG value, prefetched order, cursor and epoch. Open Actual saved checkpoint JSON (read only), then compare the selected word’s genuine encode/decode operands with the complete 49-row signed-half table. Finally read all 45 coordinate flags, seven discrete-field flags and three corresponding-update comparisons. The complete inspector retains every scalar alias, text and tensor, including axes, shape, dtype, precision and provenance. Here dtype names storage such as float64, int32 or boolean; precision is display metadata; provenance describes which actual calculation supplied a value. The word/half evidence distinguishes signed zero even where an ordinary numeric display prints both signs as 0.

How the existing five questions use this record

The lab above contains the chapter’s only five graded questions. This is a reading key for that same set, not another quiz. Every selected answer immediately shows Correct. or Try again. followed by the same explanatory reasoning; changing an answer permits correction.

Actual question IDCorrect choice in the lab and its reasoning
iv53-continuation-stateThird option: Adam needs moments and its counter, and continuation needs current order/cursor plus future RNG under the same fixed context. A past loss or equal displayed weights cannot replace those dependencies, authenticate origin or certify a different backend.
iv53-word-inventorySecond option: 3×15+4=49 float words, two signed halves each, stored as [49,2] with 98 cells. The integer optimizer/counters/iterator occupy their separate numeric slots. Neither dropping config words nor inventing float words for integer fields describes this format.
iv53-current-prefix-cursorSecond option, filled from the actual current Prefix_Order[Prefix_Position[0]]. At split 1 its saved cursor is 1; at split 2 it is 0. The displayed document can be A or B depending on the actual prefetched order. Decode preserves that pending choice; a fresh RNG draw is not needed on every selection. The case is always original Prefix, before mode 2 or 3, independent of inspection selections.
iv53-current-comparisonFirst option: roundtripEqual compares prefix/decode, while stateEqual and trajectoryEqual compare baseline/resumed evidence. thetaEqual alone is insufficient. The prompt includes the actual seed, split, mode, eta, optimizer and saved flags; its feedback follows the branches explained below.
iv53-fixed-rng-transferThird option for its explicitly fixed split-1/mode-2/eta-.1/Adam cases: seed 0 can keep samples A,B,A and weight arithmetic while RNG differs; seed 3 changes the third sample from B to A. Neither conclusion forces every numerical value to differ or proves another backend or authentic origin.

The comparison feedback covers every recovery mode: mode 0 alters nothing after decode and uses conditional same-backend induction; mode 1 changes only m/v to positive zero and preserves old counters/data; mode 2 changes only future RNG while retaining the current prefetched choice; mode 3 changes only cursor and deliberately leaves epoch/completedUpdates untouched. For SGD it explains that already-zero moments make mode 1 a possible no-op. For Adam it explains that resetting moments retains the old correction step and changes optimizer memory, without claiming every weight must differ. At split 2 it explains cursor 0→0; at split 1 it explains cursor 1→0 with the old order/counters retained. With eta=0 it separates fixed weights from advancing data/counters and Adam memories; with positive eta it rejects guaranteed divergence or guaranteed loss decrease. The feedback compares all 45 floating coordinates and seven discrete coordinates, then the sample/loss/gradient/post-state evidence in the trajectory. Coincident interventions are legitimate results.

What a checkpoint must remember

A checkpoint is a saved description of a computation’s continuation state: the values needed to perform its next operation. A parameter is a model number that training can replace. An optimizer uses derivatives of a loss, called a gradient, to choose parameter changes. Its memory is also state. An iterator determines which example comes next; its cursor is a position in an already selected order.

A random-number generator, abbreviated RNG, is a deterministic rule with saved internal state. A pseudorandom generator produces a repeatable sequence from that state. Its initial seed starts the sequence. Saving the initial seed alone does not say how far the generator has advanced.

This lesson uses two fixed authored documents: A=a and B=b. Their tokenizer converts text into public token IDs, with corpus abab and zero byte-pair merges. Content tokenization has its automatic end marker switched off; one explicit end-of-sequence token, EOS, is appended to each document. Thus the sequences are [97,512] and [98,512]. Each update observes one input token and predicts the known EOS target, ID 512. It does not generate its own training answer.

The fixed tiny decoder first computes both documents’ feature arrays with two genuine isolated forwards. A forward calculates outputs from inputs and current model settings. The saved feature array Y has shape [1,1,2]: one batch item, one input position, two features. Removing its two singleton axes gives a feature row y of shape [2]. We reuse those actual features for readout-only training. The embedding, attention, normalization and feed-forward layers remain fixed; this is not full Transformer backpropagation.

The readout turns features into class scores. Its weight array U has shape [2,5], with feature rows and model-vocabulary columns; its bias b has shape [5]. Only three compact classes are active: a, b and EOS. A compact class index c is an array offset 0, 1 or 2, not the public token ID 97, 98 or 512. The other two stored columns remain present, with structural zero derivatives and no invented probabilities.

Collect the ten U entries followed by the five biases into theta, written θ, a vector of shape [15]. Its order is U00…U04, U10…U14, b0…b4. Initially U00=U11=1 and every other entry is positive zero. The Adam memory vectors m and v each have shape [15], initially zero. A shape lists axis lengths; a tensor is an array with those axes given mathematical roles. Book II’s II.9 — Matrix × vector explains matrix/vector orientation. Here y is a feature row, while U has feature rows and class columns; the equivalent column-vector calculation uses the transpose of U.

State fieldShape or domainWhat the next transition needs it for
theta[15], finite binary64Current readout weights and biases
m[15], finite binary64Adam’s decaying gradient memory
v[15], finite, nonnegative binary64Adam’s decaying squared-gradient memory
tAdamNonnegative integerAdam’s bias correction step
completedUpdatesNonnegative integerNumber of completed optimizer transitions
rngInteger 0…4294967295Source state for the next newly generated order
order[2], either [0,1] or [1,0]Current prefetched document order; 0=A, 1=B
cursorInteger 0 or 1Next position within that saved order
epochNonnegative integerNumber of completed two-example traversals

These are nine named fields, not nine numbers. The three floating vectors contain 45 values. Some information is redundant on an ordinary run; the representation keeps it explicit so that recovery interventions remain understandable. Past gradients, past losses and a full trace are useful evidence, but do not replace these continuation fields. Fixed model, tokenizer, data, arithmetic and optimizer settings must also agree. They are the context in which the state has meaning.

The three-update comparison and the meaning of a loss

The uninterrupted branch starts from a detached initial state and performs three updates. The interrupted branch starts from an identical detached state, performs k updates, saves and decodes a checkpoint, then performs the remaining 3−k updates. The split k is 1 or 2. There are exactly 3+k+(3−k)=6 genuine optimizer transitions across the comparison; the checkpoint is not a seventh training step.

The five raw settings, in order, are seed=0, split=1, mode=0, eta=.1 and optimizer=1. The seed is an unsigned 32-bit integer; split is 1 or 2; mode is an integer 0…3; eta, written η, is the learning rate in [0,1]; optimizer is numeric 0 for plain stochastic gradient descent (SGD), or 1 for Adam. Adam’s two decay factors are fixed at β1=β2=1/2. Its positive stabilizer ε is the binary64 value represented by 1e-8.

For one selected feature row, the class-c logit, or score before normalization, is calculated in this order:

product0 = y0 * U0c
product1 = y1 * U1c
sum = product0 + product1
zc = sum + bc

Softmax turns the three active scores into probabilities. Let M be their maximum, ec=exp(zc−M), and S the sum of these exponentials in compact-class order. Then Pc=ec/S. Here exp is the exponential function and log below is the natural logarithm. The target loss is the negative log-likelihood, NLL:

gap = M − zEOS
NLL = gap + log(S)

Lower NLL means greater probability assigned to the known EOS answer. Its units are nats. This stable formula avoids taking the logarithm of a probability that might have underflowed to zero. The one actual row has loss mask 1, meaning included, and included-target count N=1. The active logit derivative is (Pc−Ic)*1/N, where indicator Ic is 1 for EOS and 0 otherwise. Multiplying that derivative by yd gives the derivative for Udc; it is already the derivative for bc. The gradient g has shape [15], in exactly theta’s order, with explicit zeros for inactive columns.

Every recorded NLL belongs to the parameters before its associated update. The third row is not an evaluation of the final parameters after update three. Different rows may use different documents, so their values are not repeated measurements of one fixed evaluation objective. Neither a monotonic learning curve nor a final objective evaluation follows from these six records. Training may increase a selected loss; reproducibility concerns repeating what happened, not making it improve.

Why Adam’s moments and step cannot be discarded

SGD subtracts η*gk from each old parameter θk. Adam also uses its old memories. Here k indexes a parameter coordinate, while t is the old Adam step. A prime marks a new value and a hat marks bias correction. With both β factors equal to 1/2, the exact-real equations for one coordinate are

t′ = t + 1
m′ = (1/2)*m + (1/2)*g
v′ = (1/2)*v + (1/2)*(g*g)
mHat = m′ / (1 − (1/2)^t′)
vHat = v′ / (1 − (1/2)^t′)
root = sqrt(vHat)
denominator = root + ε
normalized = mHat / denominator
delta = η * normalized
θ′ = θ − delta

The first moment m remembers signed gradients; the second moment v remembers squared gradients. “Moment” here means a decaying summary, not a new model weight. Epsilon is added after the square root. Every new coordinate is computed from the same old state and current gradient; later coordinates do not consume earlier new weights. Completed updates increments for both optimizers; tAdam increments only for Adam. SGD keeps tAdam=0 and zero m/v.

The actual scalar helper separately computes each decay product, gradient square, addition, correction, root and division. The equations do not authorize reassociation or fusion of floating-point operations. At steps 1, 2 and 3 the mathematical powers of 1/2 are exactly 1/2, 1/4 and 1/8; their corrections are 1/2, 3/4 and 7/8. These dyadic fractions are exactly representable in binary64. Matching the helper’s actual power results to those values is a required backend premise to verify later, not a claim about arbitrary power-function accuracy.

Here is a hand example of why memory matters, separate from the actual a/b gradients. Take one legal Adam coordinate with old t=1, next g=1 and η=1. If old m=v=1, the new uncorrected memories are each 1/2+1/2=1; dividing by correction 1−1/4=3/4 gives mHat=vHat=4/3. If recovery instead zeroes both memories while retaining t=1, each new memory is 1/2 and each corrected memory is 2/3. Thus the two proposed parameter subtractions are

(4/3)/(sqrt(4/3)+ε)
(2/3)/(sqrt(2/3)+ε)

They differ in exact-real arithmetic. Keeping weights and the counter while losing moments changes the next calculation. Conversely, keeping zero memories and g=1 but changing old t from 1 to 2 changes the correction from 3/4 to 7/8 and the corrected memories from 2/3 to 4/7. The step count matters too. These rational examples explain dependence; they are not fabricated outputs from the chapter’s training experiment.

Even rounding a memory for display can lose required state. The binary64 numbers 1 and 1+2^-52 are distinct adjacent values near one. With g=0 and β=1/2, the next memories are exactly 1/2 and 1/2+2^-53, also distinct and representable. A short decimal display might show both old values as 1. That display is inadequate for restoration even if a later subtraction happens to round both weights to the same value. The same example applies to a nonnegative v. Save every bit of every coordinate, including inactive ones.

The iterator has already made a choice

An epoch here is one traversal of the two documents. Prefetching means generating the next order before its first example is consumed. The saved current order and cursor determine the next sample immediately. The RNG affects the next fresh order; resetting it does not retroactively change a prefetched choice.

The deliberately small teaching generator is a 32-bit linear congruential generator, or LCG. For current state s, define

product = 1664525 * s
sum = product + 1013904223
next = sum mod 4294967296
bit = floor(next / 2147483648)

The operation mod takes the nonnegative remainder; floor discards the fractional part. Since next lies between 0 and 2^32−1, bit is 0 or 1, the highest binary digit. Bit 0 selects [0,1]; bit 1 selects [1,0]. This is not a cryptographic generator, an industrial shuffle or a claim of independent random choices. The multiplier and addend specify this exact repeatable teaching sequence.

At initialization, advance the raw seed once, save next as rng, save its order, and set cursor=epoch=completedUpdates=0. To update, select order[cursor], perform the real readout/loss/gradient/optimizer transition, then advance cursor. When it reaches 2, reset cursor to 0, increment epoch and immediately advance the RNG to prefetch another order. This includes an epoch boundary reached by the final update. Failed arithmetic must not partly consume an example or advance the saved RNG.

For seed 0, the first multiplication is 0, the sum is 1013904223 and the remainder is 1013904223. This is below 2147483648, so bit=0 and order=[0,1]. For the second draw, all the integer arithmetic is

1664525 * 1013904223 = 1687668926789075
1687668926789075 + 1013904223 = 1687669940693298
1687669940693298 = 392941 * 4294967296 + 1196435762

The second remainder is also below 2147483648. Consequently the first three selected samples are A, B, A. The normal states around them are:

Completed updatesrngordercursorepochNext sample
01013904223[0,1]00A
11013904223[0,1]10B
21196435762[0,1]01A
31196435762[0,1]11B

These are manually derived iterator states, not measured losses. Every product and sum is exact as an integer in binary64: for any unsigned 32-bit s, 1664525*s+1013904223 < (1664525+1)*2^32 < 2^53. Binary64 represents all integers in this range exactly.

Seed 3 gives a useful different case without changing the default. First,

1664525 * 3 = 4993575
4993575 + 1013904223 = 1018897798

The first order is A,B. For the next draw,

1664525 * 1018897798 = 1695980857215950
1695980857215950 + 1013904223 = 1695981871120173
1695981871120173 = 394876 * 4294967296 + 2365144877

Now the remainder exceeds 2147483648, so the second order is B,A and the normal first three samples are A,B,B. Resetting only future RNG to raw seed 3 after update 1 preserves the pending B, then regenerates the first order, making the three samples A,B,A. This establishes a sample difference. It does not prove that all resulting parameters or losses differ.

Decode first, then distinguish recovery experiments

Mode 0 restores every field of the actual prefix checkpoint. The other modes first perform the same complete valid decode and then apply exactly one declared intervention:

ModeRecovery changeFields deliberately retained
1Set all m and v entries to positive zerotheta, tAdam, completedUpdates, RNG and entire iterator
2Set rng to the raw initial seedtheta, moments, counters, current order, cursor and epoch
3Set cursor to 0theta, moments, counters, rng, order and epoch

A mode describes a controlled recovery mistake, not a different decoder standard. Preserve the original saved checkpoint and decoded state separately from the altered continuation. Detached arrays prevent a recovery edit from rewriting earlier evidence.

For a normal run, completedUpdates=2*epoch+cursor, and order equals the order selected by the saved RNG’s high bit. These are facts established by the initialization and normal transitions. They are not structural decoder guards. Mode 3 can break the first relation; mode 2 can break the second. The altered fields still specify legal future operations. Accepting their structure does not authenticate them as a reconstruction of the original history.

Not every mistake causes visible numerical divergence. With SGD the moments are already zero, so mode 1 can change nothing. At split 2 the cursor is already 0, so mode 3 can change nothing. At split 2 the third sample is prefetched, so a future-RNG reset cannot change that sample. With default seed 0 and split 1, mode 2 can preserve samples A,B,A and all weight arithmetic while leaving a different RNG state. At η=0 the parameters can remain fixed while Adam memories, counters and iterator still change. Compare all fields and actual per-coordinate words; matching weights or one loss alone is insufficient evidence of complete restoration.

Store bits rather than rounded decimal appearances

Binary64 is the IEEE floating-point format with one sign bit, eleven exponent bits and 52 explicitly stored fraction bits. A finite value has one exact stored 64-bit pattern. Big-endian order places its most significant byte first. One hexadecimal digit represents four bits, so a full word is exactly sixteen lowercase hexadecimal digits, including leading zeros.

Finite valueCanonical big-endian wordSigned 32-bit high halfSigned 32-bit low half
+0000000000000000000
−08000000000000000−21474836480
1/23fe000000000000010716446720
13ff000000000000010726932480
−1bff0000000000000−10747904000
1+2^-523ff000000000000110726932481

The two halves are signed int32 bit representations, not two floating-point contributions to add. If a signed half h is negative, its unsigned bit-pattern value is h+2^32; otherwise it is h. For −0 the high pattern is hexadecimal 80000000, whose unsigned value is 2147483648 but whose signed int32 value is −2147483648. Decode reconstructs the eight bytes and reads them as binary64; numerically casting an integer half to a float is a different operation.

JavaScript DataView and Python struct provide explicit big-endian byte operations. Writing a finite binary64 number into eight bytes, retaining all eight, then reading those same bytes gives the identical pattern. The fixed-length hex mapping is reversible digit by digit, so decodeFloat(encodeFloat(x)) preserves every finite x’s bits. Nonfinite patterns, including infinities and NaNs, are rejected.

Signed zero deserves care: ordinary numerical equality treats +0 and −0 as equal, and a JavaScript numeric JSON roundtrip can turn −0 into +0. Checkpoint word equality distinguishes them. A JSON string containing "8000000000000000" preserves the sign bit; a bare numeric zero does not provide that guarantee. Even where a zero-moment validity check accepts either sign, lossless serialization retains the actual sign. Display rounding never enters this mapping. Book II’s Rounding and representation error gives the numerical background.

The ten-slot checkpoint and configuration identity

The checkpoint is standard JSON containing arrays, strings and permitted numeric integer fields. JSON is a text format for structured data. Its root is an array of exactly ten ordered slots; arrays inside it also have fixed lengths. Objects are not accepted anywhere.

Root slotContents
0Format version 1
1Fixed-model identity string
2Data and tokenizer identity string
3Operation and binary64 arithmetic identity string
4[optimizer, etaWord, beta1Word, beta2Word, epsilonWord]
5Fifteen theta words
6Fifteen m words
7Fifteen v words
8[tAdam, completedUpdates]
9[rng, order0, order1, cursor, epoch]

There are 49 floating words: 45 state words and four configuration words. Encoding and decoding the configuration are real conversions too. The optimizer choice is a numeric integer, not a fiftieth float word. The signed high/low evidence fits a [49,2] tensor, with Word and Half axes; flattening all 98 halves into one axis would exceed the lesson platform’s per-axis bound of 64. State words alone account for 90 halves, also too many for one axis. Neither unsigned RNG values nor high unsigned bit halves should silently overflow signed int32 storage.

Configuration must be normalized by meaning and stored bits, not by how a user happened to spell a number. Eta is an actual finite numeric value in its domain; its word stores that represented value. Beta and epsilon words must match the fixed represented settings. Integer JSON spellings such as 1, 1.0 and 1e0 have the same integer value and can describe version 1. A boolean is not an integer setting. Python must explicitly reject booleans and range-check arbitrarily large integers before converting them to float.

The identities name the expected compiled experiment. Model identity binds the fixed encoder and vocabulary; data identity binds the actual documents, tokenizer rules, explicit EOS policy, classes and targets; operation identity binds arithmetic order, dtype and prefetch/RNG rules. They are revision labels, not cryptographic hashes, signatures or certificates of origin. Unknown contexts or different configuration cannot silently become a matching checkpoint. Original seed is provenance and the input to mode 2; saving current RNG/order/cursor suffices for normal future draws without reconstructing them from that seed.

A decoder first bounds the actual text length before parsing with the standard JSON parser, then checks every fixed slot, type, identity and configuration value. It accepts only canonical lowercase sixteen-digit float words, decodes them, requires finite theta/m/v and nonnegative v, and checks counter and iterator domains with room for the requested suffix. For fixed Adam, tAdam equals completedUpdates; for SGD tAdam=0 and m/v are zero. At tAdam=0, m/v must also be zero. Finite restored or derived weights are not forced back into initial editor bounds.

For direct raw controls and numerical-state helpers, own data fields and dense ordinary arrays must be validated before captured values are used. Missing fields, extras, symbols, getters and exotic structures are invalid. All five raw numbers are checked for actual finite numeric type in declared order before their domains, including inactive settings. Malformed structure gives INVALID_INPUT; nonnumeric/nonfinite raw values give NONFINITE; finite out-of-domain values give INVALID_INPUT. There is no string coercion or default filling.

The checkpoint decoder itself has a text-only surface. Rejecting all parsed objects also rejects duplicate-key objects categorically, so accepting the checkpoint needs no custom general JSON parser or history registry. Parse syntax failures are handled narrowly around parsing; unexpected implementation exceptions propagate. A pure decoder performs no training, forward, RNG draw or provenance lookup. A structurally coherent fabricated state can pass these checks. That establishes usable structure, not authentic execution origin or guaranteed finiteness of all future arithmetic.

Follow the complete saved record

A defined result has exactly five root fields in order: status, outputs, steps, tensors, texts. A known unavailable result instead has status, code, reason, with no partial successful record. The actual source inventory contains 496 frames, 389 tensors, 67 initial scalar summaries and 49 text entries, including all three genuine RNG draws. These counts describe saved source loops; they are not measurements from a validation run. Each step has exactly id, label, equation, explanation, inputs, outputs.

Begin at setup, then follow the complete docA_ tokenizer, explicit EOS append, docB_ tokenizer and append. Each old tokenizer has 17 frames and 18 tensors. Both initial forwardA_ and forwardB_ witnesses retain all 57 frames and all 57 tensors; initial readout evidence remains present even though repeated training uses only saved Y. initial_rng and initial_state establish the common prefetched state. The baseline visits baseline_1, baseline_2, baseline_3; the interrupted path visits prefix_1 through its split, then encoding, decoding, recovery and the remaining resume_ updates numbered by completed update index.

For an update prefix P such as baseline_1, read these actual saved groups in order:

Saved step or groupArithmetic to inspect
P_selectCurrent order[cursor], observed input and known EOS target
P_readout_0…2Two actual feature products, sum and bias for each active class
P_class_max, P_class_exp_0…2, P_class_normalize, P_class_probability_0…2, P_class_argmaxSaved maximum, shifts, exponentials, ascending sums, logS, probabilities and computed-logit choice
P_lossActual pre-update gap, NLL, masked NLL, accumulation and mean
P_gradient_count, P_gradient_row_0, P_gradient_parameter_0…14N=1, active derivatives and every actual contraction, including inactive zero contributions
P_optimizer_setup, P_optimizer_parameter_0…14Old-state SGD or Adam operations; for Adam the actual powers, corrections, moments and epsilon outside sqrt
P_rng only on wrap, then P_advanceActual eager prefetch if cursor reaches 2, followed by complete committed state and reported normal-history relations

Each update has 48 frames excluding its optional draw. One shared initial draw and one wrap on each branch give three draws. The baseline wrap is baseline_2_rng. The interrupted wrap is prefix_2_rng at split 2; at split 1 it is resume_2_rng for modes 0–2, or resume_3_rng for mode 3. A non-wrap update has no invented RNG frame.

encode_config and decode_config retain all four genuine config conversions. encode_parameter_0…14 and decode_parameter_0…14 each group the theta/m/v conversions for their coordinate. compare_parameter_0…14 compares original prefix versus decode separately from baseline versus resumed final floats. compare_fields retains tAdam, completedUpdates, rng, order0, order1, cursor and epoch; compare_update_1…3 retains samples, losses, every gradient and all post-update state coordinates. finish reduces the actual flags without evaluating a final objective.

Each state boundary has seven tensors: _Theta[15], _M[15], _V[15], _Counters[2], _RNG[1], _Order[2], _Position[2]. Counters are tAdam then completedUpdates; position is cursor then epoch. The unsigned RNG is float64 with precision 0 so every uint32 value remains exact; it is not narrowed into signed int32. Counters/order/position use int32 with precision 0. Theta/m/v use float64 with precision 8. All eighteen boundary groups remain, including both sides of every actual update and the separate Initial, Prefix, Decoded, Recovered, BaselineFinal and ResumedFinal states. Each tensor has exactly id, shape, axes, dtype, values, provenance, precision.

The scalar summaries come first: 45 new summaries, then eleven genuine tokenizer summaries for A and eleven for B. After them, each actual step output has one alias formed from its step ID, underscore and output key: for example baseline_1_loss_meanNLL and decode_parameter_0_theta. These are saved-output names, not additional numerical operations. The 49 text entries comprise 24 context/policy/inventory entries, both tokenizers’ eleven entries, then checkpointJSON, checkpointWords and checkpointConfigWords. State words are theta15, m15, v15; config words are eta, beta1, beta2, epsilon. bitWordOrder puts config first for the [49,2] bit tensors.

The checkpoint’s actual compiled labels are:

model: iv53:tiny-b1-d2-h1-ffn3-default-encoder-v1
data: iv53:a,b:abab-bpe-lex-v1:merges0:eos-off+512:position0:classes97,98,512:target512:mask1:b1-v1
operation: iv53:binary64-separate-rn:class-ascending:gradient-feature-order:adam-half-eps1e-8:lcg32-highbit-eager-prefetch-v1

These labels specify the intended compiled context; copying them into a fabricated checkpoint does not prove its origin or certify a numerical backend. Before parsing, the actual cap is 8192 UTF-16 code units, JavaScript string.length. Python uses the existing explicit UTF-16 counter. A supplementary character such as 🦊 occupies two such units, so 4097 copies exceed the cap even though Python counts 4097 characters. Oversize text gives UNSUPPORTED_SIZE with reason checkpoint text exceeds 8192 UTF-16 code units. before syntax/schema work. This is neither a UTF-8 byte cap nor a normalization rule.

The chapter bounds tAdam, completedUpdates and epoch to integers 0…3, and remaining to 0…3. Require completedUpdates+remaining<=3 and epoch+floor((cursor+remaining)/2)<=3, reserving room for actual future wraps. These are size/headroom checks. They do not reconstruct or authenticate history. Four config word syntaxes and all 45 state word syntaxes are checked before any decoding; config floats are decoded and matched by bits before state floats. The restored v must be nonnegative, including admissible −0. A configuration eta of −0 has a different word from +0 and must match exactly even though both have numerical value zero.

The Python checkpoint parser catches ValueError only around its actual json.loads call. Unknown RuntimeError or RecursionError exceptions propagate; they are not silently classified as an ordinary malformed checkpoint. This narrow boundary differs from validating the decoded state or running a training transition.

Why exact continuation follows under stated conditions

Write C for the fixed context: model/data/tokenizer identities, identical actual features, configuration and backend operation rules. Write S for all nine continuation fields. One successful transition is a function T_C(S) producing the next state, together with a record R_C(S) containing the selected example, its pre-update loss and actual gradient/update arithmetic. Here “function” means equal operands under the same deterministic rules give equal results.

At split k, let Sk be the state reached by the interrupted prefix. Identical initialization and normal transitions make it equal to the uninterrupted state at the same point. A complete lossless roundtrip gives decode(encode(Sk))=Sk: all floating words match bit for bit, and all discrete values match exactly. Mode 0 alters nothing.

For the next transition, equal order and cursor select the same document. Equal actual features and theta produce the same ordered products, logits, distribution, NLL and gradient. Equal m/v/tAdam and configuration produce the same optimizer arithmetic and new parameters. Equal counters and iterator/RNG fields produce the same increment and, when required, the same LCG draw and prefetched order. Thus both next states and their corresponding numerical records agree.

This is the induction step: equality before one transition implies equality after it. Apply it repeatedly for 3−k transitions to obtain the same suffix and final state. Trace prefixes label different branches, so compare corresponding update numbers and numerical fields rather than requiring branch names to be identical. Full evidence includes the actual operations, operands, texts, tensor axes and provenance; a private comparison of three summaries is not a verdict on the complete public record. If an actual transition faults, report its fault rather than inventing a successful suffix.

This argument assumes deterministic operations on the same backend, meaning the combination of numerical implementation, libraries and execution environment. It also assumes any regenerated fixed features match. A serializer alone cannot establish those premises. Different exp/log/sqrt implementations, fused versus separate arithmetic, parallel reduction order, hardware, compiler options or nondeterministic accelerator kernels can change numerical results. Exact TypeScript/Python or CPU/GPU identity requires separate evidence; a word-preserving file format does not supply it. Reproducibility metadata helps specify the conditions, while an authenticated origin would require a separate trust mechanism.

Read the actual Python reference

The twelve panels below display the actual source files. Keep their code/python/pNN/ directories and relative locations together. NumPy supplies real float64 arrays for features and parameter/moment storage, and int32 or boolean arrays for appropriate discrete data. Individual builtin-float products, additions and divisions preserve the declared scalar order; writing an array does not authorize a reordered matrix multiplication. Displaying source does not establish reference execution or validation results.

The file graph is p13/iv53.py → p13/checkpoint_reference.py → p13/training_reference.py. Training loads p13/packing_reference.py, p10/tiny_reference.py and p11/choice_reference.py. Packing loads p09/iv39.py → p09/bpe_reference.py → p09/token_reference.py. Tiny loads the same BPE source plus p07/component_reference.py, p07/ffn_reference.py and p06/head_reference.py. That is twelve distinct source paths; multiple file-relative loads can create more than twelve module instances. The previous chapter’s iv52.py wrapper is not in this closure. Its one-step reset would discard the very optimizer history this lesson must preserve.

Follow the actual helper in this order:

  1. raw_state checks the exact five fields, every actual finite-number type before any finite domain, then compares Python integers against their domains before conversion. optimizer_config fixes the two betas and epsilon. Neither a numeric string nor a boolean is a control value.
  2. fixed_context calls the existing two-document tokenizer and two complete observed-ID forwards. It copies actual Y values from the saved tensors. training_reference.old_forward_prose locally binds the old numerical steps to their adopted labels, equations and explanations; it does not replace their arithmetic or edit the old kernel.
  3. initial_state makes one actual prefetched order and a fifteen-entry theta plus two zero moment vectors. transition validates a detached state, selects its current document, calls finite_readout, scores EOS with mask 1 and N=1, calls readout_gradients, then calls optimizer_update with the old moments and counters. The iterator advances only after successful arithmetic.
  4. encode_checkpoint performs four configuration and 45 state conversions. decode_checkpoint bounds text, parses, validates fixed slots and every word, matches configuration bits and returns detached state. The helper publishes one configuration frame and fifteen grouped parameter frames in each direction. Grouping three conversions per parameter frame retains every actual value and signed half.
  5. recover_state changes only the chosen field after complete valid decode. Continuing uses that resulting state; it never reconstructs moments from theta, resets the Adam step, retokenizes a prediction, or passes derived weights through an initial editor clamp. compare_states compares float bytes and discrete values separately.

This commented reading guide composes those existing helpers. It is executable Python source, not an execution report or a replacement canonical panel. book must be the absolute directory containing this book’s code folder; the helper’s own imports resolve from its file location.

from copy import deepcopy
import importlib.util
from pathlib import Path

book = Path("/media/mario-geometry/WD_SN7100_NVMe/coding-projects/interactive-books-worktrees/book-iv-development/Interactive-Neural-Networks-Transformers-LLMs-Book")
path = book / "code/python/p13/checkpoint_reference.py"
spec = importlib.util.spec_from_file_location("checkpoint_reading_guide", path)
if spec is None or spec.loader is None:
    raise ImportError(f"Cannot load canonical source: {path}")
checkpoint = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checkpoint)

# Actual canonical controls and fixed context, not decimal feature fixtures.
raw = checkpoint.raw_state(dict(checkpoint.DEFAULT_IV53))
config = checkpoint.optimizer_config(raw)
trace = checkpoint._training.TrainingTrace()
context = checkpoint.fixed_context(trace)  # two tokenizers, two complete forwards
initial = checkpoint.initial_state(raw, trace)

# Each loop carries ALL nine fields forward; no one-step wrapper reset.
def continue_updates(start, count, branch):
    current = deepcopy(start)
    rows = []
    for _ in range(count):
        number = current["completedUpdates"] + 1
        row = checkpoint.transition(current, context, config, trace,
                                    f"{branch}_{number}")
        rows.append(row)  # actual pre-update loss, gradient and after-state
        current = deepcopy(row["after"])
    return current, rows

baseline, baseline_rows = continue_updates(initial, 3, "baseline")
prefix, prefix_rows = continue_updates(initial, raw["split"], "prefix")
saved = checkpoint.encode_checkpoint(prefix, config, trace)
decoded = checkpoint.decode_checkpoint(saved["text"], config, trace,
                                      remaining=3 - raw["split"])
recovered = checkpoint.recover_state(decoded["state"], raw, trace)
resumed, resumed_rows = continue_updates(recovered, 3 - raw["split"], "resume")

# These are actual comparison values, not hard-coded expected answers.
roundtrip = checkpoint.compare_states(prefix, decoded["state"])
final_comparison = checkpoint.compare_states(baseline, resumed)
# Retain saved["text"], stateWords, configWords and bits for full inspection.
# This helper composition is not the wrapper's full five-field public record.

The NumPy dimensions in this path are small enough to read without flattening away their meaning. Each fixed forward has Y [1,1,2]; its saved two-value feature row feeds readout logits and probabilities [3]. The gradient helper stores row derivatives [1,5], U derivatives [2,5], bias derivatives [5] and their concatenation [15]. New theta/m/v arrays are each [15]. A flat public dU list still describes the named [2,5] array. Bit evidence has shape [49,2], configuration first, then theta, m and v, high half before low half. Rank counts axes: Y has rank three, U rank two, and theta rank one; rank does not mean the size or quality of the model.

Chapter composition — p13/iv53.py: the actual six-update experiment and public binding source.

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.

"""IV53 actual six-update experiment mechanics — SOURCE ONLY, UNRUN.

Owner-adopted complete public binding preserves both full old tokenizers and
forwards, all six stateful updates, all49 config/state words and every actual
comparison. Import and ordinary queries execute zero self-checks.
"""
from copy import deepcopy
import importlib.util
from pathlib import Path

_spec = importlib.util.spec_from_file_location(
    "_p13_iv53_checkpoint", Path(__file__).resolve().with_name("checkpoint_reference.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent checkpoint_reference.py")
_checkpoint = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_checkpoint)
DEFAULT_IV53 = _checkpoint.DEFAULT_IV53


def mechanics_experiment(state):
    """INTERNAL evidence holder, consumed once by the complete public binder.

    The pure codec uses adopted fixed compiled model/data/operation strings.
    The public binder reuses these actual operations and saved evidence.
    """
    raw = _checkpoint.raw_state(state)
    config = _checkpoint.optimizer_config(raw)
    trace = _checkpoint._training.TrainingTrace()
    trace.add("setup", "Declare the fixed three-update resumption experiment", "baseline3; prefix=split; suffix=3-split; actual updates=6",
              "All five raw finite-number checks precede every finite domain check. Only the fifteen readout parameters train; all old full-forward evidence is retained.",
              dict(raw), dict(totalUpdates=3, realUpdates=6, tokenizerCalls=2, appendedEOS=2, fullForwardCalls=2, classCount=3, trainableParameters=15, beta1=0.5, beta2=0.5, epsilon=1e-8))
    context = _checkpoint.fixed_context(trace)
    initial = _checkpoint.initial_state(raw, trace)

    def updates(start, count, branch):
        current, records = _checkpoint.checkpoint_state(start, raw["optimizer"], count), []
        for _ in range(count):
            index = current["completedUpdates"] + 1
            record = _checkpoint.transition(current, context, config, trace, f"{branch}_{index}")
            records.append(record)
            current = deepcopy(record["after"])
        return current, records

    baseline, baseline_rows = updates(initial, 3, "baseline")
    prefix, prefix_rows = updates(initial, raw["split"], "prefix")
    encoded = _checkpoint.encode_checkpoint(prefix, config, trace)
    decoded = _checkpoint.decode_checkpoint(encoded["text"], config, trace, remaining=3 - raw["split"])
    restored = _checkpoint.recover_state(decoded["state"], raw, trace)
    resumed, resumed_rows = updates(restored, 3 - raw["split"], "resume")
    comparison = _checkpoint.compare_states(baseline, resumed)
    roundtrip = _checkpoint.compare_states(prefix, decoded["state"])
    return dict(raw=raw, config=config, context=context, initial=deepcopy(initial), baseline=baseline,
                prefix=prefix, encoded=encoded, decoded=decoded, restored=restored, resumed=resumed,
                baselineRows=baseline_rows, prefixRows=prefix_rows, resumedRows=resumed_rows,
                comparison=comparison, roundtrip=roundtrip, steps=deepcopy(trace.steps))


def derive_iv53(state):
    """Complete IV53 record; raw5 replacement, actual six updates, no checks."""
    try:
        return _derive_iv53(state)
    except _checkpoint.KNOWN_FAULTS as error:
        return dict(status="unavailable", code=error.code, reason=str(error))


def _derive_iv53(state):
    experiment = mechanics_experiment(state)
    raw, context = experiment["raw"], experiment["context"]
    initial, baseline, prefix = (experiment[key] for key in ("initial", "baseline", "prefix"))
    encoded, decoded, recovered, resumed = (experiment[key] for key in ("encoded", "decoded", "restored", "resumed"))
    baseline_rows, prefix_rows, resumed_rows = (experiment[key] for key in ("baselineRows", "prefixRows", "resumedRows"))
    interrupted_rows = prefix_rows + resumed_rows
    trace = _checkpoint._training.TrainingTrace()
    trace.steps = experiment["steps"]
    tensors, tokenizer_outputs = [], {}
    class_ids = context["classIDs"]
    parameter_keys = list(_checkpoint._training.PARAMETER_KEYS)
    fields = ["tAdam", "completedUpdates", "rng", "order0", "order1", "cursor", "epoch"]
    texts = dict(
        docA="a", docB="b",
        trainingScope="Six genuine readout-only updates: baseline3 plus interrupted prefix and decoded suffix totaling3. Actual old fixed encoder features; no full Transformer gradients or final diagnostic evaluation.",
        tokenizerPolicy="Two actual IV51 helper calls use old EOS-off IV39 tokenization with corpus abab and merges0. Each helper appends exactly one explicit EOS512. Positions restart at zero.",
        objectivePolicy="Each consumed sample has one actual input token, known target EOS512, mask1 and N1. Its loss is evaluated BEFORE its associated update: gap=max-targetLogit; nll=gap+logS; weightedNLL=mask*nll; lossSum=0+weightedNLL; meanNLL=lossSum/N.",
        optimizerPolicy="Fixed beta1=beta2=0.5 and represented epsilon1e-8, outside sqrt. Every coordinate uses the same old theta, moments and gradient; SGD leaves unused Adam moments/tAdam zero. Eta0 still consumes data and advances counters; Adam still updates moments.",
        iteratorPolicy="Draw one pedagogical uint32 LCG state to prefetch the initial two-item order. Select order[cursor]. After a successful update advance cursor; cursor2 resets0, increments epoch and immediately draws/prefetches the next order. RNG is the state for the next fresh order; saved current order is independently authoritative.",
        recoveryPolicy="Decode the valid normal prefix first. Mode0 restores all fields; mode1 changes ONLY m/v to positive zeros; mode2 changes ONLY future RNG to raw seed; mode3 changes ONLY cursor to0. Some interventions coincide with the baseline; no divergence is forced.",
        checkpointPolicy="Array-only standard JSON with ten fixed slots. Forty-five state and four config floats use sixteen-digit lowercase big-endian binary64 words. Decode validates structure/config/context, not authentic origin. Saved original text is retained; no editable parser UI or re-encode computation is needed.",
        numericCoherence="Actual saved Y comes from two complete old forwards. Each readout, NLL and gradient uses the same current-theta evaluation. Finite public helper operands alone do not authenticate encoder origin or historical execution. Normal count/order relations are witnessed facts, never universal decoder guards.",
        backendPolicy="Mode0 identity follows from exact decoded state and deterministic transitions on the same operation backend. Word losslessness does not prove cross-language, CPU/GPU, libm, compiler, fusion or nondeterministic backend identity. Changing selected samples means these pre-update losses are not one monotone evaluation curve.",
        powerPremise="The helper computes and retains actual powers, corrections, root and epsilon arithmetic. The conditional operation premise for beta=1/2 at t1,2,3 is exact powers 1/2,1/4,1/8 and corrections 1/2,3/4,7/8; the later independent validation must check this premise. No arbitrary pow accuracy claim.",
        provenance="Authored fixed raw a/b documents, actual old tokenizer and full forwards, deterministic default encoder and explicit seeded pedagogical LCG. No hidden randomness, external corpus, pretrained weights or history registry.",
        modelVocabulary=[f"compact row {row}: public ID {identifier}" for row, identifier in enumerate(class_ids)],
        parameterKeys=parameter_keys,
        stateFields=["theta[15]", "m[15]", "v[15]", "tAdam", "completedUpdates", "rng", "order[2]", "cursor", "epoch"],
        checkpointSlots=["version", "modelIdentity", "dataIdentity", "operationIdentity", "config", "thetaWords", "mWords", "vWords", "counters", "iterator"],
        configFields=["optimizer", "etaWord", "beta1Word", "beta2Word", "epsilonWord"],
        lossFields=["max", "targetLogit", "logS", "probability", "gap", "nll", "weightedNLL", "lossSum", "meanNLL"],
        comparisonFields=fields,
        bitWordOrder=["eta", "beta1", "beta2", "epsilon"] + [f"{key}:{name}" for key in ("theta", "m", "v") for name in parameter_keys],
        modelIdentity=_checkpoint.CHECKPOINT_IDENTITIES["model"], dataIdentity=_checkpoint.CHECKPOINT_IDENTITIES["data"], operationIdentity=_checkpoint.CHECKPOINT_IDENTITIES["operation"],
    )

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

    def save_int(identifier, shape, axes, values, provenance):
        record = save_float(identifier, shape, axes, values, provenance)
        if any(int(number) != number or number < -2147483648 or number > 2147483647 for number in values):
            raise _checkpoint.NumericalFault("INVALID_INPUT", f"{identifier} requires signed int32 values.")
        record["dtype"], record["precision"] = "int32", 0
        record["values"] = _checkpoint.np.array(values, dtype=_checkpoint.np.int32).reshape(-1).tolist()

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

    def save_state(scope, current):
        save_float(scope + "_Theta", [15], ["Parameter"], current["theta"], "Detached actual continuation parameters in TRAINABLE_KEYS order; finite derived values have no raw editor clamp.")
        save_float(scope + "_M", [15], ["Parameter"], current["m"], "Detached actual first moments, preserving all finite bits including signed zero.")
        save_float(scope + "_V", [15], ["Parameter"], current["v"], "Detached actual nonnegative second moments; numerical nonnegativity admits signed zero.")
        save_int(scope + "_Counters", [2], ["Counter"], [current["tAdam"], current["completedUpdates"]], "Ordered Adam-only tAdam, global completedUpdates; bounded integer value semantics.")
        rng = save_float(scope + "_RNG", [1], ["RNGState"], [current["rng"]], "Exact uint32 future generator state stored as float64, never overflowed into signed int32.")
        rng["precision"] = 0
        save_int(scope + "_Order", [2], ["OrderPosition"], current["order"], "Actual independently authoritative current prefetched two-item order.")
        save_int(scope + "_Position", [2], ["IteratorField"], [current["cursor"], current["epoch"]], "Ordered cursor,epoch; structural state does not certify relation to completedUpdates.")

    for d, document in enumerate(context["documents"]):
        scope = "docA" if d == 0 else "docB"
        old = document["record"]
        save_scoped(old["tensors"], scope, f"Actual {scope} IV39 call; fixed corpus abab, EOS off. ")
        for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"):
            tokenizer_outputs[f"{scope}_{key}"] = old["outputs"][key]
        for key, value in old["texts"].items():
            texts[f"{scope}_{key}"] = deepcopy(value)
        save_int(scope + "_ContentIDs", [len(document["contentIDs"])], ["ContentPosition"], document["contentIDs"].tolist(), "Actual old EOS-off TargetIDs, copied without lookup or retokenization.")
        save_int(scope + "_SequenceIDs", [len(document["sequenceIDs"])], ["DocumentPosition"], document["sequenceIDs"].tolist(), "Actual content IDs followed by exactly one explicit EOS512.")
    save_int("ActiveIDs", [len(class_ids)], ["Class"], class_ids, "Restricted active prediction classes, not the full tokenizer vocabulary; public IDs are labels.")
    for d, forward in enumerate(context["forwards"]):
        scope = "forwardA" if d == 0 else "forwardB"
        save_scoped(forward["result"]["tensors"], scope, f"Actual isolated {scope} at initial weights; positions restart at zero. ")
    save_state("Initial", initial)

    def save_rows(rows, branch):
        for row in rows:
            scope = f"{branch}_{row['after']['completedUpdates']}"
            save_state(scope + "_Before", row["before"])
            distribution, loss, gradients = row["distribution"], row["loss"], row["gradients"]
            save_scoped(distribution["tensors"], scope, f"Actual {scope} current readout on saved initial Y, not another encoder forward. ")
            loss_values = [distribution["max"], distribution["logits"][2], distribution["logS"], distribution["probabilities"][2]] + list(loss.values())
            save_float(scope + "_Loss", [9], ["LossField"], loss_values, "Actual same-evaluation pre-update loss fields in texts.lossFields order; every mask/add/division is performed.")
            save_float(scope + "_dLogits", [1, 5], ["PredictionRow", "ModelRow"], gradients["rowGradients"], "Actual same-evaluation mask*(P-indicator)/N; inactive structural zeros, no fabricated inactive P.")
            save_float(scope + "_dU", [2, 5], ["D", "ModelRow"], gradients["dU"], "Actual fixed Y products accumulated from zero in the accepted helper order.")
            save_float(scope + "_db", [5], ["ModelRow"], gradients["db"], "Actual same-evaluation logit derivatives accumulated from zero.")
            save_float(scope + "_Gradient", [15], ["Parameter"], gradients["gradient"], "All fifteen analytic current-theta readout-only derivatives in TRAINABLE_KEYS order.")
            save_state(scope + "_After", row["after"])

    save_rows(baseline_rows, "baseline")
    save_state("BaselineFinal", baseline)
    save_rows(prefix_rows, "prefix")
    save_state("Prefix", prefix)
    save_state("Decoded", decoded["state"])
    save_state("Recovered", recovered)
    save_rows(resumed_rows, "resume")
    save_state("ResumedFinal", resumed)
    texts.update(checkpointJSON=encoded["text"], checkpointWords=encoded["stateWords"], checkpointConfigWords=encoded["configWords"])
    for name, bits in (("CheckpointBits", encoded["bits"]), ("DecodedBits", decoded["bits"])):
        save_int(name, [49, 2], ["Word", "Half"], bits, "All49 actual big-endian binary64 conversions: four config then theta15,m15,v15; signed int32 high/low halves, no flattened oversized axis.")

    roundtrip, final = [[], [], []], [[], [], []]
    for k in range(15):
        inputs, outputs = dict(k=k), {}
        for a, key in enumerate(("theta", "m", "v")):
            inputs.update({"prefix" + key: prefix[key][k], "decoded" + key: decoded["state"][key][k], "baseline" + key: baseline[key][k], "resumed" + key: resumed[key][k]})
            exact, equal = int(experiment["roundtrip"][key][k]), int(experiment["comparison"][key][k])
            outputs.update({"roundtrip" + key: exact, key + "Equal": equal})
            roundtrip[a].append(exact)
            final[a].append(equal)
        trace.add(f"compare_parameter_{k}", "Compare actual decoded and final coordinate bits",
                  "finite float equality=Object.is, including signed zero; compare theta,m,v separately",
                  "Every coordinate is compared. Final differences are allowed for declared interventions; unchanged interventions are also legitimate.", inputs, outputs)

    def discrete(current):
        return [current["tAdam"], current["completedUpdates"], current["rng"], *current["order"], current["cursor"], current["epoch"]]

    prefix_fields, decoded_fields, baseline_fields, resumed_fields = map(discrete, (prefix, decoded["state"], baseline, resumed))
    roundtrip_fields, final_fields, field_inputs, field_outputs = [], [], {}, {}
    for i, key in enumerate(fields):
        field_inputs.update({"prefix_" + key: prefix_fields[i], "decoded_" + key: decoded_fields[i], "baseline_" + key: baseline_fields[i], "resumed_" + key: resumed_fields[i]})
        exact, equal = int(prefix_fields[i] == decoded_fields[i]), int(baseline_fields[i] == resumed_fields[i])
        field_outputs.update({"roundtrip_" + key: exact, "equal_" + key: equal})
        roundtrip_fields.append(exact)
        final_fields.append(equal)
    trace.add("compare_fields", "Compare every discrete continuation field", "integer fields use exact numeric value equality; order has two separately compared entries",
              "Weights alone cannot certify future RNG, iterator or optimizer-counter restoration. No normal-history relation is substituted for these actual field comparisons.", field_inputs, field_outputs)
    save_int("RoundtripCoordinatesEqual", [3, 15], ["StateVector", "Parameter"], [flag for vector in roundtrip for flag in vector], "Object.is equality for prefix versus decoded theta,m,v, in that vector order.")
    save_int("FinalCoordinatesEqual", [3, 15], ["StateVector", "Parameter"], [flag for vector in final for flag in vector], "Object.is equality for actual baseline versus resumed final theta,m,v, in that vector order.")
    save_int("RoundtripFieldsEqual", [7], ["ContinuationField"], roundtrip_fields, "Exact numeric equality for prefix versus decoded fields in texts.comparisonFields order.")
    save_int("FinalFieldsEqual", [7], ["ContinuationField"], final_fields, "Exact numeric equality for baseline versus resumed fields in texts.comparisonFields order.")
    trajectory = dict(sampleLoss=[], gradient=[], theta=[], m=[], v=[], fields=[])
    for i, (a, b) in enumerate(zip(baseline_rows, interrupted_rows)):
        inputs = dict(baselineSample=a["docID"], resumedSample=b["docID"], baselineLoss=a["loss"]["meanNLL"], resumedLoss=b["loss"]["meanNLL"])
        outputs = dict(sampleEqual=int(a["docID"] == b["docID"]), lossEqual=int(_checkpoint.same_float(a["loss"]["meanNLL"], b["loss"]["meanNLL"])))
        trajectory["sampleLoss"].extend((outputs["sampleEqual"], outputs["lossEqual"]))
        for k in range(15):
            inputs.update({f"baselineGradient{k}": a["gradients"]["gradient"][k], f"resumedGradient{k}": b["gradients"]["gradient"][k]})
            equal = int(_checkpoint.same_float(a["gradients"]["gradient"][k], b["gradients"]["gradient"][k]))
            outputs[f"gradient{k}"] = equal
            trajectory["gradient"].append(equal)
            for key in ("theta", "m", "v"):
                inputs.update({f"baseline{key}{k}": a["after"][key][k], f"resumed{key}{k}": b["after"][key][k]})
                equal = int(_checkpoint.same_float(a["after"][key][k], b["after"][key][k]))
                outputs[f"{key}{k}"] = equal
                trajectory[key].append(equal)
        da, db = discrete(a["after"]), discrete(b["after"])
        for f, key in enumerate(fields):
            inputs.update({"baseline_" + key: da[f], "resumed_" + key: db[f]})
            equal = int(da[f] == db[f])
            outputs["equal_" + key] = equal
            trajectory["fields"].append(equal)
        trace.add(f"compare_update_{i + 1}", "Compare corresponding actual update records",
                  "compare sample, pre-update loss, all15 gradients, all45 post-update coordinates and all7 discrete fields",
                  "Corresponding optimizer-update indices are paired across different trace prefixes. Floating equality preserves zero signs; integer fields have value semantics.", inputs, outputs)
    save_int("TrajectorySampleLossEqual", [3, 2], ["Update", "Comparison"], trajectory["sampleLoss"], "Per update: actual sample identity, then Object.is pre-update loss equality.")
    for name, key in (("Gradient", "gradient"), ("Theta", "theta"), ("M", "m"), ("V", "v")):
        save_int(f"Trajectory{name}Equal", [3, 15], ["Update", "Parameter"], trajectory[key], "Object.is comparison of corresponding actual baseline/interrupted update records; no tolerance or display rounding.")
    save_int("TrajectoryFieldsEqual", [3, 7], ["Update", "ContinuationField"], trajectory["fields"], "Per-update exact numeric field comparisons in texts.comparisonFields order.")
    roundtrip_equal = int(all(flag == 1 for vector in roundtrip for flag in vector) and all(flag == 1 for flag in roundtrip_fields))
    theta_equal, m_equal, v_equal = (int(all(flag == 1 for flag in vector)) for vector in final)
    state_equal = int(theta_equal == m_equal == v_equal == 1 and all(flag == 1 for flag in final_fields))
    trajectory_equal = int(all(flag == 1 for entries in trajectory.values() for flag in entries))
    all_rows = baseline_rows + prefix_rows + resumed_rows
    real_updates = readout_calls = len(all_rows)
    rng_draws = sum(step["id"] == "initial_rng" or step["id"].endswith("_rng") for step in trace.steps)
    tokenizer_frames = sum(len(doc["record"]["steps"]) for doc in context["documents"])
    forward_frames = sum(len(forward["steps"]) for forward in context["forwards"])
    trace.add("finish", "Disclose the actual complete experiment and comparisons", "realUpdates=3+split+(3-split); full state/trajectory equality reduce every saved flag",
              "No final objective evaluation, extra encoder calls, dropped no-op updates or truncated helper frames. Bit losslessness and same-backend deterministic continuation are separate from external origin/backend guarantees.",
              dict(tokenizerFrames=tokenizer_frames, forwardFrames=forward_frames, split=raw["split"], mode=raw["mode"]),
              dict(realUpdates=real_updates, readoutCalls=readout_calls, rngDraws=rng_draws, roundtripEqual=roundtrip_equal, thetaEqual=theta_equal, mEqual=m_equal, vEqual=v_equal,
                   stateEqual=state_equal, trajectoryEqual=trajectory_equal, baselineCompleted=baseline["completedUpdates"], resumedCompleted=resumed["completedUpdates"]))
    if len(trace.steps) > 512:
        raise _checkpoint.NumericalFault("UNSUPPORTED_SIZE", "IV53 supports at most 512 complete trace frames.")
    outputs = dict(
        seed=raw["seed"], split=raw["split"], mode=raw["mode"], eta=raw["eta"], optimizer=raw["optimizer"],
        totalUpdates=3, realUpdates=real_updates, baselineUpdates=len(baseline_rows), prefixUpdates=len(prefix_rows), resumeUpdates=len(resumed_rows),
        tokenizerCalls=2, appendedEOS=2, fullForwardCalls=2, readoutCalls=readout_calls, classCount=len(class_ids), trainableParameters=15, validTargets=1,
        checkpointSlots=10, stateWords=len(encoded["stateWords"]), configWords=len(encoded["configWords"]), totalWords=len(encoded["bits"])//2,
        checkpointCharacters=_checkpoint._training._packing._token.utf16_length(encoded["text"]), checkpointLimit=_checkpoint.MAX_CHECKPOINT_UNITS, encodeFrames=16, decodeFrames=16, rngDraws=rng_draws,
        roundtripEqual=roundtrip_equal, thetaEqual=theta_equal, mEqual=m_equal, vEqual=v_equal, countersEqual=int(final_fields[0] == final_fields[1] == 1), rngEqual=final_fields[2], orderEqual=int(final_fields[3] == final_fields[4] == 1),
        cursorEqual=final_fields[5], epochEqual=final_fields[6], stateEqual=state_equal, trajectoryEqual=trajectory_equal, baselineCompleted=baseline["completedUpdates"], resumedCompleted=resumed["completedUpdates"],
        baselineTAdam=baseline["tAdam"], resumedTAdam=resumed["tAdam"], baselineLossBefore3=baseline_rows[2]["loss"]["meanNLL"], resumedLossBefore3=interrupted_rows[2]["loss"]["meanNLL"],
        frames=len(trace.steps), tensorCount=len(tensors),
    )
    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 run():
    """Default/full raw5 JSON/'-' stdin; --self-check alone is explicit."""
    _checkpoint._training._packing.run(derive_iv53, DEFAULT_IV53, source_self_check)


def source_self_check():
    """Explicit DEFERRED experiment leaf; never calls another check leaf."""
    assert __debug__, "Deferred checks require assertions enabled."
    for optimizer in (0, 1):
        for split in (1, 2):
            record = mechanics_experiment({**DEFAULT_IV53, "optimizer": optimizer, "split": split})
            all_rows = record["baselineRows"] + record["prefixRows"] + record["resumedRows"]
            assert len(all_rows) == 6 and len(record["steps"]) <= 512
            assert len(record["context"]["forwards"]) == 2
            assert all(len(forward["result"]["tensors"]) == 57 for forward in record["context"]["forwards"])
            assert all(all(value) if type(value) is list else value for value in record["comparison"].values())
            assert all(all(value) if type(value) is list else value for value in record["roundtrip"].values())
            for row in all_rows:
                assert row["after"]["completedUpdates"] == row["before"]["completedUpdates"] + 1
                assert row["after"]["completedUpdates"] == 2*row["after"]["epoch"] + row["after"]["cursor"]
                assert row["after"]["order"] == ([0, 1] if row["after"]["rng"] < 2147483648 else [1, 0])
                assert len(row["gradients"]["gradient"]) == 15 and row["gradients"]["validTargets"] == 1
                assert row["loss"]["meanNLL"] == row["loss"]["nll"]
                if optimizer == 1:
                    setup = next(step for step in row["steps"] if step["id"].endswith("_optimizer_setup"))
                    expected = (0.5, 0.25, 0.125)[row["after"]["tAdam"] - 1]
                    assert setup["outputs"]["power1"] == setup["outputs"]["power2"] == expected
            # Pair actual arithmetic records; branch prefixes are presentation.
            continued = record["prefixRows"] + record["resumedRows"]
            for a, b in zip(record["baselineRows"], continued):
                assert a["docID"] == b["docID"] and a["distribution"] == b["distribution"]
                assert a["loss"] == b["loss"] and a["gradients"] == b["gradients"]
    correct = mechanics_experiment({**DEFAULT_IV53, "seed": 3})
    wrong = mechanics_experiment({**DEFAULT_IV53, "seed": 3, "mode": 2})
    assert [row["docID"] for row in correct["baselineRows"]] == [0, 1, 1]
    assert [row["docID"] for row in wrong["prefixRows"] + wrong["resumedRows"]] == [0, 1, 0]
    coincident = mechanics_experiment({**DEFAULT_IV53, "mode": 2})
    assert all(coincident["comparison"]["theta"]) and not coincident["comparison"]["rng"]
    cursor_noop = mechanics_experiment({**DEFAULT_IV53, "mode": 3, "split": 2})
    assert all(all(value) if type(value) is list else value for value in cursor_noop["comparison"].values())
    sgd_noop = mechanics_experiment({**DEFAULT_IV53, "mode": 1, "optimizer": 0})
    assert all(all(value) if type(value) is list else value for value in sgd_noop["comparison"].values())
    eta_zero = mechanics_experiment({**DEFAULT_IV53, "eta": 0})
    assert eta_zero["initial"]["theta"] == eta_zero["baseline"]["theta"]
    assert any(eta_zero["baseline"]["m"]) and eta_zero["baseline"]["completedUpdates"] == 3
    summary_keys = ["seed", "split", "mode", "eta", "optimizer", "totalUpdates", "realUpdates", "baselineUpdates", "prefixUpdates", "resumeUpdates", "tokenizerCalls", "appendedEOS", "fullForwardCalls", "readoutCalls", "classCount", "trainableParameters", "validTargets", "checkpointSlots", "stateWords", "configWords", "totalWords", "checkpointCharacters", "checkpointLimit", "encodeFrames", "decodeFrames", "rngDraws", "roundtripEqual", "thetaEqual", "mEqual", "vEqual", "countersEqual", "rngEqual", "orderEqual", "cursorEqual", "epochEqual", "stateEqual", "trajectoryEqual", "baselineCompleted", "resumedCompleted", "baselineTAdam", "resumedTAdam", "baselineLossBefore3", "resumedLossBefore3", "frames", "tensorCount"]
    text_keys = ["docA", "docB", "trainingScope", "tokenizerPolicy", "objectivePolicy", "optimizerPolicy", "iteratorPolicy", "recoveryPolicy", "checkpointPolicy", "numericCoherence", "backendPolicy", "powerPremise", "provenance", "modelVocabulary", "parameterKeys", "stateFields", "checkpointSlots", "configFields", "lossFields", "comparisonFields", "bitWordOrder", "modelIdentity", "dataIdentity", "operationIdentity"]
    for scope in ("docA", "docB"):
        summary_keys.extend(f"{scope}_{key}" for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"))
        text_keys.extend(f"{scope}_{key}" for key in ("corpus", "input", "corpusDecoded", "decoded", "corpusLabels", "corpusExpansions", "targetLabels", "targetExpansions", "ruleLabels", "ruleExpansions", "trainingStop"))
    text_keys += ["checkpointJSON", "checkpointWords", "checkpointConfigWords"]

    def public_record(record):
        assert list(record) == ["status", "outputs", "steps", "tensors", "texts"] and record["status"] == "defined"
        assert len(summary_keys) == 67 and list(record["outputs"])[:67] == summary_keys
        assert len(text_keys) == 49 and list(record["texts"]) == text_keys
        assert len(record["steps"]) == record["outputs"]["frames"] == 496
        assert len(record["tensors"]) == record["outputs"]["tensorCount"] == 389
        assert record["outputs"]["realUpdates"] == record["outputs"]["readoutCalls"] == 6
        assert record["outputs"]["rngDraws"] == 3 and record["outputs"]["fullForwardCalls"] == 2
        aliases = []
        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 _checkpoint.same_float(record["outputs"][alias], value)
        assert list(record["outputs"])[67:] == aliases and len(set(aliases)) == len(aliases)
        assert len({step["id"] for step in record["steps"]}) == 496
        assert len({item["id"] for item in record["tensors"]}) == 389
        for item in record["tensors"]:
            assert list(item) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
            assert len(item["shape"]) == len(item["axes"]) == len(set(item["axes"]))
            assert all(type(d) is int and 1 <= d <= 64 for d in item["shape"])
            assert _checkpoint.math.prod(item["shape"]) == len(item["values"]) <= 4096
            assert item["provenance"] and item["dtype"] in ("float64", "int32", "bool")
            expected_type = int if item["dtype"] == "int32" else bool if item["dtype"] == "bool" else float
            assert all(type(value) is expected_type for value in item["values"])
            assert item["precision"] == (0 if item["dtype"] == "int32" or item["id"].endswith("_RNG") else 8)
        cells = {item["id"]: item for item in record["tensors"]}
        assert cells["CheckpointBits"]["shape"] == cells["DecodedBits"]["shape"] == [49, 2]
        assert cells["CheckpointBits"]["values"] == cells["DecodedBits"]["values"]
        assert len(record["texts"]["checkpointWords"]) == 45 and len(record["texts"]["checkpointConfigWords"]) == 4
        assert len(record["texts"]["bitWordOrder"]) == 49
        assert all(record["outputs"][key] == 1 for key in ("roundtripEqual", "thetaEqual", "mEqual", "vEqual", "stateEqual", "trajectoryEqual"))
        for scope in ("forwardA", "forwardB"):
            assert len([item for item in record["tensors"] if item["id"].startswith(scope + "_")]) == 57
        for scope in ("baseline_1", "baseline_2", "baseline_3", "prefix_1", "resume_2", "resume_3"):
            loss = cells[scope + "_Loss"]["values"]
            assert loss[4] == loss[0]-loss[1] and loss[5] == loss[4]+loss[2]
            assert loss[6] == 1*loss[5] and loss[7] == 0+loss[6] and loss[8] == loss[7]/1
            assert len(cells[scope + "_Gradient"]["values"]) == 15
        return cells

    public_record(derive_iv53(dict(DEFAULT_IV53)))
    signed = derive_iv53({**DEFAULT_IV53, "eta": -0.0})
    public_record(signed)
    assert _checkpoint.same_float(signed["outputs"]["eta"], -0.0)
    assert signed["texts"]["checkpointConfigWords"][0] == "8000000000000000"
    for state, code in (({}, "INVALID_INPUT"), ({**DEFAULT_IV53, "seed": -1, "optimizer": True}, "NONFINITE"),
                        ({**DEFAULT_IV53, "seed": 10**1000}, "INVALID_INPUT")):
        fault = derive_iv53(state)
        assert list(fault) == ["status", "code", "reason"] and fault["status"] == "unavailable" and fault["code"] == code

    # The actual CLI is exercised only inside this explicit deferred leaf.
    from contextlib import redirect_stdout
    from io import StringIO
    import sys
    cli, training = _checkpoint._training._packing, _checkpoint._training
    modules = (_checkpoint, training, cli, cli._iv39, cli._iv39._bpe,
               training._tiny, training._tiny._bpe, training._choice)
    saved_checks = [(module, module.source_self_check) for module in modules]
    saved_local = source_self_check
    saved_argv, saved_stdin = sys.argv, sys.stdin

    def forbidden_check():
        raise AssertionError("Query invoked a check leaf")

    try:
        for module, _ in saved_checks:
            module.source_self_check = forbidden_check
        globals()["source_self_check"] = forbidden_check
        default_json = cli.json.dumps(dict(DEFAULT_IV53))
        for query, stdin_text in ((None, None), (default_json, None), ("-", default_json),
                                  ("-", cli.json.dumps({**DEFAULT_IV53, "eta": -0.0})),
                                  ("{}", None), ('{"seed":0,"seed":1}', None), ("NaN", None), ("{", None)):
            sys.argv = ["iv53.py"] + ([] if query is None else [query])
            sys.stdin = StringIO("" if stdin_text is None else stdin_text)
            stream = StringIO()
            with redirect_stdout(stream):
                run()
            observed = cli.json.loads(stream.getvalue())
            if query in (None, default_json, "-"):
                public_record(observed)
                if stdin_text is not None and "-0.0" in stdin_text:
                    assert _checkpoint.same_float(observed["outputs"]["eta"], -0.0)
            else:
                assert list(observed) == ["status", "code", "reason"] and observed["status"] == "unavailable" and observed["code"] == "INVALID_INPUT"
        original_mechanics = mechanics_experiment
        try:
            for sentinel in (RuntimeError("unknown runtime"), ValueError("unknown semantic value")):
                def unknown(_):
                    raise sentinel
                globals()["mechanics_experiment"] = unknown
                sys.argv = ["iv53.py"]
                try:
                    run()
                except (RuntimeError, ValueError) as error:
                    assert error is sentinel
                else:
                    raise AssertionError("Unknown semantic failure was swallowed")
        finally:
            globals()["mechanics_experiment"] = original_mechanics
        for sentinel in (AssertionError("explicit assertion"), _checkpoint.NumericalFault("INVALID_INPUT", "explicit known check failure"),
                         RuntimeError("explicit runtime"), ValueError("explicit value")):
            def failed_check():
                raise sentinel
            globals()["source_self_check"] = failed_check
            sys.argv = ["iv53.py", "--self-check"]
            try:
                run()
            except (AssertionError, RuntimeError, ValueError) as error:
                assert error is sentinel
            else:
                raise AssertionError("Explicit check failure was swallowed")
    finally:
        globals()["source_self_check"] = saved_local
        for module, check in saved_checks:
            module.source_self_check = check
        sys.argv, sys.stdin = saved_argv, saved_stdin


if __name__ == "__main__":
    run()

Checkpoint and continuation mechanics — p13/checkpoint_reference.py: structural state, strict word/slot codec, actual fixed context, LCG, transition, recovery and per-field comparison.

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.

"""IV53 actual checkpoint mechanics — SOURCE ONLY; ALL EXECUTION UNRUN.

The owner-adopted pure codec binds compiled context, not authentic execution
origin. The complete public binder follows the parent's explicit source adoption.
Only adjacent training_reference is loaded; no TS, oracle or answer imports.
"""
from copy import deepcopy
import importlib.util
import json
import math
from pathlib import Path
import struct
from types import MappingProxyType
import numpy as np

_spec = importlib.util.spec_from_file_location(
    "_iv53_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)
NumericalFault = _training.NumericalFault
KNOWN_FAULTS = _training.KNOWN_FAULTS
DEFAULT_IV53 = MappingProxyType(dict(seed=0, split=1, mode=0, eta=0.1, optimizer=1))
CHECKPOINT_IDENTITIES = MappingProxyType(dict(
    model="iv53:tiny-b1-d2-h1-ffn3-default-encoder-v1",
    data="iv53:a,b:abab-bpe-lex-v1:merges0:eos-off+512:position0:classes97,98,512:target512:mask1:b1-v1",
    operation="iv53:binary64-separate-rn:class-ascending:gradient-feature-order:adam-half-eps1e-8:lcg32-highbit-eager-prefetch-v1",
))
STATE_KEYS = ("theta", "m", "v", "tAdam", "completedUpdates", "rng", "order", "cursor", "epoch")
CONFIG_KEYS = ("eta", "optimizer", "beta1", "beta2", "epsilon")
FLOAT_CONFIG_KEYS = ("eta", "beta1", "beta2", "epsilon")
MAX_CHECKPOINT_UNITS = 8192


def raw_state(value):
    """Exact raw5; all finite-number types BEFORE any finite-domain check."""
    raw = _training._object(value, tuple(DEFAULT_IV53), "state")
    for key, number in raw.items():
        _number(number, key)
    domains = dict(seed=(0, 4294967295, "seed must be a uint32 integer."),
                   split=(1, 2, "split must be numeric 1 or 2."),
                   mode=(0, 3, "mode must be an integer from 0 to 3."),
                   eta=(0, 1, "eta must be between 0 and 1."),
                   optimizer=(0, 1, "optimizer must be numeric 0 or 1."))
    checked = {}
    for key, number in raw.items():
        low, high, reason = domains[key]
        # Compare unbounded Python integers BEFORE any binary64 conversion.
        if not low <= number <= high or (key != "eta" and int(number) != number):
            raise NumericalFault("INVALID_INPUT", reason)
        checked[key] = float(number) if key == "eta" else int(number)
    return checked


def optimizer_config(raw):
    checked = raw_state(raw)
    return dict(eta=checked["eta"], optimizer=checked["optimizer"], beta1=0.5, beta2=0.5, epsilon=1e-8)


def _number(value, label):
    """Integer domains are checked before converting Python's unbounded ints."""
    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.")
    return value


def _dense(value, length, label):
    if type(value) is not list:
        raise NumericalFault("INVALID_INPUT", f"{label} must be a dense ordinary array.")
    if len(value) != length:
        raise NumericalFault("INVALID_INPUT", f"{label} requires exactly {length} entries.")
    return value[:]


def validate_config(value):
    raw = _training._object(value, CONFIG_KEYS, "config")
    for key, number in raw.items():
        _number(number, f"config.{key}")
    if not 0 <= raw["eta"] <= 1:
        raise NumericalFault("INVALID_INPUT", "eta must be between 0 and 1.")
    if raw["optimizer"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "optimizer must be numeric 0 or 1.")
    if raw["beta1"] != 0.5 or raw["beta2"] != 0.5 or raw["epsilon"] != 1e-8:
        raise NumericalFault("INVALID_INPUT", "IV53 requires beta1=beta2=0.5 and represented epsilon=1e-8.")
    return {key: int(number) if key == "optimizer" else float(number) for key, number in raw.items()}


def checkpoint_state(value, optimizer, remaining=0):
    """Detached nine-field structural state; no history or RNG/order guard.

    Counter/epoch bounds 0..3 reserve exactly the requested suffix. Python
    exact dict/list guards reject subclasses before reading any custom hooks.
    """
    _number(optimizer, "optimizer")
    _number(remaining, "remaining")
    if optimizer not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "optimizer must be numeric 0 or 1.")
    if not 0 <= remaining <= 3 or int(remaining) != remaining:
        raise NumericalFault("INVALID_INPUT", "remaining must be an integer from 0 to 3.")
    remaining = int(remaining)
    raw = _training._object(value, STATE_KEYS, "checkpointState")
    arrays = {key: _dense(raw[key], size, key)
              for key, size in (("theta", 15), ("m", 15), ("v", 15), ("order", 2))}
    checked = {}
    for key, entries in arrays.items():
        checked[key] = [(_number(number, f"{key}[{i}]") if key == "order"
                         else _training._numeric(number, f"{key}[{i}]"))
                        for i, number in enumerate(entries)]
    for key in ("tAdam", "completedUpdates", "rng", "cursor", "epoch"):
        _number(raw[key], key)
    for key in ("tAdam", "completedUpdates", "epoch"):
        number = raw[key]
        if not 0 <= number <= 3 or int(number) != number:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer from 0 to 3.")
    if raw["completedUpdates"] + remaining > 3:
        raise NumericalFault("INVALID_INPUT", "completedUpdates must leave room for the requested remaining updates.")
    if any(number < 0 for number in checked["v"]):
        raise NumericalFault("INVALID_INPUT", "Every second moment v must be nonnegative.")
    if optimizer == 1 and raw["tAdam"] != raw["completedUpdates"]:
        raise NumericalFault("INVALID_INPUT", "Fixed Adam requires tAdam=completedUpdates.")
    if (raw["tAdam"] == 0 or optimizer == 0) and (any(number != 0 for number in checked["m"]) or any(number != 0 for number in checked["v"])):
        raise NumericalFault("INVALID_INPUT", "Zero Adam steps or SGD require zero m and v.")
    if optimizer == 0 and raw["tAdam"] != 0:
        raise NumericalFault("INVALID_INPUT", "SGD requires tAdam=0.")
    if not 0 <= raw["rng"] <= 4294967295 or int(raw["rng"]) != raw["rng"]:
        raise NumericalFault("INVALID_INPUT", "rng must be a uint32 integer.")
    if checked["order"] not in ([0, 1], [1, 0]):
        raise NumericalFault("INVALID_INPUT", "order must be exactly [0,1] or [1,0].")
    if raw["cursor"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "cursor must be numeric 0 or 1.")
    if raw["epoch"] + (raw["cursor"] + remaining) // 2 > 3:
        raise NumericalFault("INVALID_INPUT", "epoch must leave room for the requested remaining updates.")
    return dict(theta=checked["theta"], m=checked["m"], v=checked["v"],
                tAdam=int(raw["tAdam"]), completedUpdates=int(raw["completedUpdates"]), rng=int(raw["rng"]),
                order=[int(number) for number in checked["order"]], cursor=int(raw["cursor"]), epoch=int(raw["epoch"]))


def validate_state(value, config, remaining=0):
    """Internal training adapter; public codec uses checkpoint_state directly."""
    return checkpoint_state(value, validate_config(config)["optimizer"], remaining)


def draw_order(seed, trace, prefix):
    """One genuine high-bit LCG draw; exact integer arithmetic below 2^53."""
    _training._prefix(prefix)
    _number(seed, "rng")
    if not 0 <= seed <= 4294967295 or int(seed) != seed:
        raise NumericalFault("INVALID_INPUT", "rng must be a uint32 integer.")
    source = int(seed)
    multiplier, increment, modulus, high_divisor = 1664525, 1013904223, 4294967296, 2147483648
    product = multiplier * source
    summed = product + increment
    next_rng = summed % modulus
    bit = next_rng // high_divisor
    order = [0, 1] if bit == 0 else [1, 0]
    trace.add(prefix, "Advance the actual future RNG and prefetch an order",
              "product=1664525*rng; sum=product+1013904223; next=sum%4294967296; bit=floor(next/2147483648); order=bit0?[0,1]:[1,0]",
              "All integer operands/results are exact below 2^53. This explicit pedagogical LCG is not cryptographic and does not promise independent shuffles.",
              dict(rng=source, multiplier=multiplier, increment=increment, modulus=modulus, highDivisor=high_divisor),
              dict(product=product, sum=summed, next=next_rng, bit=bit, order0=order[0], order1=order[1]))
    return dict(rng=next_rng, order=order)


def initial_state(raw, trace):
    checked = raw_state(raw)
    draw = draw_order(checked["seed"], trace, "initial_rng")
    theta = np.array([_training._tiny.NUMERIC_DEFAULTS[key] for key in _training.PARAMETER_KEYS], dtype=np.float64)
    zeros = np.zeros(15, dtype=np.float64)
    state = checkpoint_state(dict(theta=theta.tolist(), m=zeros.tolist(), v=zeros.tolist(), tAdam=0, completedUpdates=0,
                                  rng=draw["rng"], order=draw["order"], cursor=0, epoch=0), checked["optimizer"], 3)
    high_bit = state["rng"] // 2147483648
    trace.add("initial_state", "Detach the common prefetched starting state",
              "theta=default U,bias; m=v=positive zeros; tAdam=completedUpdates=cursor=epoch=0; preserve actual prefetched RNG/order",
              "Baseline and interrupted runs each detach this identical actual starting state. Normal history relations hold here and are not decoder authenticity guards.",
              dict(seed=checked["seed"], rng=state["rng"], order0=state["order"][0], order1=state["order"][1]),
              dict(tAdam=state["tAdam"], completedUpdates=state["completedUpdates"], cursor=state["cursor"], epoch=state["epoch"],
                   normalCountRelation=int(state["completedUpdates"] == 2*state["epoch"] + state["cursor"]),
                   normalOrderRelation=int(state["order"][0] == high_bit and state["order"][1] == 1-high_bit)))
    return state


def encode_word(value):
    """One finite double → eight actual big-endian bytes → signed halves/hex."""
    number = _training._numeric(value, "word value")
    packed = struct.pack(">d", number)
    high, low = struct.unpack(">ii", packed)
    return dict(value=number, high=high, low=low, word=packed.hex())


def _word(value, label):
    if type(value) is not str or len(value) != 16 or any(char not in "0123456789abcdef" for char in value):
        raise NumericalFault("INVALID_INPUT", f"{label} must be exactly sixteen lowercase hexadecimal digits.")
    return value


def decode_word(word, label="word"):
    packed = bytes.fromhex(_word(word, label))
    high, low = struct.unpack(">ii", packed)
    value = struct.unpack(">d", packed)[0]
    _number(value, label)
    return dict(value=value, high=high, low=low, word=word)


def _config_frame(trace, phase, optimizer, values):
    inputs, outputs = dict(optimizer=optimizer), {}
    for key, entry in zip(FLOAT_CONFIG_KEYS, values):
        if phase == "encode":
            inputs[key] = entry["value"]
            outputs.update({key + "High": entry["high"], key + "Low": entry["low"]})
        else:
            inputs.update({key + "High": entry["high"], key + "Low": entry["low"]})
            outputs[key] = entry["value"]
    trace.add(phase + "_config", phase + ": four actual config words",
              "setFloat64(value,bigEndian); high=getInt32(0); low=getInt32(4); word=hex32(high)||hex32(low)" if phase == "encode" else "parse high/low hex; setUint32 halves bigEndian; value=getFloat64(0)",
              "Four genuine conversions in eta,beta1,beta2,epsilon order. Signed int32 halves are bit evidence, not overflowed unsigned tensor values.", inputs, outputs)


def _state_frames(trace, phase, values):
    for k in range(15):
        inputs, outputs = dict(k=k), {}
        for key, entries in zip(("theta", "m", "v"), values):
            entry = entries[k]
            if phase == "encode":
                inputs[key] = entry["value"]
                outputs.update({key + "High": entry["high"], key + "Low": entry["low"]})
            else:
                inputs.update({key + "High": entry["high"], key + "Low": entry["low"]})
                outputs[key] = entry["value"]
        trace.add(f"{phase}_parameter_{k}", f"{phase}: all three state words at parameter {k}",
                  "for theta,m,v: setFloat64(value,bigEndian); high=getInt32(0); low=getInt32(4); word=hex32(high)||hex32(low)" if phase == "encode" else "for theta,m,v: parse high/low hex; setUint32 halves bigEndian; value=getFloat64(0)",
                  "Three actual conversions per grouped parameter frame; all fifteen coordinates and all forty-five state values are retained, including signed zero.", inputs, outputs)


def encode_checkpoint(value, config, trace):
    """Adopted text/stateWords/configWords/bits inventory; 49 real conversions."""
    cfg = validate_config(config)
    state = checkpoint_state(value, cfg["optimizer"])
    config_values = [encode_word(cfg[key]) for key in FLOAT_CONFIG_KEYS]
    state_values = [[encode_word(number) for number in state[key]] for key in ("theta", "m", "v")]
    _config_frame(trace, "encode", cfg["optimizer"], config_values)
    _state_frames(trace, "encode", state_values)
    config_words = [entry["word"] for entry in config_values]
    vectors = [[entry["word"] for entry in entries] for entries in state_values]
    record = [1, *CHECKPOINT_IDENTITIES.values(), [cfg["optimizer"], *config_words], *vectors,
              [state["tAdam"], state["completedUpdates"]],
              [state["rng"], *state["order"], state["cursor"], state["epoch"]]]
    text = json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False)
    if _training._packing._token.utf16_length(text) > MAX_CHECKPOINT_UNITS:
        raise NumericalFault("UNSUPPORTED_SIZE", "checkpoint text exceeds 8192 UTF-16 code units.")
    return dict(text=text, stateWords=[word for entries in vectors for word in entries], configWords=config_words,
                bits=[entry[half] for entries in [config_values, *state_values] for entry in entries for half in ("high", "low")])


def _reject_constant(value):
    raise ValueError(f"Nonstandard JSON constant: {value}")


def decode_checkpoint(text, config, trace, remaining=0):
    """Text only; validate ALL word syntax before decoding, publish frames last."""
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", "checkpoint text must be an actual string.")
    if _training._packing._token.utf16_length(text) > MAX_CHECKPOINT_UNITS:
        raise NumericalFault("UNSUPPORTED_SIZE", "checkpoint text exceeds 8192 UTF-16 code units.")
    try:
        parsed = json.loads(text, parse_constant=_reject_constant)
    except ValueError as error:
        # Only the actual parse boundary handles known malformed-text failures.
        raise NumericalFault("INVALID_INPUT", "checkpoint text must contain exactly one standard JSON value.") from error
    root = _dense(parsed, 10, "checkpoint")
    config_slots = _dense(root[4], 5, "checkpoint.config")
    vectors = [_dense(root[slot], 15, f"checkpoint[{slot}]") for slot in (5, 6, 7)]
    counters = _dense(root[8], 2, "checkpoint.counters")
    iterator = _dense(root[9], 5, "checkpoint.iterator")
    if type(root[0]) not in (int, float) or root[0] != 1 or root[1:4] != list(CHECKPOINT_IDENTITIES.values()):
        raise NumericalFault("INVALID_INPUT", "checkpoint version and compiled model/data/operation identities must match.")
    expected = validate_config(config)
    optimizer = _number(config_slots[0], "checkpoint.config.optimizer")
    config_words = [_word(value, f"checkpoint.config[{i + 1}]") for i, value in enumerate(config_slots[1:])]
    state_words = [[_word(value, f"checkpoint[{a + 5}][{k}]") for k, value in enumerate(entries)] for a, entries in enumerate(vectors)]
    config_values = [decode_word(word, f"checkpoint.config[{i + 1}]") for i, word in enumerate(config_words)]
    # Compare with the ORIGINAL expected config, preserving the sign of zero.
    if optimizer != expected["optimizer"] or any(struct.pack(">d", entry["value"]) != struct.pack(">d", expected[key]) for key, entry in zip(FLOAT_CONFIG_KEYS, config_values)):
        raise NumericalFault("INVALID_INPUT", "checkpoint config must match the current experiment exactly, including float bits.")
    state_values = [[decode_word(word, f"checkpoint[{a + 5}][{k}]") for k, word in enumerate(entries)] for a, entries in enumerate(state_words)]
    state = checkpoint_state(dict(theta=[entry["value"] for entry in state_values[0]], m=[entry["value"] for entry in state_values[1]],
                                  v=[entry["value"] for entry in state_values[2]], tAdam=counters[0], completedUpdates=counters[1],
                                  rng=iterator[0], order=iterator[1:3], cursor=iterator[3], epoch=iterator[4]), expected["optimizer"], remaining)
    _config_frame(trace, "decode", optimizer, config_values)
    _state_frames(trace, "decode", state_values)
    return dict(state=state, stateWords=[word for entries in state_words for word in entries], configWords=config_words,
                bits=[entry[half] for entries in [config_values, *state_values] for entry in entries for half in ("high", "low")])


def fixed_context(trace):
    """Two genuine EOS-off tokenizers and two full old forwards, all retained.

    Current training_reference.old_forward_prose binds the complete old steps;
    none of the old 57-tensor forwards is cropped or regenerated from answers.
    """
    tokenized = _training.tokenize_training_documents(dict(_training.DEFAULT_IV52))
    documents = [tokenized["docA"], tokenized["docB"]]
    forwards, features = [], []
    for d, document in enumerate(documents):
        prefix = "docA" if d == 0 else "docB"
        for step in document["record"]["steps"]:
            trace.add(f"{prefix}_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
        trace.add(prefix + "_append_eos", 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(document["contentIDs"]), tokenizerEOS=document["record"]["outputs"]["eos"]),
                  dict(eosPosition=len(document["contentIDs"]), eosID=512, sequenceTokens=len(document["sequenceIDs"])))
    for d, document in enumerate(documents):
        prefix = "forwardA" if d == 0 else "forwardB"
        saved = _training._tiny.tiny_trace()
        result = _training._tiny.forward_tiny(dict(_training._tiny.NUMERIC_DEFAULTS), document["sequenceIDs"][:-1].tolist(), saved)
        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"])
        actual_y = next(item["values"] for item in result["tensors"] if item["id"] == "Y")
        features.append(actual_y[:])
        forwards.append(dict(result=deepcopy(result), steps=deepcopy(saved.steps)))
    return dict(documents=deepcopy(documents), forwards=forwards, features=features, classIDs=list(_training.ALL_IDS[:3]))


def transition(state, context, config, trace, prefix):
    """Actual current-sample evaluation/update; commit only a detached next state."""
    _training._prefix(prefix)
    cfg = validate_config(config)
    before = checkpoint_state(state, cfg["optimizer"], 1)
    doc_id = before["order"][before["cursor"]]
    doc = context["documents"][doc_id]
    input_id, target_id = int(doc["sequenceIDs"][0]), int(doc["sequenceIDs"][1])
    target_row, mask, valid_targets = context["classIDs"].index(target_id), 1, 1
    y = context["features"][doc_id][:]
    trace_start = len(trace.steps)
    trace.add(prefix + "_select", "Select the actual current prefetched sample",
              "docID=order[cursor]; inputID=sequence[0]; targetID=sequence[1]; mask=1; N=1",
              "One real current sample, with the known appended EOS target. Neither a prediction nor a fabricated inactive probability selects data.",
              dict(completedUpdates=before["completedUpdates"], rng=before["rng"], order0=before["order"][0], order1=before["order"][1], cursor=before["cursor"], epoch=before["epoch"]),
              dict(docID=doc_id, inputID=input_id, targetID=target_id, targetRow=target_row, mask=mask, position=0, validTargets=valid_targets))
    distribution = _training.finite_readout(y, before["theta"], context["classIDs"], trace, prefix)
    maximum, target_logit, probability = distribution["max"], distribution["logits"][target_row], distribution["probabilities"][target_row]
    gap = _training.finite(maximum - target_logit, "target gap")
    nll = _training.finite(gap + distribution["logS"], "target NLL")
    weighted = _training.finite(mask * nll, "masked NLL")
    previous_sum = 0.0
    loss_sum = _training.finite(previous_sum + weighted, "masked loss sum")
    mean = _training.finite(loss_sum / valid_targets, "mean NLL")
    loss = dict(gap=gap, nll=nll, weightedNLL=weighted, lossSum=loss_sum, meanNLL=mean)
    trace.add(prefix + "_loss", "Score the selected sample BEFORE its update",
              "gap=max-targetLogit; nll=gap+logS; weightedNLL=mask*nll; lossSum=0+weightedNLL; meanNLL=lossSum/N",
              "The current genuine distribution supplies all operands. This is one pre-update loss, not a final-theta objective or a monotonic curve.",
              dict(docID=doc_id, position=0, targetID=target_id, targetRow=target_row, mask=mask, max=maximum, targetLogit=target_logit,
                   logS=distribution["logS"], probability=probability, previousSum=previous_sum, validTargets=valid_targets), loss)
    gradients = _training.readout_gradients([dict(y=y, probabilities=distribution["probabilities"][:], targetID=target_id, mask=mask)],
                                           context["classIDs"], trace, prefix + "_gradient")
    updated = _training.optimizer_update({key: deepcopy(before[key]) for key in STATE_KEYS[:5]}, gradients["gradient"], cfg, trace, prefix + "_optimizer")
    cursor_increment = before["cursor"] + 1
    wraps = cursor_increment == 2
    cursor, epoch, rng, order = cursor_increment, before["epoch"], before["rng"], before["order"][:]
    if wraps:
        cursor, epoch = 0, before["epoch"] + 1
        draw = draw_order(before["rng"], trace, prefix + "_rng")
        rng, order = draw["rng"], draw["order"]
    after = checkpoint_state(dict(**updated, rng=rng, order=order, cursor=cursor, epoch=epoch), cfg["optimizer"])
    high_bit, normal_count = rng // 2147483648, 2*epoch + cursor
    trace.add(prefix + "_advance", "Commit the optimizer and actual iterator transition",
              "cursorIncrement=cursor+1; if2: cursor=0,epoch=epoch+1,draw/prefetch now; else keep RNG/order/epoch",
              "The complete next state is published after successful numerical work. Normal history relations are reported, not enforced after a declared faulty recovery.",
              dict(cursor=before["cursor"], epoch=before["epoch"], rng=before["rng"], order0=before["order"][0], order1=before["order"][1], completedNew=updated["completedUpdates"], tNew=updated["tAdam"]),
              dict(cursorIncrement=cursor_increment, wraps=int(wraps), cursor=cursor, epoch=epoch, rng=rng, order0=order[0], order1=order[1],
                   completedUpdates=after["completedUpdates"], tAdam=after["tAdam"], highBit=high_bit, normalCount=normal_count,
                   normalCountRelation=int(after["completedUpdates"] == normal_count), normalOrderRelation=int(order[0] == high_bit and order[1] == 1-high_bit)))
    return dict(before=before, after=after, docID=doc_id, y=y, distribution=deepcopy(distribution),
                loss=loss, gradients=deepcopy(gradients), steps=deepcopy(trace.steps[trace_start:]))


def recover_state(decoded, raw, trace):
    """Apply ONLY the declared alteration AFTER valid decode, then validate it."""
    checked = raw_state(raw)
    before = checkpoint_state(decoded, checked["optimizer"], 3-checked["split"])
    after = deepcopy(before)
    if checked["mode"] == 1:
        after["m"], after["v"] = [0.0]*15, [0.0]*15
    elif checked["mode"] == 2:
        after["rng"] = checked["seed"]
    elif checked["mode"] == 3:
        after["cursor"] = 0
    after = checkpoint_state(after, checked["optimizer"], 3-checked["split"])
    trace.add("recovery", "Apply only the declared recovery intervention AFTER valid decode",
              "mode0: complete; mode1: m/v=positive zero; mode2: rng=raw seed; mode3: cursor=0",
              "Retain the original checkpoint text and decoded state. The transformed state passes the same structural guard; legal continuation state does not authenticate historical restoration.",
              dict(mode=checked["mode"], seed=checked["seed"], decodedRNG=before["rng"], decodedCursor=before["cursor"]),
              dict(resetMoments=int(checked["mode"] == 1), resetFutureRNG=int(checked["mode"] == 2), resetCursor=int(checked["mode"] == 3),
                   rng=after["rng"], cursor=after["cursor"], epoch=after["epoch"], tAdam=after["tAdam"], completedUpdates=after["completedUpdates"]))
    return after


def same_float(left, right):
    """Finite binary64 Object.is equivalent; comparison is not codec evidence."""
    return struct.pack(">d", left) == struct.pack(">d", right)


def compare_states(left, right):
    """Actual per-coordinate float BIT identity and discrete-field equality.

    This comparison performs no traced codec operation; it cannot be mistaken
    for a third checkpoint encode/decode or proof of deterministic backends.
    """
    result = {key: [same_float(a, b) for a, b in zip(left[key], right[key])]
              for key in ("theta", "m", "v")}
    result.update({key: left[key] == right[key] for key in STATE_KEYS[3:]})
    return result


def source_self_check():
    """Explicit DEFERRED mechanics leaf; no import/query calls this function."""
    assert __debug__, "Deferred checks require assertions enabled."
    trace = _training.TrainingTrace()
    first = draw_order(3, trace, "first")
    second = draw_order(first["rng"], trace, "second")
    assert first == dict(rng=1018897798, order=[0, 1])
    assert second == dict(rng=2365144877, order=[1, 0])
    high = draw_order(4294967295, trace, "high")
    assert high["rng"] == (1664525*4294967295+1013904223) % 4294967296
    assert trace.steps[-1]["outputs"]["sum"] < 2**53
    for number in (0.0, -0.0, 1.0, -1.0, float.fromhex("0x0.0000000000001p-1022"), float.fromhex("0x1.fffffffffffffp+1023")):
        encoded = encode_word(number)
        decoded = decode_word(encoded["word"])
        assert struct.pack(">d", decoded["value"]) == struct.pack(">d", number)
        assert struct.pack(">ii", decoded["high"], decoded["low"]).hex() == encoded["word"]
    assert encode_word(-0.0) == dict(value=-0.0, high=-2147483648, low=0, word="8000000000000000")
    cfg = optimizer_config(dict(DEFAULT_IV53))
    state = initial_state(dict(DEFAULT_IV53), _training.TrainingTrace())
    state["theta"][0], state["m"][0], state["v"][0] = -0.0, -0.0, -0.0
    encoded = encode_checkpoint(state, cfg, trace)
    decoded = decode_checkpoint(encoded["text"], cfg, trace, remaining=3)
    assert all(all(value) if type(value) is list else value for value in compare_states(state, decoded["state"]).values())
    assert len(encoded["configWords"]) == 4 and len(encoded["stateWords"]) == 45 and len(encoded["bits"]) == 98
    assert (decoded["stateWords"], decoded["configWords"], decoded["bits"]) == (encoded["stateWords"], encoded["configWords"], encoded["bits"])
    assert len([step for step in trace.steps if step["id"].startswith("encode_parameter_")]) == 15
    # Integer JSON spellings have VALUE semantics; bool is never an integer.
    array = json.loads(encoded["text"])
    array[0], array[4][0], array[8], array[9] = 1.0, 1.0, [0.0, 0.0], [state["rng"]*1.0, 0.0, 1.0, 0.0, 0.0]
    assert decode_checkpoint(json.dumps(array), cfg, _training.TrainingTrace())["state"]["rng"] == state["rng"]
    for key in DEFAULT_IV53:
        for value, code in ((True, "NONFINITE"), (float("nan"), "NONFINITE"), (10**1000, "INVALID_INPUT")):
            try:
                raw_state({**DEFAULT_IV53, key: value})
            except NumericalFault as error:
                assert error.code == code
            else:
                raise AssertionError("Invalid raw field accepted")
    try:
        raw_state({**DEFAULT_IV53, "seed": -1, "optimizer": True})
    except NumericalFault as error:
        assert error.code == "NONFINITE" and "optimizer" in str(error)
    else:
        raise AssertionError("Domains preceded all numeric guards")
    for text in ("{}", "[", "NaN", "9"*5000, " "*(MAX_CHECKPOINT_UNITS+1)):
        try:
            decode_checkpoint(text, cfg, _training.TrainingTrace())
        except NumericalFault as error:
            assert error.code in ("INVALID_INPUT", "UNSUPPORTED_SIZE")
        else:
            raise AssertionError("Malformed checkpoint accepted")
    for slot, patch in ((0, True), (1, "stale"), (4, [1, "0000000000000000", "3fe0000000000000", "3fe0000000000000", {}]),
                        (5, ["7ff0000000000000"]*15), (8, [True, 0]), (9, [10**1000, 0, 1, 0, 0])):
        array = json.loads(encoded["text"])
        array[slot] = patch
        try:
            decode_checkpoint(json.dumps(array), cfg, _training.TrainingTrace())
        except NumericalFault:
            pass
        else:
            raise AssertionError("Invalid checkpoint field accepted")
    negative_cfg = {**cfg, "eta": -0.0}
    encoded_negative = encode_checkpoint(state, negative_cfg, _training.TrainingTrace())
    try:
        decode_checkpoint(encoded_negative["text"], {**cfg, "eta": 0.0}, _training.TrainingTrace())
    except NumericalFault as error:
        assert error.code == "INVALID_INPUT" and "including float bits" in str(error)
    else:
        raise AssertionError("Config signed-zero bits lost")
    # Legal fabricated continuation states are accepted without history checks.
    fabricated = {**state, "rng": 4294967295, "order": [0, 1], "cursor": 1, "epoch": 0, "tAdam": 2, "completedUpdates": 2}
    assert validate_state(fabricated, cfg, 1)["cursor"] == 1
    class HostileList(list):
        def __iter__(self):
            raise RuntimeError("Subclass must never be read")
    try:
        validate_state({**state, "order": HostileList([0, 1])}, cfg)
    except NumericalFault as error:
        assert error.code == "INVALID_INPUT"
    else:
        raise AssertionError("Array subclass accepted")
    class ThrowingTrace:
        def add(self, *args):
            raise RuntimeError("Unknown trace sentinel")
    try:
        draw_order(0, ThrowingTrace(), "unknown")
    except RuntimeError as error:
        assert str(error) == "Unknown trace sentinel"
    else:
        raise AssertionError("Unknown observer failure swallowed")
    # UTF-16 units, not Python code points: malformed supplementary text hits
    # the same size guard as JS before any JSON syntax/schema work.
    try:
        decode_checkpoint("🦊"*4097, cfg, _training.TrainingTrace())
    except NumericalFault as error:
        assert error.code == "UNSUPPORTED_SIZE" and "UTF-16" in str(error)
    else:
        raise AssertionError("Non-BMP checkpoint budget used Python len")
    assert validate_state(state, cfg, 1.0) == validate_state(state, cfg, 1)
    assert validate_state(state, cfg, -0.0) == validate_state(state, cfg, 0)
    for remaining, code in ((True, "NONFINITE"), (float("nan"), "NONFINITE"), (10**1000, "INVALID_INPUT"), (1.5, "INVALID_INPUT")):
        try:
            validate_state(state, cfg, remaining)
        except NumericalFault as error:
            assert error.code == code
        else:
            raise AssertionError("Invalid integer-valued remaining accepted")
    # Adopted return/frame order and mixed-fault precedence, all DEFERRED.
    codec_trace = _training.TrainingTrace()
    saved = encode_checkpoint(state, negative_cfg, codec_trace)
    copy = decode_checkpoint(saved["text"], negative_cfg, codec_trace)
    assert list(saved) == ["text", "stateWords", "configWords", "bits"]
    assert list(copy) == ["state", "stateWords", "configWords", "bits"]
    assert [step["id"] for step in codec_trace.steps] == [f"{phase}_config" if k == -1 else f"{phase}_parameter_{k}" for phase in ("encode", "decode") for k in range(-1, 15)]
    assert saved["bits"][:2] == saved["bits"][8:10] == [-2147483648, 0]
    assert saved["stateWords"][0] == saved["stateWords"][15] == saved["stateWords"][30] == "8000000000000000"
    assert list(codec_trace.steps[0]["inputs"]) == ["optimizer", "eta", "beta1", "beta2", "epsilon"]
    assert list(codec_trace.steps[1]["outputs"]) == ["thetaHigh", "thetaLow", "mHigh", "mLow", "vHigh", "vLow"]
    assert list(codec_trace.steps[16]["outputs"]) == list(FLOAT_CONFIG_KEYS)
    assert all(list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"] for step in codec_trace.steps)

    def rejected(text, expected, code, reason, remaining=0):
        observer = _training.TrainingTrace()
        try:
            decode_checkpoint(text, expected, observer, remaining)
        except NumericalFault as error:
            assert error.code == code and str(error) == reason
            assert observer.steps == []  # Rejected decode publishes no frames.
        else:
            raise AssertionError("Mixed-fault checkpoint was accepted")

    rejected("🦊"*4097, {}, "UNSUPPORTED_SIZE", "checkpoint text exceeds 8192 UTF-16 code units.")
    rejected("[", {}, "INVALID_INPUT", "checkpoint text must contain exactly one standard JSON value.")
    rejected("[]", {}, "INVALID_INPUT", "checkpoint requires exactly 10 entries.")
    mixed = json.loads(saved["text"])
    mixed[4][1], mixed[7][14] = "7ff0000000000000", "bad"
    rejected(json.dumps(mixed), negative_cfg, "INVALID_INPUT", "checkpoint[7][14] must be exactly sixteen lowercase hexadecimal digits.")
    mixed = json.loads(saved["text"])
    mixed[4][1], mixed[4][4] = "0000000000000000", "7ff0000000000000"
    rejected(json.dumps(mixed), negative_cfg, "NONFINITE", "checkpoint.config[4] must be an actual finite number.")
    mixed = json.loads(saved["text"])
    mixed[4][1], mixed[5][0] = "0000000000000000", "7ff0000000000000"
    rejected(json.dumps(mixed), negative_cfg, "INVALID_INPUT", "checkpoint config must match the current experiment exactly, including float bits.")
    rejected(saved["text"], negative_cfg, "NONFINITE", "remaining must be an actual finite number.", True)
    headroom = {**state, "epoch": 3, "cursor": 0}
    assert checkpoint_state(headroom, 1.0, 1.0)["epoch"] == 3
    rejected(encode_checkpoint(headroom, cfg, _training.TrainingTrace())["text"], cfg,
             "INVALID_INPUT", "epoch must leave room for the requested remaining updates.", 2.0)
    for field in ("tAdam", "completedUpdates", "rng", "cursor", "epoch"):
        try:
            checkpoint_state({**state, field: 10**1000}, 1)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Huge integer structural field accepted")

Stateful training — p13/training_reference.py: actual scalar-ordered finite readout, all fifteen contractions, simultaneous optimizer and local old-forward prose binding.

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")

Existing document helper — p13/packing_reference.py: two actual EOS-off tokenizers with one explicit EOS append each. Its separate packing grid is not executed by tokenization.

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 wrapper — p09/iv39.py: complete corpus/target records and actual inverse reconstructions.

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)

Byte-pair operations — p09/bpe_reference.py: pair counting, numeric ties, ranked replacement and expansion; zero merges here retains actual byte IDs.

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]))]))

Unicode and integer storage — p09/token_reference.py: explicit UTF-8 mechanics, UTF-16 length accounting and actual integer 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=(",", ":")))

Fixed decoder — p10/tiny_reference.py: both complete old forwards with all 57 tensors each. Only their actual saved Y feeds repeated readout training.

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 residuals — p07/component_reference.py: feature statistics, same-shape addition and finite named tensor storage.

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: real two-to-three-to-two arrays. Tiny supplies explicit fixed overrides; standalone FFN defaults describe 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, explicit reshape/permutation, causal key softmax, weighted values and output projection. Tiny supplies its one-head identity settings and position-zero rotary pairs.

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=(",", ":")))

Distribution — p11/choice_reference.py: stable active-class probabilities, saved logS and strict computed-logit selection. Its prediction never replaces the EOS 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 tiny loader temporarily supplies its own canonical component module for the unchanged FFN bare import, then restores the prior module binding. These file-relative relationships do not search the caller’s current directory for substitute numerical answers. No oracle supplies a production answer.

Entry points and explicit checks

The public Python entry is derive_iv53(state). It returns the complete five-field record and catches the explicit known numerical-fault family; unknown implementation failures propagate. mechanics_experiment(state) is an internal evidence holder used by that binder and by the reading guide’s analogous helper composition. Its extra fields are not the public JSON schema. The actual dispatcher is zero-argument run(); it supplies derive_iv53, defaults and the explicit local callback to the existing strict packing CLI.

These are command examples, not an execution transcript. They use an absolute source path, so their entry location does not depend on the caller’s current directory:

python -E /media/mario-geometry/WD_SN7100_NVMe/coding-projects/interactive-books-worktrees/book-iv-development/Interactive-Neural-Networks-Transformers-LLMs-Book/code/python/p13/iv53.py
python -E /media/mario-geometry/WD_SN7100_NVMe/coding-projects/interactive-books-worktrees/book-iv-development/Interactive-Neural-Networks-Transformers-LLMs-Book/code/python/p13/iv53.py '{"seed":3,"split":1,"mode":2,"eta":0.1,"optimizer":1}'
python -E /media/mario-geometry/WD_SN7100_NVMe/coding-projects/interactive-books-worktrees/book-iv-development/Interactive-Neural-Networks-Transformers-LLMs-Book/code/python/p13/iv53.py -

No argument uses all five defaults. One JSON argument is a complete replacement raw state, not a patch; - reads that complete JSON from stdin. Missing/extra fields and duplicate object keys are rejected; nonstandard NaN/Infinity constants are rejected at parsing. A parsed raw boolean is rejected as a number. Query parsing handles its known text/I/O failures before deriving; an unknown ValueError from the derivation is outside that parse catch. Standard output contains the computed public record, which is not an independent correctness certificate.

The separate explicit --self-check flag selects only iv53.source_self_check, outside query error handling; it cannot be combined with a state query. Import, defaults, full JSON and stdin queries invoke zero check leaves. The twelve-file closure declares eight source_self_check functions: iv53, checkpoint_reference, training_reference, packing_reference, iv39, bpe_reference, tiny_reference and choice_reference. Seven are terminal checks; the unchanged explicitly invoked iv39 check also calls BPE’s check. The new iv53 and checkpoint checks call neither one another nor inherited check leaves. Token/component/FFN/head declare no such leaf. These authored checks are distinct from independent mathematical authority, cross-language parity and browser/accessibility verification.

Optional: derive one fixed feature row without inventing a fixture

The actual source remains the numerical authority. For understanding its exact-real counterpart, start with A’s embedding (1,0). Its mean is 1/2 and its population variance is 1/4. With normalization epsilon 1, the normalized row is (α,−α), where α=(1/2)/sqrt(5/4)=1/sqrt(5). A single allowed attention key has weight one, so identity projections and position-zero rotation return that row. The first residual is (1+α,−α).

Its mean is again 1/2. Put d=1/2+α; centering gives (d,−d), variance d², and the second normalized row is (r,−r) with r=d/sqrt(1+d²). The fixed three-coordinate hidden affine produces (r,−r,0). ReLU, which keeps positive entries and replaces nonpositive ones with zero, gives (r,0,0). The fixed output projection returns (r,0). Adding the residual gives Y_A=(A,−α), where A=1+α+r. Swapping the input embedding coordinates gives Y_B=(−α,A).

At the initial readout, A’s active scores are (A,−α,0). Define Z=exp(A)+exp(−α)+1, p=exp(A)/Z, q=exp(−α)/Z and s=1/Z. Its exact-real EOS loss is log(Z). The gradient consists of the feature-0 row A*(p,q,s−1,0,0), feature-1 row −α*(p,q,s−1,0,0), then bias row (p,q,s−1,0,0). B swaps the two feature roles and the first two probabilities. Equal initial losses therefore do not imply equal selected documents or equal gradients.

These symbols explain the source; they are not rounded feature constants to paste into a checkpoint. The actual trace saves each normalization, product, sum and represented feature. Binary64 associations, zero signs and elementary-function behavior must be considered separately when comparing implementations. In particular, a mixed-sign zero maximum can follow JavaScript’s Math.max policy or Python’s first-tie policy; any independent numerical witness must use one consistent admitted policy throughout its graph, rather than choose convenient signs at individual steps. That premise is separate from same-backend determinism and word preservation.

Recap and bridge

  • A full continuation state includes weights, optimizer memory and step, plus current prefetched order, cursor, epoch and future RNG state.
  • All 49 state/configuration floating words preserve bits, including signed zero; a short display is not a checkpoint.
  • Structural validation does not certify training origin. Normal-history relations remain consequences of normal transitions.
  • Same-state continuation follows by induction under the same deterministic context and backend; recovery mistakes can sometimes coincide.
  • Each saved NLL precedes its associated update. Three selected-example losses do not establish generalization or a scaling law.

The next chapter, Scaling Limits and Generalization, separates capacity, compute, data quality and evaluation uncertainty. Reproducing three updates is a useful reliability property; evaluating what a trained model has learned requires further evidence.