The neural notebook
← All chapters

IV-54 / Part XIII · Training Language Models

Scaling Limits and Generalization

Separate capacity, update count, label quality and validation membership sensitivity in a tiny fixed-feature regression experiment with fully worked half-MSE gradients.

Review the ideas this chapter uses

A model can improve its training score without becoming more useful on new inputs. It can also have enough adjustable numbers to express the right answer, yet take a poor step toward it. We will separate four questions: what the model can represent, how many updates it takes, which answers it trains against, and how much its reported validation score depends on the few points we inspect.

Generalization means prediction quality on inputs beyond those used for parameter updates.

Learning objective: Distinguish capacity, compute, data quality and evaluation uncertainty.

In IV-52 — Language-Model Training Steps and Batches, a frozen toy decoder supplied features to a trainable class readout, using cross-entropy. Here we deliberately use a smaller scalar regression network. Scalar means one number; regression predicts a numeric target rather than a class. A readout combines fixed input features into that prediction. Its hidden ReLU features stay fixed, and its loss is half the mean squared error. This lets us follow every training and validation example without implying that we trained a language model or differentiated an entire Transformer.

Compute it yourself

Scaling Limits and Generalization

Try to predict |x|, the distance of a number from zero. A tiny network has two fixed ReLU features and three stored readout coordinates. Change capacity, update count, one known wrong training label or the learning rate; compare fitting the observed labels with error against clean truth and held-out inputs.

This is an authored toy experiment with a fresh zero initialization after each edit. The stage table shows actual saved evaluations, including final parameters, and the inspectors explain every operation. The four-point validation grid is small and nonrandom.

observedTrainHalfMSE0.08033092692494392
cleanTrainHalfMSE0.08033092692494392
validationHalfMSE0.03074241615831852
enabledParameters3
Exact starting inputs for this saved calculation

observedTrainHalfMSE 0.08033092692494392. cleanTrainHalfMSE 0.08033092692494392. validationHalfMSE 0.03074241615831852. enabledParameters 3. Declare the bounded training and validation experiment. Every raw finite-number check precedes every finite domain check, including controls inactive at zero updates. This smaller regression readout bridges from IV52 without claiming full model training.

Declare the bounded training and validation experiment

capacity0:2 enabled; capacity1:3 enabled; always3 stored; train4; validation4; fixedFeatures2

Every raw finite-number check precedes every finite domain check, including controls inactive at zero updates. This smaller regression readout bridges from IV52 without claiming full model training.

Saved inputs

capacity
1
updates
2
corrupt
0
eta
0.25

Saved outputs

storedParameters
3
enabledParameters
3
trainSamples
4
validationSamples
4
fixedFeatures
2

Actual evaluated stages: three different questions about error

Current saved case: capacity=1, updates=2, corrupt=0, η=0.25. There are 3 enabled and 3 stored coordinates. Each raw edit starts again at θ=[+0,+0,+0].

Observed training loss asks how closely predictions fit the labels used for updates. Clean training loss compares the same predictions with the original truth. Validation loss compares predictions on four distinct clean inputs held out of the gradient. Lower half-MSE means smaller average squared error; it is not an accuracy percentage or token cross-entropy.

Every actual stage: same-theta coordinates and four-point objective means
Stage / next actionaPlusaMinusbObserved train half-MSEClean train half-MSEClean validation half-MSE
0 / then update0000.31250.31250.15625
1 / then update0.0781250.0781250.18750.15351867675781250.15351867675781250.06394195556640625
2 / final; diagnostic gradient only0.1325683593750.1325683593750.31347656250.080330926924943920.080330926924943920.03074241615831852

Stage 0 precedes every update; stage 2 genuinely evaluates the final parameters. The table contains only saved evaluations: no fitted curve, padding, analytic optimum or interpolated measurements. More updates or enabled parameters need not improve validation. η=0 still performs requested updates; updates=0 has one evaluated stage and no update.

Inspecting stage 0, sample train0, coordinate aPlus, omission 0. These selectors preserve the four raw controls, trace cursor and whole-root question cases.

Selected trace: setup. Matching operations below are marked current. The trace cursor and local inspection are independent.

All eight samples at stage 0

A feature is a fixed numeric input to the readout. φPlus=max(0,x) keeps the positive part; φMinus=max(0,−x) keeps the negative magnitude. Prediction=(aPlus×φPlus+aMinus×φMinus)+b. θ (theta) names the three readout coordinates. Here θ=[0, 0, 0]. The features stay fixed while enabled readout coordinates learn.

Stage 0: all authored inputs, fixed features, predictions, targets and half-losses
Sample / gradient rolexφPlusφMinusPredictionClean targetObserved training targetObserved train half-lossClean half-loss
train0 / trains-1010110.50.5
train1 / trains-0.500.500.50.50.1250.125
train2 / trains0.50.5000.50.50.1250.125
train3 / trains1100110.50.5
validation0 / held out-0.7500.7500.75Not a training labelNot in training objective0.28125
validation1 / held out-0.2500.2500.25Not a training labelNot in training objective0.03125
validation2 / held out0.250.25000.25Not a training labelNot in training objective0.03125
validation3 / held out0.750.75000.75Not a training labelNot in training objective0.28125

Only train0 can have a wrong observed target: corrupt=1 changes 1 to 1.5. Original clean truth remains |x|. Validation targets never change; validation predictions can change when trained θ changes. These authored grids are distinct, nonrandom inputs with no claim of population representativeness or an unseen test set.

Selected sample train0: every feature, product, error, square and half-loss

data_0: Compute fixed ReLU features and authored targets

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); cleanTarget=abs(x); observedTarget=corrupted?1.5:cleanTarget

All eight nonzero inputs are authored and distinct. Only the first training label can be corrupted; validation labels remain clean. These fixed features are computed once.

Saved inputs
sample
0
training
1
x
-1
zero
0
corrupt
0
corruptTarget
1.5
Saved outputs
negatedX
1
phiPlus
0
phiMinus
1
cleanTarget
1
corrupted
0
observedTarget
1

stage_0_forward_0: Evaluate both fixed features at the same current theta

productPlus=aPlus*phiPlus; productMinus=aMinus*phiMinus; featureSum=productPlus+productMinus; prediction=featureSum+b

Both products are performed in either capacity. Bias is added last; all eight rows use the same unchanged theta.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
aPlus
0
aMinus
0
b
0
Saved outputs
productPlus
0
productMinus
0
featureSum
0
prediction
0

stage_0_loss_0: Compute separate observed and clean training losses

cleanError=prediction-cleanTarget; cleanSquare=cleanError*cleanError; cleanHalf=cleanSquare/2; observedError=prediction-observedTarget; observedSquare=observedError*observedError; observedHalf=observedSquare/2

Both sets of arithmetic are actually evaluated, even when the targets coincide. Only observed errors enter the optimizer.

Saved inputs
sample
0
prediction
0
observedTarget
1
cleanTarget
1
divisor
2
Saved outputs
cleanError
-1
cleanSquare
1
cleanHalf
0.5
observedError
-1
observedSquare
1
observedHalf
0.5
Stage 0: all ordered objective sums and divisions

For each point, error=prediction−target, square=error×error and half-loss=square/2. Start at +0, add four saved half-losses in original row order, then divide by 4. This is Σ error²/8. Observed and clean losses are calculated separately even when equal.

stage_0_observed_mean: Average four saved per-point half-losses in order

sum starts at +0; sum0=sum+loss0; sum1=sum0+loss1; sum2=sum1+loss2; sum3=sum2+loss3; mean=sum3/4

The association is sum(error squared divided by two) divided by four. Display rounding is never used as an operand.

Saved inputs
initialSum
0
divisor
4
loss0
0.5
loss1
0.125
loss2
0.125
loss3
0.5
Saved outputs
sum0
0.5
sum1
0.625
sum2
0.75
sum3
1.25
mean
0.3125

stage_0_clean_mean: Average four saved per-point half-losses in order

sum starts at +0; sum0=sum+loss0; sum1=sum0+loss1; sum2=sum1+loss2; sum3=sum2+loss3; mean=sum3/4

The association is sum(error squared divided by two) divided by four. Display rounding is never used as an operand.

Saved inputs
initialSum
0
divisor
4
loss0
0.5
loss1
0.125
loss2
0.125
loss3
0.5
Saved outputs
sum0
0.5
sum1
0.625
sum2
0.75
sum3
1.25
mean
0.3125

stage_0_validation_mean: Average four saved per-point half-losses in order

sum starts at +0; sum0=sum+loss0; sum1=sum0+loss1; sum2=sum1+loss2; sum3=sum2+loss3; mean=sum3/4

The association is sum(error squared divided by two) divided by four. Display rounding is never used as an operand.

Saved inputs
initialSum
0
divisor
4
loss0
0.28125
loss1
0.03125
loss2
0.03125
loss3
0.28125
Saved outputs
sum0
0.28125
sum1
0.3125
sum2
0.34375
sum3
0.625
mean
0.15625

Mathematical gradient, effective gradient and simultaneous update

The gradient tells how the underlying real training objective changes for a small coordinate change at the saved θ. For each feature coordinate it is Σ(feature×observed error)/4. For b it is Σ observed error/4; the code sums errors directly. Validation and clean diagnostic truth never replace observed errors in this gradient.

Stage 0: all mathematical derivatives, enabled selectors and effective optimizer gradients
CoordinateSaved θEnabled selectorMathematical gradientEffective gradient
aPlus01-0.3125-0.3125
aMinus01-0.3125-0.3125
b01-0.75-0.75

A frozen aMinus can have a nonzero mathematical derivative. Capacity=0 selects effective +0 and explicitly preserves its committed +0. The selector is a conditional choice; no multiplication is invented. Both feature products and every mathematical derivative are still computed.

Stage 0: four actual observed-error contributions to aPlus
Training rowObserved errorFixed featureActual feature × errorOrdered running sum
train0-10-00
train1-0.50-00
train2-0.50.5-0.25-0.25
train3-11-1-1.25

Divide the final sum by 4 to obtain aPlus mathematical gradient -0.3125.

Update 1: all proposals from the same old θ, committed together
CoordinateOldMathematical gradientEffective gradientEnabledη × effectiveProposed old − deltaCommitted
aPlus0-0.3125-0.31251-0.0781250.0781250.078125
aMinus0-0.3125-0.31251-0.0781250.0781250.078125
b0-0.75-0.751-0.18750.18750.1875

Compute delta=η×effective, proposed=old−delta, and committed=enabled?proposed:+0 for all three coordinates. No new coordinate feeds another gradient. Only then publish the vector and evaluate all eight rows again at stage 1.

Selected coordinate update and simultaneous commit

update_1_coordinate_0: Propose one coordinate from the same old state

delta=eta*effective; proposed=old-delta; committed=enabled==1?proposed:+0

All three stored coordinates get real delta/proposal records. The frozen coordinate commits positive zero; no new coordinate is used to recompute another gradient.

Saved inputs
coordinate
0
old
0
mathematical
-0.3125
effective
-0.3125
enabled
1
eta
0.25
frozenZero
0
Saved outputs
delta
-0.078125
proposed
0.078125
committed
0.078125

update_1_commit: Publish the three simultaneous SGD coordinates together

nextTheta=[committed0,committed1,committed2]

This completes exactly one optimizer batch. A subsequent stage genuinely reevaluates all eight samples; no final diagnostic gradient causes another update.

Saved inputs
old0
0
old1
0
old2
0
Saved outputs
theta0
0.078125
theta1
0.078125
theta2
0.1875
Why these derivatives work, and what the shapes mean

One half-loss is (prediction−target)²/2. Differentiating the square gives 2×error; dividing by 2 cancels that factor. The derivative of prediction with respect to aPlus is φPlus, with respect to aMinus is φMinus, and with respect to b is 1. Average four row contributions. The fixed features do not depend on these coordinates, so this is a smooth quadratic in θ; we are not differentiating ReLU with respect to x at a kink.

For one sample, augmented feature column [φPlus,φMinus,1]ᵀ has shape [3,1], as does θ; θᵀ times that column gives one scalar. Explicitly turning four samples into rows gives F:[4,3] and Fθ:[4,1]. The implementation stores θ:[3] and adds b last after two products. Data:[8,5] stores sample × data field; stage forwards:[8,4] store sample × forward field. Named axes and every stored value are available in the house inspector below.

stage_0_gradient_0: Differentiate the observed training objective

product_i=feature_i*observedError_i; sum starts at +0; sum_i=sum_previous+product_i in row order; gradient=sum3/4

All three mathematical gradients are evaluated, including the frozen coordinate and the final diagnostic stage. The bias sums errors directly without invented products.

Saved inputs
coordinate
0
initialSum
0
divisor
4
error0
-1
feature0
0
error1
-0.5
feature1
0
error2
-0.5
feature2
0.5
error3
-1
feature3
1
Saved outputs
product0
-0
sum0
0
product1
-0
sum1
0
product2
-0.25
sum2
-0.25
product3
-1
sum3
-1.25
gradient
-0.3125

stage_0_gate: Select the enabled optimizer coordinates

mask=[1,capacity==1?1:0,1]; effective_j=mask_j==1?mathematical_j:+0

This is a conditional selector, not a multiplication or a claim that a frozen coordinate has zero mathematical derivative.

Saved inputs
capacity
1
mathematical0
-0.3125
mathematical1
-0.3125
mathematical2
-0.75
frozenZero
0
Saved outputs
mask0
1
mask1
1
mask2
1
effective0
-0.3125
effective1
-0.3125
effective2
-0.75

How sensitive is validation to membership in this tiny grid?

The full stage-0 validation half-MSE is 0.15625. Each row below omits one of its four saved losses, adds the other three in their original order from +0, then divides by 3. There is no retraining, random draw, resplit or extra prediction.

Stage 0: all four actual validation omission means
Omitted validation sampleIncluded original indicesMean of three saved half-losses
validation01, 2, 30.11458333333333333
validation10, 2, 30.19791666666666666
validation20, 1, 30.19791666666666666
validation30, 1, 20.11458333333333333

Actual omission minimum=0.11458333333333333; maximum=0.19791666666666666. This is descriptive membership sensitivity on four authored points. The overlapping subsets do not form a confidence interval or a cross-validation experiment with retraining. Even zero spread cannot prove zero uncertainty outside this grid. Repeated selection against this validation set can overfit the selection.

Stage 0: omission 0 ordered accumulation
Included positionOriginal validation indexSaved half-lossRunning sum
010.031250.03125
120.031250.0625
230.281250.34375

Last sum / 3 = 0.11458333333333333. Division by 3 is generally rounded in binary64 even when its input losses are exact dyadic fractions.

Selected omission and every actual minimum/maximum comparison

stage_0_omit_0: Omit one saved validation loss and average the other three

sum starts at +0; add the three included saved half-losses in original index order; mean=sum2/3

No retraining, resplit or extra forward evaluation occurs. Division by three is generally rounded binary64; these overlapping subsets describe membership sensitivity.

Saved inputs
omitted
0
initialSum
0
divisor
3
included0
1
loss0
0.03125
included1
2
loss1
0.03125
included2
3
loss2
0.28125
Saved outputs
sum0
0.03125
sum1
0.0625
sum2
0.34375
mean
0.11458333333333333

stage_0_range_1: Compare actual omission means to the running range

lower=value<oldMinimum; higher=value>oldMaximum; minimum=lower?value:oldMinimum; maximum=higher?value:oldMaximum

Initialize both endpoints from omission mean zero, then compare means one through three. The resulting descriptive range is not a confidence interval.

Saved inputs
omission
1
value
0.19791666666666666
oldMinimum
0.11458333333333333
oldMaximum
0.11458333333333333
Saved outputs
lower
0
higher
1
minimum
0.11458333333333333
maximum
0.19791666666666666

stage_0_range_2: Compare actual omission means to the running range

lower=value<oldMinimum; higher=value>oldMaximum; minimum=lower?value:oldMinimum; maximum=higher?value:oldMaximum

Initialize both endpoints from omission mean zero, then compare means one through three. The resulting descriptive range is not a confidence interval.

Saved inputs
omission
2
value
0.19791666666666666
oldMinimum
0.11458333333333333
oldMaximum
0.19791666666666666
Saved outputs
lower
0
higher
0
minimum
0.11458333333333333
maximum
0.19791666666666666

stage_0_range_3: Compare actual omission means to the running range

lower=value<oldMinimum; higher=value>oldMaximum; minimum=lower?value:oldMinimum; maximum=higher?value:oldMaximum

Initialize both endpoints from omission mean zero, then compare means one through three. The resulting descriptive range is not a confidence interval.

Saved inputs
omission
3
value
0.11458333333333333
oldMinimum
0.11458333333333333
oldMaximum
0.19791666666666666
Saved outputs
lower
0
higher
0
minimum
0.11458333333333333
maximum
0.19791666666666666

Count the actual work separately from the requested updates

Whole current root: actual algorithmic work and stored-record counts
QuantityActual count
Fixed feature maps (once)8
Evaluated stages3
Sample forward evaluations24
Gradient batches, including final diagnostic3
Training rows in all gradient batches12
Coordinate gradient contractions9
Completed optimizer batches2
Training rows used by optimizer batches8
Stored-coordinate update records6
Enabled-coordinate updates6
Three-point omission means12
Minimum/maximum comparisons18
Saved operation frames112
Saved tensors46

There are 8 feature maps once, 8 sample forwards per evaluated stage, 4 training rows and 3 mathematical contractions per gradient batch, and 3 stored-coordinate proposal records per requested update. All gradients are computed even when one coordinate is frozen. Final gradients and omission statistics add work without adding optimizer batches. These are algorithmic counts, not FLOPs, elapsed time, throughput or hardware scaling measurements.

Hand-worked anchors, capacity proof and counterexamples

Fixed clean initial case: θ=[0,0,0]. Training squares are [1,1/4,1/4,1], so training half-MSE=(1+1/4+1/4+1)/8=5/16. Validation squares are [9/16,1/16,1/16,9/16], giving 5/32. Initial validation half-losses are [9/32,1/32,1/32,9/32]; omitting an endpoint gives (1/32+1/32+9/32)/3=11/96, while omitting an inner point gives 19/96. These fractions are mathematical anchors; the /3 displays are rounded.

Fixed full-capacity, clean, η=1/4 first update: gPlus=(0+0−1/4−1)/4=−5/16, gMinus=(−1−1/4+0+0)/4=−5/16, and gB=(−1−1/2−1/2−1)/4=−3/4. Thus θ₁=[5/64,5/64,3/16]. At x=1, prediction=(5/64×1+5/64×0)+3/16=17/64; error=−47/64, square=2209/4096, half-loss=2209/8192. At |x|=1/2, prediction=29/128 and error=−35/128. Averaging the four actual half-losses gives train 10061/65536; validation gives 8381/131072. Capacity=0 instead commits [5/64,0,3/16].

Representational proof: θ=[1,1,0] gives max(0,x)+max(0,−x)=|x| for every real x by construction. When aMinus=0, every negative input predicts the same b, so the two negative training targets 1 and 1/2 cannot both be fitted. This algebraic possibility does not say that three updates reach the ideal, that learned hidden features generalize, or that more capacity always improves validation.

Fixed full-capacity, clean, one update at η=2: θ₁=[5/8,5/8,3/2]. Training errors at |x|=1 and 1/2 are 9/8 and 21/16, giving train 765/1024 > 5/16=320/1024. This valid overshoot refutes guaranteed improvement. In the distinct full-capacity, one-update η=1/4 cases, corrupt=1 gives validation 6969/131072, below clean 8381/131072. One wrong label can accidentally help this small validation mean; that is no general benefit of corruption.

The underlying observed objective is quadratic, so its exact-real centered difference has zero truncation error. An exact binary64 arithmetic proof is restricted to η=1/4 or 2, stages 0..3, either capacity/quality choice, enabled coordinates and h=2⁻¹². It requires distinct exactly represented endpoints and bounds on every operation; signed-zero words need separate treatment. It excludes omission /3 statistics and does not extend to arbitrary η. Displayed decimals are round-trip strings of saved binary64 numbers, not exact-real fractions.

IV-52 used cross-entropy on a frozen decoder readout. Here a deliberately smaller scalar regression network uses fixed ReLU features and half-MSE so capacity, compute, label quality and evaluation membership are inspectable. This short authored experiment cannot establish universal LLM scaling laws, natural-text generalization or frontier performance. Part XIV builds on the distinction between changing parameters and evaluating an adaptation.

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.

Data

Sample=8 × DataField=5 · float64 · precision 8 · Actual once-computed authored data in texts.sampleKeys and texts.dataFields order; first four train, last four held-out validation; clean labels are abs(x).

Zero-based storage indexStored value
0-1
10
21
31
41
5-0.5
60
70.5
80.5
90.5
100.5
110.5
120
130.5
140.5
151
161
170
181
191
20-0.75
210
220.75
230.75
240.75
25-0.25
260
270.25
280.25
290.25
300.25
310.25
320
330.25
340.25
350.75
360.75
370
380.75
390.75

InitialTheta

Coordinate=3 · float64 · precision 8 · Authored floating positive-zero readout initialization in aPlus,aMinus,b order.

Zero-based storage indexStored value
00
10
20

EnabledMask

Coordinate=3 · int32 · precision 0 · Authored capacity-dependent integer selectors in aPlus,aMinus,b order; never feature or gradient multipliers.

Zero-based storage indexStored value
01
11
21

stage_0_Theta

Coordinate=3 · float64 · precision 8 · Actual saved represented theta in aPlus,aMinus,b order; no raw-editor bounds on derived coordinates.

Zero-based storage indexStored value
00
10
20

stage_0_Forward

Sample=8 × ForwardField=4 · float64 · precision 8 · Actual two products, feature sum and bias-last prediction, in texts.forwardFields order.

Zero-based storage indexStored value
00
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310

stage_0_TrainLoss

TrainSample=4 × TrainLossField=8 · float64 · precision 8 · Actual separately computed observed and clean fields in texts.trainLossFields order; authored truth remains distinct from optimizer labels.

Zero-based storage indexStored value
01
1-1
21
30.5
41
5-1
61
70.5
80.5
9-0.5
100.25
110.125
120.5
13-0.5
140.25
150.125
160.5
17-0.5
180.25
190.125
200.5
21-0.5
220.25
230.125
241
25-1
261
270.5
281
29-1
301
310.5

stage_0_ValidationLoss

ValidationSample=4 × ValidationLossField=4 · float64 · precision 8 · Actual clean validation fields in texts.validationLossFields order; never gradient targets.

Zero-based storage indexStored value
00.75
1-0.75
20.5625
30.28125
40.25
5-0.25
60.0625
70.03125
80.25
9-0.25
100.0625
110.03125
120.75
13-0.75
140.5625
150.28125

stage_0_Means

Objective=3 · float64 · precision 8 · Ordered observed training, clean training, clean validation half-MSE; each averages four saved half-losses.

Zero-based storage indexStored value
00.3125
10.3125
20.15625

stage_0_GradientRows

Coordinate=3 × TrainSample=4 × GradientRowField=2 · float64 · precision 8 · Actual contribution and ordered partial sum; feature products for coordinates0/1, direct error contributions for bias2.

Zero-based storage indexStored value
0-0
10
2-0
30
4-0.25
5-0.25
6-1
7-1.25
8-1
9-1
10-0.25
11-1.25
12-0
13-1.25
14-0
15-1.25
16-1
17-1
18-0.5
19-1.5
20-0.5
21-2
22-1
23-3

stage_0_MathematicalGradient

Coordinate=3 · float64 · precision 8 · All three observed-objective derivatives at the same saved theta; final-stage values are diagnostic.

Zero-based storage indexStored value
0-0.3125
1-0.3125
2-0.75

stage_0_EffectiveGradient

Coordinate=3 · float64 · precision 8 · Actual conditional optimizer selection; disabled coordinate is floating positive zero.

Zero-based storage indexStored value
0-0.3125
1-0.3125
2-0.75

stage_0_OmissionRows

Omission=4 × IncludedPosition=3 × OmissionRowField=3 · float64 · precision 8 · Included original index, saved loss and actual ordered partial sum; no total-minus-omitted shortcut.

Zero-based storage indexStored value
01
10.03125
20.03125
32
40.03125
50.0625
63
70.28125
80.34375
90
100.28125
110.28125
122
130.03125
140.3125
153
160.28125
170.59375
180
190.28125
200.28125
211
220.03125
230.3125
243
250.28125
260.59375
270
280.28125
290.28125
301
310.03125
320.3125
332
340.03125
350.34375

stage_0_OmissionMeans

Omission=4 · float64 · precision 8 · Four actual division-by-three means in omitted-index order, generally rounded binary64.

Zero-based storage indexStored value
00.11458333333333333
10.19791666666666666
20.19791666666666666
30.11458333333333333

stage_0_RangeComparisons

Comparison=3 × RangeField=7 · float64 · precision 8 · Actual comparison operands, numeric flags and selected endpoints in texts.rangeFields order.

Zero-based storage indexStored value
00.19791666666666666
10.11458333333333333
20.11458333333333333
30
41
50.11458333333333333
60.19791666666666666
70.19791666666666666
80.11458333333333333
90.19791666666666666
100
110
120.11458333333333333
130.19791666666666666
140.11458333333333333
150.11458333333333333
160.19791666666666666
170
180
190.11458333333333333
200.19791666666666666

stage_0_OmissionRange

Endpoint=2 · float64 · precision 8 · Minimum then maximum of the four actual omission means; descriptive membership sensitivity only.

Zero-based storage indexStored value
00.11458333333333333
10.19791666666666666

stage_0_Stats

StageField=7 · float64 · precision 8 · Actual same-theta stage metrics and diagnostic/update selectors in texts.stageFields order.

Zero-based storage indexStored value
00.3125
10.3125
20.15625
30.11458333333333333
40.19791666666666666
50
61

update_1_Update

Coordinate=3 × UpdateField=7 · float64 · precision 8 · Actual old, mathematical, effective, enabled, delta, proposed, committed fields in texts.updateFields order; all proposals use the same old theta.

Zero-based storage indexStored value
00
1-0.3125
2-0.3125
31
4-0.078125
50.078125
60.078125
70
8-0.3125
9-0.3125
101
11-0.078125
120.078125
130.078125
140
15-0.75
16-0.75
171
18-0.1875
190.1875
200.1875

stage_1_Theta

Coordinate=3 · float64 · precision 8 · Actual saved represented theta in aPlus,aMinus,b order; no raw-editor bounds on derived coordinates.

Zero-based storage indexStored value
00.078125
10.078125
20.1875

stage_1_Forward

Sample=8 × ForwardField=4 · float64 · precision 8 · Actual two products, feature sum and bias-last prediction, in texts.forwardFields order.

Zero-based storage indexStored value
00
10.078125
20.078125
30.265625
40
50.0390625
60.0390625
70.2265625
80.0390625
90
100.0390625
110.2265625
120.078125
130
140.078125
150.265625
160
170.05859375
180.05859375
190.24609375
200
210.01953125
220.01953125
230.20703125
240.01953125
250
260.01953125
270.20703125
280.05859375
290
300.05859375
310.24609375

stage_1_TrainLoss

TrainSample=4 × TrainLossField=8 · float64 · precision 8 · Actual separately computed observed and clean fields in texts.trainLossFields order; authored truth remains distinct from optimizer labels.

Zero-based storage indexStored value
01
1-0.734375
20.539306640625
30.2696533203125
41
5-0.734375
60.539306640625
70.2696533203125
80.5
9-0.2734375
100.07476806640625
110.037384033203125
120.5
13-0.2734375
140.07476806640625
150.037384033203125
160.5
17-0.2734375
180.07476806640625
190.037384033203125
200.5
21-0.2734375
220.07476806640625
230.037384033203125
241
25-0.734375
260.539306640625
270.2696533203125
281
29-0.734375
300.539306640625
310.2696533203125

stage_1_ValidationLoss

ValidationSample=4 × ValidationLossField=4 · float64 · precision 8 · Actual clean validation fields in texts.validationLossFields order; never gradient targets.

Zero-based storage indexStored value
00.75
1-0.50390625
20.2539215087890625
30.12696075439453125
40.25
5-0.04296875
60.0018463134765625
70.00092315673828125
80.25
9-0.04296875
100.0018463134765625
110.00092315673828125
120.75
13-0.50390625
140.2539215087890625
150.12696075439453125

stage_1_Means

Objective=3 · float64 · precision 8 · Ordered observed training, clean training, clean validation half-MSE; each averages four saved half-losses.

Zero-based storage indexStored value
00.1535186767578125
10.1535186767578125
20.06394195556640625

stage_1_GradientRows

Coordinate=3 × TrainSample=4 × GradientRowField=2 · float64 · precision 8 · Actual contribution and ordered partial sum; feature products for coordinates0/1, direct error contributions for bias2.

Zero-based storage indexStored value
0-0
10
2-0
30
4-0.13671875
5-0.13671875
6-0.734375
7-0.87109375
8-0.734375
9-0.734375
10-0.13671875
11-0.87109375
12-0
13-0.87109375
14-0
15-0.87109375
16-0.734375
17-0.734375
18-0.2734375
19-1.0078125
20-0.2734375
21-1.28125
22-0.734375
23-2.015625

stage_1_MathematicalGradient

Coordinate=3 · float64 · precision 8 · All three observed-objective derivatives at the same saved theta; final-stage values are diagnostic.

Zero-based storage indexStored value
0-0.2177734375
1-0.2177734375
2-0.50390625

stage_1_EffectiveGradient

Coordinate=3 · float64 · precision 8 · Actual conditional optimizer selection; disabled coordinate is floating positive zero.

Zero-based storage indexStored value
0-0.2177734375
1-0.2177734375
2-0.50390625

stage_1_OmissionRows

Omission=4 × IncludedPosition=3 × OmissionRowField=3 · float64 · precision 8 · Included original index, saved loss and actual ordered partial sum; no total-minus-omitted shortcut.

Zero-based storage indexStored value
01
10.00092315673828125
20.00092315673828125
32
40.00092315673828125
50.0018463134765625
63
70.12696075439453125
80.12880706787109375
90
100.12696075439453125
110.12696075439453125
122
130.00092315673828125
140.1278839111328125
153
160.12696075439453125
170.25484466552734375
180
190.12696075439453125
200.12696075439453125
211
220.00092315673828125
230.1278839111328125
243
250.12696075439453125
260.25484466552734375
270
280.12696075439453125
290.12696075439453125
301
310.00092315673828125
320.1278839111328125
332
340.00092315673828125
350.12880706787109375

stage_1_OmissionMeans

Omission=4 · float64 · precision 8 · Four actual division-by-three means in omitted-index order, generally rounded binary64.

Zero-based storage indexStored value
00.042935689290364586
10.08494822184244792
20.08494822184244792
30.042935689290364586

stage_1_RangeComparisons

Comparison=3 × RangeField=7 · float64 · precision 8 · Actual comparison operands, numeric flags and selected endpoints in texts.rangeFields order.

Zero-based storage indexStored value
00.08494822184244792
10.042935689290364586
20.042935689290364586
30
41
50.042935689290364586
60.08494822184244792
70.08494822184244792
80.042935689290364586
90.08494822184244792
100
110
120.042935689290364586
130.08494822184244792
140.042935689290364586
150.042935689290364586
160.08494822184244792
170
180
190.042935689290364586
200.08494822184244792

stage_1_OmissionRange

Endpoint=2 · float64 · precision 8 · Minimum then maximum of the four actual omission means; descriptive membership sensitivity only.

Zero-based storage indexStored value
00.042935689290364586
10.08494822184244792

stage_1_Stats

StageField=7 · float64 · precision 8 · Actual same-theta stage metrics and diagnostic/update selectors in texts.stageFields order.

Zero-based storage indexStored value
00.1535186767578125
10.1535186767578125
20.06394195556640625
30.042935689290364586
40.08494822184244792
50
61

update_2_Update

Coordinate=3 × UpdateField=7 · float64 · precision 8 · Actual old, mathematical, effective, enabled, delta, proposed, committed fields in texts.updateFields order; all proposals use the same old theta.

Zero-based storage indexStored value
00.078125
1-0.2177734375
2-0.2177734375
31
4-0.054443359375
50.132568359375
60.132568359375
70.078125
8-0.2177734375
9-0.2177734375
101
11-0.054443359375
120.132568359375
130.132568359375
140.1875
15-0.50390625
16-0.50390625
171
18-0.1259765625
190.3134765625
200.3134765625

stage_2_Theta

Coordinate=3 · float64 · precision 8 · Actual saved represented theta in aPlus,aMinus,b order; no raw-editor bounds on derived coordinates.

Zero-based storage indexStored value
00.132568359375
10.132568359375
20.3134765625

stage_2_Forward

Sample=8 × ForwardField=4 · float64 · precision 8 · Actual two products, feature sum and bias-last prediction, in texts.forwardFields order.

Zero-based storage indexStored value
00
10.132568359375
20.132568359375
30.446044921875
40
50.0662841796875
60.0662841796875
70.3797607421875
80.0662841796875
90
100.0662841796875
110.3797607421875
120.132568359375
130
140.132568359375
150.446044921875
160
170.09942626953125
180.09942626953125
190.41290283203125
200
210.03314208984375
220.03314208984375
230.34661865234375
240.03314208984375
250
260.03314208984375
270.34661865234375
280.09942626953125
290
300.09942626953125
310.41290283203125

stage_2_TrainLoss

TrainSample=4 × TrainLossField=8 · float64 · precision 8 · Actual separately computed observed and clean fields in texts.trainLossFields order; authored truth remains distinct from optimizer labels.

Zero-based storage indexStored value
01
1-0.553955078125
20.30686622858047485
30.15343311429023743
41
5-0.553955078125
60.30686622858047485
70.15343311429023743
80.5
9-0.1202392578125
100.014457479119300842
110.007228739559650421
120.5
13-0.1202392578125
140.014457479119300842
150.007228739559650421
160.5
17-0.1202392578125
180.014457479119300842
190.007228739559650421
200.5
21-0.1202392578125
220.014457479119300842
230.007228739559650421
241
25-0.553955078125
260.30686622858047485
270.15343311429023743
281
29-0.553955078125
300.30686622858047485
310.15343311429023743

stage_2_ValidationLoss

ValidationSample=4 × ValidationLossField=4 · float64 · precision 8 · Actual clean validation fields in texts.validationLossFields order; never gradient targets.

Zero-based storage indexStored value
00.75
1-0.33709716796875
20.11363450065255165
30.056817250326275826
40.25
50.09661865234375
60.009335163980722427
70.004667581990361214
80.25
90.09661865234375
100.009335163980722427
110.004667581990361214
120.75
13-0.33709716796875
140.11363450065255165
150.056817250326275826

stage_2_Means

Objective=3 · float64 · precision 8 · Ordered observed training, clean training, clean validation half-MSE; each averages four saved half-losses.

Zero-based storage indexStored value
00.08033092692494392
10.08033092692494392
20.03074241615831852

stage_2_GradientRows

Coordinate=3 × TrainSample=4 × GradientRowField=2 · float64 · precision 8 · Actual contribution and ordered partial sum; feature products for coordinates0/1, direct error contributions for bias2.

Zero-based storage indexStored value
0-0
10
2-0
30
4-0.06011962890625
5-0.06011962890625
6-0.553955078125
7-0.61407470703125
8-0.553955078125
9-0.553955078125
10-0.06011962890625
11-0.61407470703125
12-0
13-0.61407470703125
14-0
15-0.61407470703125
16-0.553955078125
17-0.553955078125
18-0.1202392578125
19-0.6741943359375
20-0.1202392578125
21-0.79443359375
22-0.553955078125
23-1.348388671875

stage_2_MathematicalGradient

Coordinate=3 · float64 · precision 8 · All three observed-objective derivatives at the same saved theta; final-stage values are diagnostic.

Zero-based storage indexStored value
0-0.1535186767578125
1-0.1535186767578125
2-0.33709716796875

stage_2_EffectiveGradient

Coordinate=3 · float64 · precision 8 · Actual conditional optimizer selection; disabled coordinate is floating positive zero.

Zero-based storage indexStored value
0-0.1535186767578125
1-0.1535186767578125
2-0.33709716796875

stage_2_OmissionRows

Omission=4 × IncludedPosition=3 × OmissionRowField=3 · float64 · precision 8 · Included original index, saved loss and actual ordered partial sum; no total-minus-omitted shortcut.

Zero-based storage indexStored value
01
10.004667581990361214
20.004667581990361214
32
40.004667581990361214
50.009335163980722427
63
70.056817250326275826
80.06615241430699825
90
100.056817250326275826
110.056817250326275826
122
130.004667581990361214
140.06148483231663704
153
160.056817250326275826
170.11830208264291286
180
190.056817250326275826
200.056817250326275826
211
220.004667581990361214
230.06148483231663704
243
250.056817250326275826
260.11830208264291286
270
280.056817250326275826
290.056817250326275826
301
310.004667581990361214
320.06148483231663704
332
340.004667581990361214
350.06615241430699825

stage_2_OmissionMeans

Omission=4 · float64 · precision 8 · Four actual division-by-three means in omitted-index order, generally rounded binary64.

Zero-based storage indexStored value
00.022050804768999416
10.03943402754763762
20.03943402754763762
30.022050804768999416

stage_2_RangeComparisons

Comparison=3 × RangeField=7 · float64 · precision 8 · Actual comparison operands, numeric flags and selected endpoints in texts.rangeFields order.

Zero-based storage indexStored value
00.03943402754763762
10.022050804768999416
20.022050804768999416
30
41
50.022050804768999416
60.03943402754763762
70.03943402754763762
80.022050804768999416
90.03943402754763762
100
110
120.022050804768999416
130.03943402754763762
140.022050804768999416
150.022050804768999416
160.03943402754763762
170
180
190.022050804768999416
200.03943402754763762

stage_2_OmissionRange

Endpoint=2 · float64 · precision 8 · Minimum then maximum of the four actual omission means; descriptive membership sensitivity only.

Zero-based storage indexStored value
00.022050804768999416
10.03943402754763762

stage_2_Stats

StageField=7 · float64 · precision 8 · Actual same-theta stage metrics and diagnostic/update selectors in texts.stageFields order.

Zero-based storage indexStored value
00.08033092692494392
10.08033092692494392
20.03074241615831852
30.022050804768999416
40.03943402754763762
51
60

StageMetrics

Stage=3 × Objective=3 · float64 · precision 8 · Only actual evaluated stages0..updates in texts.objectiveKeys order; no padded, interpolated, fitted or analytic-optimum points.

Zero-based storage indexStored value
00.3125
10.3125
20.15625
30.1535186767578125
40.1535186767578125
50.06394195556640625
60.08033092692494392
70.08033092692494392
80.03074241615831852

StageTheta

Stage=3 × Coordinate=3 · float64 · precision 8 · Only actual same-stage readout coordinates in aPlus,aMinus,b order, including genuinely evaluated final theta.

Zero-based storage indexStored value
00
10
20
30.078125
40.078125
50.1875
60.132568359375
70.132568359375
80.3134765625

Check your understanding

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

1. What does capacity=0 change in this fixed-feature regression network?
2. Fixed case: capacity=1, updates=0, corrupt=0, η=1/4. At θ=[0,0,0], train targets are [1,1/2,1/2,1]. What is the observed training half-MSE and the explicit augmented row-design shape?
3. Fixed case: capacity=0, updates=1, corrupt=0, η=1/4. At initialization the mathematical gradient is [-5/16,-5/16,-3/4]. What is the simultaneously committed θ after one update?
4. Current whole saved root: capacity=1, updates=2, corrupt=0, η=0.25; final observed train=0.08033092692494392, clean train=0.08033092692494392, validation=0.03074241615831852; enabled=3, stages=3, optimizer batches=2, sample forwards=24. Which interpretation is justified? Inspection selectors do not change this case.
5. Fixed transfer cases: full capacity, one update. With clean labels and η=2, training half-MSE changes from 5/16 to 765/1024. At η=1/4, corrupt=1 gives validation 6969/131072 versus clean 8381/131072. What can these cases and the four omission means establish?

Exactly five graded questions follow the saved calculation. Fixed cases state all four inputs; the live case uses the whole current root. Local inspection preserves answers and numerical state; raw edits, reset and trace navigation clear answers.

Four different questions

Capacity means the outputs a model can represent as its allowed parameters vary. Our choice enables two or three coordinates while always storing three. Compute here means a bounded number of full-batch updates: each update uses all four training samples together. Evaluation computes predictions and losses at given parameters; a diagnostic reports information without changing those parameters. We count that work separately. Data quality means whether one known training answer is deliberately wrong. Evaluation uncertainty here means the descriptive sensitivity of a validation mean to leaving out one of four saved validation losses.

These are different interventions. A larger capacity does not choose good parameters for us. An extra update can move the parameters in the wrong direction. A smaller observed training loss can mean fitting a wrong label. A precise mean over four selected points does not establish performance outside those points. Review III-04 — Training, Validation, Testing and Generalization for the roles of training, validation and testing, and III-36 — Learning Curves and Model Selection for learning curves and the risk of selecting a model against the same validation set repeatedly.

The experiment has exactly four numerical inputs, in this order:

InputDefaultAllowed valuesMeaning
capacity10 or 10 freezes the negative-side coefficient; 1 enables it
updates2Integers 0 through 3Number of simultaneous full-batch parameter replacements
corrupt00 or 11 changes only the first observed training label
eta1/4Finite numbers from 0 through 2Learning rate, written η\eta in equations

Changing a case starts from the same zero parameters. It does not continue training the preceding case. Zero updates still has an initial evaluation and diagnostic gradient. A zero learning rate still performs the requested updates and subsequent evaluations, although the parameter values do not move. All four inputs must be valid in either case; an inactive control does not excuse an invalid value. A learning rate of 2 is valid and supplies a useful overshoot counterexample.

Explore one calculation without changing its evidence

Start with Reset example. The four summary boxes report the final observed training half-MSE, clean training half-MSE, validation half-MSE and enabled parameter count. The default has two updates, so the stage table contains stages 0, 1 and 2. The inspection selectors initially show stage 0. Its table explains the first update while the summary still reports the final stage 2; those are deliberately different views of one calculation.

The first three raw controls are choices; the learning rate accepts a finite number in its stated range. An empty or out-of-range learning-rate entry shows an error and hides the numerical projection and graded questions until it is valid. It is not silently clamped to a nearby valid case. Every raw edit starts from zero again, returns the calculation trace to its beginning and clears graded answers. Reset restores all four defaults and clears answers too.

Below the stage table are four separate inspection-only selectors:

Selector labelWhat it selects from the saved calculation
Evaluated stage (inspection only)One actual stage from 0 through updates; all eight sample rows, gradients, omissions and any following update belong to that stage
Sample (inspection only)One of train0 through train3, then validation0 through validation3, for detailed feature, forward and loss operations
Readout coordinate (inspection only)aPlus, aMinus or b for the four observed-error contributions and selected coordinate update
Omitted validation sample (inspection only)Which of validation0 through validation3 is left out of the detailed three-loss accumulation

These selectors do not retrain, change the four raw inputs, move the calculation trace or clear graded answers. The stage index is bounded before reading a saved stage: if stage 3 was selected and you reduce updates to 0, inspection shows the available stage 0 immediately. Increasing updates later may reveal the remembered selection again. Sample, coordinate and omission selections are also bounded to their current saved domains. Reset restores the numerical case; choose stage 0 explicitly when following the first-step arithmetic below.

Try the following guided comparisons. These are explorations of the one lab, not additional graded questions:

  1. With the defaults, inspect stage 0, sample train0 and coordinate aMinus. Open the selected-sample details to follow both products, their sum, the bias addition, the error, its square and its half-loss. Open the objective sums to see the four additions and division by 4. The gradient contribution table divides its last sum by 4 too.
  2. Change capacity to 0. The mathematical aMinus gradient is still visible, but its effective gradient and committed coordinate are positive zero. The update table retains all three coordinates, including the frozen proposal; no training rows disappear.
  3. Select the final evaluated stage. It retains predictions, all three means, all three diagnostic gradients and all omissions, but has no next-update table or extra stage. Setting updates to 0 makes stage 0 that final stage. Setting the learning rate to 0 with positive updates instead keeps all requested transitions, evaluations and work counts, with unchanged parameters.
  4. Set full capacity, one update, clean labels and learning rate 2. Compare stages 0 and 1 to examine a valid overshoot. Then compare clean and corrupted labels at learning rate 1/4 with one update: observe the three distinct loss reports rather than assuming a wrong label must worsen every finite-step validation score.

For a validation sample, the table explicitly says there is no observed training label or training-objective loss; those cells are not missing zeros. For coordinate b, contributions are the observed errors directly, without fictitious feature products. The omission selector reveals three included original indices, their saved losses and each running sum. The following details show the actual minimum/maximum comparisons.

Previous step, Next step and Calculation step move through the saved operation trace independently of local inspection and clear graded answers. Detailed operations mark a matching trace step when it is among the selected details; trace navigation does not choose a new local stage for you. The full inspector exposes the same stored scalars, text and named tensors. Each wide evidence table is a named keyboard-focusable scroll region. The five graded questions occur only inside this lab: fixed questions state their cases, and the live interpretation question uses the complete current calculation’s final results, not the locally inspected stage.

Eight genuine examples, with different jobs

A sample is an input and its target answer. A feature is a number extracted from an input. A parameter is a stored model number; an enabled parameter may change during training. The prediction is the model’s numerical answer. An error is prediction minus target, including its sign. A loss turns that error into a nonnegative penalty.

Our authored rule is y=∣x∣y=|x|: the target is the distance of xx from zero. The fixed hidden features are

ϕ+(x)=max⁡(0,x),ϕ−(x)=max⁡(0,−x).\phi_+(x)=\max(0,x),\qquad \phi_-(x)=\max(0,-x).

ReLU, the rectified linear unit, keeps a positive input and replaces a negative input with zero. The positive-side feature responds to positive xx; the negative-side feature responds to negative xx. Both features are computed for every example, including the feature whose value is zero.

Split and indexInput xxPositive feature ϕ+\phi_+Negative feature ϕ−\phi_-Clean targetObserved target when corrupt=1
Train 0−10113/2
Train 1−1/201/21/21/2
Train 21/21/201/21/2
Train 311011
Validation 0−3/403/43/4Unchanged: 3/4
Validation 1−1/401/41/4Unchanged: 1/4
Validation 21/41/401/4Unchanged: 1/4
Validation 33/43/403/4Unchanged: 3/4

The training and validation inputs are disjoint: none of the four validation inputs appears in training. All eight feature pairs are also distinct. These are fixed, hand-authored grids, not random draws or a random split. We do not assert that they are independent and identically distributed (IID) samples from a population: independently drawn examples all following the same probability distribution. There is no final unseen test set here.

With corrupt=0, observed training targets equal the clean targets. With corrupt=1, only Train 0 changes from 1 to 3/2 in the observed labels. Its clean truth remains 1 so we can separately diagnose the effect. Validation targets never change and never contribute to the training gradient. Training can still change validation predictions because both splits use the same parameters.

What can this network express?

Store the parameter column θ=(a+,a−,b)T\theta=(a_+,a_-,b)^T, initially all positive zeros. The superscript TT means transpose: writing the tuple as a column. Its three coordinates are the positive-side coefficient, negative-side coefficient and bias. The prediction is

y^(x)=(a+ϕ+(x)+a−ϕ−(x))+b.\widehat y(x)=\bigl(a_+\phi_+(x)+a_-\phi_-(x)\bigr)+b.

The hat marks a prediction, not a target. The parentheses specify the arithmetic: compute both products, add them, then add bb. The bias shifts every prediction by the same amount. For example, at x=−1/2x=-1/2, the products are a+⋅0a_+\cdot0 and a−⋅(1/2)a_-\cdot(1/2), so the prediction is a−/2+ba_-/2+b.

At capacity 1, all three coordinates are enabled. Choosing (a+,a−,b)=(1,1,0)(a_+,a_-,b)=(1,1,0) expresses ∣x∣|x| for every real xx, since its two ReLU parts sum to ∣x∣|x|. This is an algebraic property of this architecture and target; it does not say a few updates reach those parameters or demonstrate learned population generalization.

At capacity 0, a−a_- is frozen at positive zero: two enabled coordinates, still three stored. Every negative input then predicts bb. One constant cannot equal both negative-side training targets 1 and 1/2. More updates cannot remove that representational restriction. Both features, both prediction products and all three mathematical gradients are still computed; enabling fewer coordinates is not a measured hardware or FLOP saving.

A tensor is an array with named axes. A shape tells us how many entries lie along each axis. In ordinary column-vector mathematics, one augmented feature column is f(x)=(ϕ+,ϕ−,1)T:[3,1]f(x)=(\phi_+,\phi_-,1)^T:[3,1], and θ:[3,1]\theta:[3,1]. The row θT:[1,3]\theta^T:[1,3] times f:[3,1]f:[3,1] gives one scalar [1,1][1,1]. The final 1 represents the bias coefficient; do not add another bias after using that augmented form.

For a batch, explicitly turn the feature columns into rows of a design matrix F:[4,3]F:[4,3]. Its axes are Sample, Coordinate; columns are positive feature, negative feature, bias-one. Then Fθ:[4,1]F\theta:[4,1] gives four predictions. This is an explanatory equivalent of the separate-product, bias-last scalar calculation above. Predictions, targets, errors and half-losses each have a Sample axis of length 4 per split. A conceptual array of the two features for all eight inputs would have shape [8,2], axes Sample, Feature; the stored data table includes those features alongside inputs and targets. No reshape silently changes samples into features. Review II.9 — Matrix × vector for matrix–vector multiplication and II.4 — Dot product, angle, and orthogonality for the dot product.

Match the shapes to the saved tensors

The implementation stores a three-entry vector as [3]; its mathematical column interpretation remains [3,1]. A field axis names which quantities share one row. Values are flattened in row order for storage: finish one row’s fields before starting the next. The inspector publishes field names and provenance (where each value came from), so a storage position is not an unexplained feature or extra sample. Let S=updates+1S=\texttt{updates}+1 be the number of evaluated stages. A name beginning stage_s_ belongs to one selected stage ss; there is no additional hidden history tensor for every possible quantity.

Saved tensor or suffixShape and named axesEntries in field order
Data[8,5]: Sample, DataFieldx, phiPlus, phiMinus, clean target, observed-target slot; the validation slot copies clean truth and is never an optimizer label
InitialTheta, EnabledMask, stage_s_Theta[3]: CoordinateaPlus, aMinus, b; the mask entries are integer enabled selectors
stage_s_Forward[8,4]: Sample, ForwardFieldPositive product, negative product, product sum, prediction
stage_s_TrainLoss[4,8]: TrainSample, TrainLossFieldObserved target/error/square/half, then clean target/error/square/half
stage_s_ValidationLoss[4,4]: ValidationSample, ValidationLossFieldClean target, error, square, half-loss
stage_s_Means[3]: ObjectiveObserved training, clean training, validation half-MSE
stage_s_GradientRows[3,4,2]: Coordinate, TrainSample, GradientRowFieldEach actual contribution and its ordered running sum
stage_s_MathematicalGradient, stage_s_EffectiveGradient[3]: CoordinateAll mathematical derivatives, or the selected optimizer derivatives
stage_s_OmissionRows[4,3,3]: Omission, IncludedPosition, OmissionRowFieldOriginal validation index, saved half-loss, running sum for each included position
stage_s_OmissionMeans[4]: OmissionMean after omitting validation index 0, 1, 2 or 3
stage_s_RangeComparisons[3,7]: Comparison, RangeFieldCandidate, old minimum, old maximum, lower flag, higher flag, selected minimum, selected maximum
stage_s_OmissionRange[2]: EndpointMinimum, maximum of the four omission means
stage_s_Stats[7]: StageFieldThree means, omission minimum, omission maximum, diagnostic-only flag, next-update flag
update_t_Update[3,7]: Coordinate, UpdateFieldOld value, mathematical gradient, effective gradient, enabled flag, delta, proposal, committed value; t=s+1t=s+1 only when an update exists
StageMetrics[S,3]: Stage, ObjectiveThree actual objective means at every evaluated stage
StageTheta[S,3]: Stage, CoordinateThree actual coordinates at every evaluated stage

A flag is 0 for false and 1 for true. The data type (dtype) is float64, a binary64 number, except EnabledMask, which uses int32, a signed integer type. Index and flag fields inside mixed numeric tables still describe discrete choices, not additional measurements. Display precision metadata does not change stored arithmetic. In particular, there is no update tensor after the final stage and no padded update tensor when updates is zero.

One loss, three reporting roles

For sample index ii, define ei=y^i−yie_i=\widehat y_i-y_i and its half-squared loss ℓi=ei2/2\ell_i=e_i^2/2. The index ii runs over the four samples of one split. Squaring removes the error’s sign; halving makes the derivative especially simple. For n=4n=4 examples, the dataset half-MSE is

L=1n∑i=0n−1ℓi=12n∑i=0n−1ei2=18∑i=03ei2.L=\frac{1}{n}\sum_{i=0}^{n-1}\ell_i =\frac{1}{2n}\sum_{i=0}^{n-1}e_i^2 =\frac{1}{8}\sum_{i=0}^{3}e_i^2.

∑\sum means add the indexed quantities, and nn is the number of examples, not the number of enabled parameters. Ordinary MSE omits the factor 1/2; all losses in this chapter include it. This is regression, with no class threshold, accuracy percentage or cross-entropy.

Report three means: observed training uses the labels available to the optimizer; clean training uses the retained true training labels; validation uses only the clean validation labels. Only the first is optimized. Each training sample computes its observed and clean error, square and half-loss separately, even when the labels agree. A validation sample computes its clean loss. Reductions start at floating positive zero, add the four half-losses in dataset order, then divide by 4. Display rounding never feeds back into these operations.

Work the default first step by hand

This is the default case capacity=1, updates=2, corrupt=0, eta=1/4. The fractions below are hand-derived mathematical anchors, not a report of an executed training run or values to substitute for recomputation.

At stage 0, θ0=(0,0,0)\theta_0=(0,0,0), so all eight predictions are zero. Ordered training errors are (−1,−1/2,−1/2,−1)(−1,−1/2,−1/2,−1); squares are (1,1/4,1/4,1)(1,1/4,1/4,1); half-losses are (1/2,1/8,1/8,1/2)(1/2,1/8,1/8,1/2). The running half-loss sums are 1/2,5/8,3/4,5/41/2,5/8,3/4,5/4. Dividing the last sum by 4 gives both initial training means 5/165/16.

Validation errors are (−3/4,−1/4,−1/4,−3/4)(−3/4,−1/4,−1/4,−3/4). Their squares are (9/16,1/16,1/16,9/16)(9/16,1/16,1/16,9/16), and half-losses (9/32,1/32,1/32,9/32)(9/32,1/32,1/32,9/32). Ordered sums are 9/32,10/32,11/32,20/329/32,10/32,11/32,20/32; dividing by 4 gives Lval,0=5/32L_{\mathrm{val},0}=5/32. Its smaller initial mean reflects these different input magnitudes, not successful training.

A gradient is one derivative per parameter: the local loss change per small change in that coordinate. For the observed training objective, the three mathematical derivatives are

g+=14∑i=03ϕ+(xi)ei,g−=14∑i=03ϕ−(xi)ei,gb=14∑i=03ei.g_+=\frac{1}{4}\sum_{i=0}^{3}\phi_+(x_i)e_i, \qquad g_-=\frac{1}{4}\sum_{i=0}^{3}\phi_-(x_i)e_i, \qquad g_b=\frac{1}{4}\sum_{i=0}^{3}e_i.

Here g+,g−,gbg_+,g_-,g_b correspond to a+,a−,ba_+,a_-,b. Each eie_i in these formulas uses the observed training label at the same old parameter vector. There are no validation terms.

GradientFour ordered row contributionsOrdered running sumsDivide by 4
g+g_+0,0,−1/4,−10,0,−1/4,−10,0,−1/4,−5/40,0,−1/4,−5/4−5/16−5/16
g−g_-−1,−1/4,0,0−1,−1/4,0,0−1,−5/4,−5/4,−5/4−1,−5/4,−5/4,−5/4−5/16−5/16
gbg_b−1,−1/2,−1/2,−1−1,−1/2,−1/2,−1−1,−3/2,−2,−3−1,−3/2,−2,−3−3/4−3/4

The feature rows multiply feature by error. The bias row directly sums errors; no extra multiplication by 1 is needed in that scalar calculation. Every sum starts at positive zero.

The effective gradient is what the optimizer is allowed to use. Capacity 1 selects all three mathematical derivatives. Capacity 0 selects (g+,0,gb)(g_+,0,g_b) while retaining g−g_- for explanation. This selection is a gate, not a claim that g−g_- mathematically equals zero.

For coordinate index j=0,1,2j=0,1,2 (positive coefficient, negative coefficient, bias), form δj=ηgeffective,j\delta_j=\eta g_{\mathrm{effective},j} and propose θ0,j−δj\theta_{0,j}-\delta_j. At full capacity the three deltas are (−5/64,−5/64,−3/16)(−5/64,−5/64,−3/16), so

θ1=(0−(−5/64),  0−(−5/64),  0−(−3/16))=(5/64,5/64,3/16).\theta_1=\left(0-(-5/64),\;0-(-5/64),\;0-(-3/16)\right) =(5/64,5/64,3/16).

All three use the same θ0\theta_0 and same gradient. Computing a later gradient after changing the first coordinate would be a different algorithm. Gradient descent subtracts a learning-rate-scaled gradient. This is the full-batch form of an SGD (stochastic gradient descent) update; stochastic means randomly sampled, but there is no such sampling here. The frozen coordinate also retains its delta and proposed subtraction, but its committed value is explicitly positive zero. Thus the restricted first state is (5/64,0,3/16)(5/64,0,3/16) even though its mathematical g−=−5/16g_-=-5/16.

Now really evaluate all eight points at θ1\theta_1; the update’s old loss is not its new loss.

Sample xxPositive productNegative productProduct sumPrediction after +3/16+3/16Clean errorHalf-loss
Train −105/645/6417/64−47/642209/8192
Train −1/205/1285/12829/128−35/1281225/32768
Train 1/25/12805/12829/128−35/1281225/32768
Train 15/6405/6417/64−47/642209/8192
Validation −3/4015/25615/25663/256−129/25616641/131072
Validation −1/405/2565/25653/256−11/256121/131072
Validation 1/45/25605/25653/256−11/256121/131072
Validation 3/415/256015/25663/256−129/25616641/131072

For example, Train −1/2 has error 29/128−1/2=−35/12829/128-1/2=-35/128, square 1225/163841225/16384, then half-loss 1225/327681225/32768. Training running sums, with denominator 32768, have numerators 8836,10061,11286,201228836,10061,11286,20122. Dividing the final sum by 4 gives both training means 10061/65536. Validation running sums, with denominator 131072, have numerators 16641,16762,16883,3352416641,16762,16883,33524. Dividing by 4 gives 8381/131072.

The default requests two updates. At stage 1, the next gradient is (−223/1024,−223/1024,−129/256)(−223/1024,−223/1024,−129/256), giving θ2=(543/4096,543/4096,321/1024)\theta_2=(543/4096,543/4096,321/1024). This stage needs its own evaluation: hand-derived train errors are (−2269/4096,−985/8192,−985/8192,−2269/4096)(−2269/4096,−985/8192,−985/8192,−2269/4096); validation errors are (−5523/16384,1583/16384,1583/16384,−5523/16384)(−5523/16384,1583/16384,1583/16384,−5523/16384). The two positive inner validation errors are real overpredictions. Squaring, halving, ordered summing and dividing by 4 gives training 21563669/268435456 and validation 16504709/536870912. These hand anchors explain the case; they do not replace actual stage calculations.

Follow the default second update and final evaluation in full

At stage 1, the positive-coefficient contributions are 0,0,−35/256,−47/640,0,-35/256,-47/64, giving running sums 0,0,−35/256,−223/2560,0,-35/256,-223/256. The negative-coefficient contributions are −47/64,−35/256,0,0-47/64,-35/256,0,0, with sums −188/256,−223/256,−223/256,−223/256-188/256,-223/256,-223/256,-223/256. Each final sum divided by 4 is −223/1024-223/1024. The bias directly adds the errors: its running sums are −94/128,−129/128,−164/128,−258/128-94/128,-129/128,-164/128,-258/128, then division by 4 gives −129/256-129/256.

Multiply these three gradients by η=1/4\eta=1/4 to obtain deltas (−223/4096,−223/4096,−129/1024)(-223/4096,-223/4096,-129/1024). From the common old state, each feature coefficient becomes 320/4096−(−223/4096)=543/4096320/4096-(-223/4096)=543/4096; the bias becomes 192/1024−(−129/1024)=321/1024192/1024-(-129/1024)=321/1024. Commit all three together. With clean labels and symmetric coefficients, opposite inputs of equal magnitude have equal predictions; one of the two feature products is zero at each input.

Split / input magnitudeNonzero feature productBias in the same denominatorPredictionErrorSquareHalf-loss
Train 1543/40961284/40961827/4096−2269/40965148361/167772165148361/33554432
Train 1/2543/81922568/81923111/8192−985/8192970225/67108864970225/134217728
Validation 3/41629/163845136/163846765/16384−5523/1638430503529/26843545630503529/536870912
Validation 1/4543/163845136/163845679/163841583/163842505889/2684354562505889/536870912

In original training order, use denominator 134217728 for half-losses. Their numerators are 20593444,970225,970225,2059344420593444,970225,970225,20593444; running-sum numerators are 20593444,21563669,22533894,4312733820593444,21563669,22533894,43127338. Divide the last sum by 4 and simplify to 21563669/26843545621563669/268435456. For validation, denominator 536870912 gives half-loss numerators 30503529,2505889,2505889,3050352930503529,2505889,2505889,30503529; running sums are 30503529,33009418,35515307,6601883630503529,33009418,35515307,66018836. Divide by 4 to obtain 16504709/53687091216504709/536870912.

Stage 2 is the default’s final evaluation. Its mathematical gradients are still computed for inspection, but they cause no third update. These exact hand fractions describe this named dyadic case (a fraction is dyadic when its denominator is a power of two) only; they are not a table of answers used by the lab.

Why the gradient has this form

For one sample, differentiating ei2/2e_i^2/2 with respect to eie_i gives eie_i. Changing a+a_+ changes prediction by ϕ+(xi)\phi_+(x_i) times that change. The chain rule therefore gives eiϕ+(xi)e_i\phi_+(x_i). The negative feature works the same way. Changing bb changes prediction one-for-one, giving eie_i. Finally the mean divides each sum by 4. There is no extra factor 2 because the half in the loss cancels it.

The hidden features do not depend on the trained coordinates. Prediction is linear in those coordinates; squaring a linear expression makes the objective quadratic in them, and its gradient linear plus a constant. ReLU is nonlinear in xx, but we are not differentiating xx or training the hidden features. All authored xx are nonzero. This does not assert that ReLU has a unique derivative at zero.

Optional deeper derivation: the matrix quadratic

Using the training row design FF defined above, let y:[4,1]y:[4,1] be the observed target column. Let H=FTF/4:[3,3]H=F^TF/4:[3,3], c=FTy/4:[3,1]c=F^Ty/4:[3,1], and q=yTy/8q=y^Ty/8 be a scalar. Expanding the sum of squared errors gives

L(θ)=12θTHθ−cTθ+q,∇L(θ)=Hθ−c,L(\theta)=\tfrac12\theta^TH\theta-c^T\theta+q, \qquad \nabla L(\theta)=H\theta-c,H=(5/1603/805/163/83/83/81).H=\begin{pmatrix}5/16&0&3/8\\0&5/16&3/8\\3/8&3/8&1\end{pmatrix}.

∇L\nabla L names the whole gradient column. Clean labels give c=(5/16,5/16,3/4)Tc=(5/16,5/16,3/4)^T and q=5/16q=5/16; the corrupted observed labels give c=(5/16,7/16,7/8)Tc=(5/16,7/16,7/8)^T and q=15/32q=15/32. Features determine HH, so changing the label leaves HH unchanged. This is an exact-real derivation, not a different floating-point reduction to substitute into the scalar trace. The ideal full-capacity representation (1,1,0)(1,1,0) is not an extra point in a three-update trajectory.

More capacity, more steps and better labels are different claims

A first restricted clean update gives training 22477/131072 and validation 18877/262144. These exceed the full-capacity first-step values in this named case. They do not prove that greater capacity always improves validation at every step or for every target.

For a concrete step-size failure, keep full capacity and clean labels but set η=2\eta=2. The initial gradient is unchanged, giving θ1=(5/8,5/8,3/2)\theta_1=(5/8,5/8,3/2). At training magnitudes 1 and 1/2, predictions are 17/817/8 and 29/1629/16; errors are 9/89/8 and 21/1621/16. Thus

Ltrain,1=2(9/8)2+2(21/16)28=7651024>3201024=516.L_{\mathrm{train},1} =\frac{2(9/8)^2+2(21/16)^2}{8} =\frac{765}{1024} >\frac{320}{1024}=\frac{5}{16}.

This is a valid update that increases loss. The negative gradient points downhill locally; a large finite move can pass the useful region. Extra steps are not a guarantee of progress, and a trajectory may rise, fall or plateau.

Now keep η=1/4\eta=1/4 and full capacity but corrupt only Train 0. Initially the observed mean becomes 15/32, while clean training remains 5/16 and validation 5/32. The observed gradient is (−5/16,−7/16,−7/8)(−5/16,−7/16,−7/8), giving θ1=(5/64,7/64,7/32)\theta_1=(5/64,7/64,7/32). Its observed training mean is 16201/65536, clean training 8649/65536, and validation 6969/131072.

The last value is smaller than the clean-label first-step validation mean 8381/1310728381/131072. A bad label has accidentally improved this particular small validation score at this particular early step. The clean first step was underpredicting; the changed slope and bias move some predictions closer to this grid’s targets. The negative outer validation error magnitudes become 115/256115/256 and 121/256121/256, with inner errors −1/256−1/256 and −3/256−3/256. This is neither universal harm from noise at every finite step nor evidence that corrupting labels improves generalization. It demonstrates why the optimized labels, the retained truth and the evaluation set must be named separately.

What the saved stages count

Stage ss means the parameters after ss completed updates, where s=0,…,us=0,\ldots,u and u=updatesu=\texttt{updates}. Evaluate all eight samples at that stage’s same parameter vector; compute the three means and the observed training gradient there. If s<us<u, use that gradient for one simultaneous update. At s=us=u, the gradient is diagnostic only: it is not an extra SGD step. There are no padded stages or hidden copies of an old forward pretending to evaluate new parameters.

Work quantityCount for uu updatesDefault u=2u=2
Fixed feature maps, computed once88
Evaluated stagesu+1u+13
Sample forward evaluations8(u+1)8(u+1)24
Three-coordinate gradient batches, including final diagnosticu+1u+13
Training-row contributions to those gradient batches4(u+1)4(u+1)12
Optimizer batchesuu2
Training rows used for actual updates4u4u8
Stored-coordinate update records3u3u6
Enabled-coordinate updates2u2u or 3u3u4 or 6
Validation omission means4(u+1)4(u+1)12

Each gradient batch contains three contractions over the same four rows: here a contraction means accumulating the row contributions into one coordinate’s derivative. These are algorithmic counts, not timings, throughput (work per unit time) or FLOPs (floating-point operation counts). Frozen-coordinate arithmetic still occurs, and diagnostic work is disclosed separately. Inspecting another saved sample, coordinate or stage should use that saved evidence; it must not create a hidden forward evaluation. A plotted line between evaluated stages can only guide the eye; it is not evidence of additional measured points or a fitted scaling law.

Four validation omissions: descriptive sensitivity

At one saved stage, call the four validation half-losses v0,v1,v2,v3v_0,v_1,v_2,v_3. The all-four mean is (v0+v1+v2+v3)/4(v_0+v_1+v_2+v_3)/4. For each omitted index kk, compute mkm_k: start at positive zero, add the other three saved losses in their original order, then divide by 3. For example, omitting index 1 uses v0,v2,v3v_0,v_2,v_3. This is three additions and one division, not a rounded total-minus-omitted shortcut.

At initialization, (v0,v1,v2,v3)=(9/32,1/32,1/32,9/32)(v_0,v_1,v_2,v_3)=(9/32,1/32,1/32,9/32). Omitting index 0 gives ordered sums 1/32,2/32,11/321/32,2/32,11/32, then m0=11/96m_0=11/96. Omitting index 1 gives 9/32,10/32,19/329/32,10/32,19/32, then m1=19/96m_1=19/96. Omitting index 2 also gives 19/9619/96, and omitting index 3 gives 11/9611/96. Their exact-real minimum and maximum are [11/96,19/96], around the all-four mean 5/325/32.

That range reports descriptive membership sensitivity on these four authored validation points. All four subsets overlap and reuse saved losses. There is no retraining, cross-validation with retraining, new random draw, re-split or extra forward call. It is not a confidence interval, population error bound or independent replication. Equal subset means would only say that these particular omissions give equal means; they would not remove uncertainty outside this grid.

Repeatedly choosing capacity, step count or learning rate by the best displayed validation score can overfit the selection to these four points. Disjointness from training is useful, but it does not make this grid a representative population or an untouched final test set.

Exact fractions and computer values

The hand-worked fractions express real-number mathematics. Binary64 stores a number using 64 bits, with 53 significant binary digits for normal nonzero values. Each separate addition, subtraction, product and division rounds to the nearest representable value; if two are equally near, ties-to-even selects the one with an even last significand bit. Gradual underflow allows smaller values with fewer significant bits before rounding to zero. There is no fused multiply-add combining a product and addition into one rounding. Inputs and intermediate results must be finite, meaning neither infinity nor the invalid numeric marker NaN. The local tables display decimal strings that recover the saved binary64 value when read back; those strings are not exact-real fractions. Positive and negative zero represent the same real zero but have different stored signs; the local operation tables preserve that distinction. In particular, dividing the omission sums by 3 generally rounds even when the input losses are exactly representable powers-of-two fractions. Do not infer that every allowed learning rate has an exact rational trajectory in binary64, or that equal printed decimals imply equal stored words.

The mathematical gradient describes the underlying real quadratic at the saved represented parameters. It is not a derivative through the discontinuities of floating-point rounding. Independent checking must separately account for operation order, rounding and signed zero. A hand derivation explains a named case; it does not certify a program’s numerical correctness.

Read the actual Python mechanics

The complete source below is p13/generalization_reference.py, imported directly from the reference file. NumPy stores the input grids and the three-coordinate parameter vector; explicit scalar loops perform the arithmetic. There is no matrix library reduction hiding a different addition order. This file provides the numerical mechanics and retained evidence; its internal evidence dictionary is not the five-field public lesson record.

Read it in this order:

  1. raw_state captures the four values, checks all four numerical inputs before their domains, then normalizes the discrete selectors. It excludes booleans and strings rather than coercing them. fixed_data computes the eight actual feature pairs once for mechanics_experiment, retaining clean and observed targets separately.
  2. _loss saves the target, error, square and division by 2. _mean saves every previousSum, added value and new sum, followed by its explicit divisor and mean. These same ordered reductions explain the hand arithmetic above.
  3. _evaluate computes each prediction’s plusProduct, minusProduct, featureSum and bias addition from one saved theta. It evaluates both training target roles separately, the validation losses, all three mathematicalGradient entries and the selected effectiveGradient. Its omissions reuse the saved validation losses. The range starts from the first actual omission mean and retains the subsequent comparisons; it never invents a numerical sentinel or another model evaluation.
  4. mechanics_experiment appends one evaluation per actual stage. Each update saves old, mathematical and effective gradients, delta, proposed and committed for every coordinate. It builds the complete next_theta before replacing the NumPy vector. The last stage has usedForUpdate=0, with a real final evaluation and diagnostic gradient.
  5. work records the actual loop counts. In addition to the table above, each stage has three gradient contractions, eight feature-error products, twelve loss records, twelve additions for the three loss means, twelve gradient additions, twelve omission additions and six range comparisons. Twelve loss records means two target roles on each of four training forwards plus one on each of four validation forwards; it does not mean twelve forward evaluations.

The separate evaluate_generalization(theta, capacity, corrupt) endpoint evaluates an arbitrary finite three-coordinate state with fresh fixed data. It performs no update and does not certify that the supplied state came from training. The stage loop uses its retained data and internal _evaluate directly; it does not secretly call this endpoint to make extra copies of the forward computation. Its mathematical derivative is still with respect to the readout coordinates, not the discrete selectors.

The helper’s numerical inputs and intermediates have explicit finite guards. Only its known NumericalFault family denotes a declared input or numerical failure; an unknown programming failure should not be reinterpreted as a valid numerical answer. Reading or displaying this source is not evidence that it has been executed or independently validated.

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.

"""IV54 ordered fixed-feature regression mechanics — SOURCE ONLY, UNRUN.

NumPy stores the three-coordinate vectors; explicit scalar operations preserve
(predictionPlus + predictionMinus) + bias and dataset order. There is no BLAS,
vector reduction, tokenizer, old neural-network import or implicit self-check.
The public lesson record is a separate owner-adopted binding of this evidence.
"""
from copy import deepcopy
import math
import sys
from types import MappingProxyType

import numpy as np

DEFAULT_IV54 = MappingProxyType(dict(capacity=1, updates=2, corrupt=0, eta=0.25))
RAW_KEYS = ("capacity", "updates", "corrupt", "eta")


class NumericalFault(ValueError):
    """Only this known numerical/input failure becomes unavailable."""

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


def _number(value, label):
    # bool and numeric subclasses must not invoke coercion or custom hooks.
    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 _finite(value, label):
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def raw_state(value):
    """Exact raw4 replacement; all four finite checks precede all domains.

    Ordinary dict is Python's data-only object boundary. Capture every value in
    contract order before validation. Huge ints reach domains before float().
    """
    if type(value) is not dict:
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    if len(value) != 4 or any(type(key) is not str for key in value) or set(value) != set(RAW_KEYS):
        raise NumericalFault("INVALID_INPUT", "state must have exactly capacity, updates, corrupt, eta as own fields.")
    raw = {key: value[key] for key in RAW_KEYS}
    for key in RAW_KEYS:
        _number(raw[key], key)
    if raw["capacity"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "capacity must be numeric 0 or 1.")
    if not 0 <= raw["updates"] <= 3 or int(raw["updates"]) != raw["updates"]:
        raise NumericalFault("INVALID_INPUT", "updates must be an integer from 0 to 3.")
    if raw["corrupt"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "corrupt must be numeric 0 or 1.")
    if not 0.0 <= raw["eta"] <= 2.0:
        raise NumericalFault("INVALID_INPUT", "eta must be between 0 and 2.")
    return dict(capacity=int(raw["capacity"]), updates=int(raw["updates"]),
                corrupt=int(raw["corrupt"]), eta=float(raw["eta"]))


def _theta(value):
    """Pure evaluation accepts any three representable finite coordinates.

    This is a state boundary, not the raw eta domain; there is no learned-state
    clipping. Compare unbounded ints before float conversion to avoid overflow.
    """
    if type(value) is not list or len(value) != 3:
        raise NumericalFault("INVALID_INPUT", "theta must be an ordinary dense three-entry array.")
    saved = value[:]
    for index, number in enumerate(saved):
        _number(number, f"theta[{index}]")
    for number in saved:
        if not -sys.float_info.max <= number <= sys.float_info.max:
            raise NumericalFault("NONFINITE", "theta requires representable finite binary64 coordinates.")
    return [float(number) for number in saved]


def fixed_data(corrupt):
    """Eight fixed feature maps, once per experiment; no random sampling.

    Each training row retains clean truth separately from its observed target.
    Validation rows have only clean truth and never contribute to a gradient.
    """
    _number(corrupt, "corrupt")
    if corrupt not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "corrupt must be numeric 0 or 1.")
    train_x = np.array([-1.0, -0.5, 0.5, 1.0], dtype=np.float64)
    valid_x = np.array([-0.75, -0.25, 0.25, 0.75], dtype=np.float64)
    rows = []
    for split, values in (("train", train_x), ("validation", valid_x)):
        for index in range(4):
            x = float(values[index])
            negative_x = -x
            phi_plus = max(0.0, x)
            phi_minus = max(0.0, negative_x)
            clean = abs(x)
            row = dict(split=split, index=index, x=x, negativeX=negative_x,
                       zero=0.0, phiPlus=phi_plus, phiMinus=phi_minus, cleanTarget=clean,
                       corrupted=int(split == "train" and index == 0 and corrupt == 1))
            if split == "train":
                row["observedTarget"] = 1.5 if row["corrupted"] else clean
            rows.append(row)
    return rows


def _loss(prediction, target):
    error = _finite(prediction - target, "loss error")
    square = _finite(error * error, "loss square")
    half = _finite(square / 2.0, "half loss")
    return dict(target=target, error=error, square=square, divisor=2.0, half=half)


def _mean(values, divisor):
    """Every actual addition, including the first +0.0, is retained."""
    total, additions = 0.0, []
    for index, value in enumerate(values):
        previous = total
        total = _finite(previous + value, "ordered sum")
        additions.append(dict(index=index, previousSum=previous, value=value, sum=total))
    mean = _finite(total / divisor, "ordered mean")
    return dict(initialSum=0.0, values=values[:], additions=additions,
                sum=total, divisor=divisor, mean=mean)


def _evaluate(theta, data, capacity):
    """Internal trusted fixed-data path; all eight forwards share this theta."""
    samples = []
    for row in data:
        plus = _finite(theta[0] * row["phiPlus"], "aPlus feature product")
        minus = _finite(theta[1] * row["phiMinus"], "aMinus feature product")
        feature_sum = _finite(plus + minus, "feature product sum")
        prediction = _finite(feature_sum + theta[2], "bias addition")
        sample = dict(split=row["split"], index=row["index"], theta=theta[:],
                      phiPlus=row["phiPlus"], phiMinus=row["phiMinus"],
                      plusProduct=plus, minusProduct=minus, featureSum=feature_sum,
                      bias=theta[2], prediction=prediction)
        # Compute both losses independently even when observed equals clean.
        clean = _loss(prediction, row["cleanTarget"])
        if row["split"] == "train":
            sample["observed"] = _loss(prediction, row["observedTarget"])
        sample["clean"] = clean
        samples.append(sample)
    train, validation = samples[:4], samples[4:]
    observed_mean = _mean([row["observed"]["half"] for row in train], 4.0)
    clean_mean = _mean([row["clean"]["half"] for row in train], 4.0)
    validation_mean = _mean([row["clean"]["half"] for row in validation], 4.0)

    # Four observed errors alone drive all three mathematical derivatives.
    gradients, mathematical = [], []
    for coordinate in range(3):
        contributions, terms, additions, total = [], [], [], 0.0
        for index in range(4):
            error = train[index]["observed"]["error"]
            if coordinate < 2:
                feature = data[index]["phiPlus" if coordinate == 0 else "phiMinus"]
                term = _finite(feature * error, "feature-error product")
                contributions.append(dict(index=index, feature=feature, error=error, product=term))
            else:
                # Bias directly sums errors; no fictitious 1*error operation.
                term = error
                contributions.append(dict(index=index, error=error))
            terms.append(term)
            previous = total
            total = _finite(previous + term, "gradient sum")
            additions.append(dict(index=index, previousSum=previous, value=term, sum=total))
        mean = _finite(total / 4.0, "mathematical gradient")
        contraction = dict(initialSum=0.0, values=terms, additions=additions,
                           sum=total, divisor=4.0, mean=mean)
        mathematical.append(contraction["mean"])
        gradients.append(dict(coordinate=coordinate, contributions=contributions, contraction=contraction))
    mask = [1, capacity, 1]
    effective = [mathematical[0], mathematical[1] if capacity == 1 else 0.0, mathematical[2]]

    omissions = []
    saved_losses = [row["clean"]["half"] for row in validation]
    for omitted in range(4):
        included = [index for index in range(4) if index != omitted]
        reduction = _mean([saved_losses[index] for index in included], 3.0)
        omissions.append(dict(omittedIndex=omitted, includedIndices=included, reduction=reduction))
    # Initialize from a genuine saved mean, never an Infinity sentinel.
    minimum = maximum = omissions[0]["reduction"]["mean"]
    comparisons = []
    for index in range(1, 4):
        candidate = omissions[index]["reduction"]["mean"]
        old_minimum, old_maximum = minimum, maximum
        less, greater = candidate < old_minimum, candidate > old_maximum
        minimum = candidate if less else old_minimum
        maximum = candidate if greater else old_maximum
        comparisons.append(dict(index=index, candidate=candidate, oldMinimum=old_minimum,
                                oldMaximum=old_maximum, less=int(less), greater=int(greater),
                                minimum=minimum, maximum=maximum))
    return dict(theta=theta[:], samples=samples, observedTrain=observed_mean, cleanTrain=clean_mean,
                validation=validation_mean, gradients=gradients, mathematicalGradient=mathematical,
                mask=mask, effectiveGradient=effective, omissions=omissions,
                rangeInitial=omissions[0]["reduction"]["mean"], comparisons=comparisons,
                minimum=minimum, maximum=maximum)


def evaluate_generalization(theta, capacity, corrupt):
    """Pure arbitrary-state endpoint: finite theta[3], capacity/corrupt 0 or 1.

    Fresh data and a full eight-row evaluation are returned. This endpoint does
    not authenticate training history and performs no update or self-check.
    """
    saved = _theta(theta)
    _number(capacity, "capacity")
    _number(corrupt, "corrupt")
    if capacity not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "capacity must be numeric 0 or 1.")
    if corrupt not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "corrupt must be numeric 0 or 1.")
    return _evaluate(saved, fixed_data(corrupt), int(capacity))


def mechanics_experiment(value):
    """Complete numerical evidence, not the adopted five-field lesson root.

    u transitions give u+1 evaluated stages, including a final diagnostic
    gradient. The NumPy vector is replaced only after all three updates have
    been computed from the same saved old theta and gradient.
    """
    raw = raw_state(value)
    data = fixed_data(raw["corrupt"])
    theta = np.array([0.0, 0.0, 0.0], dtype=np.float64)
    stages, updates = [], []
    for stage_index in range(raw["updates"] + 1):
        old = [float(theta[index]) for index in range(3)]
        evaluation = _evaluate(old, data, raw["capacity"])
        evaluation["stage"] = stage_index
        evaluation["usedForUpdate"] = int(stage_index < raw["updates"])
        stages.append(evaluation)
        if stage_index == raw["updates"]:
            break
        coordinates, next_theta = [], []
        for coordinate in range(3):
            mathematical = evaluation["mathematicalGradient"][coordinate]
            effective = evaluation["effectiveGradient"][coordinate]
            enabled = evaluation["mask"][coordinate]
            delta = _finite(raw["eta"] * effective, "eta effective-gradient product")
            proposed = _finite(old[coordinate] - delta, "coordinate subtraction")
            committed = proposed if enabled == 1 else 0.0
            coordinates.append(dict(coordinate=coordinate, old=old[coordinate],
                                    mathematicalGradient=mathematical, effectiveGradient=effective,
                                    enabled=enabled, eta=raw["eta"], delta=delta,
                                    proposed=proposed, committed=committed))
            next_theta.append(committed)
        updates.append(dict(stage=stage_index, before=old[:], coordinates=coordinates, after=next_theta[:]))
        theta = np.array(next_theta, dtype=np.float64)
    stage_count = len(stages)
    enabled_count = 2 + raw["capacity"]
    work = dict(stageCount=stage_count, forwardSampleEvaluations=8 * stage_count,
                featureMaps=8, gradientBatches=stage_count, gradientRowContributions=4 * stage_count,
                optimizerBatches=len(updates), usedForUpdateRows=4 * len(updates),
                storedCoordinateUpdateRecords=3 * len(updates), enabledCoordinateUpdates=enabled_count * len(updates),
                omissionMeans=4 * stage_count, gradientContractions=3 * stage_count,
                featureGradientProducts=8 * stage_count, lossRecords=12 * stage_count,
                lossMeanAdditions=12 * stage_count, gradientAdditions=12 * stage_count,
                omissionAdditions=12 * stage_count, rangeComparisons=6 * stage_count)
    return dict(raw=raw, data=deepcopy(data), initialTheta=[0.0, 0.0, 0.0],
                stages=stages, updates=updates, finalTheta=stages[-1]["theta"][:],
                enabledParameters=enabled_count, storedParameters=3, work=work)

Read the complete Python lesson record and command line

The second complete panel is p13/iv54.py. Keep it adjacent to generalization_reference.py: together they are the complete authored Python source needed for this lesson, using NumPy and Python’s standard library. The wrapper loads that adjacent helper relative to its own file location. It neither copies precomputed trajectories nor substitutes an older training program.

derive_iv54(value) calls mechanics_experiment(value), then _defined_record publishes the result. _bind_evaluation copies each saved operation’s operands and answers into the ordered steps and tensors; it does not recalculate the model using a second reduction. The public record contains status, outputs, steps, tensors and texts. Its first four outputs are the actual final observed training mean, clean training mean, validation mean and enabled coordinate count. Later outputs retain raw controls, work counts, final state and one named copy of each operation output. This explains why the lab summary and detailed evidence describe the same calculation even when you inspect an earlier stage.

The wrapper catches only the declared NumericalFault family from a numerical query, returning status="unavailable", a code and a reason. An unknown programming or backend failure propagates. Input checking never supplies missing controls from defaults: defaults apply only when the command has no argument.

The following are usage examples. From the Book IV directory, no argument requests the complete default case:

python3 code/python/p13/iv54.py

One JSON argument replaces the entire raw input, so provide all four fields. JSON is a text notation for objects and numbers; use double quotes around keys, and shell single quotes around the complete object:

python3 code/python/p13/iv54.py '{"capacity":0,"updates":1,"corrupt":0,"eta":0.25}'

A single - argument reads one complete JSON value from standard input. For example, after saving that same four-field object in case.json:

python3 code/python/p13/iv54.py - < case.json

A valid query prints the complete public record as JSON. Malformed JSON, duplicate object members at any depth and nonstandard NaN/Infinity tokens produce a declared invalid-input record at the parsing boundary. A valid JSON value with missing/extra fields, wrong numeric types or an out-of-domain control is rejected by the numerical boundary instead. Even when updates is zero, every field is checked. Booleans and numeric strings are not numbers here. Integer-valued JSON numbers such as 1.0 are allowed for discrete controls. The learning rate may be zero or negative zero; its stored floating sign is preserved. More than one command-line argument prints usage on standard error and returns exit code 2. An ordinary declared unavailable record is printed with exit code 0, so inspect status rather than treating that exit code as numerical validation.

Importing the wrapper, calling derive_iv54 and making default, replacement or standard-input queries do not run its local self-checks. Only the separate explicit command requests them:

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

source_self_check calls six named checks: hand anchors; guards and JSON behavior; stage/work invariants; the public record; query/check isolation; and the command-line boundary. Those are commented local checks, not an independent numerical authority or proof of Python/browser parity. The explicit self-check call is outside the parsing and numerical-query catches, so a failed assertion cannot become a successful unavailable query. Displaying source or listing a command claims no passing result.

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.

"""IV54 complete canonical lesson record — SOURCE ONLY, ALL EXECUTION UNRUN.

The adjacent NumPy/scalar helper computes real evidence; this module binds its
saved operands to the adopted ordered root, trace, tensors and learner texts.
No TS parser, oracle, old neural kernel or generated answer is imported.

After explicit owner runtime clearance only:
  python3 code/python/p13/iv54.py
  python3 code/python/p13/iv54.py '{"capacity":0,"updates":1,"corrupt":0,"eta":0.25}'
  python3 code/python/p13/iv54.py -  # one complete JSON replacement from stdin
  python3 code/python/p13/iv54.py --self-check

Import and ordinary queries never call source_self_check or its check leaves.
"""
from copy import deepcopy
import importlib.util
import json
from pathlib import Path
import sys

_spec = importlib.util.spec_from_file_location(
    "_p13_iv54_generalization", Path(__file__).resolve().with_name("generalization_reference.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent generalization_reference.py")
_reference = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_reference)
DEFAULT_IV54 = _reference.DEFAULT_IV54
NumericalFault = _reference.NumericalFault
mechanics_experiment = _reference.mechanics_experiment
evaluate_generalization = _reference.evaluate_generalization


def _texts():
    """Literal transcription of the actual owner-adopted A public inventory."""
    return dict(
        trainingScope='A smaller scalar regression network with two fixed ReLU features and three stored readout coordinates. All actual stages0..updates are evaluated; the final gradient is diagnostic. This is not full Transformer or LLM training.',
        dataPolicy='Authored nonzero training x=[-1,-0.5,0.5,1] and distinct validation x=[-0.75,-0.25,0.25,0.75]. Clean truth is abs(x). Corrupt1 replaces only the first observed training target1 with1.5. Validation remains clean and never supplies gradients.',
        capacityPolicy='Capacity0 enables aPlus,b and freezes aMinus at positive zero; capacity1 enables all three. Both fixed features, both forward products and all three mathematical gradients are computed in either capacity. This is representational capacity, not a hardware speed claim.',
        objectivePolicy='Prediction=(aPlus*phiPlus+aMinus*phiMinus)+b. Each loss computes error=prediction-target, square=error*error, half=square/2. Each four-point mean accumulates those half-losses from floating positive zero in sample order, then divides by4. Observed and clean training losses are computed separately even when equal.',
        gradientPolicy='All three mathematical derivatives use only the current observed training errors. Feature coordinates sum feature*error in row order and divide by4; bias sums errors directly and divides by4. The derivative concerns the underlying real quadratic at represented theta, not rounding discontinuities. Effective gradients use a conditional selector with frozen positive zero.',
        updatePolicy='Each coordinate computes delta=eta*effective, proposed=old-delta, committed=enabled?proposed:positiveZero. All three proposals use the same old theta and gradient, then commit together. Eta0 still performs every requested transition. Every following stage genuinely reevaluates all eight samples, including final theta.',
        evaluationPolicy='The four omission means each sum the other three saved validation half-losses from positive zero in original index order, then divide by3. No retraining, resplit or extra prediction occurs. Their actual minimum/maximum are descriptive membership sensitivity, not a confidence interval or population error bound.',
        computePolicy='Work counts report actual feature maps, evaluated samples, gradient batches including the final diagnostic, row contributions, optimizer batches, stored/enabled coordinate updates and omission means. They are algorithmic counts, not FLOPs, timing, throughput, benchmarks or a scaling law.',
        numericPolicy='Separate binary64 round-to-nearest ties-to-even +,-,*,/ with gradual underflow and no fused multiply-add; fixed-input max/abs and explicit comparisons. All inputs and intermediates are finite-checked. Arbitrary valid eta can round or underflow; signed zero is preserved, including raw eta and delta/proposal records.',
        diagnosticPolicy='A centered gradient comparison with h=2^-12 has an exact arithmetic proof only for eta1/4 or2, stages0..3, either capacity or corruption choice, and enabled coordinates. The observed-training objective is quadratic. The proof covers distinct endpoints and every operation; signed-zero words need separate treatment. It does not extend to arbitrary learning rates.',
        scientificLimits='The grid is authored, not random, IID or population-representative; there is no unseen test set. More capacity or updates need not improve validation. A corrupted first step can accidentally lower this validation mean: noisy6969/131072 versus clean8381/131072. Repeated selection can overfit this same validation set. This toy cannot establish universal LLM scaling or frontier performance.',
        provenance='Authored toy inputs, clean abs(x) labels, one explicit optional wrong observed training label, positive-zero initialization and future live deterministic computation. Source authorship is not a claim that training or a historical measurement has already run.',
        rawFields=['capacity', 'updates', 'corrupt', 'eta'],
        parameterKeys=['aPlus', 'aMinus', 'b'],
        dataFields=['x', 'phiPlus', 'phiMinus', 'cleanTarget', 'observedTarget'],
        sampleKeys=['train0', 'train1', 'train2', 'train3', 'validation0', 'validation1', 'validation2', 'validation3'],
        forwardFields=['productPlus', 'productMinus', 'featureSum', 'prediction'],
        trainLossFields=['observedTarget', 'observedError', 'observedSquare', 'observedHalf', 'cleanTarget', 'cleanError', 'cleanSquare', 'cleanHalf'],
        validationLossFields=['cleanTarget', 'cleanError', 'cleanSquare', 'cleanHalf'],
        objectiveKeys=['observedTrainHalfMSE', 'cleanTrainHalfMSE', 'validationHalfMSE'],
        gradientRowFields=['contribution', 'sum'],
        omissionRowFields=['includedIndex', 'loss', 'sum'],
        rangeFields=['value', 'oldMinimum', 'oldMaximum', 'lower', 'higher', 'minimum', 'maximum'],
        endpointKeys=['minimum', 'maximum'],
        updateFields=['old', 'mathematical', 'effective', 'enabled', 'delta', 'proposed', 'committed'],
        stageFields=['observedTrainHalfMSE', 'cleanTrainHalfMSE', 'validationHalfMSE', 'omissionMinimum', 'omissionMaximum', 'diagnosticOnly', 'hasNextUpdate'],
    )


def _step(steps, identifier, label, equation, explanation, inputs, outputs):
    """Copy retained arithmetic; binding never recomputes a model operation."""
    if not identifier or any(step['id'] == identifier for step in steps):
        raise NumericalFault('INVALID_INPUT', 'Trace IDs must be nonempty and unique.')
    for key, value in (*inputs.items(), *outputs.items()):
        _reference._finite(value, key)
    if len(steps) >= 512:
        raise NumericalFault('UNSUPPORTED_SIZE', 'At most 512 operations are supported.')
    steps.append(deepcopy(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=outputs)))


def _tensor(identifier, shape, axes, values, provenance, dtype='float64', precision=8):
    # All dimensions here are fixed by the bounded retained evidence inventory.
    return dict(id=identifier, shape=shape[:], axes=axes[:], dtype=dtype,
                values=values[:], provenance=provenance, precision=precision)


def _bind_evaluation(evaluated, data, capacity, steps, tensors, prefix):
    """Publish the saved eight-row evaluation in adopted step/tensor order."""
    theta = evaluated['theta']
    forward_rows, train_loss_rows, validation_loss_rows = [], [], []
    for i, sample in enumerate(evaluated['samples']):
        row = data[i]
        forward = dict(productPlus=sample['plusProduct'], productMinus=sample['minusProduct'],
                       featureSum=sample['featureSum'], prediction=sample['prediction'])
        forward_rows.extend(forward.values())
        _step(steps, f'{prefix}_forward_{i}', 'Evaluate both fixed features at the same current theta',
              'productPlus=aPlus*phiPlus; productMinus=aMinus*phiMinus; featureSum=productPlus+productMinus; prediction=featureSum+b',
              'Both products are performed in either capacity. Bias is added last; all eight rows use the same unchanged theta.',
              dict(sample=i, x=row['x'], phiPlus=row['phiPlus'], phiMinus=row['phiMinus'],
                   aPlus=theta[0], aMinus=theta[1], b=theta[2]), forward)
        clean = sample['clean']
        losses = dict(cleanError=clean['error'], cleanSquare=clean['square'], cleanHalf=clean['half'])
        if i < 4:
            observed = sample['observed']
            losses.update(observedError=observed['error'], observedSquare=observed['square'], observedHalf=observed['half'])
            train_loss_rows.extend([observed['target'], observed['error'], observed['square'], observed['half'],
                                    clean['target'], clean['error'], clean['square'], clean['half']])
            _step(steps, f'{prefix}_loss_{i}', 'Compute separate observed and clean training losses',
                  'cleanError=prediction-cleanTarget; cleanSquare=cleanError*cleanError; cleanHalf=cleanSquare/2; observedError=prediction-observedTarget; observedSquare=observedError*observedError; observedHalf=observedSquare/2',
                  'Both sets of arithmetic are actually evaluated, even when the targets coincide. Only observed errors enter the optimizer.',
                  dict(sample=i, prediction=sample['prediction'], observedTarget=observed['target'], cleanTarget=clean['target'], divisor=2.0), losses)
        else:
            validation_loss_rows.extend([clean['target'], clean['error'], clean['square'], clean['half']])
            _step(steps, f'{prefix}_loss_{i}', 'Compute a held-out clean validation loss',
                  'cleanError=prediction-cleanTarget; cleanSquare=cleanError*cleanError; cleanHalf=cleanSquare/2',
                  'Validation never enters the training gradient. This is a real current-theta prediction, including at the final evaluated stage.',
                  dict(sample=i, prediction=sample['prediction'], cleanTarget=clean['target'], divisor=2.0), losses)
    means = []
    for name, key in (('observed_mean', 'observedTrain'), ('clean_mean', 'cleanTrain'), ('validation_mean', 'validation')):
        reduction = evaluated[key]
        inputs = dict(initialSum=reduction['initialSum'], divisor=reduction['divisor'])
        outputs = {}
        for i, addition in enumerate(reduction['additions']):
            inputs[f'loss{i}'] = addition['value']
            outputs[f'sum{i}'] = addition['sum']
        outputs['mean'] = reduction['mean']
        means.append(reduction['mean'])
        _step(steps, f'{prefix}_{name}', 'Average four saved per-point half-losses in order',
              'sum starts at +0; sum0=sum+loss0; sum1=sum0+loss1; sum2=sum1+loss2; sum3=sum2+loss3; mean=sum3/4',
              'The association is sum(error squared divided by two) divided by four. Display rounding is never used as an operand.', inputs, outputs)
    gradient_rows = []
    for coordinate, gradient in enumerate(evaluated['gradients']):
        reduction = gradient['contraction']
        inputs = dict(coordinate=coordinate, initialSum=reduction['initialSum'], divisor=reduction['divisor'])
        outputs = {}
        for i, contribution in enumerate(gradient['contributions']):
            inputs[f'error{i}'] = contribution['error']
            if coordinate < 2:
                inputs[f'feature{i}'] = contribution['feature']
                outputs[f'product{i}'] = contribution['product']
            addition = reduction['additions'][i]
            outputs[f'sum{i}'] = addition['sum']
            gradient_rows.extend([addition['value'], addition['sum']])
        outputs['gradient'] = reduction['mean']
        equation = ('product_i=feature_i*observedError_i; sum starts at +0; sum_i=sum_previous+product_i in row order; gradient=sum3/4'
                    if coordinate < 2 else 'sum starts at +0; sum_i=sum_previous+observedError_i in row order; gradient=sum3/4')
        _step(steps, f'{prefix}_gradient_{coordinate}', 'Differentiate the observed training objective', equation,
              'All three mathematical gradients are evaluated, including the frozen coordinate and the final diagnostic stage. The bias sums errors directly without invented products.', inputs, outputs)
    mathematical, effective, mask = evaluated['mathematicalGradient'], evaluated['effectiveGradient'], evaluated['mask']
    _step(steps, f'{prefix}_gate', 'Select the enabled optimizer coordinates',
          'mask=[1,capacity==1?1:0,1]; effective_j=mask_j==1?mathematical_j:+0',
          'This is a conditional selector, not a multiplication or a claim that a frozen coordinate has zero mathematical derivative.',
          dict(capacity=capacity, mathematical0=mathematical[0], mathematical1=mathematical[1], mathematical2=mathematical[2], frozenZero=0.0),
          dict(mask0=mask[0], mask1=mask[1], mask2=mask[2], effective0=effective[0], effective1=effective[1], effective2=effective[2]))
    omission_rows, omission_means = [], []
    for omitted, omission in enumerate(evaluated['omissions']):
        reduction = omission['reduction']
        inputs, outputs = dict(omitted=omitted, initialSum=reduction['initialSum'], divisor=reduction['divisor']), {}
        for position, index in enumerate(omission['includedIndices']):
            addition = reduction['additions'][position]
            inputs[f'included{position}'] = index
            inputs[f'loss{position}'] = addition['value']
            outputs[f'sum{position}'] = addition['sum']
            omission_rows.extend([index, addition['value'], addition['sum']])
        outputs['mean'] = reduction['mean']
        omission_means.append(reduction['mean'])
        _step(steps, f'{prefix}_omit_{omitted}', 'Omit one saved validation loss and average the other three',
              'sum starts at +0; add the three included saved half-losses in original index order; mean=sum2/3',
              'No retraining, resplit or extra forward evaluation occurs. Division by three is generally rounded binary64; these overlapping subsets describe membership sensitivity.', inputs, outputs)
    range_rows = []
    for comparison in evaluated['comparisons']:
        value, old_minimum, old_maximum = comparison['candidate'], comparison['oldMinimum'], comparison['oldMaximum']
        lower, higher, minimum, maximum = comparison['less'], comparison['greater'], comparison['minimum'], comparison['maximum']
        range_rows.extend([value, old_minimum, old_maximum, lower, higher, minimum, maximum])
        _step(steps, f"{prefix}_range_{comparison['index']}", 'Compare actual omission means to the running range',
              'lower=value<oldMinimum; higher=value>oldMaximum; minimum=lower?value:oldMinimum; maximum=higher?value:oldMaximum',
              'Initialize both endpoints from omission mean zero, then compare means one through three. The resulting descriptive range is not a confidence interval.',
              dict(omission=comparison['index'], value=value, oldMinimum=old_minimum, oldMaximum=old_maximum),
              dict(lower=lower, higher=higher, minimum=minimum, maximum=maximum))
    tensors.extend([
        _tensor(f'{prefix}_Theta', [3], ['Coordinate'], theta, 'Actual saved represented theta in aPlus,aMinus,b order; no raw-editor bounds on derived coordinates.'),
        _tensor(f'{prefix}_Forward', [8, 4], ['Sample', 'ForwardField'], forward_rows, 'Actual two products, feature sum and bias-last prediction, in texts.forwardFields order.'),
        _tensor(f'{prefix}_TrainLoss', [4, 8], ['TrainSample', 'TrainLossField'], train_loss_rows, 'Actual separately computed observed and clean fields in texts.trainLossFields order; authored truth remains distinct from optimizer labels.'),
        _tensor(f'{prefix}_ValidationLoss', [4, 4], ['ValidationSample', 'ValidationLossField'], validation_loss_rows, 'Actual clean validation fields in texts.validationLossFields order; never gradient targets.'),
        _tensor(f'{prefix}_Means', [3], ['Objective'], means, 'Ordered observed training, clean training, clean validation half-MSE; each averages four saved half-losses.'),
        _tensor(f'{prefix}_GradientRows', [3, 4, 2], ['Coordinate', 'TrainSample', 'GradientRowField'], gradient_rows, 'Actual contribution and ordered partial sum; feature products for coordinates0/1, direct error contributions for bias2.'),
        _tensor(f'{prefix}_MathematicalGradient', [3], ['Coordinate'], mathematical, 'All three observed-objective derivatives at the same saved theta; final-stage values are diagnostic.'),
        _tensor(f'{prefix}_EffectiveGradient', [3], ['Coordinate'], effective, 'Actual conditional optimizer selection; disabled coordinate is floating positive zero.'),
        _tensor(f'{prefix}_OmissionRows', [4, 3, 3], ['Omission', 'IncludedPosition', 'OmissionRowField'], omission_rows, 'Included original index, saved loss and actual ordered partial sum; no total-minus-omitted shortcut.'),
        _tensor(f'{prefix}_OmissionMeans', [4], ['Omission'], omission_means, 'Four actual division-by-three means in omitted-index order, generally rounded binary64.'),
        _tensor(f'{prefix}_RangeComparisons', [3, 7], ['Comparison', 'RangeField'], range_rows, 'Actual comparison operands, numeric flags and selected endpoints in texts.rangeFields order.'),
        _tensor(f'{prefix}_OmissionRange', [2], ['Endpoint'], [evaluated['minimum'], evaluated['maximum']], 'Minimum then maximum of the four actual omission means; descriptive membership sensitivity only.'),
    ])


def _defined_record(evidence):
    raw, data, stages, transitions = evidence['raw'], evidence['data'], evidence['stages'], evidence['updates']
    steps, tensors = [], []
    enabled = evidence['enabledParameters']
    mask = stages[0]['mask']
    _step(steps, 'setup', 'Declare the bounded training and validation experiment',
          'capacity0:2 enabled; capacity1:3 enabled; always3 stored; train4; validation4; fixedFeatures2',
          'Every raw finite-number check precedes every finite domain check, including controls inactive at zero updates. This smaller regression readout bridges from IV52 without claiming full model training.',
          raw.copy(), dict(storedParameters=3, enabledParameters=enabled, trainSamples=4, validationSamples=4, fixedFeatures=2))
    for i, row in enumerate(data):
        _step(steps, f'data_{i}', 'Compute fixed ReLU features and authored targets',
              'negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); cleanTarget=abs(x); observedTarget=corrupted?1.5:cleanTarget',
              'All eight nonzero inputs are authored and distinct. Only the first training label can be corrupted; validation labels remain clean. These fixed features are computed once.',
              dict(sample=i, training=int(i < 4), x=row['x'], zero=row['zero'], corrupt=raw['corrupt'], corruptTarget=1.5),
              dict(negatedX=row['negativeX'], phiPlus=row['phiPlus'], phiMinus=row['phiMinus'], cleanTarget=row['cleanTarget'],
                   corrupted=row['corrupted'], observedTarget=row['observedTarget'] if i < 4 else row['cleanTarget']))
    initial = evidence['initialTheta']
    _step(steps, 'initial', 'Initialize all stored coordinates at positive zero',
          'theta=[+0,+0,+0]; mask=[1,capacity==1?1:0,1]',
          'Every raw edit starts this experiment again from these initial coordinates. Inspection does not warm-start or change its numerical record.',
          dict(capacity=raw['capacity'], positiveZero=0.0),
          dict(theta0=initial[0], theta1=initial[1], theta2=initial[2], mask0=mask[0], mask1=mask[1], mask2=mask[2]))
    data_values = []
    for i, row in enumerate(data):
        data_values.extend([row['x'], row['phiPlus'], row['phiMinus'], row['cleanTarget'],
                            row['observedTarget'] if i < 4 else row['cleanTarget']])
    tensors.extend([
        _tensor('Data', [8, 5], ['Sample', 'DataField'], data_values, 'Actual once-computed authored data in texts.sampleKeys and texts.dataFields order; first four train, last four held-out validation; clean labels are abs(x).'),
        _tensor('InitialTheta', [3], ['Coordinate'], initial, 'Authored floating positive-zero readout initialization in aPlus,aMinus,b order.'),
        _tensor('EnabledMask', [3], ['Coordinate'], mask, 'Authored capacity-dependent integer selectors in aPlus,aMinus,b order; never feature or gradient multipliers.', 'int32', 0),
    ])
    stage_metrics, stage_theta = [], []
    for s, evaluated in enumerate(stages):
        prefix = f'stage_{s}'
        _bind_evaluation(evaluated, data, raw['capacity'], steps, tensors, prefix)
        means = [evaluated['observedTrain']['mean'], evaluated['cleanTrain']['mean'], evaluated['validation']['mean']]
        diagnostic_only, has_next = int(s == raw['updates']), evaluated['usedForUpdate']
        stats = [*means, evaluated['minimum'], evaluated['maximum'], diagnostic_only, has_next]
        stage_metrics.extend(means)
        stage_theta.extend(evaluated['theta'])
        tensors.append(_tensor(f'{prefix}_Stats', [7], ['StageField'], stats, 'Actual same-theta stage metrics and diagnostic/update selectors in texts.stageFields order.'))
        _step(steps, f'{prefix}_stats', 'Retain the evaluated stage and its actual update boundary',
              'all metrics belong to theta_stage; diagnosticOnly=(stage==updates); hasNextUpdate=(stage<updates)',
              'The final stage is an actual final-theta evaluation, with all three diagnostic gradients and no additional SGD update.',
              dict(stage=s, updates=raw['updates'], theta0=evaluated['theta'][0], theta1=evaluated['theta'][1], theta2=evaluated['theta'][2]),
              dict(observedTrainHalfMSE=means[0], cleanTrainHalfMSE=means[1], validationHalfMSE=means[2],
                   omissionMinimum=evaluated['minimum'], omissionMaximum=evaluated['maximum'], diagnosticOnly=diagnostic_only, hasNextUpdate=has_next))
        if has_next:
            transition = transitions[s]
            update_prefix, rows = f'update_{s + 1}', []
            for j, coordinate in enumerate(transition['coordinates']):
                old, mathematical, effective = coordinate['old'], coordinate['mathematicalGradient'], coordinate['effectiveGradient']
                enabled_coordinate = coordinate['enabled']
                delta, proposed, committed = coordinate['delta'], coordinate['proposed'], coordinate['committed']
                rows.extend([old, mathematical, effective, enabled_coordinate, delta, proposed, committed])
                _step(steps, f'{update_prefix}_coordinate_{j}', 'Propose one coordinate from the same old state',
                      'delta=eta*effective; proposed=old-delta; committed=enabled==1?proposed:+0',
                      'All three stored coordinates get real delta/proposal records. The frozen coordinate commits positive zero; no new coordinate is used to recompute another gradient.',
                      dict(coordinate=j, old=old, mathematical=mathematical, effective=effective, enabled=enabled_coordinate, eta=coordinate['eta'], frozenZero=0.0),
                      dict(delta=delta, proposed=proposed, committed=committed))
            before, after = transition['before'], transition['after']
            _step(steps, f'{update_prefix}_commit', 'Publish the three simultaneous SGD coordinates together',
                  'nextTheta=[committed0,committed1,committed2]',
                  'This completes exactly one optimizer batch. A subsequent stage genuinely reevaluates all eight samples; no final diagnostic gradient causes another update.',
                  dict(old0=before[0], old1=before[1], old2=before[2]), dict(theta0=after[0], theta1=after[1], theta2=after[2]))
            tensors.append(_tensor(f'{update_prefix}_Update', [3, 7], ['Coordinate', 'UpdateField'], rows, 'Actual old, mathematical, effective, enabled, delta, proposed, committed fields in texts.updateFields order; all proposals use the same old theta.'))
    stage_count, work = len(stages), evidence['work']
    tensors.extend([
        _tensor('StageMetrics', [stage_count, 3], ['Stage', 'Objective'], stage_metrics, 'Only actual evaluated stages0..updates in texts.objectiveKeys order; no padded, interpolated, fitted or analytic-optimum points.'),
        _tensor('StageTheta', [stage_count, 3], ['Stage', 'Coordinate'], stage_theta, 'Only actual same-stage readout coordinates in aPlus,aMinus,b order, including genuinely evaluated final theta.'),
    ])
    counts = dict(featureMaps=work['featureMaps'], stageCount=stage_count,
                  forwardSampleEvaluations=work['forwardSampleEvaluations'], gradientBatches=work['gradientBatches'],
                  gradientRowContributions=work['gradientRowContributions'], gradientContractions=work['gradientContractions'],
                  optimizerBatches=work['optimizerBatches'], usedForUpdateRows=work['usedForUpdateRows'],
                  storedCoordinateUpdateRecords=work['storedCoordinateUpdateRecords'], enabledCoordinateUpdates=work['enabledCoordinateUpdates'],
                  omissionMeans=work['omissionMeans'], rangeComparisons=work['rangeComparisons'], finalStage=stage_count - 1)
    _step(steps, 'finish', 'Report actual work and final evaluated state',
          'stageCount=actual evaluated stages; optimizerBatches=actual completed transitions; finalStage=stageCount-1',
          'Feature maps are computed once. Final diagnostic contractions count as gradient work but not optimizer work; all three stored-coordinate proposals count even when one is frozen.',
          dict(requestedUpdates=raw['updates'], enabledParameters=enabled, storedParameters=3), counts)
    final = stages[-1]
    outputs = dict(observedTrainHalfMSE=final['observedTrain']['mean'], cleanTrainHalfMSE=final['cleanTrain']['mean'],
                   validationHalfMSE=final['validation']['mean'], enabledParameters=enabled,
                   capacity=raw['capacity'], updates=raw['updates'], corrupt=raw['corrupt'], eta=raw['eta'],
                   storedParameters=3, fixedFeatures=2, trainSamples=4, validationSamples=4, **counts,
                   finalTheta0=final['theta'][0], finalTheta1=final['theta'][1], finalTheta2=final['theta'][2],
                   omissionMinimum=final['minimum'], omissionMaximum=final['maximum'], frames=len(steps), tensorCount=len(tensors))
    for step in steps:
        for key, value in step['outputs'].items():
            alias = f"{step['id']}_{key}"
            if alias in outputs:
                raise RuntimeError('IV54 output aliases must be unique.')
            outputs[alias] = value
    return deepcopy(dict(status='defined', outputs=outputs, steps=steps, tensors=tensors, texts=_texts()))


def derive_iv54(value):
    """Full public root; only the declared numerical-fault family is caught."""
    try:
        return _defined_record(mechanics_experiment(value))
    except NumericalFault as error:
        return dict(status='unavailable', code=error.code, reason=str(error))


class QueryJSONError(ValueError):
    """Known JSON lexical/duplicate-member failure, never a semantic catch."""


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


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


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return int(token)
    except ValueError as error:
        # A decimal digit-limit failure belongs to parsing, not query semantics.
        raise QueryJSONError("JSON integer exceeds the interpreter's decimal digit limit.") from error


def parse_query(text):
    """Strict standard JSON; duplicate members at any depth are rejected."""
    return json.loads(text, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)


def query_mechanics(value):
    """Known input/numerical faults only; unexpected backend/program errors escape."""
    try:
        evidence = mechanics_experiment(value)
    except NumericalFault as error:
        return dict(status="unavailable", code=error.code, reason=str(error))
    return dict(status="defined", evidence=evidence)


def _expect_fault(call, code):
    try:
        call()
    except NumericalFault as error:
        assert error.code == code
    else:
        raise AssertionError(f"Expected {code}")


def check_hand_anchors():
    """Independent paper fractions, not generated expected trajectories."""
    initial = mechanics_experiment(dict(capacity=1, updates=0, corrupt=0, eta=0.25))
    stage = initial["stages"][0]
    assert stage["observedTrain"]["mean"] == 5 / 16
    assert stage["cleanTrain"]["mean"] == 5 / 16
    assert stage["validation"]["mean"] == 5 / 32
    assert stage["mathematicalGradient"] == [-5 / 16, -5 / 16, -3 / 4]
    assert [row["reduction"]["mean"] for row in stage["omissions"]] == [11 / 96, 19 / 96, 19 / 96, 11 / 96]
    assert stage["minimum"] == 11 / 96 and stage["maximum"] == 19 / 96
    assert initial["updates"] == [] and initial["work"]["forwardSampleEvaluations"] == 8

    full = mechanics_experiment(dict(capacity=1, updates=1, corrupt=0, eta=0.25))
    last = full["stages"][1]
    assert last["theta"] == [5 / 64, 5 / 64, 3 / 16]
    assert last["observedTrain"]["mean"] == 10061 / 65536
    assert last["validation"]["mean"] == 8381 / 131072
    assert last["mathematicalGradient"] == [-223 / 1024, -223 / 1024, -129 / 256]
    assert last["usedForUpdate"] == 0

    restricted = mechanics_experiment(dict(capacity=0, updates=1, corrupt=0, eta=0.25))
    last = restricted["stages"][1]
    assert last["theta"] == [5 / 64, 0.0, 3 / 16]
    assert last["observedTrain"]["mean"] == 22477 / 131072
    assert last["validation"]["mean"] == 18877 / 262144
    frozen = restricted["updates"][0]["coordinates"][1]
    assert frozen["mathematicalGradient"] == -5 / 16
    assert frozen["effectiveGradient"].hex() == "0x0.0p+0"
    assert frozen["committed"].hex() == "0x0.0p+0"

    noisy = mechanics_experiment(dict(capacity=1, updates=1, corrupt=1, eta=0.25))
    assert noisy["stages"][0]["observedTrain"]["mean"] == 15 / 32
    assert noisy["stages"][0]["mathematicalGradient"] == [-5 / 16, -7 / 16, -7 / 8]
    last = noisy["stages"][1]
    assert last["theta"] == [5 / 64, 7 / 64, 7 / 32]
    assert last["observedTrain"]["mean"] == 16201 / 65536
    assert last["cleanTrain"]["mean"] == 8649 / 65536
    assert last["validation"]["mean"] == 6969 / 131072
    assert noisy["data"][0]["cleanTarget"] == 1.0 and noisy["data"][0]["observedTarget"] == 1.5
    assert all("observedTarget" not in row for row in noisy["data"][4:])
    # The corrupted first step really has LOWER validation loss in this case.
    assert last["validation"]["mean"] < full["stages"][1]["validation"]["mean"]

    default = mechanics_experiment(dict(DEFAULT_IV54))
    assert default["finalTheta"] == [543 / 4096, 543 / 4096, 321 / 1024]
    assert default["stages"][-1]["observedTrain"]["mean"] == 21563669 / 268435456
    assert default["stages"][-1]["validation"]["mean"] == 16504709 / 536870912
    overshoot = mechanics_experiment(dict(capacity=1, updates=1, corrupt=0, eta=2.0))
    assert overshoot["finalTheta"] == [5 / 8, 5 / 8, 3 / 2]
    assert overshoot["stages"][1]["observedTrain"]["mean"] == 765 / 1024
    assert overshoot["stages"][1]["validation"]["mean"] == 1773 / 2048
    assert overshoot["stages"][1]["observedTrain"]["mean"] > overshoot["stages"][0]["observedTrain"]["mean"]


def check_guards_and_cli():
    """Guard precedence, zero signs, JSON and unexpected-error propagation."""
    global mechanics_experiment
    _expect_fault(lambda: mechanics_experiment(dict(capacity=9, updates=0, corrupt=0, eta=True)), "NONFINITE")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=10**400, updates=0, corrupt=0, eta=0.25)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=0, corrupt=0, eta=10**400)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=0, corrupt=0, eta=float("nan"))), "NONFINITE")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=0, corrupt=0, eta=-0.1)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=0, corrupt=0, eta=2.01)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=0.5, corrupt=0, eta=0.25)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=4, corrupt=0, eta=0.25)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(capacity=1, updates=0, corrupt=2, eta=0.25)), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment({}), "INVALID_INPUT")
    _expect_fault(lambda: mechanics_experiment(dict(DEFAULT_IV54, extra=0)), "INVALID_INPUT")
    _expect_fault(lambda: evaluate_generalization([10**400, 0.0, 0.0], 1, 0), "NONFINITE")
    # Derived coordinates are not clamped to eta's [0,2] editor domain.
    assert evaluate_generalization([3.0, 0.0, 0.0], 1, 0)["theta"][0] == 3.0
    huge = sys.float_info.max
    _expect_fault(lambda: evaluate_generalization([huge, huge, huge], 1, 0), "NONFINITE")
    class Object(dict):
        def __getitem__(self, key):
            raise AssertionError("custom hooks must not run")
    _expect_fault(lambda: mechanics_experiment(Object(DEFAULT_IV54)), "INVALID_INPUT")

    signed = mechanics_experiment(dict(capacity=0.0, updates=1.0, corrupt=-0.0, eta=-0.0))
    assert signed["raw"]["eta"].hex() == "-0x0.0p+0"
    frozen = signed["updates"][0]["coordinates"][1]
    assert frozen["delta"].hex() == "-0x0.0p+0"
    assert frozen["committed"].hex() == "0x0.0p+0"
    assert query_mechanics(dict(DEFAULT_IV54))["status"] == "defined"
    assert query_mechanics({})["code"] == "INVALID_INPUT"
    parsed = parse_query('{"capacity":1.0,"updates":0,"corrupt":0,"eta":-0.0}')
    assert parsed["eta"].hex() == "-0x0.0p+0"
    assert parse_query("-0").hex() == "-0x0.0p+0"
    for text in ('{"eta":0,"eta":1}', '{"nested":{"x":0,"x":1}}', 'NaN', 'Infinity', '-Infinity', '{'):
        try:
            parse_query(text)
        except (json.JSONDecodeError, QueryJSONError):
            pass
        else:
            raise AssertionError("Strict JSON parser accepted a forbidden form")

    # A query must not swallow an unforeseen backend/program failure.
    original = mechanics_experiment
    def unexpected(value):
        raise RuntimeError("sentinel unexpected backend fault")
    try:
        mechanics_experiment = unexpected
        try:
            query_mechanics(dict(DEFAULT_IV54))
        except RuntimeError as error:
            assert str(error) == "sentinel unexpected backend fault"
        else:
            raise AssertionError("Query swallowed an unexpected error")
    finally:
        mechanics_experiment = original


def check_stage_and_work_invariants():
    """Every saved stage, endpoint copy and actual-work count; no full-root claim."""
    for capacity in (0, 1):
        for corrupt in (0, 1):
            for count in range(4):
                for eta in (0.0, -0.0, 0.25, 2.0):
                    evidence = mechanics_experiment(dict(capacity=capacity, updates=count, corrupt=corrupt, eta=eta))
                    stages, transitions = evidence["stages"], evidence["updates"]
                    work = evidence["work"]
                    assert len(stages) == count + 1 and len(transitions) == count
                    assert work["stageCount"] == count + 1
                    assert work["forwardSampleEvaluations"] == 8 * (count + 1)
                    assert work["featureMaps"] == 8
                    assert work["gradientBatches"] == count + 1
                    assert work["gradientRowContributions"] == 4 * (count + 1)
                    assert work["optimizerBatches"] == count
                    assert work["usedForUpdateRows"] == 4 * count
                    assert work["storedCoordinateUpdateRecords"] == 3 * count
                    assert work["enabledCoordinateUpdates"] == (2 + capacity) * count
                    assert work["omissionMeans"] == 4 * (count + 1)
                    for index, stage in enumerate(stages):
                        endpoint = evaluate_generalization(stage["theta"], capacity, corrupt)
                        # JSON retains signed-zero spelling here; ordinary == does not.
                        actual = {key: value for key, value in stage.items() if key not in ("stage", "usedForUpdate")}
                        assert json.dumps(actual, allow_nan=False) == json.dumps(endpoint, allow_nan=False)
                        assert len(stage["samples"]) == 8
                        assert stage["usedForUpdate"] == int(index < count)
                        assert all(row["theta"] == stage["theta"] for row in stage["samples"])
                        if capacity == 0:
                            assert stage["theta"][1].hex() == "0x0.0p+0"
                        if index < count:
                            transition = transitions[index]
                            assert transition["before"] == stage["theta"]
                            assert transition["after"] == stages[index + 1]["theta"]
                            assert len(transition["coordinates"]) == 3
                    assert evidence["finalTheta"] == stages[-1]["theta"]
                    # Caller mutation cannot rewrite another saved state.
                    old = stages[0]["theta"][0]
                    evidence["finalTheta"][0] = 999.0
                    assert stages[0]["theta"][0] == old


def check_public_record():
    """Local root/count/copy checks; independent whole-root authority is separate."""
    for updates in range(4):
        record = derive_iv54(dict(DEFAULT_IV54, updates=updates))
        assert list(record) == ['status', 'outputs', 'steps', 'tensors', 'texts']
        assert list(record['outputs'])[:4] == ['observedTrainHalfMSE', 'cleanTrainHalfMSE', 'validationHalfMSE', 'enabledParameters']
        assert len(record['steps']) == 42 + 35 * updates
        assert len(record['tensors']) == 18 + 14 * updates
        assert len(record['outputs']) == 251 + 159 * updates
        assert len(record['texts']) == 26
        assert all(list(step) == ['id', 'label', 'equation', 'explanation', 'inputs', 'outputs'] for step in record['steps'])
        assert all(list(tensor) == ['id', 'shape', 'axes', 'dtype', 'values', 'provenance', 'precision'] for tensor in record['tensors'])
        aliases = {f"{step['id']}_{key}": value for step in record['steps'] for key, value in step['outputs'].items()}
        assert list(record['outputs'])[32:] == list(aliases)
        for alias, value in aliases.items():
            assert record['outputs'][alias] == value
            if type(value) is float:
                assert record['outputs'][alias].hex() == value.hex()
        assert record['tensors'][2]['dtype'] == 'int32' and record['tensors'][2]['precision'] == 0
        for tensor in record['tensors']:
            cells = 1
            for dimension in tensor['shape']:
                assert 1 <= dimension <= 64
                cells *= dimension
            assert cells == len(tensor['values']) <= 4096
        final_theta = next(t for t in record['tensors'] if t['id'] == f'stage_{updates}_Theta')['values']
        final_before = final_theta[:]
        record['tensors'][-1]['values'][-1] = 999.0
        assert final_theta == final_before
    default = derive_iv54(dict(DEFAULT_IV54))
    assert default['outputs']['observedTrainHalfMSE'] == 21563669 / 268435456
    assert default['outputs']['validationHalfMSE'] == 16504709 / 536870912
    assert derive_iv54(None) == dict(status='unavailable', code='INVALID_INPUT', reason='state must be a plain object.')
    assert derive_iv54({}) == dict(status='unavailable', code='INVALID_INPUT', reason='state must have exactly capacity, updates, corrupt, eta as own fields.')
    signed = derive_iv54(dict(capacity=0, updates=1, corrupt=0, eta=-0.0))
    assert signed['outputs']['eta'].hex() == '-0x0.0p+0'
    assert signed['outputs']['update_1_coordinate_1_delta'].hex() == '-0x0.0p+0'
    assert signed['outputs']['update_1_coordinate_1_committed'].hex() == '0x0.0p+0'


def check_query_check_isolation():
    """Tripwire hooks: default/replacement/stdin/public queries call zero checks."""
    from contextlib import redirect_stdout
    from io import StringIO
    names = ['source_self_check', 'self_check', 'check_hand_anchors', 'check_guards_and_cli',
             'check_stage_and_work_invariants', 'check_public_record',
             'check_query_check_isolation', 'check_cli_boundary']
    saved = {name: globals()[name] for name in names}
    original_stdin, original_argv = sys.stdin, sys.argv
    def forbidden():
        raise AssertionError('An ordinary query called a check entry point')
    try:
        for name in names:
            globals()[name] = forbidden
        assert derive_iv54(dict(DEFAULT_IV54))['status'] == 'defined'
        for args in ([], [json.dumps(dict(DEFAULT_IV54))], ['-']):
            sys.stdin = StringIO(json.dumps(dict(DEFAULT_IV54)))
            output = StringIO()
            with redirect_stdout(output):
                sys.argv = ["iv54.py", *args]
                assert run() == 0
            assert list(json.loads(output.getvalue())) == ['status', 'outputs', 'steps', 'tensors', 'texts']
    finally:
        globals().update(saved)
        sys.stdin, sys.argv = original_stdin, original_argv


def check_cli_boundary():
    """Known parse failures stop at parsing; unforeseen semantic errors escape."""
    from contextlib import redirect_stdout, redirect_stderr
    from io import StringIO
    for text in ('{', '{"eta":0,"eta":1}', 'NaN'):
        output = StringIO()
        with redirect_stdout(output):
            assert main([text]) == 0
        assert json.loads(output.getvalue())['code'] == 'INVALID_INPUT'
    for text in ('{}', 'null', '{"capacity":1,"updates":0,"corrupt":0,"eta":1e400}'):
        output = StringIO()
        with redirect_stdout(output):
            assert main([text]) == 0
        assert json.loads(output.getvalue())['status'] == 'unavailable'
    output, errors = StringIO(), StringIO()
    with redirect_stdout(output), redirect_stderr(errors):
        assert main(['{}', '{}']) == 2
    assert not output.getvalue() and errors.getvalue()
    parsed = parse_query('{"capacity":1,"updates":0,"corrupt":0,"eta":-0}')
    assert derive_iv54(parsed)['outputs']['eta'].hex() == '-0x0.0p+0'
    original = globals()['mechanics_experiment']
    def unexpected(value):
        # Even a JSON-looking exception raised by semantics must propagate.
        raise json.JSONDecodeError('semantic sentinel', '', 0)
    try:
        globals()['mechanics_experiment'] = unexpected
        for call in (lambda: derive_iv54(dict(DEFAULT_IV54)), lambda: main([])):
            try:
                call()
            except json.JSONDecodeError as error:
                assert error.msg == 'semantic sentinel'
            else:
                raise AssertionError('Semantic exception was swallowed by the parse boundary')
    finally:
        globals()['mechanics_experiment'] = original


def source_self_check():
    """Six explicit parameterless terminal checks; never implicit query work."""
    check_hand_anchors()
    check_guards_and_cli()
    check_stage_and_work_invariants()
    check_public_record()
    check_query_check_isolation()
    check_cli_boundary()


self_check = source_self_check


def main(argv=None):
    args = sys.argv[1:] if argv is None else argv
    if args == ['--self-check']:
        source_self_check()  # Outside both parsing and numerical query catches.
        print('IV54 canonical source self-checks completed.')
        return 0
    if len(args) > 1:
        print("Use no argument, one complete JSON object, '-' for stdin, or --self-check.", file=sys.stderr)
        return 2
    if not args:
        value = dict(DEFAULT_IV54)
    else:
        text = sys.stdin.read() if args[0] == '-' else args[0]
        try:
            value = parse_query(text)
        except (json.JSONDecodeError, QueryJSONError) as error:
            print(json.dumps(dict(status='unavailable', code='INVALID_INPUT', reason=str(error)), allow_nan=False))
            return 0
    result = derive_iv54(value)
    print(json.dumps(result, allow_nan=False))
    return 0


def run():
    """Stable zero-argument canonical CLI entry point."""
    return main()


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

Recap and bridge

  • Capacity changes which functions the enabled coordinates can express; this network always stores three coordinates.
  • Updates use observed training labels and one common old parameter vector. Final-stage gradients are diagnostic.
  • Clean training and clean validation are separate reports. A wrong training label can accidentally improve one early validation score.
  • Four omission means describe sensitivity to this grid’s membership; they do not estimate population confidence.
  • A few authored toy stages cannot establish universal LLM scaling laws, frontier performance, hardware tradeoffs or an empirical scaling exponent.

Part XIII connected data boundaries, actual updates, continuation state and evaluation limits. Part XIV turns to Fine-Tuning and Alignment: once a starting model and evaluation question are fixed, which parameters should adaptation change, and what can a chosen objective establish? The distinctions between representational capacity, optimization and evidence remain essential.