The neural notebook
← All chapters

IV-56 / Part XIV · Fine-Tuning and Alignment

Low-Rank Adaptation (LoRA)

Derive an additive low-rank update, follow its first factor gradients and simultaneous step, and distinguish trainable counts and structural rank from rounded numerical results.

Review the ideas this chapter uses

Suppose a small model already has useful weights, but its new task asks for different answers. We could change every weight, as in the previous chapter. Another choice is to keep those weights and learn an addition made from two smaller matrices. We will calculate that addition, its first update, and the resulting predictions by hand.

Learning objective: Derive W0+(α/r)BAW_0+(\alpha/r)BA and compute gradients and trainable counts. Review IV-55 — Pretraining, Fine-Tuning and Transfer for the actual pretraining calculation and II.10 — Matrix × matrix as composition for matrix composition. These are the chapter’s prerequisites.

Source checkpoint: The lab and four complete Python source panels bind the actual IV56 implementation. The hand calculations explain its operations. The source panels and hand calculations are not execution or passing-check results.

Start with the default case: identity-row AA, zero BB, one adapter update. The first four summaries show the final held-out loss, final training loss, factor trainable count and structural rank bound. They describe the whole experiment even when you inspect an earlier stage. The detailed walkthrough below explains the saved tables and controls.

Reading the saved numbers: WORD means the exact 64-bit stored number pattern, including the sign of zero. VALUE means an abstract integer selector or count. For example, a copied factor zero retains its WORD sign, while a sample index is compared by integer VALUE.

Compute it yourself

Low-Rank Adaptation (LoRA)

Keep a readout that the lab really prepared, and learn an additive change through two factors. Change rank, α, initialization, update count or η to recompute the full experiment. The default shows one actual adapter step after two PRE updates from zero.

Compare frozen base storage, trainable factors and actual losses. This tiny example has no trainable-count saving: rank1 equals full tuning and rank2 uses more. The four local selectors inspect saved evidence without changing the model or answers.

adaptValidationLoss0.10121981213160325
adaptTrainLoss0.2024396242632065
adapterTrainableParameters4
structuralRankBound1
Exact starting inputs for this saved calculation

adaptValidationLoss 0.10121981213160325. adaptTrainLoss 0.2024396242632065. adapterTrainableParameters 4. structuralRankBound 1. Freeze an actual prepared readout and learn additive factors. First really prepare W0 from zero. Then optimize only the factors of an additive update. Editing any raw field restarts this complete declared experiment. The structural bound describes the exact-real factorization, while the saved effective matrix follows explicit binary64 operations.

Freeze an actual prepared readout and learn additive factors

W_eff=W0+(alpha/r)*BA; A:[r,2]; B:[2,r]; trainable=4r; full=4; PRE updates=2 at eta0.5

First really prepare W0 from zero. Then optimize only the factors of an additive update. Editing any raw field restarts this complete declared experiment. The structural bound describes the exact-real factorization, while the saved effective matrix follows explicit binary64 operations.

Saved inputs

rank
1
alpha
1
initialization
0
updates
1
eta
0.5

Saved outputs

adapterTrainableParameters
4
fullFineTuneParameters
4
frozenBaseParameters
4
storedBaseAndFactors
8
structuralRankBound
1
scale
1
fixedFeatures
2
outputsPerSample
2
trainSamples
4
validationSamples
4
preUpdates
2
preEta
0.5

Freeze an actual prepared base; learn its additive change

Whole current case: rank=1, alpha=1, initialization=0, updates=1, η=0.5, c=1. A:[1,2], B:[2,1], BA:[2,2]. Adapter trainables=4; full tuning=4; frozen base stored=4; base plus factors=8. Every raw edit restarts the complete PRE and adapter experiment.

A factor is a smaller matrix whose entries can learn. A base is the readout prepared before adapter learning. The fixed features φ=[max(0,x),max(0,−x)]ᵀ keep positive and negative input parts. W0 and W_eff have output rows and feature columns. B times A is legal because their rank axes match. AB instead has shape [r,r]. A sample prediction is W_eff:[2,2] times φ:[2,1]; four feature rows F:[4,2] use F W_effᵀ:[4,2].

PRE: all three actual states and two updates from zero
Task / stage / next actionW00W01W10W11Training meanHeld-out mean
pre 0 / then update00000.31250.15625
pre 1 / then update0.15625000.156250.222473144531250.111236572265625
pre 2 / final diagnostic only0.2880859375000.28808593750.158381760120391850.07919088006019592
Frozen base: exact PRE2 copy and every selected-stage copy
CoordinatePRE initialPRE2 evaluated WFrozenBaseSelected helper BaseSelected materialized W_effSelected readout W
W0000.28808593750.28808593750.28808593750.28808593750.2880859375
W01000000
W10000000
W1100.28808593750.28808593750.28808593750.28808593750.2880859375

PRE starts with four positive zeros and really performs two simultaneous full-coordinate updates at η=0.5. The resulting base is copied word for word; its readout gradient during ADAPT is diagnostic evidence for factor gradients, never a base optimizer proposal.

Every PRE state: complete readout evidence and both simultaneous transitions

pre_initial: Start actual PRE at positive-zero weights

weights=[+0,+0,+0,+0]

These authored zeros start the feature-copy target task. The next three evaluations and two full-coordinate transitions actually construct the frozen base; no prepared fraction is inserted.

Saved inputs
source0
0
source1
0
source2
0
source3
0
Saved outputs
weight0
0
weight1
0
weight2
0
weight3
0

PRE stage 0: feature-copy targets

pre_stage_0: all eight samples, targets, predictions and losses
Sample / rolexphiPlusphiMinuspreTarget0preTarget1adaptTarget0adaptTarget1Prediction 0Prediction 1Sample loss
train0 / training-101010.51000.5
train1 / training-0.500.500.50.250.5000.125
train2 / training0.50.500.500.5-0.25000.125
train3 / training110101-0.5000.5
validation0 / held out-0.7500.7500.750.3750.75000.28125
validation1 / held out-0.2500.2500.250.1250.25000.03125
validation2 / held out0.250.2500.2500.25-0.125000.03125
validation3 / held out0.750.7500.7500.75-0.375000.28125
All eight forwards and two-output losses
pre_stage_0: four products and two output sums per sample
Sampleproduct00product01product10product11prediction0prediction1
train0000000
train1000000
train2000000
train3000000
validation0000000
validation1000000
validation2000000
validation3000000
pre_stage_0: targets, errors, squares, halves and sample sums
Sampletarget0target1error0error1square0square1half0half1sampleLoss
train0010-10100.50.5
train100.50-0.500.2500.1250.125
train20.50-0.500.2500.12500.125
train310-10100.500.5
validation000.750-0.7500.562500.281250.28125
validation100.250-0.2500.062500.031250.03125
validation20.250-0.2500.062500.0312500.03125
validation30.750-0.7500.562500.2812500.28125
pre_stage_0: both ordered four-sample loss reductions
Dataset / rowlossoldSumsum
training / 00.500.5
training / 10.1250.50.625
training / 20.1250.6250.75
training / 30.50.751.25
validation / 00.2812500.28125
validation / 10.031250.281250.3125
validation / 20.031250.31250.34375
validation / 30.281250.343750.625

Training mean=0.3125; held-out mean=0.15625. Each reduction starts at +0 and divides its own final sum by 4. Each sample loss first sums two output half-losses; the denominator is four samples, not eight scalar outputs.

pre_stage_0: actual readout weights, gradients and mask
CoordinateSaved WMathematical G_WEffective gradientMask (VALUE)
W000-0.3125-0.31251
W010001
W100001
W110-0.3125-0.31251
All sixteen training gradient contributions, including old partial sums
pre_stage_0: G_W training contractions
Coordinate / training rowerrorfeaturecontributionoldSumsum
W00 / train000000
W00 / train100000
W00 / train2-0.50.5-0.250-0.25
W00 / train3-11-1-0.25-1.25
W01 / train001000
W01 / train100.5000
W01 / train2-0.50-000
W01 / train3-10-000
W10 / train0-10-000
W10 / train1-0.50-000
W10 / train200.5000
W10 / train301000
W11 / train0-11-10-1
W11 / train1-0.50.5-0.25-1-1.25
W11 / train2000-1.25-1.25
W11 / train3000-1.25-1.25

pre_stage_0_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
0
feature0
0
error1
0
feature1
0
error2
-0.5
feature2
0.5
error3
-1
feature3
1
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0.25
sum2
-0.25
contribution3
-1
sum3
-1.25
mathematical
-0.3125

pre_stage_0_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
0
feature0
1
error1
0
feature1
0.5
error2
-0.5
feature2
0
error3
-1
feature3
0
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0
sum2
0
contribution3
-0
sum3
0
mathematical
0

pre_stage_0_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-1
feature0
0
error1
-0.5
feature1
0
error2
0
feature2
0.5
error3
0
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0
sum2
0
contribution3
0
sum3
0
mathematical
0

pre_stage_0_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-1
feature0
1
error1
-0.5
feature1
0.5
error2
0
feature2
0
error3
0
feature3
0
Saved outputs
contribution0
-1
sum0
-1
contribution1
-0.25
sum1
-1.25
contribution2
0
sum2
-1.25
contribution3
0
sum3
-1.25
mathematical
-0.3125
Selected sample, both means and mask: complete saved operands

data_0: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
0
training
1
x
-1
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
1
phiPlus
0
phiMinus
1
preTarget0
0
preTarget1
1
scaledMinus
0.5
adaptTarget0
0.5
scaledPlus
-0
adaptTarget1
1

pre_stage_0_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
0
prediction0
0
prediction1
0
target0
0
target1
1
divisor
2
Saved outputs
error0
0
error1
-1
square0
0
square1
1
half0
0
half1
0.5
sampleLoss
0.5

pre_stage_0_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
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

pre_stage_0_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
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

pre_stage_0_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.3125
enabled0
1
mathematical1
0
enabled1
1
mathematical2
0
enabled2
1
mathematical3
-0.3125
enabled3
1
Saved outputs
effective0
-0.3125
effective1
0
effective2
0
effective3
-0.3125
PRE update 1: all four old-state proposals
Coordinateoldmathematicaleffectiveenableddeltaproposedcommitted
W000-0.3125-0.31251-0.156250.156250.15625
W010001000
W100001000
W110-0.3125-0.31251-0.156250.156250.15625

pre_update_1_coordinate_0: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
0
old
0
mathematical
-0.3125
effective
-0.3125
enabled
1
eta
0.5
Saved outputs
delta
-0.15625
proposed
0.15625
committed
0.15625

pre_update_1_coordinate_1: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
1
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_1_coordinate_2: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
2
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_1_coordinate_3: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
3
old
0
mathematical
-0.3125
effective
-0.3125
enabled
1
eta
0.5
Saved outputs
delta
-0.15625
proposed
0.15625
committed
0.15625

pre_update_1_commit: Publish all four proposed coordinates together

nextWeights=[committed0,committed1,committed2,committed3]

This simultaneous publication completes one optimizer step. No coordinate update changes a gradient used for another coordinate. A later stage evaluates the resulting weights again; its final diagnostic gradient causes no additional step.

Saved inputs
old0
0
old1
0
old2
0
old3
0
Saved outputs
weight0
0.15625
weight1
0
weight2
0
weight3
0.15625

pre_stage_0_stats: Save the actual PRE state and its diagnostic status

diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W

Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base.

Saved inputs
task
0
stage
0
requestedUpdates
2
weight0
0
weight1
0
weight2
0
weight3
0
trainHalfMSE
0.3125
validationHalfMSE
0.15625
Saved outputs
trainHalfMSE
0.3125
validationHalfMSE
0.15625
diagnosticOnly
0
hasNextUpdate
1

PRE stage 1: feature-copy targets

pre_stage_1: all eight samples, targets, predictions and losses
Sample / rolexphiPlusphiMinuspreTarget0preTarget1adaptTarget0adaptTarget1Prediction 0Prediction 1Sample loss
train0 / training-101010.5100.156250.35595703125
train1 / training-0.500.500.50.250.500.0781250.0889892578125
train2 / training0.50.500.500.5-0.250.07812500.0889892578125
train3 / training110101-0.50.1562500.35595703125
validation0 / held out-0.7500.7500.750.3750.7500.11718750.200225830078125
validation1 / held out-0.2500.2500.250.1250.2500.03906250.022247314453125
validation2 / held out0.250.2500.2500.25-0.1250.039062500.022247314453125
validation3 / held out0.750.7500.7500.75-0.3750.117187500.200225830078125
All eight forwards and two-output losses
pre_stage_1: four products and two output sums per sample
Sampleproduct00product01product10product11prediction0prediction1
train00000.1562500.15625
train10000.07812500.078125
train20.0781250000.0781250
train30.156250000.156250
validation00000.117187500.1171875
validation10000.039062500.0390625
validation20.03906250000.03906250
validation30.11718750000.11718750
pre_stage_1: targets, errors, squares, halves and sample sums
Sampletarget0target1error0error1square0square1half0half1sampleLoss
train0010-0.8437500.711914062500.355957031250.35595703125
train100.50-0.42187500.17797851562500.08898925781250.0889892578125
train20.50-0.42187500.17797851562500.088989257812500.0889892578125
train310-0.8437500.711914062500.3559570312500.35595703125
validation000.750-0.632812500.4004516601562500.2002258300781250.200225830078125
validation100.250-0.210937500.0444946289062500.0222473144531250.022247314453125
validation20.250-0.210937500.0444946289062500.02224731445312500.022247314453125
validation30.750-0.632812500.4004516601562500.20022583007812500.200225830078125
pre_stage_1: both ordered four-sample loss reductions
Dataset / rowlossoldSumsum
training / 00.3559570312500.35595703125
training / 10.08898925781250.355957031250.4449462890625
training / 20.08898925781250.44494628906250.533935546875
training / 30.355957031250.5339355468750.889892578125
validation / 00.20022583007812500.200225830078125
validation / 10.0222473144531250.2002258300781250.22247314453125
validation / 20.0222473144531250.222473144531250.244720458984375
validation / 30.2002258300781250.2447204589843750.4449462890625

Training mean=0.22247314453125; held-out mean=0.111236572265625. Each reduction starts at +0 and divides its own final sum by 4. Each sample loss first sums two output half-losses; the denominator is four samples, not eight scalar outputs.

pre_stage_1: actual readout weights, gradients and mask
CoordinateSaved WMathematical G_WEffective gradientMask (VALUE)
W000.15625-0.263671875-0.2636718751
W010001
W100001
W110.15625-0.263671875-0.2636718751
All sixteen training gradient contributions, including old partial sums
pre_stage_1: G_W training contractions
Coordinate / training rowerrorfeaturecontributionoldSumsum
W00 / train000000
W00 / train100000
W00 / train2-0.4218750.5-0.21093750-0.2109375
W00 / train3-0.843751-0.84375-0.2109375-1.0546875
W01 / train001000
W01 / train100.5000
W01 / train2-0.4218750-000
W01 / train3-0.843750-000
W10 / train0-0.843750-000
W10 / train1-0.4218750-000
W10 / train200.5000
W10 / train301000
W11 / train0-0.843751-0.843750-0.84375
W11 / train1-0.4218750.5-0.2109375-0.84375-1.0546875
W11 / train2000-1.0546875-1.0546875
W11 / train3000-1.0546875-1.0546875

pre_stage_1_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
0
feature0
0
error1
0
feature1
0
error2
-0.421875
feature2
0.5
error3
-0.84375
feature3
1
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0.2109375
sum2
-0.2109375
contribution3
-0.84375
sum3
-1.0546875
mathematical
-0.263671875

pre_stage_1_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
0
feature0
1
error1
0
feature1
0.5
error2
-0.421875
feature2
0
error3
-0.84375
feature3
0
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0
sum2
0
contribution3
-0
sum3
0
mathematical
0

pre_stage_1_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.84375
feature0
0
error1
-0.421875
feature1
0
error2
0
feature2
0.5
error3
0
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0
sum2
0
contribution3
0
sum3
0
mathematical
0

pre_stage_1_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.84375
feature0
1
error1
-0.421875
feature1
0.5
error2
0
feature2
0
error3
0
feature3
0
Saved outputs
contribution0
-0.84375
sum0
-0.84375
contribution1
-0.2109375
sum1
-1.0546875
contribution2
0
sum2
-1.0546875
contribution3
0
sum3
-1.0546875
mathematical
-0.263671875
Selected sample, both means and mask: complete saved operands

data_0: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
0
training
1
x
-1
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
1
phiPlus
0
phiMinus
1
preTarget0
0
preTarget1
1
scaledMinus
0.5
adaptTarget0
0.5
scaledPlus
-0
adaptTarget1
1

pre_stage_1_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0
product01
0
product10
0
product11
0.15625
prediction0
0
prediction1
0.15625

pre_stage_1_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
0
prediction0
0
prediction1
0.15625
target0
0
target1
1
divisor
2
Saved outputs
error0
0
error1
-0.84375
square0
0
square1
0.7119140625
half0
0
half1
0.35595703125
sampleLoss
0.35595703125

pre_stage_1_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.35595703125
loss1
0.0889892578125
loss2
0.0889892578125
loss3
0.35595703125
Saved outputs
sum0
0.35595703125
sum1
0.4449462890625
sum2
0.533935546875
sum3
0.889892578125
mean
0.22247314453125

pre_stage_1_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.200225830078125
loss1
0.022247314453125
loss2
0.022247314453125
loss3
0.200225830078125
Saved outputs
sum0
0.200225830078125
sum1
0.22247314453125
sum2
0.244720458984375
sum3
0.4449462890625
mean
0.111236572265625

pre_stage_1_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.263671875
enabled0
1
mathematical1
0
enabled1
1
mathematical2
0
enabled2
1
mathematical3
-0.263671875
enabled3
1
Saved outputs
effective0
-0.263671875
effective1
0
effective2
0
effective3
-0.263671875
PRE update 2: all four old-state proposals
Coordinateoldmathematicaleffectiveenableddeltaproposedcommitted
W000.15625-0.263671875-0.2636718751-0.13183593750.28808593750.2880859375
W010001000
W100001000
W110.15625-0.263671875-0.2636718751-0.13183593750.28808593750.2880859375

pre_update_2_coordinate_0: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
0
old
0.15625
mathematical
-0.263671875
effective
-0.263671875
enabled
1
eta
0.5
Saved outputs
delta
-0.1318359375
proposed
0.2880859375
committed
0.2880859375

pre_update_2_coordinate_1: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
1
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_2_coordinate_2: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
2
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_2_coordinate_3: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
3
old
0.15625
mathematical
-0.263671875
effective
-0.263671875
enabled
1
eta
0.5
Saved outputs
delta
-0.1318359375
proposed
0.2880859375
committed
0.2880859375

pre_update_2_commit: Publish all four proposed coordinates together

nextWeights=[committed0,committed1,committed2,committed3]

This simultaneous publication completes one optimizer step. No coordinate update changes a gradient used for another coordinate. A later stage evaluates the resulting weights again; its final diagnostic gradient causes no additional step.

Saved inputs
old0
0.15625
old1
0
old2
0
old3
0.15625
Saved outputs
weight0
0.2880859375
weight1
0
weight2
0
weight3
0.2880859375

pre_stage_1_stats: Save the actual PRE state and its diagnostic status

diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W

Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base.

Saved inputs
task
0
stage
1
requestedUpdates
2
weight0
0.15625
weight1
0
weight2
0
weight3
0.15625
trainHalfMSE
0.22247314453125
validationHalfMSE
0.111236572265625
Saved outputs
trainHalfMSE
0.22247314453125
validationHalfMSE
0.111236572265625
diagnosticOnly
0
hasNextUpdate
1

PRE stage 2: feature-copy targets

pre_stage_2: all eight samples, targets, predictions and losses
Sample / rolexphiPlusphiMinuspreTarget0preTarget1adaptTarget0adaptTarget1Prediction 0Prediction 1Sample loss
train0 / training-101010.5100.28808593750.25341081619262695
train1 / training-0.500.500.50.250.500.144042968750.06335270404815674
train2 / training0.50.500.500.5-0.250.1440429687500.06335270404815674
train3 / training110101-0.50.288085937500.25341081619262695
validation0 / held out-0.7500.7500.750.3750.7500.2160644531250.14254358410835266
validation1 / held out-0.2500.2500.250.1250.2500.0720214843750.015838176012039185
validation2 / held out0.250.2500.2500.25-0.1250.07202148437500.015838176012039185
validation3 / held out0.750.7500.7500.75-0.3750.21606445312500.14254358410835266
All eight forwards and two-output losses
pre_stage_2: four products and two output sums per sample
Sampleproduct00product01product10product11prediction0prediction1
train00000.288085937500.2880859375
train10000.1440429687500.14404296875
train20.144042968750000.144042968750
train30.28808593750000.28808593750
validation00000.21606445312500.216064453125
validation10000.07202148437500.072021484375
validation20.0720214843750000.0720214843750
validation30.2160644531250000.2160644531250
pre_stage_2: targets, errors, squares, halves and sample sums
Sampletarget0target1error0error1square0square1half0half1sampleLoss
train0010-0.711914062500.506821632385253900.253410816192626950.25341081619262695
train100.50-0.3559570312500.1267054080963134800.063352704048156740.06335270404815674
train20.50-0.3559570312500.1267054080963134800.0633527040481567400.06335270404815674
train310-0.711914062500.506821632385253900.2534108161926269500.25341081619262695
validation000.750-0.53393554687500.285087168216705300.142543584108352660.14254358410835266
validation100.250-0.17797851562500.0316763520240783700.0158381760120391850.015838176012039185
validation20.250-0.17797851562500.0316763520240783700.01583817601203918500.015838176012039185
validation30.750-0.53393554687500.285087168216705300.1425435841083526600.14254358410835266
pre_stage_2: both ordered four-sample loss reductions
Dataset / rowlossoldSumsum
training / 00.2534108161926269500.25341081619262695
training / 10.063352704048156740.253410816192626950.3167635202407837
training / 20.063352704048156740.31676352024078370.38011622428894043
training / 30.253410816192626950.380116224288940430.6335270404815674
validation / 00.1425435841083526600.14254358410835266
validation / 10.0158381760120391850.142543584108352660.15838176012039185
validation / 20.0158381760120391850.158381760120391850.17421993613243103
validation / 30.142543584108352660.174219936132431030.3167635202407837

Training mean=0.15838176012039185; held-out mean=0.07919088006019592. Each reduction starts at +0 and divides its own final sum by 4. Each sample loss first sums two output half-losses; the denominator is four samples, not eight scalar outputs.

pre_stage_2: actual readout weights, gradients and mask
CoordinateSaved WMathematical G_WEffective gradientMask (VALUE)
W000.2880859375-0.22247314453125-0.222473144531251
W010001
W100001
W110.2880859375-0.22247314453125-0.222473144531251
All sixteen training gradient contributions, including old partial sums
pre_stage_2: G_W training contractions
Coordinate / training rowerrorfeaturecontributionoldSumsum
W00 / train000000
W00 / train100000
W00 / train2-0.355957031250.5-0.1779785156250-0.177978515625
W00 / train3-0.71191406251-0.7119140625-0.177978515625-0.889892578125
W01 / train001000
W01 / train100.5000
W01 / train2-0.355957031250-000
W01 / train3-0.71191406250-000
W10 / train0-0.71191406250-000
W10 / train1-0.355957031250-000
W10 / train200.5000
W10 / train301000
W11 / train0-0.71191406251-0.71191406250-0.7119140625
W11 / train1-0.355957031250.5-0.177978515625-0.7119140625-0.889892578125
W11 / train2000-0.889892578125-0.889892578125
W11 / train3000-0.889892578125-0.889892578125

pre_stage_2_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
0
feature0
0
error1
0
feature1
0
error2
-0.35595703125
feature2
0.5
error3
-0.7119140625
feature3
1
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0.177978515625
sum2
-0.177978515625
contribution3
-0.7119140625
sum3
-0.889892578125
mathematical
-0.22247314453125

pre_stage_2_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
0
feature0
1
error1
0
feature1
0.5
error2
-0.35595703125
feature2
0
error3
-0.7119140625
feature3
0
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0
sum2
0
contribution3
-0
sum3
0
mathematical
0

pre_stage_2_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.7119140625
feature0
0
error1
-0.35595703125
feature1
0
error2
0
feature2
0.5
error3
0
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0
sum2
0
contribution3
0
sum3
0
mathematical
0

pre_stage_2_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.7119140625
feature0
1
error1
-0.35595703125
feature1
0.5
error2
0
feature2
0
error3
0
feature3
0
Saved outputs
contribution0
-0.7119140625
sum0
-0.7119140625
contribution1
-0.177978515625
sum1
-0.889892578125
contribution2
0
sum2
-0.889892578125
contribution3
0
sum3
-0.889892578125
mathematical
-0.22247314453125
Selected sample, both means and mask: complete saved operands

data_0: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
0
training
1
x
-1
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
1
phiPlus
0
phiMinus
1
preTarget0
0
preTarget1
1
scaledMinus
0.5
adaptTarget0
0.5
scaledPlus
-0
adaptTarget1
1

pre_stage_2_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.2880859375
prediction0
0
prediction1
0.2880859375

pre_stage_2_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
0
prediction0
0
prediction1
0.2880859375
target0
0
target1
1
divisor
2
Saved outputs
error0
0
error1
-0.7119140625
square0
0
square1
0.5068216323852539
half0
0
half1
0.25341081619262695
sampleLoss
0.25341081619262695

pre_stage_2_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.25341081619262695
loss1
0.06335270404815674
loss2
0.06335270404815674
loss3
0.25341081619262695
Saved outputs
sum0
0.25341081619262695
sum1
0.3167635202407837
sum2
0.38011622428894043
sum3
0.6335270404815674
mean
0.15838176012039185

pre_stage_2_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.14254358410835266
loss1
0.015838176012039185
loss2
0.015838176012039185
loss3
0.14254358410835266
Saved outputs
sum0
0.14254358410835266
sum1
0.15838176012039185
sum2
0.17421993613243103
sum3
0.3167635202407837
mean
0.07919088006019592

pre_stage_2_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.22247314453125
enabled0
1
mathematical1
0
enabled1
1
mathematical2
0
enabled2
1
mathematical3
-0.22247314453125
enabled3
1
Saved outputs
effective0
-0.22247314453125
effective1
0
effective2
0
effective3
-0.22247314453125

pre_stage_2_stats: Save the actual PRE state and its diagnostic status

diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W

Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base.

Saved inputs
task
0
stage
2
requestedUpdates
2
weight0
0.2880859375
weight1
0
weight2
0
weight3
0.2880859375
trainHalfMSE
0.15838176012039185
validationHalfMSE
0.07919088006019592
Saved outputs
trainHalfMSE
0.15838176012039185
validationHalfMSE
0.07919088006019592
diagnosticOnly
1
hasNextUpdate
0
ADAPT: every actual materialized state and its losses
Task / stage / next actionW00W01W10W11Training meanHeld-out mean
adapt 0 / then update0.2880859375000.28808593750.236506760120391850.11825338006019592
adapt 1 / final diagnostic only0.3993225097656250-0.0781250.28808593750.20243962426320650.10121981213160325
Both complete factor histories, including the final diagnostic state
ADAPT: all saved A and B coordinates by stage
Stage / factor coordinateSaved factor word
0 / A[0,0]1
0 / A[0,1]0
0 / B[0,0]0
0 / B[1,0]0
1 / A[0,0]1
1 / A[0,1]0
1 / B[0,0]0.111236572265625
1 / B[1,0]-0.078125

U=1: all requested transitions are retained, even if factors do not move. A positive η may underflow or round a proposal back to its old word; no strict loss decrease is guaranteed. Initially B=0 makes G_A=0, but nonzero identity-row A permits B to move. A can receive nonzero gradients later. The last evaluated gradients are diagnostic only.

Inspecting ADAPT stage 0, sample train0, A[0,0]. Local inspection only reads the saved root and preserves raw inputs, trace cursor and graded answers.

Selected trace: setup. Matching saved operations are marked current. Trace navigation and local inspection are independent.

Stage 0: materialize all four effective coordinates first

adapt_stage_0: both actual factors and their gradients
Factor coordinateOld saved wordSame-state gradient
A[0,0]10
A[0,1]00
B[0,0]0-0.22247314453125
B[1,0]00.15625
adapt_stage_0: every BA product and ordered partial sum
W coordinate / rank termOld B[o,k]Old A[k,i]ProductOld sumNew sum
W00 / k=001000
W01 / k=000000
W10 / k=001000
W11 / k=000000
adapt_stage_0: completed BA, scaled change and base addition
CoordinateFrozen baseBA contractionc=α/rdeltaW=c×BAW_eff=W0+deltaW
W000.28808593750100.2880859375
W0100100
W1000100
W110.28808593750100.2880859375

Every BA accumulator starts at floating +0, takes separate products and additions in increasing rank order, then multiplies by c once. W_eff is materialized before calling the unchanged ADAPT readout. The algebraically equivalent W0φ+cB(Aφ) can round differently and is not substituted here.

All four materialization operations and once-per-evaluation scale result

adapt_stage_0_materialize_0: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
0
output
0
feature
0
rank
1
alpha
1
scale
1
base
0.2880859375
initialSum
0
b0
0
a0
1
Saved outputs
scale
1
product0
0
sum0
0
product
0
delta
0
weight
0.2880859375

adapt_stage_0_materialize_1: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
1
output
0
feature
1
rank
1
alpha
1
scale
1
base
0
initialSum
0
b0
0
a0
0
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0

adapt_stage_0_materialize_2: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
2
output
1
feature
0
rank
1
alpha
1
scale
1
base
0
initialSum
0
b0
0
a0
1
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0

adapt_stage_0_materialize_3: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
3
output
1
feature
1
rank
1
alpha
1
scale
1
base
0.2880859375
initialSum
0
b0
0
a0
0
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0.2880859375

The actual materialized readout: all eight samples and both means

adapt_stage_0_readout: all eight samples, targets, predictions and losses
Sample / rolexphiPlusphiMinuspreTarget0preTarget1adaptTarget0adaptTarget1Prediction 0Prediction 1Sample loss
train0 / training-101010.5100.28808593750.37841081619262695
train1 / training-0.500.500.50.250.500.144042968750.09460270404815674
train2 / training0.50.500.500.5-0.250.1440429687500.09460270404815674
train3 / training110101-0.50.288085937500.37841081619262695
validation0 / held out-0.7500.7500.750.3750.7500.2160644531250.21285608410835266
validation1 / held out-0.2500.2500.250.1250.2500.0720214843750.023650676012039185
validation2 / held out0.250.2500.2500.25-0.1250.07202148437500.023650676012039185
validation3 / held out0.750.7500.7500.75-0.3750.21606445312500.21285608410835266
All eight forwards and two-output losses
adapt_stage_0_readout: four products and two output sums per sample
Sampleproduct00product01product10product11prediction0prediction1
train00000.288085937500.2880859375
train10000.1440429687500.14404296875
train20.144042968750000.144042968750
train30.28808593750000.28808593750
validation00000.21606445312500.216064453125
validation10000.07202148437500.072021484375
validation20.0720214843750000.0720214843750
validation30.2160644531250000.2160644531250
adapt_stage_0_readout: targets, errors, squares, halves and sample sums
Sampletarget0target1error0error1square0square1half0half1sampleLoss
train00.51-0.5-0.71191406250.250.50682163238525390.1250.253410816192626950.37841081619262695
train10.250.5-0.25-0.355957031250.06250.126705408096313480.031250.063352704048156740.09460270404815674
train20.5-0.25-0.355957031250.250.126705408096313480.06250.063352704048156740.031250.09460270404815674
train31-0.5-0.71191406250.50.50682163238525390.250.253410816192626950.1250.37841081619262695
validation00.3750.75-0.375-0.5339355468750.1406250.28508716821670530.07031250.142543584108352660.21285608410835266
validation10.1250.25-0.125-0.1779785156250.0156250.031676352024078370.00781250.0158381760120391850.023650676012039185
validation20.25-0.125-0.1779785156250.1250.031676352024078370.0156250.0158381760120391850.00781250.023650676012039185
validation30.75-0.375-0.5339355468750.3750.28508716821670530.1406250.142543584108352660.07031250.21285608410835266
adapt_stage_0_readout: both ordered four-sample loss reductions
Dataset / rowlossoldSumsum
training / 00.3784108161926269500.37841081619262695
training / 10.094602704048156740.378410816192626950.4730135202407837
training / 20.094602704048156740.47301352024078370.5676162242889404
training / 30.378410816192626950.56761622428894040.9460270404815674
validation / 00.2128560841083526600.21285608410835266
validation / 10.0236506760120391850.212856084108352660.23650676012039185
validation / 20.0236506760120391850.236506760120391850.26015743613243103
validation / 30.212856084108352660.260157436132431030.4730135202407837

Training mean=0.23650676012039185; held-out mean=0.11825338006019592. Each reduction starts at +0 and divides its own final sum by 4. Each sample loss first sums two output half-losses; the denominator is four samples, not eight scalar outputs.

adapt_stage_0_readout: actual readout weights, gradients and mask
CoordinateSaved WMathematical G_WEffective gradientMask (VALUE)
W000.2880859375-0.22247314453125-0.222473144531251
W010-0.15625-0.156251
W1000.156250.156251
W110.2880859375-0.22247314453125-0.222473144531251
All sixteen training gradient contributions, including old partial sums
adapt_stage_0_readout: G_W training contractions
Coordinate / training rowerrorfeaturecontributionoldSumsum
W00 / train0-0.50-000
W00 / train1-0.250-000
W00 / train2-0.355957031250.5-0.1779785156250-0.177978515625
W00 / train3-0.71191406251-0.7119140625-0.177978515625-0.889892578125
W01 / train0-0.51-0.50-0.5
W01 / train1-0.250.5-0.125-0.5-0.625
W01 / train2-0.355957031250-0-0.625-0.625
W01 / train3-0.71191406250-0-0.625-0.625
W10 / train0-0.71191406250-000
W10 / train1-0.355957031250-000
W10 / train20.250.50.12500.125
W10 / train30.510.50.1250.625
W11 / train0-0.71191406251-0.71191406250-0.7119140625
W11 / train1-0.355957031250.5-0.177978515625-0.7119140625-0.889892578125
W11 / train20.2500-0.889892578125-0.889892578125
W11 / train30.500-0.889892578125-0.889892578125

adapt_stage_0_readout_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
-0.5
feature0
0
error1
-0.25
feature1
0
error2
-0.35595703125
feature2
0.5
error3
-0.7119140625
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
-0.177978515625
sum2
-0.177978515625
contribution3
-0.7119140625
sum3
-0.889892578125
mathematical
-0.22247314453125

adapt_stage_0_readout_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
-0.5
feature0
1
error1
-0.25
feature1
0.5
error2
-0.35595703125
feature2
0
error3
-0.7119140625
feature3
0
Saved outputs
contribution0
-0.5
sum0
-0.5
contribution1
-0.125
sum1
-0.625
contribution2
-0
sum2
-0.625
contribution3
-0
sum3
-0.625
mathematical
-0.15625

adapt_stage_0_readout_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.7119140625
feature0
0
error1
-0.35595703125
feature1
0
error2
0.25
feature2
0.5
error3
0.5
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0.125
sum2
0.125
contribution3
0.5
sum3
0.625
mathematical
0.15625

adapt_stage_0_readout_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.7119140625
feature0
1
error1
-0.35595703125
feature1
0.5
error2
0.25
feature2
0
error3
0.5
feature3
0
Saved outputs
contribution0
-0.7119140625
sum0
-0.7119140625
contribution1
-0.177978515625
sum1
-0.889892578125
contribution2
0
sum2
-0.889892578125
contribution3
0
sum3
-0.889892578125
mathematical
-0.22247314453125
Selected sample, both means and mask: complete saved operands

data_0: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
0
training
1
x
-1
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
1
phiPlus
0
phiMinus
1
preTarget0
0
preTarget1
1
scaledMinus
0.5
adaptTarget0
0.5
scaledPlus
-0
adaptTarget1
1

adapt_stage_0_readout_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.2880859375
prediction0
0
prediction1
0.2880859375

adapt_stage_0_readout_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
1
prediction0
0
prediction1
0.2880859375
target0
0.5
target1
1
divisor
2
Saved outputs
error0
-0.5
error1
-0.7119140625
square0
0.25
square1
0.5068216323852539
half0
0.125
half1
0.25341081619262695
sampleLoss
0.37841081619262695

adapt_stage_0_readout_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.37841081619262695
loss1
0.09460270404815674
loss2
0.09460270404815674
loss3
0.37841081619262695
Saved outputs
sum0
0.37841081619262695
sum1
0.4730135202407837
sum2
0.5676162242889404
sum3
0.9460270404815674
mean
0.23650676012039185

adapt_stage_0_readout_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.21285608410835266
loss1
0.023650676012039185
loss2
0.023650676012039185
loss3
0.21285608410835266
Saved outputs
sum0
0.21285608410835266
sum1
0.23650676012039185
sum2
0.26015743613243103
sum3
0.4730135202407837
mean
0.11825338006019592

adapt_stage_0_readout_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.22247314453125
enabled0
1
mathematical1
-0.15625
enabled1
1
mathematical2
0.15625
enabled2
1
mathematical3
-0.22247314453125
enabled3
1
Saved outputs
effective0
-0.22247314453125
effective1
-0.15625
effective2
0.15625
effective3
-0.22247314453125

The nested readout retains weights, predictions, training mean, validation mean, mathematical gradient, effective gradient, mask and all ten tensors. Its all-one mask describes the readout derivative G_W; it grants no permission to optimize W0. Only four training rows contribute to G_W. Targets for ADAPT are Tφ with T=[[1,0.5],[−0.5,1]].

Chain rule at the same old factors

G_W is the derivative of the training mean with respect to an effective weight. Changing A[k,i] reaches output o through old B[o,k], so G_A=c(BᵀG_W). Changing B[o,k] reaches feature i through old A[k,i], so G_B=c(G_WAᵀ). These rounded calculations approximate derivatives of the corresponding real expression using saved values; they are not derivatives of rounding. Both two-term contractions finish before scaling; neither uses a proposed factor.

adapt_stage_0: selected A[0,0] two-term contraction
Contraction termOld B[o,k]G_W[o,i]ProductOld sumNew sum
Output 00-0.22247314453125-000
Output 100.15625000

Completed contraction=0; multiply AFTER both terms by c=1 to get A[0,0] gradient=0.

Every A and B chain-rule operation, with both old-factor products

adapt_stage_0_gradientA_0: Apply the chain rule to one A coordinate

term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction

Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero.

Saved inputs
coordinate
0
k
0
feature
0
scale
1
initialSum
0
b0
0
g0
-0.22247314453125
b1
0
g1
0.15625
Saved outputs
product0
-0
sum0
0
product1
0
sum1
0
contraction
0
gradient
0

adapt_stage_0_gradientA_1: Apply the chain rule to one A coordinate

term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction

Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero.

Saved inputs
coordinate
1
k
0
feature
1
scale
1
initialSum
0
b0
0
g0
-0.15625
b1
0
g1
-0.22247314453125
Saved outputs
product0
-0
sum0
0
product1
-0
sum1
0
contraction
0
gradient
0

adapt_stage_0_gradientB_0: Apply the chain rule to one B coordinate

term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction

Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero.

Saved inputs
coordinate
0
output
0
k
0
scale
1
initialSum
0
g0
-0.22247314453125
a0
1
g1
-0.15625
a1
0
Saved outputs
product0
-0.22247314453125
sum0
-0.22247314453125
product1
-0
sum1
-0.22247314453125
contraction
-0.22247314453125
gradient
-0.22247314453125

adapt_stage_0_gradientB_1: Apply the chain rule to one B coordinate

term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction

Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero.

Saved inputs
coordinate
1
output
1
k
0
scale
1
initialSum
0
g0
0.15625
a0
1
g1
-0.22247314453125
a1
0
Saved outputs
product0
0.15625
sum0
0.15625
product1
-0
sum1
0.15625
contraction
0.15625
gradient
0.15625
ADAPT update 1: all A proposals from the same old pair
Factor coordinateoldgradientdeltaproposedcommitted
A[0,0]10011
A[0,1]00000
ADAPT update 1: all B proposals from the same old pair
Factor coordinateoldgradientdeltaproposedcommitted
B[0,0]0-0.22247314453125-0.1112365722656250.1112365722656250.111236572265625
B[1,0]00.156250.078125-0.078125-0.078125

η=0.5. First compute delta=η×gradient and proposed=old−delta for every A coordinate and every B coordinate using the same old evaluation. The committed column copies the proposal published in one simultaneous pair commit after both arrays are complete. No B gradient reads an A proposal. The next stage rematerializes and evaluates the committed pair.

Every factor proposal and the single simultaneous pair commit

adapt_update_1_A_0: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
0
coordinate
0
old
1
gradient
0
eta
0.5
Saved outputs
delta
0
proposed
1
committed
1

adapt_update_1_A_1: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
0
coordinate
1
old
0
gradient
0
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

adapt_update_1_B_0: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
1
coordinate
0
old
0
gradient
-0.22247314453125
eta
0.5
Saved outputs
delta
-0.111236572265625
proposed
0.111236572265625
committed
0.111236572265625

adapt_update_1_B_1: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
1
coordinate
1
old
0
gradient
0.15625
eta
0.5
Saved outputs
delta
0.078125
proposed
-0.078125
committed
-0.078125

adapt_update_1_commit: Publish both complete factor proposals together

nextA=[all proposed A coordinates]; nextB=[all proposed B coordinates]; publish the pair simultaneously

One optimizer step commits this pair. Neither gradient used an updated factor. The next stage rematerializes the effective matrix and performs a complete new evaluation. The final requested stage has diagnostics and no additional commit.

Saved inputs
oldA0
1
oldA1
0
oldB0
0
oldB1
0
Saved outputs
A0
1
A1
0
B0
0.111236572265625
B1
-0.078125
Exact factor initialization and selected stage boundary

adapt_initial: Copy the actual PRE2 base and initialize both factors

base=copy(final evaluated PRE weights); A=initialization0?first r identity rows:positive zeros; B=positive zeros

The four base entries are copied exactly and stay frozen for every adapter stage. Initialization chooses actual factor words and shapes. Identity-row A permits B to learn immediately; both-zero factors stall through the real bilinear chain rule.

Saved inputs
rank
1
alpha
1
initialization
0
scale
1
base0
0.2880859375
base1
0
base2
0
base3
0.2880859375
Saved outputs
base0
0.2880859375
base1
0
base2
0
base3
0.2880859375
A0
1
A1
0
B0
0
B1
0

adapt_stage_0_stats: Save one complete adapter state and whether another step follows

diagnosticOnly=(stage==requestedUpdates); hasNextUpdate=(stage<requestedUpdates); losses and both gradients belong to the saved factor pair

Only actual evaluated states enter the trajectory. Stage zero already has a materialized matrix, eight forwards, two losses and both factor gradients. Final-stage gradients are diagnostic only. Even a stalled or zero-rate run retains all requested arithmetic and states.

Saved inputs
stage
0
requestedUpdates
1
rank
1
alpha
1
initialization
0
eta
0.5
scale
1
trainHalfMSE
0.23650676012039185
validationHalfMSE
0.11825338006019592
Saved outputs
trainHalfMSE
0.23650676012039185
validationHalfMSE
0.11825338006019592
diagnosticOnly
0
hasNextUpdate
1

Counts and limits belong beside the losses

Whole current root: final losses, parameters, work and record counts
Saved summary keyActual value
adaptValidationLoss0.10121981213160325
adaptTrainLoss0.2024396242632065
adapterTrainableParameters4
structuralRankBound1
rank1
alpha1
initialization0
updates1
eta0.5
scale1
fullFineTuneParameters4
frozenBaseParameters4
storedBaseAndFactors8
fixedFeatures2
outputsPerSample2
trainSamples4
validationSamples4
preUpdates2
preEta0.5
pretrainingTrainLoss0.15838176012039185
pretrainingValidationLoss0.07919088006019592
adaptInitialTrainLoss0.23650676012039185
adaptInitialValidationLoss0.11825338006019592
baseWeight00.2880859375
baseWeight10
baseWeight20
baseWeight30.2880859375
adaptWeight00.399322509765625
adaptWeight10
adaptWeight2-0.078125
adaptWeight30.2880859375
featureMaps8
featureNegations8
featureMaxSelections16
preTargetCopies16
adaptTargetScalings16
adaptTargetAdditions16
preparedWeightCopies4
pretrainingStages3
adapterStages2
stageCount5
forwardSampleEvaluations40
forwardProducts160
forwardSums80
readoutGradientBatches5
readoutGradientContractions20
gradientRowContributions20
readoutGradientProducts80
readoutGradientAdditions80
readoutGradientDivisions20
preOptimizerBatches2
preCoordinateUpdates8
adapterEvaluations2
scaleDivisions3
materializationProducts8
materializationAdditions8
materializationScalings8
baseAdditions8
factorGradientContractions8
factorGradientProducts16
factorGradientAdditions16
factorGradientScalings8
adapterOptimizerBatches1
factorCoordinateUpdates4
factorUpdateProducts4
factorUpdateSubtractions4
finalDiagnosticBatches2
lossSampleEvaluations40
lossComponentErrors80
lossSquares80
lossHalfDivisions80
lossOutputSums40
orderedLossAdditions40
datasetMeanDivisions10
frames163
tensorCount92

Rank1 trains 4 coordinates, equal to full tuning’s 4; rank2 trains 8, more. The four frozen base coordinates remain stored, alongside extra materializations, gradients and trace. Three PRE states plus U+1 adapter states give U+4 readout evaluations, each with eight forwards and final diagnostic gradients. Counts describe source operations, not measured speed, memory or quality.

Changing rank at fixed α changes c=α/r and the available directions. With identity-row A and zero B, the first effective step contains c². At rank2, α=1 gives one quarter of the first step at α=2. Holding α=r controls c=1 but does not prove a rank-quality ordering.

structuralRankBound=1 bounds only the EXACT-REAL factorized expression cBA at stored factors. It is not the exact algebraic rank of separately rounded BA, deltaW or W_eff. No numerical rank or floating determinant certificate is computed.

Separate rounded-rank arithmetic counterexample and analytical large-matrix counts

Separate arithmetic limit, not a trajectory point: epsilon=2^-27, A=[1,1+epsilon], B=A^T and scale1 have exact-real rank1. Rounded BA stores bottom-right 1+2epsilon after losing epsilon squared. The exact determinant of those stored entries is -2^-54, while a naive rounded two-product determinant is positive zero. Neither a factor count nor that floating zero certifies rounded-matrix rank.

Separate analytical example only: a 4096 by 4096 readout has 16777216 full trainables; rank8 factors have 65536, a ratio of256. The frozen base still exists. These scalar counts are not measured bytes, memory, elapsed time, speed, quality or hardware evidence.

Held-out inputs merely change magnitudes on the same two feature rays. Their real Gram matrix is half the training one, so the real held-out mean is half the real training mean for any fixed readout. Both means are still evaluated independently in binary64. These two-output regression results establish no population generalization, language-model capability, safety or alignment claim.

A prior zero centered-difference budget is scoped ONLY to initial adapter stage0, initialization0, eta=positive0.5, h=2^-12, rank1/alpha1 or rank2/alpha1 or2, after whole central and complete endpoint binding. Every A and B coordinate participates. Initial A endpoint factor words differ while losses coincide because B stays zero; B endpoint losses differ. Rank1/alpha2, both-zero, other eta and later stages receive no exact finite-difference verdict here.

All displayed floating numbers are saved round-trip decimals; −0 is shown explicitly. Display precision never feeds computation. Rank, dimensions, counts, masks and status flags are integer VALUE roles; arithmetic operands and factor/base copies retain WORD roles even when numerically integral. No numerical experiment runs inside these inspection controls.

Complete saved operation text fallback: every record in trace order

setup: Freeze an actual prepared readout and learn additive factors

W_eff=W0+(alpha/r)*BA; A:[r,2]; B:[2,r]; trainable=4r; full=4; PRE updates=2 at eta0.5

First really prepare W0 from zero. Then optimize only the factors of an additive update. Editing any raw field restarts this complete declared experiment. The structural bound describes the exact-real factorization, while the saved effective matrix follows explicit binary64 operations.

Saved inputs
rank
1
alpha
1
initialization
0
updates
1
eta
0.5
Saved outputs
adapterTrainableParameters
4
fullFineTuneParameters
4
frozenBaseParameters
4
storedBaseAndFactors
8
structuralRankBound
1
scale
1
fixedFeatures
2
outputsPerSample
2
trainSamples
4
validationSamples
4
preUpdates
2
preEta
0.5

data_0: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
0
training
1
x
-1
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
1
phiPlus
0
phiMinus
1
preTarget0
0
preTarget1
1
scaledMinus
0.5
adaptTarget0
0.5
scaledPlus
-0
adaptTarget1
1

data_1: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
1
training
1
x
-0.5
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
0.5
phiPlus
0
phiMinus
0.5
preTarget0
0
preTarget1
0.5
scaledMinus
0.25
adaptTarget0
0.25
scaledPlus
-0
adaptTarget1
0.5

data_2: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
2
training
1
x
0.5
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
-0.5
phiPlus
0.5
phiMinus
0
preTarget0
0.5
preTarget1
0
scaledMinus
0
adaptTarget0
0.5
scaledPlus
-0.25
adaptTarget1
-0.25

data_3: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
3
training
1
x
1
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
-1
phiPlus
1
phiMinus
0
preTarget0
1
preTarget1
0
scaledMinus
0
adaptTarget0
1
scaledPlus
-0.5
adaptTarget1
-0.5

data_4: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
4
training
0
x
-0.75
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
0.75
phiPlus
0
phiMinus
0.75
preTarget0
0
preTarget1
0.75
scaledMinus
0.375
adaptTarget0
0.375
scaledPlus
-0
adaptTarget1
0.75

data_5: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
5
training
0
x
-0.25
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
0.25
phiPlus
0
phiMinus
0.25
preTarget0
0
preTarget1
0.25
scaledMinus
0.125
adaptTarget0
0.125
scaledPlus
-0
adaptTarget1
0.25

data_6: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
6
training
0
x
0.25
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
-0.25
phiPlus
0.25
phiMinus
0
preTarget0
0.25
preTarget1
0
scaledMinus
0
adaptTarget0
0.25
scaledPlus
-0.125
adaptTarget1
-0.125

data_7: Prepare the two fixed features and both target pairs

negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus

A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once.

Saved inputs
sample
7
training
0
x
0.75
positiveZero
0
positiveHalf
0.5
negativeHalf
-0.5
Saved outputs
negatedX
-0.75
phiPlus
0.75
phiMinus
0
preTarget0
0.75
preTarget1
0
scaledMinus
0
adaptTarget0
0.75
scaledPlus
-0.375
adaptTarget1
-0.375

pre_initial: Start actual PRE at positive-zero weights

weights=[+0,+0,+0,+0]

These authored zeros start the feature-copy target task. The next three evaluations and two full-coordinate transitions actually construct the frozen base; no prepared fraction is inserted.

Saved inputs
source0
0
source1
0
source2
0
source3
0
Saved outputs
weight0
0
weight1
0
weight2
0
weight3
0

pre_stage_0_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_1: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
1
x
-0.5
phiPlus
0
phiMinus
0.5
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_2: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
2
x
0.5
phiPlus
0.5
phiMinus
0
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_3: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
3
x
1
phiPlus
1
phiMinus
0
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_4: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
4
x
-0.75
phiPlus
0
phiMinus
0.75
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_5: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
5
x
-0.25
phiPlus
0
phiMinus
0.25
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_6: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
6
x
0.25
phiPlus
0.25
phiMinus
0
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_forward_7: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
7
x
0.75
phiPlus
0.75
phiMinus
0
w00
0
w01
0
w10
0
w11
0
Saved outputs
product00
0
product01
0
product10
0
product11
0
prediction0
0
prediction1
0

pre_stage_0_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
0
prediction0
0
prediction1
0
target0
0
target1
1
divisor
2
Saved outputs
error0
0
error1
-1
square0
0
square1
1
half0
0
half1
0.5
sampleLoss
0.5

pre_stage_0_loss_1: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
1
task
0
prediction0
0
prediction1
0
target0
0
target1
0.5
divisor
2
Saved outputs
error0
0
error1
-0.5
square0
0
square1
0.25
half0
0
half1
0.125
sampleLoss
0.125

pre_stage_0_loss_2: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
2
task
0
prediction0
0
prediction1
0
target0
0.5
target1
0
divisor
2
Saved outputs
error0
-0.5
error1
0
square0
0.25
square1
0
half0
0.125
half1
0
sampleLoss
0.125

pre_stage_0_loss_3: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
3
task
0
prediction0
0
prediction1
0
target0
1
target1
0
divisor
2
Saved outputs
error0
-1
error1
0
square0
1
square1
0
half0
0.5
half1
0
sampleLoss
0.5

pre_stage_0_loss_4: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
4
task
0
prediction0
0
prediction1
0
target0
0
target1
0.75
divisor
2
Saved outputs
error0
0
error1
-0.75
square0
0
square1
0.5625
half0
0
half1
0.28125
sampleLoss
0.28125

pre_stage_0_loss_5: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
5
task
0
prediction0
0
prediction1
0
target0
0
target1
0.25
divisor
2
Saved outputs
error0
0
error1
-0.25
square0
0
square1
0.0625
half0
0
half1
0.03125
sampleLoss
0.03125

pre_stage_0_loss_6: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
6
task
0
prediction0
0
prediction1
0
target0
0.25
target1
0
divisor
2
Saved outputs
error0
-0.25
error1
0
square0
0.0625
square1
0
half0
0.03125
half1
0
sampleLoss
0.03125

pre_stage_0_loss_7: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
7
task
0
prediction0
0
prediction1
0
target0
0.75
target1
0
divisor
2
Saved outputs
error0
-0.75
error1
0
square0
0.5625
square1
0
half0
0.28125
half1
0
sampleLoss
0.28125

pre_stage_0_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
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

pre_stage_0_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
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

pre_stage_0_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
0
feature0
0
error1
0
feature1
0
error2
-0.5
feature2
0.5
error3
-1
feature3
1
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0.25
sum2
-0.25
contribution3
-1
sum3
-1.25
mathematical
-0.3125

pre_stage_0_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
0
feature0
1
error1
0
feature1
0.5
error2
-0.5
feature2
0
error3
-1
feature3
0
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0
sum2
0
contribution3
-0
sum3
0
mathematical
0

pre_stage_0_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-1
feature0
0
error1
-0.5
feature1
0
error2
0
feature2
0.5
error3
0
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0
sum2
0
contribution3
0
sum3
0
mathematical
0

pre_stage_0_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-1
feature0
1
error1
-0.5
feature1
0.5
error2
0
feature2
0
error3
0
feature3
0
Saved outputs
contribution0
-1
sum0
-1
contribution1
-0.25
sum1
-1.25
contribution2
0
sum2
-1.25
contribution3
0
sum3
-1.25
mathematical
-0.3125

pre_stage_0_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.3125
enabled0
1
mathematical1
0
enabled1
1
mathematical2
0
enabled2
1
mathematical3
-0.3125
enabled3
1
Saved outputs
effective0
-0.3125
effective1
0
effective2
0
effective3
-0.3125

pre_stage_0_stats: Save the actual PRE state and its diagnostic status

diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W

Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base.

Saved inputs
task
0
stage
0
requestedUpdates
2
weight0
0
weight1
0
weight2
0
weight3
0
trainHalfMSE
0.3125
validationHalfMSE
0.15625
Saved outputs
trainHalfMSE
0.3125
validationHalfMSE
0.15625
diagnosticOnly
0
hasNextUpdate
1

pre_update_1_coordinate_0: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
0
old
0
mathematical
-0.3125
effective
-0.3125
enabled
1
eta
0.5
Saved outputs
delta
-0.15625
proposed
0.15625
committed
0.15625

pre_update_1_coordinate_1: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
1
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_1_coordinate_2: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
2
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_1_coordinate_3: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
3
old
0
mathematical
-0.3125
effective
-0.3125
enabled
1
eta
0.5
Saved outputs
delta
-0.15625
proposed
0.15625
committed
0.15625

pre_update_1_commit: Publish all four proposed coordinates together

nextWeights=[committed0,committed1,committed2,committed3]

This simultaneous publication completes one optimizer step. No coordinate update changes a gradient used for another coordinate. A later stage evaluates the resulting weights again; its final diagnostic gradient causes no additional step.

Saved inputs
old0
0
old1
0
old2
0
old3
0
Saved outputs
weight0
0.15625
weight1
0
weight2
0
weight3
0.15625

pre_stage_1_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0
product01
0
product10
0
product11
0.15625
prediction0
0
prediction1
0.15625

pre_stage_1_forward_1: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
1
x
-0.5
phiPlus
0
phiMinus
0.5
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0
product01
0
product10
0
product11
0.078125
prediction0
0
prediction1
0.078125

pre_stage_1_forward_2: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
2
x
0.5
phiPlus
0.5
phiMinus
0
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0.078125
product01
0
product10
0
product11
0
prediction0
0.078125
prediction1
0

pre_stage_1_forward_3: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
3
x
1
phiPlus
1
phiMinus
0
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0.15625
product01
0
product10
0
product11
0
prediction0
0.15625
prediction1
0

pre_stage_1_forward_4: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
4
x
-0.75
phiPlus
0
phiMinus
0.75
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0
product01
0
product10
0
product11
0.1171875
prediction0
0
prediction1
0.1171875

pre_stage_1_forward_5: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
5
x
-0.25
phiPlus
0
phiMinus
0.25
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0
product01
0
product10
0
product11
0.0390625
prediction0
0
prediction1
0.0390625

pre_stage_1_forward_6: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
6
x
0.25
phiPlus
0.25
phiMinus
0
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0.0390625
product01
0
product10
0
product11
0
prediction0
0.0390625
prediction1
0

pre_stage_1_forward_7: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
7
x
0.75
phiPlus
0.75
phiMinus
0
w00
0.15625
w01
0
w10
0
w11
0.15625
Saved outputs
product00
0.1171875
product01
0
product10
0
product11
0
prediction0
0.1171875
prediction1
0

pre_stage_1_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
0
prediction0
0
prediction1
0.15625
target0
0
target1
1
divisor
2
Saved outputs
error0
0
error1
-0.84375
square0
0
square1
0.7119140625
half0
0
half1
0.35595703125
sampleLoss
0.35595703125

pre_stage_1_loss_1: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
1
task
0
prediction0
0
prediction1
0.078125
target0
0
target1
0.5
divisor
2
Saved outputs
error0
0
error1
-0.421875
square0
0
square1
0.177978515625
half0
0
half1
0.0889892578125
sampleLoss
0.0889892578125

pre_stage_1_loss_2: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
2
task
0
prediction0
0.078125
prediction1
0
target0
0.5
target1
0
divisor
2
Saved outputs
error0
-0.421875
error1
0
square0
0.177978515625
square1
0
half0
0.0889892578125
half1
0
sampleLoss
0.0889892578125

pre_stage_1_loss_3: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
3
task
0
prediction0
0.15625
prediction1
0
target0
1
target1
0
divisor
2
Saved outputs
error0
-0.84375
error1
0
square0
0.7119140625
square1
0
half0
0.35595703125
half1
0
sampleLoss
0.35595703125

pre_stage_1_loss_4: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
4
task
0
prediction0
0
prediction1
0.1171875
target0
0
target1
0.75
divisor
2
Saved outputs
error0
0
error1
-0.6328125
square0
0
square1
0.40045166015625
half0
0
half1
0.200225830078125
sampleLoss
0.200225830078125

pre_stage_1_loss_5: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
5
task
0
prediction0
0
prediction1
0.0390625
target0
0
target1
0.25
divisor
2
Saved outputs
error0
0
error1
-0.2109375
square0
0
square1
0.04449462890625
half0
0
half1
0.022247314453125
sampleLoss
0.022247314453125

pre_stage_1_loss_6: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
6
task
0
prediction0
0.0390625
prediction1
0
target0
0.25
target1
0
divisor
2
Saved outputs
error0
-0.2109375
error1
0
square0
0.04449462890625
square1
0
half0
0.022247314453125
half1
0
sampleLoss
0.022247314453125

pre_stage_1_loss_7: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
7
task
0
prediction0
0.1171875
prediction1
0
target0
0.75
target1
0
divisor
2
Saved outputs
error0
-0.6328125
error1
0
square0
0.40045166015625
square1
0
half0
0.200225830078125
half1
0
sampleLoss
0.200225830078125

pre_stage_1_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.35595703125
loss1
0.0889892578125
loss2
0.0889892578125
loss3
0.35595703125
Saved outputs
sum0
0.35595703125
sum1
0.4449462890625
sum2
0.533935546875
sum3
0.889892578125
mean
0.22247314453125

pre_stage_1_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.200225830078125
loss1
0.022247314453125
loss2
0.022247314453125
loss3
0.200225830078125
Saved outputs
sum0
0.200225830078125
sum1
0.22247314453125
sum2
0.244720458984375
sum3
0.4449462890625
mean
0.111236572265625

pre_stage_1_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
0
feature0
0
error1
0
feature1
0
error2
-0.421875
feature2
0.5
error3
-0.84375
feature3
1
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0.2109375
sum2
-0.2109375
contribution3
-0.84375
sum3
-1.0546875
mathematical
-0.263671875

pre_stage_1_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
0
feature0
1
error1
0
feature1
0.5
error2
-0.421875
feature2
0
error3
-0.84375
feature3
0
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0
sum2
0
contribution3
-0
sum3
0
mathematical
0

pre_stage_1_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.84375
feature0
0
error1
-0.421875
feature1
0
error2
0
feature2
0.5
error3
0
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0
sum2
0
contribution3
0
sum3
0
mathematical
0

pre_stage_1_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.84375
feature0
1
error1
-0.421875
feature1
0.5
error2
0
feature2
0
error3
0
feature3
0
Saved outputs
contribution0
-0.84375
sum0
-0.84375
contribution1
-0.2109375
sum1
-1.0546875
contribution2
0
sum2
-1.0546875
contribution3
0
sum3
-1.0546875
mathematical
-0.263671875

pre_stage_1_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.263671875
enabled0
1
mathematical1
0
enabled1
1
mathematical2
0
enabled2
1
mathematical3
-0.263671875
enabled3
1
Saved outputs
effective0
-0.263671875
effective1
0
effective2
0
effective3
-0.263671875

pre_stage_1_stats: Save the actual PRE state and its diagnostic status

diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W

Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base.

Saved inputs
task
0
stage
1
requestedUpdates
2
weight0
0.15625
weight1
0
weight2
0
weight3
0.15625
trainHalfMSE
0.22247314453125
validationHalfMSE
0.111236572265625
Saved outputs
trainHalfMSE
0.22247314453125
validationHalfMSE
0.111236572265625
diagnosticOnly
0
hasNextUpdate
1

pre_update_2_coordinate_0: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
0
old
0.15625
mathematical
-0.263671875
effective
-0.263671875
enabled
1
eta
0.5
Saved outputs
delta
-0.1318359375
proposed
0.2880859375
committed
0.2880859375

pre_update_2_coordinate_1: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
1
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_2_coordinate_2: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
2
old
0
mathematical
0
effective
0
enabled
1
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

pre_update_2_coordinate_3: Propose one weight change from the same old state

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

Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients.

Saved inputs
coordinate
3
old
0.15625
mathematical
-0.263671875
effective
-0.263671875
enabled
1
eta
0.5
Saved outputs
delta
-0.1318359375
proposed
0.2880859375
committed
0.2880859375

pre_update_2_commit: Publish all four proposed coordinates together

nextWeights=[committed0,committed1,committed2,committed3]

This simultaneous publication completes one optimizer step. No coordinate update changes a gradient used for another coordinate. A later stage evaluates the resulting weights again; its final diagnostic gradient causes no additional step.

Saved inputs
old0
0.15625
old1
0
old2
0
old3
0.15625
Saved outputs
weight0
0.2880859375
weight1
0
weight2
0
weight3
0.2880859375

pre_stage_2_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.2880859375
prediction0
0
prediction1
0.2880859375

pre_stage_2_forward_1: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
1
x
-0.5
phiPlus
0
phiMinus
0.5
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.14404296875
prediction0
0
prediction1
0.14404296875

pre_stage_2_forward_2: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
2
x
0.5
phiPlus
0.5
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.14404296875
product01
0
product10
0
product11
0
prediction0
0.14404296875
prediction1
0

pre_stage_2_forward_3: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
3
x
1
phiPlus
1
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.2880859375
product01
0
product10
0
product11
0
prediction0
0.2880859375
prediction1
0

pre_stage_2_forward_4: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
4
x
-0.75
phiPlus
0
phiMinus
0.75
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.216064453125
prediction0
0
prediction1
0.216064453125

pre_stage_2_forward_5: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
5
x
-0.25
phiPlus
0
phiMinus
0.25
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.072021484375
prediction0
0
prediction1
0.072021484375

pre_stage_2_forward_6: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
6
x
0.25
phiPlus
0.25
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.072021484375
product01
0
product10
0
product11
0
prediction0
0.072021484375
prediction1
0

pre_stage_2_forward_7: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
7
x
0.75
phiPlus
0.75
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.216064453125
product01
0
product10
0
product11
0
prediction0
0.216064453125
prediction1
0

pre_stage_2_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
0
prediction0
0
prediction1
0.2880859375
target0
0
target1
1
divisor
2
Saved outputs
error0
0
error1
-0.7119140625
square0
0
square1
0.5068216323852539
half0
0
half1
0.25341081619262695
sampleLoss
0.25341081619262695

pre_stage_2_loss_1: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
1
task
0
prediction0
0
prediction1
0.14404296875
target0
0
target1
0.5
divisor
2
Saved outputs
error0
0
error1
-0.35595703125
square0
0
square1
0.12670540809631348
half0
0
half1
0.06335270404815674
sampleLoss
0.06335270404815674

pre_stage_2_loss_2: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
2
task
0
prediction0
0.14404296875
prediction1
0
target0
0.5
target1
0
divisor
2
Saved outputs
error0
-0.35595703125
error1
0
square0
0.12670540809631348
square1
0
half0
0.06335270404815674
half1
0
sampleLoss
0.06335270404815674

pre_stage_2_loss_3: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
3
task
0
prediction0
0.2880859375
prediction1
0
target0
1
target1
0
divisor
2
Saved outputs
error0
-0.7119140625
error1
0
square0
0.5068216323852539
square1
0
half0
0.25341081619262695
half1
0
sampleLoss
0.25341081619262695

pre_stage_2_loss_4: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
4
task
0
prediction0
0
prediction1
0.216064453125
target0
0
target1
0.75
divisor
2
Saved outputs
error0
0
error1
-0.533935546875
square0
0
square1
0.2850871682167053
half0
0
half1
0.14254358410835266
sampleLoss
0.14254358410835266

pre_stage_2_loss_5: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
5
task
0
prediction0
0
prediction1
0.072021484375
target0
0
target1
0.25
divisor
2
Saved outputs
error0
0
error1
-0.177978515625
square0
0
square1
0.03167635202407837
half0
0
half1
0.015838176012039185
sampleLoss
0.015838176012039185

pre_stage_2_loss_6: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
6
task
0
prediction0
0.072021484375
prediction1
0
target0
0.25
target1
0
divisor
2
Saved outputs
error0
-0.177978515625
error1
0
square0
0.03167635202407837
square1
0
half0
0.015838176012039185
half1
0
sampleLoss
0.015838176012039185

pre_stage_2_loss_7: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
7
task
0
prediction0
0.216064453125
prediction1
0
target0
0.75
target1
0
divisor
2
Saved outputs
error0
-0.533935546875
error1
0
square0
0.2850871682167053
square1
0
half0
0.14254358410835266
half1
0
sampleLoss
0.14254358410835266

pre_stage_2_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.25341081619262695
loss1
0.06335270404815674
loss2
0.06335270404815674
loss3
0.25341081619262695
Saved outputs
sum0
0.25341081619262695
sum1
0.3167635202407837
sum2
0.38011622428894043
sum3
0.6335270404815674
mean
0.15838176012039185

pre_stage_2_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.14254358410835266
loss1
0.015838176012039185
loss2
0.015838176012039185
loss3
0.14254358410835266
Saved outputs
sum0
0.14254358410835266
sum1
0.15838176012039185
sum2
0.17421993613243103
sum3
0.3167635202407837
mean
0.07919088006019592

pre_stage_2_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
0
feature0
0
error1
0
feature1
0
error2
-0.35595703125
feature2
0.5
error3
-0.7119140625
feature3
1
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0.177978515625
sum2
-0.177978515625
contribution3
-0.7119140625
sum3
-0.889892578125
mathematical
-0.22247314453125

pre_stage_2_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
0
feature0
1
error1
0
feature1
0.5
error2
-0.35595703125
feature2
0
error3
-0.7119140625
feature3
0
Saved outputs
contribution0
0
sum0
0
contribution1
0
sum1
0
contribution2
-0
sum2
0
contribution3
-0
sum3
0
mathematical
0

pre_stage_2_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.7119140625
feature0
0
error1
-0.35595703125
feature1
0
error2
0
feature2
0.5
error3
0
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0
sum2
0
contribution3
0
sum3
0
mathematical
0

pre_stage_2_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.7119140625
feature0
1
error1
-0.35595703125
feature1
0.5
error2
0
feature2
0
error3
0
feature3
0
Saved outputs
contribution0
-0.7119140625
sum0
-0.7119140625
contribution1
-0.177978515625
sum1
-0.889892578125
contribution2
0
sum2
-0.889892578125
contribution3
0
sum3
-0.889892578125
mathematical
-0.22247314453125

pre_stage_2_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.22247314453125
enabled0
1
mathematical1
0
enabled1
1
mathematical2
0
enabled2
1
mathematical3
-0.22247314453125
enabled3
1
Saved outputs
effective0
-0.22247314453125
effective1
0
effective2
0
effective3
-0.22247314453125

pre_stage_2_stats: Save the actual PRE state and its diagnostic status

diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W

Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base.

Saved inputs
task
0
stage
2
requestedUpdates
2
weight0
0.2880859375
weight1
0
weight2
0
weight3
0.2880859375
trainHalfMSE
0.15838176012039185
validationHalfMSE
0.07919088006019592
Saved outputs
trainHalfMSE
0.15838176012039185
validationHalfMSE
0.07919088006019592
diagnosticOnly
1
hasNextUpdate
0

adapt_initial: Copy the actual PRE2 base and initialize both factors

base=copy(final evaluated PRE weights); A=initialization0?first r identity rows:positive zeros; B=positive zeros

The four base entries are copied exactly and stay frozen for every adapter stage. Initialization chooses actual factor words and shapes. Identity-row A permits B to learn immediately; both-zero factors stall through the real bilinear chain rule.

Saved inputs
rank
1
alpha
1
initialization
0
scale
1
base0
0.2880859375
base1
0
base2
0
base3
0.2880859375
Saved outputs
base0
0.2880859375
base1
0
base2
0
base3
0.2880859375
A0
1
A1
0
B0
0
B1
0

adapt_stage_0_materialize_0: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
0
output
0
feature
0
rank
1
alpha
1
scale
1
base
0.2880859375
initialSum
0
b0
0
a0
1
Saved outputs
scale
1
product0
0
sum0
0
product
0
delta
0
weight
0.2880859375

adapt_stage_0_materialize_1: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
1
output
0
feature
1
rank
1
alpha
1
scale
1
base
0
initialSum
0
b0
0
a0
0
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0

adapt_stage_0_materialize_2: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
2
output
1
feature
0
rank
1
alpha
1
scale
1
base
0
initialSum
0
b0
0
a0
1
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0

adapt_stage_0_materialize_3: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
3
output
1
feature
1
rank
1
alpha
1
scale
1
base
0.2880859375
initialSum
0
b0
0
a0
0
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0.2880859375

adapt_stage_0_readout_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.2880859375
prediction0
0
prediction1
0.2880859375

adapt_stage_0_readout_forward_1: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
1
x
-0.5
phiPlus
0
phiMinus
0.5
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.14404296875
prediction0
0
prediction1
0.14404296875

adapt_stage_0_readout_forward_2: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
2
x
0.5
phiPlus
0.5
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.14404296875
product01
0
product10
0
product11
0
prediction0
0.14404296875
prediction1
0

adapt_stage_0_readout_forward_3: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
3
x
1
phiPlus
1
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.2880859375
product01
0
product10
0
product11
0
prediction0
0.2880859375
prediction1
0

adapt_stage_0_readout_forward_4: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
4
x
-0.75
phiPlus
0
phiMinus
0.75
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.216064453125
prediction0
0
prediction1
0.216064453125

adapt_stage_0_readout_forward_5: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
5
x
-0.25
phiPlus
0
phiMinus
0.25
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
0
product11
0.072021484375
prediction0
0
prediction1
0.072021484375

adapt_stage_0_readout_forward_6: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
6
x
0.25
phiPlus
0.25
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.072021484375
product01
0
product10
0
product11
0
prediction0
0.072021484375
prediction1
0

adapt_stage_0_readout_forward_7: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
7
x
0.75
phiPlus
0.75
phiMinus
0
w00
0.2880859375
w01
0
w10
0
w11
0.2880859375
Saved outputs
product00
0.216064453125
product01
0
product10
0
product11
0
prediction0
0.216064453125
prediction1
0

adapt_stage_0_readout_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
1
prediction0
0
prediction1
0.2880859375
target0
0.5
target1
1
divisor
2
Saved outputs
error0
-0.5
error1
-0.7119140625
square0
0.25
square1
0.5068216323852539
half0
0.125
half1
0.25341081619262695
sampleLoss
0.37841081619262695

adapt_stage_0_readout_loss_1: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
1
task
1
prediction0
0
prediction1
0.14404296875
target0
0.25
target1
0.5
divisor
2
Saved outputs
error0
-0.25
error1
-0.35595703125
square0
0.0625
square1
0.12670540809631348
half0
0.03125
half1
0.06335270404815674
sampleLoss
0.09460270404815674

adapt_stage_0_readout_loss_2: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
2
task
1
prediction0
0.14404296875
prediction1
0
target0
0.5
target1
-0.25
divisor
2
Saved outputs
error0
-0.35595703125
error1
0.25
square0
0.12670540809631348
square1
0.0625
half0
0.06335270404815674
half1
0.03125
sampleLoss
0.09460270404815674

adapt_stage_0_readout_loss_3: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
3
task
1
prediction0
0.2880859375
prediction1
0
target0
1
target1
-0.5
divisor
2
Saved outputs
error0
-0.7119140625
error1
0.5
square0
0.5068216323852539
square1
0.25
half0
0.25341081619262695
half1
0.125
sampleLoss
0.37841081619262695

adapt_stage_0_readout_loss_4: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
4
task
1
prediction0
0
prediction1
0.216064453125
target0
0.375
target1
0.75
divisor
2
Saved outputs
error0
-0.375
error1
-0.533935546875
square0
0.140625
square1
0.2850871682167053
half0
0.0703125
half1
0.14254358410835266
sampleLoss
0.21285608410835266

adapt_stage_0_readout_loss_5: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
5
task
1
prediction0
0
prediction1
0.072021484375
target0
0.125
target1
0.25
divisor
2
Saved outputs
error0
-0.125
error1
-0.177978515625
square0
0.015625
square1
0.03167635202407837
half0
0.0078125
half1
0.015838176012039185
sampleLoss
0.023650676012039185

adapt_stage_0_readout_loss_6: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
6
task
1
prediction0
0.072021484375
prediction1
0
target0
0.25
target1
-0.125
divisor
2
Saved outputs
error0
-0.177978515625
error1
0.125
square0
0.03167635202407837
square1
0.015625
half0
0.015838176012039185
half1
0.0078125
sampleLoss
0.023650676012039185

adapt_stage_0_readout_loss_7: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
7
task
1
prediction0
0.216064453125
prediction1
0
target0
0.75
target1
-0.375
divisor
2
Saved outputs
error0
-0.533935546875
error1
0.375
square0
0.2850871682167053
square1
0.140625
half0
0.14254358410835266
half1
0.0703125
sampleLoss
0.21285608410835266

adapt_stage_0_readout_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.37841081619262695
loss1
0.09460270404815674
loss2
0.09460270404815674
loss3
0.37841081619262695
Saved outputs
sum0
0.37841081619262695
sum1
0.4730135202407837
sum2
0.5676162242889404
sum3
0.9460270404815674
mean
0.23650676012039185

adapt_stage_0_readout_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.21285608410835266
loss1
0.023650676012039185
loss2
0.023650676012039185
loss3
0.21285608410835266
Saved outputs
sum0
0.21285608410835266
sum1
0.23650676012039185
sum2
0.26015743613243103
sum3
0.4730135202407837
mean
0.11825338006019592

adapt_stage_0_readout_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
-0.5
feature0
0
error1
-0.25
feature1
0
error2
-0.35595703125
feature2
0.5
error3
-0.7119140625
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
-0.177978515625
sum2
-0.177978515625
contribution3
-0.7119140625
sum3
-0.889892578125
mathematical
-0.22247314453125

adapt_stage_0_readout_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
-0.5
feature0
1
error1
-0.25
feature1
0.5
error2
-0.35595703125
feature2
0
error3
-0.7119140625
feature3
0
Saved outputs
contribution0
-0.5
sum0
-0.5
contribution1
-0.125
sum1
-0.625
contribution2
-0
sum2
-0.625
contribution3
-0
sum3
-0.625
mathematical
-0.15625

adapt_stage_0_readout_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.7119140625
feature0
0
error1
-0.35595703125
feature1
0
error2
0.25
feature2
0.5
error3
0.5
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0.125
sum2
0.125
contribution3
0.5
sum3
0.625
mathematical
0.15625

adapt_stage_0_readout_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.7119140625
feature0
1
error1
-0.35595703125
feature1
0.5
error2
0.25
feature2
0
error3
0.5
feature3
0
Saved outputs
contribution0
-0.7119140625
sum0
-0.7119140625
contribution1
-0.177978515625
sum1
-0.889892578125
contribution2
0
sum2
-0.889892578125
contribution3
0
sum3
-0.889892578125
mathematical
-0.22247314453125

adapt_stage_0_readout_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.22247314453125
enabled0
1
mathematical1
-0.15625
enabled1
1
mathematical2
0.15625
enabled2
1
mathematical3
-0.22247314453125
enabled3
1
Saved outputs
effective0
-0.22247314453125
effective1
-0.15625
effective2
0.15625
effective3
-0.22247314453125

adapt_stage_0_gradientA_0: Apply the chain rule to one A coordinate

term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction

Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero.

Saved inputs
coordinate
0
k
0
feature
0
scale
1
initialSum
0
b0
0
g0
-0.22247314453125
b1
0
g1
0.15625
Saved outputs
product0
-0
sum0
0
product1
0
sum1
0
contraction
0
gradient
0

adapt_stage_0_gradientA_1: Apply the chain rule to one A coordinate

term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction

Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero.

Saved inputs
coordinate
1
k
0
feature
1
scale
1
initialSum
0
b0
0
g0
-0.15625
b1
0
g1
-0.22247314453125
Saved outputs
product0
-0
sum0
0
product1
-0
sum1
0
contraction
0
gradient
0

adapt_stage_0_gradientB_0: Apply the chain rule to one B coordinate

term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction

Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero.

Saved inputs
coordinate
0
output
0
k
0
scale
1
initialSum
0
g0
-0.22247314453125
a0
1
g1
-0.15625
a1
0
Saved outputs
product0
-0.22247314453125
sum0
-0.22247314453125
product1
-0
sum1
-0.22247314453125
contraction
-0.22247314453125
gradient
-0.22247314453125

adapt_stage_0_gradientB_1: Apply the chain rule to one B coordinate

term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction

Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero.

Saved inputs
coordinate
1
output
1
k
0
scale
1
initialSum
0
g0
0.15625
a0
1
g1
-0.22247314453125
a1
0
Saved outputs
product0
0.15625
sum0
0.15625
product1
-0
sum1
0.15625
contraction
0.15625
gradient
0.15625

adapt_stage_0_stats: Save one complete adapter state and whether another step follows

diagnosticOnly=(stage==requestedUpdates); hasNextUpdate=(stage<requestedUpdates); losses and both gradients belong to the saved factor pair

Only actual evaluated states enter the trajectory. Stage zero already has a materialized matrix, eight forwards, two losses and both factor gradients. Final-stage gradients are diagnostic only. Even a stalled or zero-rate run retains all requested arithmetic and states.

Saved inputs
stage
0
requestedUpdates
1
rank
1
alpha
1
initialization
0
eta
0.5
scale
1
trainHalfMSE
0.23650676012039185
validationHalfMSE
0.11825338006019592
Saved outputs
trainHalfMSE
0.23650676012039185
validationHalfMSE
0.11825338006019592
diagnosticOnly
0
hasNextUpdate
1

adapt_update_1_A_0: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
0
coordinate
0
old
1
gradient
0
eta
0.5
Saved outputs
delta
0
proposed
1
committed
1

adapt_update_1_A_1: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
0
coordinate
1
old
0
gradient
0
eta
0.5
Saved outputs
delta
0
proposed
0
committed
0

adapt_update_1_B_0: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
1
coordinate
0
old
0
gradient
-0.22247314453125
eta
0.5
Saved outputs
delta
-0.111236572265625
proposed
0.111236572265625
committed
0.111236572265625

adapt_update_1_B_1: Propose one factor coordinate from the unchanged old state

delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit

All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation.

Saved inputs
factor
1
coordinate
1
old
0
gradient
0.15625
eta
0.5
Saved outputs
delta
0.078125
proposed
-0.078125
committed
-0.078125

adapt_update_1_commit: Publish both complete factor proposals together

nextA=[all proposed A coordinates]; nextB=[all proposed B coordinates]; publish the pair simultaneously

One optimizer step commits this pair. Neither gradient used an updated factor. The next stage rematerializes the effective matrix and performs a complete new evaluation. The final requested stage has diagnostics and no additional commit.

Saved inputs
oldA0
1
oldA1
0
oldB0
0
oldB1
0
Saved outputs
A0
1
A1
0
B0
0.111236572265625
B1
-0.078125

adapt_stage_1_materialize_0: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
0
output
0
feature
0
rank
1
alpha
1
scale
1
base
0.2880859375
initialSum
0
b0
0.111236572265625
a0
1
Saved outputs
scale
1
product0
0.111236572265625
sum0
0.111236572265625
product
0.111236572265625
delta
0.111236572265625
weight
0.399322509765625

adapt_stage_1_materialize_1: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
1
output
0
feature
1
rank
1
alpha
1
scale
1
base
0
initialSum
0
b0
0.111236572265625
a0
0
Saved outputs
product0
0
sum0
0
product
0
delta
0
weight
0

adapt_stage_1_materialize_2: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
2
output
1
feature
0
rank
1
alpha
1
scale
1
base
0
initialSum
0
b0
-0.078125
a0
1
Saved outputs
product0
-0.078125
sum0
-0.078125
product
-0.078125
delta
-0.078125
weight
-0.078125

adapt_stage_1_materialize_3: Materialize one effective readout coordinate

scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta

Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized.

Saved inputs
coordinate
3
output
1
feature
1
rank
1
alpha
1
scale
1
base
0.2880859375
initialSum
0
b0
-0.078125
a0
0
Saved outputs
product0
-0
sum0
0
product
0
delta
0
weight
0.2880859375

adapt_stage_1_readout_forward_0: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
0
x
-1
phiPlus
0
phiMinus
1
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
-0
product11
0.2880859375
prediction0
0
prediction1
0.2880859375

adapt_stage_1_readout_forward_1: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
1
x
-0.5
phiPlus
0
phiMinus
0.5
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
-0
product11
0.14404296875
prediction0
0
prediction1
0.14404296875

adapt_stage_1_readout_forward_2: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
2
x
0.5
phiPlus
0.5
phiMinus
0
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0.1996612548828125
product01
0
product10
-0.0390625
product11
0
prediction0
0.1996612548828125
prediction1
-0.0390625

adapt_stage_1_readout_forward_3: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
3
x
1
phiPlus
1
phiMinus
0
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0.399322509765625
product01
0
product10
-0.078125
product11
0
prediction0
0.399322509765625
prediction1
-0.078125

adapt_stage_1_readout_forward_4: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
4
x
-0.75
phiPlus
0
phiMinus
0.75
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
-0
product11
0.216064453125
prediction0
0
prediction1
0.216064453125

adapt_stage_1_readout_forward_5: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
5
x
-0.25
phiPlus
0
phiMinus
0.25
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0
product01
0
product10
-0
product11
0.072021484375
prediction0
0
prediction1
0.072021484375

adapt_stage_1_readout_forward_6: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
6
x
0.25
phiPlus
0.25
phiMinus
0
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0.09983062744140625
product01
0
product10
-0.01953125
product11
0
prediction0
0.09983062744140625
prediction1
-0.01953125

adapt_stage_1_readout_forward_7: Read out two numbers from the same fixed feature column

product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11

W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax.

Saved inputs
sample
7
x
0.75
phiPlus
0.75
phiMinus
0
w00
0.399322509765625
w01
0
w10
-0.078125
w11
0.2880859375
Saved outputs
product00
0.29949188232421875
product01
0
product10
-0.05859375
product11
0
prediction0
0.29949188232421875
prediction1
-0.05859375

adapt_stage_1_readout_loss_0: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
0
task
1
prediction0
0
prediction1
0.2880859375
target0
0.5
target1
1
divisor
2
Saved outputs
error0
-0.5
error1
-0.7119140625
square0
0.25
square1
0.5068216323852539
half0
0.125
half1
0.25341081619262695
sampleLoss
0.37841081619262695

adapt_stage_1_readout_loss_1: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
1
task
1
prediction0
0
prediction1
0.14404296875
target0
0.25
target1
0.5
divisor
2
Saved outputs
error0
-0.25
error1
-0.35595703125
square0
0.0625
square1
0.12670540809631348
half0
0.03125
half1
0.06335270404815674
sampleLoss
0.09460270404815674

adapt_stage_1_readout_loss_2: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
2
task
1
prediction0
0.1996612548828125
prediction1
-0.0390625
target0
0.5
target1
-0.25
divisor
2
Saved outputs
error0
-0.3003387451171875
error1
0.2109375
square0
0.09020336181856692
square1
0.04449462890625
half0
0.04510168090928346
half1
0.022247314453125
sampleLoss
0.06734899536240846

adapt_stage_1_readout_loss_3: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
3
task
1
prediction0
0.399322509765625
prediction1
-0.078125
target0
1
target1
-0.5
divisor
2
Saved outputs
error0
-0.600677490234375
error1
0.421875
square0
0.3608134472742677
square1
0.177978515625
half0
0.18040672363713384
half1
0.0889892578125
sampleLoss
0.26939598144963384

adapt_stage_1_readout_loss_4: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
4
task
1
prediction0
0
prediction1
0.216064453125
target0
0.375
target1
0.75
divisor
2
Saved outputs
error0
-0.375
error1
-0.533935546875
square0
0.140625
square1
0.2850871682167053
half0
0.0703125
half1
0.14254358410835266
sampleLoss
0.21285608410835266

adapt_stage_1_readout_loss_5: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
5
task
1
prediction0
0
prediction1
0.072021484375
target0
0.125
target1
0.25
divisor
2
Saved outputs
error0
-0.125
error1
-0.177978515625
square0
0.015625
square1
0.03167635202407837
half0
0.0078125
half1
0.015838176012039185
sampleLoss
0.023650676012039185

adapt_stage_1_readout_loss_6: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
6
task
1
prediction0
0.09983062744140625
prediction1
-0.01953125
target0
0.25
target1
-0.125
divisor
2
Saved outputs
error0
-0.15016937255859375
error1
0.10546875
square0
0.02255084045464173
square1
0.0111236572265625
half0
0.011275420227320865
half1
0.00556182861328125
sampleLoss
0.016837248840602115

adapt_stage_1_readout_loss_7: Measure the two output errors for one sample

error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1

Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates.

Saved inputs
sample
7
task
1
prediction0
0.29949188232421875
prediction1
-0.05859375
target0
0.75
target1
-0.375
divisor
2
Saved outputs
error0
-0.45050811767578125
error1
0.31640625
square0
0.20295756409177557
square1
0.1001129150390625
half0
0.10147878204588778
half1
0.05005645751953125
sampleLoss
0.15153523956541903

adapt_stage_1_readout_mean_0: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
0
initialSum
0
divisor
4
loss0
0.37841081619262695
loss1
0.09460270404815674
loss2
0.06734899536240846
loss3
0.26939598144963384
Saved outputs
sum0
0.37841081619262695
sum1
0.4730135202407837
sum2
0.5403625156031922
sum3
0.809758497052826
mean
0.2024396242632065

adapt_stage_1_readout_mean_1: Average four saved sample losses in their original order

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

Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight.

Saved inputs
dataset
1
initialSum
0
divisor
4
loss0
0.21285608410835266
loss1
0.023650676012039185
loss2
0.016837248840602115
loss3
0.15153523956541903
Saved outputs
sum0
0.21285608410835266
sum1
0.23650676012039185
sum2
0.25334400896099396
sum3
0.404879248526413
mean
0.10121981213160325

adapt_stage_1_readout_gradient_0: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
0
output
0
feature
0
initialSum
0
divisor
4
error0
-0.5
feature0
0
error1
-0.25
feature1
0
error2
-0.3003387451171875
feature2
0.5
error3
-0.600677490234375
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
-0.15016937255859375
sum2
-0.15016937255859375
contribution3
-0.600677490234375
sum3
-0.7508468627929688
mathematical
-0.1877117156982422

adapt_stage_1_readout_gradient_1: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
1
output
0
feature
1
initialSum
0
divisor
4
error0
-0.5
feature0
1
error1
-0.25
feature1
0.5
error2
-0.3003387451171875
feature2
0
error3
-0.600677490234375
feature3
0
Saved outputs
contribution0
-0.5
sum0
-0.5
contribution1
-0.125
sum1
-0.625
contribution2
-0
sum2
-0.625
contribution3
-0
sum3
-0.625
mathematical
-0.15625

adapt_stage_1_readout_gradient_2: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
2
output
1
feature
0
initialSum
0
divisor
4
error0
-0.7119140625
feature0
0
error1
-0.35595703125
feature1
0
error2
0.2109375
feature2
0.5
error3
0.421875
feature3
1
Saved outputs
contribution0
-0
sum0
0
contribution1
-0
sum1
0
contribution2
0.10546875
sum2
0.10546875
contribution3
0.421875
sum3
0.52734375
mathematical
0.1318359375

adapt_stage_1_readout_gradient_3: Differentiate one readout coordinate using training errors

contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4

A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates.

Saved inputs
coordinate
3
output
1
feature
1
initialSum
0
divisor
4
error0
-0.7119140625
feature0
1
error1
-0.35595703125
feature1
0.5
error2
0.2109375
feature2
0
error3
0.421875
feature3
0
Saved outputs
contribution0
-0.7119140625
sum0
-0.7119140625
contribution1
-0.177978515625
sum1
-0.889892578125
contribution2
0
sum2
-0.889892578125
contribution3
0
sum3
-0.889892578125
mathematical
-0.22247314453125

adapt_stage_1_readout_mask: Choose which derivatives the optimizer may use

effective_i=enabled_i==1?mathematical_i:+0

The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask.

Saved inputs
positiveZero
0
mathematical0
-0.1877117156982422
enabled0
1
mathematical1
-0.15625
enabled1
1
mathematical2
0.1318359375
enabled2
1
mathematical3
-0.22247314453125
enabled3
1
Saved outputs
effective0
-0.1877117156982422
effective1
-0.15625
effective2
0.1318359375
effective3
-0.22247314453125

adapt_stage_1_gradientA_0: Apply the chain rule to one A coordinate

term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction

Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero.

Saved inputs
coordinate
0
k
0
feature
0
scale
1
initialSum
0
b0
0.111236572265625
g0
-0.1877117156982422
b1
-0.078125
g1
0.1318359375
Saved outputs
product0
-0.020880407828371972
sum0
-0.020880407828371972
product1
-0.0102996826171875
sum1
-0.031180090445559472
contraction
-0.031180090445559472
gradient
-0.031180090445559472

adapt_stage_1_gradientA_1: Apply the chain rule to one A coordinate

term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction

Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero.

Saved inputs
coordinate
1
k
0
feature
1
scale
1
initialSum
0
b0
0.111236572265625
g0
-0.15625
b1
-0.078125
g1
-0.22247314453125
Saved outputs
product0
-0.017380714416503906
sum0
-0.017380714416503906
product1
0.017380714416503906
sum1
0
contraction
0
gradient
0

adapt_stage_1_gradientB_0: Apply the chain rule to one B coordinate

term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction

Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero.

Saved inputs
coordinate
0
output
0
k
0
scale
1
initialSum
0
g0
-0.1877117156982422
a0
1
g1
-0.15625
a1
0
Saved outputs
product0
-0.1877117156982422
sum0
-0.1877117156982422
product1
-0
sum1
-0.1877117156982422
contraction
-0.1877117156982422
gradient
-0.1877117156982422

adapt_stage_1_gradientB_1: Apply the chain rule to one B coordinate

term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction

Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero.

Saved inputs
coordinate
1
output
1
k
0
scale
1
initialSum
0
g0
0.1318359375
a0
1
g1
-0.22247314453125
a1
0
Saved outputs
product0
0.1318359375
sum0
0.1318359375
product1
-0
sum1
0.1318359375
contraction
0.1318359375
gradient
0.1318359375

adapt_stage_1_stats: Save one complete adapter state and whether another step follows

diagnosticOnly=(stage==requestedUpdates); hasNextUpdate=(stage<requestedUpdates); losses and both gradients belong to the saved factor pair

Only actual evaluated states enter the trajectory. Stage zero already has a materialized matrix, eight forwards, two losses and both factor gradients. Final-stage gradients are diagnostic only. Even a stalled or zero-rate run retains all requested arithmetic and states.

Saved inputs
stage
1
requestedUpdates
1
rank
1
alpha
1
initialization
0
eta
0.5
scale
1
trainHalfMSE
0.2024396242632065
validationHalfMSE
0.10121981213160325
Saved outputs
trainHalfMSE
0.2024396242632065
validationHalfMSE
0.10121981213160325
diagnosticOnly
1
hasNextUpdate
0

finish: Report the actual final adapter losses and honest parameter counts

report saved final losses; factor trainables=4r versus full4; frozen base4 remains stored; structural exact-real rank bound=r

Compare actual evaluated losses, not fitted curves. Rank one saves no trainable coordinates in this toy and rank two uses more; the frozen base remains stored. Structural rank concerns the real factorization and does not certify rounded-matrix rank. Counts describe source work, not measured time, memory or LLM performance.

Saved inputs
rank
1
alpha
1
initialization
0
updates
1
eta
0.5
scale
1
adaptValidationLoss
0.10121981213160325
adaptTrainLoss
0.2024396242632065
adapterTrainableParameters
4
structuralRankBound
1
featureMaps
8
featureNegations
8
featureMaxSelections
16
preTargetCopies
16
adaptTargetScalings
16
adaptTargetAdditions
16
preparedWeightCopies
4
pretrainingStages
3
adapterStages
2
stageCount
5
forwardSampleEvaluations
40
forwardProducts
160
forwardSums
80
readoutGradientBatches
5
readoutGradientContractions
20
gradientRowContributions
20
readoutGradientProducts
80
readoutGradientAdditions
80
readoutGradientDivisions
20
preOptimizerBatches
2
preCoordinateUpdates
8
adapterEvaluations
2
scaleDivisions
3
materializationProducts
8
materializationAdditions
8
materializationScalings
8
baseAdditions
8
factorGradientContractions
8
factorGradientProducts
16
factorGradientAdditions
16
factorGradientScalings
8
adapterOptimizerBatches
1
factorCoordinateUpdates
4
factorUpdateProducts
4
factorUpdateSubtractions
4
finalDiagnosticBatches
2
lossSampleEvaluations
40
lossComponentErrors
80
lossSquares
80
lossHalfDivisions
80
lossOutputSums
40
orderedLossAdditions
40
datasetMeanDivisions
10
Saved outputs
adaptValidationLoss
0.10121981213160325
adaptTrainLoss
0.2024396242632065
adapterTrainableParameters
4
structuralRankBound
1
featureMaps
8
featureNegations
8
featureMaxSelections
16
preTargetCopies
16
adaptTargetScalings
16
adaptTargetAdditions
16
preparedWeightCopies
4
pretrainingStages
3
adapterStages
2
stageCount
5
forwardSampleEvaluations
40
forwardProducts
160
forwardSums
80
readoutGradientBatches
5
readoutGradientContractions
20
gradientRowContributions
20
readoutGradientProducts
80
readoutGradientAdditions
80
readoutGradientDivisions
20
preOptimizerBatches
2
preCoordinateUpdates
8
adapterEvaluations
2
scaleDivisions
3
materializationProducts
8
materializationAdditions
8
materializationScalings
8
baseAdditions
8
factorGradientContractions
8
factorGradientProducts
16
factorGradientAdditions
16
factorGradientScalings
8
adapterOptimizerBatches
1
factorCoordinateUpdates
4
factorUpdateProducts
4
factorUpdateSubtractions
4
finalDiagnosticBatches
2
lossSampleEvaluations
40
lossComponentErrors
80
lossSquares
80
lossHalfDivisions
80
lossOutputSums
40
orderedLossAdditions
40
datasetMeanDivisions
10

The house inspector below also exposes every scalar alias, all text evidence, all tensor axes, dtype, precision, provenance and full storage indices from this same result. It includes every history, old/new contraction partial, factor proposal and base copy. IV-57 next asks how preference examples can provide a different training signal.

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=7 · float64 · precision 8 · Actual once-prepared readonly55 data in texts.dataFields order; training rows0..3, held-out rows4..7.

Zero-based storage indexStored value
0-1
10
21
30
41
50.5
61
7-0.5
80
90.5
100
110.5
120.25
130.5
140.5
150.5
160
170.5
180
190.5
20-0.25
211
221
230
241
250
261
27-0.5
28-0.75
290
300.75
310
320.75
330.375
340.75
35-0.25
360
370.25
380
390.25
400.125
410.25
420.25
430.25
440
450.25
460
470.25
48-0.125
490.75
500.75
510
520.75
530
540.75
55-0.375

pre_InitialWeights

Output=2 × Feature=2 · float64 · precision 8 · Actual PRE initialization: four authored floating positive zeros.

Zero-based storage indexStored value
00
10
20
30

pre_stage_0_Weights

Output=2 × Feature=2 · float64 · precision 8 · Detached actual same-state W, row-major 00,01,10,11; arbitrary finite represented weights are permitted.

Zero-based storage indexStored value
00
10
20
30

pre_stage_0_Predictions

Sample=8 × Output=2 · float64 · precision 8 · Actual two-output predictions from all four products and both sums per sample, with the same W for all eight rows.

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

pre_stage_0_Forward

Sample=8 × ForwardField=6 · float64 · precision 8 · Actual product00,product01,product10,product11,prediction0,prediction1; no zero-product shortcut.

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
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470

pre_stage_0_Loss

Sample=8 × LossField=9 · float64 · precision 8 · Actual target0,target1,error0,error1,square0,square1,half0,half1,sampleLoss in sample order; each sample loss sums both output half-losses.

Zero-based storage indexStored value
00
11
20
3-1
40
51
60
70.5
80.5
90
100.5
110
12-0.5
130
140.25
150
160.125
170.125
180.5
190
20-0.5
210
220.25
230
240.125
250
260.125
271
280
29-1
300
311
320
330.5
340
350.5
360
370.75
380
39-0.75
400
410.5625
420
430.28125
440.28125
450
460.25
470
48-0.25
490
500.0625
510
520.03125
530.03125
540.25
550
56-0.25
570
580.0625
590
600.03125
610
620.03125
630.75
640
65-0.75
660
670.5625
680
690.28125
700
710.28125

pre_stage_0_Reductions

Dataset=2 × DatasetSample=4 × ReductionField=3 · float64 · precision 8 · Actual saved loss, oldSum, sum for each ordered four-sample reduction, training then validation, each initialized at floating positive zero.

Zero-based storage indexStored value
00.5
10
20.5
30.125
40.5
50.625
60.125
70.625
80.75
90.5
100.75
111.25
120.28125
130
140.28125
150.03125
160.28125
170.3125
180.03125
190.3125
200.34375
210.28125
220.34375
230.625

pre_stage_0_Means

Dataset=2 · float64 · precision 8 · Actual independent training and validation means; each divides its own ordered four-sample sum by floating four.

Zero-based storage indexStored value
00.3125
10.15625

pre_stage_0_GradientRows

Coordinate=4 × TrainSample=4 × GradientRowField=5 · float64 · precision 8 · Actual error,feature,contribution,oldSum,sum in coordinate-major then training-row order; each contraction starts at floating positive zero.

Zero-based storage indexStored value
00
10
20
30
40
50
60
70
80
90
10-0.5
110.5
12-0.25
130
14-0.25
15-1
161
17-1
18-0.25
19-1.25
200
211
220
230
240
250
260.5
270
280
290
30-0.5
310
32-0
330
340
35-1
360
37-0
380
390
40-1
410
42-0
430
440
45-0.5
460
47-0
480
490
500
510.5
520
530
540
550
561
570
580
590
60-1
611
62-1
630
64-1
65-0.5
660.5
67-0.25
68-1
69-1.25
700
710
720
73-1.25
74-1.25
750
760
770
78-1.25
79-1.25

pre_stage_0_MathematicalGradient

Output=2 × Feature=2 · float64 · precision 8 · All four actual derivatives of the current training objective; the final cohort stage is diagnostic only.

Zero-based storage indexStored value
0-0.3125
10
20
3-0.3125

pre_stage_0_EffectiveGradient

Output=2 × Feature=2 · float64 · precision 8 · Actual conditional mathematical-gradient or floating-positive-zero selection, in row-major W order.

Zero-based storage indexStored value
0-0.3125
10
20
3-0.3125

pre_stage_0_Mask

Output=2 × Feature=2 · int32 · precision 0 · Actual numeric zero-or-one selectors in row-major W order; integer values select effective gradients, never rescale features.

Zero-based storage indexStored value
01
11
21
31

pre_stage_0_Stats

StageField=4 · float64 · precision 8 · Actual PRE losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors.

Zero-based storage indexStored value
00.3125
10.15625
20
31

pre_update_1_Update

Coordinate=4 × UpdateField=7 · float64 · precision 8 · Actual old,mathematical,effective,enabled,delta,proposed,committed; enabled is an integer VALUE in this mixed float table. Frozen commits copy the old word, including nonzero values and negative zero.

Zero-based storage indexStored value
00
1-0.3125
2-0.3125
31
4-0.15625
50.15625
60.15625
70
80
90
101
110
120
130
140
150
160
171
180
190
200
210
22-0.3125
23-0.3125
241
25-0.15625
260.15625
270.15625

pre_stage_1_Weights

Output=2 × Feature=2 · float64 · precision 8 · Detached actual same-state W, row-major 00,01,10,11; arbitrary finite represented weights are permitted.

Zero-based storage indexStored value
00.15625
10
20
30.15625

pre_stage_1_Predictions

Sample=8 × Output=2 · float64 · precision 8 · Actual two-output predictions from all four products and both sums per sample, with the same W for all eight rows.

Zero-based storage indexStored value
00
10.15625
20
30.078125
40.078125
50
60.15625
70
80
90.1171875
100
110.0390625
120.0390625
130
140.1171875
150

pre_stage_1_Forward

Sample=8 × ForwardField=6 · float64 · precision 8 · Actual product00,product01,product10,product11,prediction0,prediction1; no zero-product shortcut.

Zero-based storage indexStored value
00
10
20
30.15625
40
50.15625
60
70
80
90.078125
100
110.078125
120.078125
130
140
150
160.078125
170
180.15625
190
200
210
220.15625
230
240
250
260
270.1171875
280
290.1171875
300
310
320
330.0390625
340
350.0390625
360.0390625
370
380
390
400.0390625
410
420.1171875
430
440
450
460.1171875
470

pre_stage_1_Loss

Sample=8 × LossField=9 · float64 · precision 8 · Actual target0,target1,error0,error1,square0,square1,half0,half1,sampleLoss in sample order; each sample loss sums both output half-losses.

Zero-based storage indexStored value
00
11
20
3-0.84375
40
50.7119140625
60
70.35595703125
80.35595703125
90
100.5
110
12-0.421875
130
140.177978515625
150
160.0889892578125
170.0889892578125
180.5
190
20-0.421875
210
220.177978515625
230
240.0889892578125
250
260.0889892578125
271
280
29-0.84375
300
310.7119140625
320
330.35595703125
340
350.35595703125
360
370.75
380
39-0.6328125
400
410.40045166015625
420
430.200225830078125
440.200225830078125
450
460.25
470
48-0.2109375
490
500.04449462890625
510
520.022247314453125
530.022247314453125
540.25
550
56-0.2109375
570
580.04449462890625
590
600.022247314453125
610
620.022247314453125
630.75
640
65-0.6328125
660
670.40045166015625
680
690.200225830078125
700
710.200225830078125

pre_stage_1_Reductions

Dataset=2 × DatasetSample=4 × ReductionField=3 · float64 · precision 8 · Actual saved loss, oldSum, sum for each ordered four-sample reduction, training then validation, each initialized at floating positive zero.

Zero-based storage indexStored value
00.35595703125
10
20.35595703125
30.0889892578125
40.35595703125
50.4449462890625
60.0889892578125
70.4449462890625
80.533935546875
90.35595703125
100.533935546875
110.889892578125
120.200225830078125
130
140.200225830078125
150.022247314453125
160.200225830078125
170.22247314453125
180.022247314453125
190.22247314453125
200.244720458984375
210.200225830078125
220.244720458984375
230.4449462890625

pre_stage_1_Means

Dataset=2 · float64 · precision 8 · Actual independent training and validation means; each divides its own ordered four-sample sum by floating four.

Zero-based storage indexStored value
00.22247314453125
10.111236572265625

pre_stage_1_GradientRows

Coordinate=4 × TrainSample=4 × GradientRowField=5 · float64 · precision 8 · Actual error,feature,contribution,oldSum,sum in coordinate-major then training-row order; each contraction starts at floating positive zero.

Zero-based storage indexStored value
00
10
20
30
40
50
60
70
80
90
10-0.421875
110.5
12-0.2109375
130
14-0.2109375
15-0.84375
161
17-0.84375
18-0.2109375
19-1.0546875
200
211
220
230
240
250
260.5
270
280
290
30-0.421875
310
32-0
330
340
35-0.84375
360
37-0
380
390
40-0.84375
410
42-0
430
440
45-0.421875
460
47-0
480
490
500
510.5
520
530
540
550
561
570
580
590
60-0.84375
611
62-0.84375
630
64-0.84375
65-0.421875
660.5
67-0.2109375
68-0.84375
69-1.0546875
700
710
720
73-1.0546875
74-1.0546875
750
760
770
78-1.0546875
79-1.0546875

pre_stage_1_MathematicalGradient

Output=2 × Feature=2 · float64 · precision 8 · All four actual derivatives of the current training objective; the final cohort stage is diagnostic only.

Zero-based storage indexStored value
0-0.263671875
10
20
3-0.263671875

pre_stage_1_EffectiveGradient

Output=2 × Feature=2 · float64 · precision 8 · Actual conditional mathematical-gradient or floating-positive-zero selection, in row-major W order.

Zero-based storage indexStored value
0-0.263671875
10
20
3-0.263671875

pre_stage_1_Mask

Output=2 × Feature=2 · int32 · precision 0 · Actual numeric zero-or-one selectors in row-major W order; integer values select effective gradients, never rescale features.

Zero-based storage indexStored value
01
11
21
31

pre_stage_1_Stats

StageField=4 · float64 · precision 8 · Actual PRE losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors.

Zero-based storage indexStored value
00.22247314453125
10.111236572265625
20
31

pre_update_2_Update

Coordinate=4 × UpdateField=7 · float64 · precision 8 · Actual old,mathematical,effective,enabled,delta,proposed,committed; enabled is an integer VALUE in this mixed float table. Frozen commits copy the old word, including nonzero values and negative zero.

Zero-based storage indexStored value
00.15625
1-0.263671875
2-0.263671875
31
4-0.1318359375
50.2880859375
60.2880859375
70
80
90
101
110
120
130
140
150
160
171
180
190
200
210.15625
22-0.263671875
23-0.263671875
241
25-0.1318359375
260.2880859375
270.2880859375

pre_stage_2_Weights

Output=2 × Feature=2 · float64 · precision 8 · Detached actual same-state W, row-major 00,01,10,11; arbitrary finite represented weights are permitted.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375

pre_stage_2_Predictions

Sample=8 × Output=2 · float64 · precision 8 · Actual two-output predictions from all four products and both sums per sample, with the same W for all eight rows.

Zero-based storage indexStored value
00
10.2880859375
20
30.14404296875
40.14404296875
50
60.2880859375
70
80
90.216064453125
100
110.072021484375
120.072021484375
130
140.216064453125
150

pre_stage_2_Forward

Sample=8 × ForwardField=6 · float64 · precision 8 · Actual product00,product01,product10,product11,prediction0,prediction1; no zero-product shortcut.

Zero-based storage indexStored value
00
10
20
30.2880859375
40
50.2880859375
60
70
80
90.14404296875
100
110.14404296875
120.14404296875
130
140
150
160.14404296875
170
180.2880859375
190
200
210
220.2880859375
230
240
250
260
270.216064453125
280
290.216064453125
300
310
320
330.072021484375
340
350.072021484375
360.072021484375
370
380
390
400.072021484375
410
420.216064453125
430
440
450
460.216064453125
470

pre_stage_2_Loss

Sample=8 × LossField=9 · float64 · precision 8 · Actual target0,target1,error0,error1,square0,square1,half0,half1,sampleLoss in sample order; each sample loss sums both output half-losses.

Zero-based storage indexStored value
00
11
20
3-0.7119140625
40
50.5068216323852539
60
70.25341081619262695
80.25341081619262695
90
100.5
110
12-0.35595703125
130
140.12670540809631348
150
160.06335270404815674
170.06335270404815674
180.5
190
20-0.35595703125
210
220.12670540809631348
230
240.06335270404815674
250
260.06335270404815674
271
280
29-0.7119140625
300
310.5068216323852539
320
330.25341081619262695
340
350.25341081619262695
360
370.75
380
39-0.533935546875
400
410.2850871682167053
420
430.14254358410835266
440.14254358410835266
450
460.25
470
48-0.177978515625
490
500.03167635202407837
510
520.015838176012039185
530.015838176012039185
540.25
550
56-0.177978515625
570
580.03167635202407837
590
600.015838176012039185
610
620.015838176012039185
630.75
640
65-0.533935546875
660
670.2850871682167053
680
690.14254358410835266
700
710.14254358410835266

pre_stage_2_Reductions

Dataset=2 × DatasetSample=4 × ReductionField=3 · float64 · precision 8 · Actual saved loss, oldSum, sum for each ordered four-sample reduction, training then validation, each initialized at floating positive zero.

Zero-based storage indexStored value
00.25341081619262695
10
20.25341081619262695
30.06335270404815674
40.25341081619262695
50.3167635202407837
60.06335270404815674
70.3167635202407837
80.38011622428894043
90.25341081619262695
100.38011622428894043
110.6335270404815674
120.14254358410835266
130
140.14254358410835266
150.015838176012039185
160.14254358410835266
170.15838176012039185
180.015838176012039185
190.15838176012039185
200.17421993613243103
210.14254358410835266
220.17421993613243103
230.3167635202407837

pre_stage_2_Means

Dataset=2 · float64 · precision 8 · Actual independent training and validation means; each divides its own ordered four-sample sum by floating four.

Zero-based storage indexStored value
00.15838176012039185
10.07919088006019592

pre_stage_2_GradientRows

Coordinate=4 × TrainSample=4 × GradientRowField=5 · float64 · precision 8 · Actual error,feature,contribution,oldSum,sum in coordinate-major then training-row order; each contraction starts at floating positive zero.

Zero-based storage indexStored value
00
10
20
30
40
50
60
70
80
90
10-0.35595703125
110.5
12-0.177978515625
130
14-0.177978515625
15-0.7119140625
161
17-0.7119140625
18-0.177978515625
19-0.889892578125
200
211
220
230
240
250
260.5
270
280
290
30-0.35595703125
310
32-0
330
340
35-0.7119140625
360
37-0
380
390
40-0.7119140625
410
42-0
430
440
45-0.35595703125
460
47-0
480
490
500
510.5
520
530
540
550
561
570
580
590
60-0.7119140625
611
62-0.7119140625
630
64-0.7119140625
65-0.35595703125
660.5
67-0.177978515625
68-0.7119140625
69-0.889892578125
700
710
720
73-0.889892578125
74-0.889892578125
750
760
770
78-0.889892578125
79-0.889892578125

pre_stage_2_MathematicalGradient

Output=2 × Feature=2 · float64 · precision 8 · All four actual derivatives of the current training objective; the final cohort stage is diagnostic only.

Zero-based storage indexStored value
0-0.22247314453125
10
20
3-0.22247314453125

pre_stage_2_EffectiveGradient

Output=2 × Feature=2 · float64 · precision 8 · Actual conditional mathematical-gradient or floating-positive-zero selection, in row-major W order.

Zero-based storage indexStored value
0-0.22247314453125
10
20
3-0.22247314453125

pre_stage_2_Mask

Output=2 × Feature=2 · int32 · precision 0 · Actual numeric zero-or-one selectors in row-major W order; integer values select effective gradients, never rescale features.

Zero-based storage indexStored value
01
11
21
31

pre_stage_2_Stats

StageField=4 · float64 · precision 8 · Actual PRE losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors.

Zero-based storage indexStored value
00.15838176012039185
10.07919088006019592
21
30

pre_StageMetrics

Stage=3 × Dataset=2 · float64 · precision 8 · Actual PRE stages0,1,2; training then independently evaluated held-out loss.

Zero-based storage indexStored value
00.3125
10.15625
20.22247314453125
30.111236572265625
40.15838176012039185
50.07919088006019592

pre_StageWeights

Stage=3 × Coordinate=4 · float64 · precision 8 · Actual PRE evaluated weights in row-major 00,01,10,11 order; two real updates separate the three states.

Zero-based storage indexStored value
00
10
20
30
40.15625
50
60
70.15625
80.2880859375
90
100
110.2880859375

FrozenBase

Output=2 × Feature=2 · float64 · precision 8 · Exact floating-word copy of final evaluated pre_stage_2_Weights; retained and never proposed during adapter SGD.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375

adapt_InitialA

Rank=1 × Feature=2 · float64 · precision 8 · Actual first r identity rows for initialization0, or floating positive zeros for initialization1.

Zero-based storage indexStored value
01
10

adapt_InitialB

Output=2 × Rank=1 · float64 · precision 8 · Actual floating positive-zero B for either initialization; no randomness.

Zero-based storage indexStored value
00
10

adapt_stage_0_Base

Output=2 × Feature=2 · float64 · precision 8 · Exact floating-word copy of the frozen base supplied to this evaluation; no base optimizer proposal.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375

adapt_stage_0_A

Rank=1 × Feature=2 · float64 · precision 8 · Detached actual old A factor in rank-major then feature order.

Zero-based storage indexStored value
01
10

adapt_stage_0_B

Output=2 × Rank=1 · float64 · precision 8 · Detached actual old B factor in output-major then rank order.

Zero-based storage indexStored value
00
10

adapt_stage_0_ProductRows

Output=2 × Feature=2 × Rank=1 × ContractionField=3 · float64 · precision 8 · Actual product,oldSum,sum for BA; coordinate-major, increasing rank; every accumulator starts at floating positive zero.

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

adapt_stage_0_Product

Output=2 × Feature=2 · float64 · precision 8 · Actual separately rounded BA entries after their ordered contractions; no numerical rank certificate.

Zero-based storage indexStored value
00
10
20
30

adapt_stage_0_Delta

Output=2 × Feature=2 · float64 · precision 8 · Actual scale times completed BA entries; structural exact-real rank(cBA)<=r does not certify the exact rank of these rounded words.

Zero-based storage indexStored value
00
10
20
30

adapt_stage_0_Weights

Output=2 × Feature=2 · float64 · precision 8 · Actual base+delta entries, materialized before the unchanged IV55 ADAPT evaluation.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375

adapt_stage_0_readout_Weights

Output=2 × Feature=2 · float64 · precision 8 · Detached actual same-state W, row-major 00,01,10,11; arbitrary finite represented weights are permitted.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375

adapt_stage_0_readout_Predictions

Sample=8 × Output=2 · float64 · precision 8 · Actual two-output predictions from all four products and both sums per sample, with the same W for all eight rows.

Zero-based storage indexStored value
00
10.2880859375
20
30.14404296875
40.14404296875
50
60.2880859375
70
80
90.216064453125
100
110.072021484375
120.072021484375
130
140.216064453125
150

adapt_stage_0_readout_Forward

Sample=8 × ForwardField=6 · float64 · precision 8 · Actual product00,product01,product10,product11,prediction0,prediction1; no zero-product shortcut.

Zero-based storage indexStored value
00
10
20
30.2880859375
40
50.2880859375
60
70
80
90.14404296875
100
110.14404296875
120.14404296875
130
140
150
160.14404296875
170
180.2880859375
190
200
210
220.2880859375
230
240
250
260
270.216064453125
280
290.216064453125
300
310
320
330.072021484375
340
350.072021484375
360.072021484375
370
380
390
400.072021484375
410
420.216064453125
430
440
450
460.216064453125
470

adapt_stage_0_readout_Loss

Sample=8 × LossField=9 · float64 · precision 8 · Actual target0,target1,error0,error1,square0,square1,half0,half1,sampleLoss in sample order; each sample loss sums both output half-losses.

Zero-based storage indexStored value
00.5
11
2-0.5
3-0.7119140625
40.25
50.5068216323852539
60.125
70.25341081619262695
80.37841081619262695
90.25
100.5
11-0.25
12-0.35595703125
130.0625
140.12670540809631348
150.03125
160.06335270404815674
170.09460270404815674
180.5
19-0.25
20-0.35595703125
210.25
220.12670540809631348
230.0625
240.06335270404815674
250.03125
260.09460270404815674
271
28-0.5
29-0.7119140625
300.5
310.5068216323852539
320.25
330.25341081619262695
340.125
350.37841081619262695
360.375
370.75
38-0.375
39-0.533935546875
400.140625
410.2850871682167053
420.0703125
430.14254358410835266
440.21285608410835266
450.125
460.25
47-0.125
48-0.177978515625
490.015625
500.03167635202407837
510.0078125
520.015838176012039185
530.023650676012039185
540.25
55-0.125
56-0.177978515625
570.125
580.03167635202407837
590.015625
600.015838176012039185
610.0078125
620.023650676012039185
630.75
64-0.375
65-0.533935546875
660.375
670.2850871682167053
680.140625
690.14254358410835266
700.0703125
710.21285608410835266

adapt_stage_0_readout_Reductions

Dataset=2 × DatasetSample=4 × ReductionField=3 · float64 · precision 8 · Actual saved loss, oldSum, sum for each ordered four-sample reduction, training then validation, each initialized at floating positive zero.

Zero-based storage indexStored value
00.37841081619262695
10
20.37841081619262695
30.09460270404815674
40.37841081619262695
50.4730135202407837
60.09460270404815674
70.4730135202407837
80.5676162242889404
90.37841081619262695
100.5676162242889404
110.9460270404815674
120.21285608410835266
130
140.21285608410835266
150.023650676012039185
160.21285608410835266
170.23650676012039185
180.023650676012039185
190.23650676012039185
200.26015743613243103
210.21285608410835266
220.26015743613243103
230.4730135202407837

adapt_stage_0_readout_Means

Dataset=2 · float64 · precision 8 · Actual independent training and validation means; each divides its own ordered four-sample sum by floating four.

Zero-based storage indexStored value
00.23650676012039185
10.11825338006019592

adapt_stage_0_readout_GradientRows

Coordinate=4 × TrainSample=4 × GradientRowField=5 · float64 · precision 8 · Actual error,feature,contribution,oldSum,sum in coordinate-major then training-row order; each contraction starts at floating positive zero.

Zero-based storage indexStored value
0-0.5
10
2-0
30
40
5-0.25
60
7-0
80
90
10-0.35595703125
110.5
12-0.177978515625
130
14-0.177978515625
15-0.7119140625
161
17-0.7119140625
18-0.177978515625
19-0.889892578125
20-0.5
211
22-0.5
230
24-0.5
25-0.25
260.5
27-0.125
28-0.5
29-0.625
30-0.35595703125
310
32-0
33-0.625
34-0.625
35-0.7119140625
360
37-0
38-0.625
39-0.625
40-0.7119140625
410
42-0
430
440
45-0.35595703125
460
47-0
480
490
500.25
510.5
520.125
530
540.125
550.5
561
570.5
580.125
590.625
60-0.7119140625
611
62-0.7119140625
630
64-0.7119140625
65-0.35595703125
660.5
67-0.177978515625
68-0.7119140625
69-0.889892578125
700.25
710
720
73-0.889892578125
74-0.889892578125
750.5
760
770
78-0.889892578125
79-0.889892578125

adapt_stage_0_readout_MathematicalGradient

Output=2 × Feature=2 · float64 · precision 8 · All four actual derivatives of the current training objective; the final cohort stage is diagnostic only.

Zero-based storage indexStored value
0-0.22247314453125
1-0.15625
20.15625
3-0.22247314453125

adapt_stage_0_readout_EffectiveGradient

Output=2 × Feature=2 · float64 · precision 8 · Actual conditional mathematical-gradient or floating-positive-zero selection, in row-major W order.

Zero-based storage indexStored value
0-0.22247314453125
1-0.15625
20.15625
3-0.22247314453125

adapt_stage_0_readout_Mask

Output=2 × Feature=2 · int32 · precision 0 · Actual numeric zero-or-one selectors in row-major W order; integer values select effective gradients, never rescale features.

Zero-based storage indexStored value
01
11
21
31

adapt_stage_0_GradientRowsA

Rank=1 × Feature=2 × Output=2 × ContractionField=3 · float64 · precision 8 · Actual product,oldSum,sum for B-transpose times the same saved G_W; output0 then output1; scale applied only after each contraction.

Zero-based storage indexStored value
0-0
10
20
30
40
50
6-0
70
80
9-0
100
110

adapt_stage_0_GradientRowsB

Output=2 × Rank=1 × Feature=2 × ContractionField=3 · float64 · precision 8 · Actual product,oldSum,sum for the same saved G_W times A-transpose; feature0 then feature1; scale applied only after each contraction.

Zero-based storage indexStored value
0-0.22247314453125
10
2-0.22247314453125
3-0
4-0.22247314453125
5-0.22247314453125
60.15625
70
80.15625
9-0
100.15625
110.15625

adapt_stage_0_GradientA

Rank=1 × Feature=2 · float64 · precision 8 · Actual scale*(B-transpose G_W), computed entirely from old factors and saved materialized readout errors.

Zero-based storage indexStored value
00
10

adapt_stage_0_GradientB

Output=2 × Rank=1 · float64 · precision 8 · Actual scale*(G_W A-transpose), computed entirely from the same old factors and readout errors.

Zero-based storage indexStored value
0-0.22247314453125
10.15625

adapt_stage_0_Stats

StageField=4 · float64 · precision 8 · Actual adapter losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors.

Zero-based storage indexStored value
00.23650676012039185
10.11825338006019592
20
31

adapt_update_1_UpdateA

Rank=1 × Feature=2 × FactorUpdateField=5 · float64 · precision 8 · Actual old,gradient,delta,proposed,committed for every A coordinate; committed copies the proposal published with all B proposals.

Zero-based storage indexStored value
01
10
20
31
41
50
60
70
80
90

adapt_update_1_UpdateB

Output=2 × Rank=1 × FactorUpdateField=5 · float64 · precision 8 · Actual old,gradient,delta,proposed,committed for every B coordinate; all gradients belong to the same old A/B pair.

Zero-based storage indexStored value
00
1-0.22247314453125
2-0.111236572265625
30.111236572265625
40.111236572265625
50
60.15625
70.078125
8-0.078125
9-0.078125

adapt_stage_1_Base

Output=2 × Feature=2 · float64 · precision 8 · Exact floating-word copy of the frozen base supplied to this evaluation; no base optimizer proposal.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375

adapt_stage_1_A

Rank=1 × Feature=2 · float64 · precision 8 · Detached actual old A factor in rank-major then feature order.

Zero-based storage indexStored value
01
10

adapt_stage_1_B

Output=2 × Rank=1 · float64 · precision 8 · Detached actual old B factor in output-major then rank order.

Zero-based storage indexStored value
00.111236572265625
1-0.078125

adapt_stage_1_ProductRows

Output=2 × Feature=2 × Rank=1 × ContractionField=3 · float64 · precision 8 · Actual product,oldSum,sum for BA; coordinate-major, increasing rank; every accumulator starts at floating positive zero.

Zero-based storage indexStored value
00.111236572265625
10
20.111236572265625
30
40
50
6-0.078125
70
8-0.078125
9-0
100
110

adapt_stage_1_Product

Output=2 × Feature=2 · float64 · precision 8 · Actual separately rounded BA entries after their ordered contractions; no numerical rank certificate.

Zero-based storage indexStored value
00.111236572265625
10
2-0.078125
30

adapt_stage_1_Delta

Output=2 × Feature=2 · float64 · precision 8 · Actual scale times completed BA entries; structural exact-real rank(cBA)<=r does not certify the exact rank of these rounded words.

Zero-based storage indexStored value
00.111236572265625
10
2-0.078125
30

adapt_stage_1_Weights

Output=2 × Feature=2 · float64 · precision 8 · Actual base+delta entries, materialized before the unchanged IV55 ADAPT evaluation.

Zero-based storage indexStored value
00.399322509765625
10
2-0.078125
30.2880859375

adapt_stage_1_readout_Weights

Output=2 × Feature=2 · float64 · precision 8 · Detached actual same-state W, row-major 00,01,10,11; arbitrary finite represented weights are permitted.

Zero-based storage indexStored value
00.399322509765625
10
2-0.078125
30.2880859375

adapt_stage_1_readout_Predictions

Sample=8 × Output=2 · float64 · precision 8 · Actual two-output predictions from all four products and both sums per sample, with the same W for all eight rows.

Zero-based storage indexStored value
00
10.2880859375
20
30.14404296875
40.1996612548828125
5-0.0390625
60.399322509765625
7-0.078125
80
90.216064453125
100
110.072021484375
120.09983062744140625
13-0.01953125
140.29949188232421875
15-0.05859375

adapt_stage_1_readout_Forward

Sample=8 × ForwardField=6 · float64 · precision 8 · Actual product00,product01,product10,product11,prediction0,prediction1; no zero-product shortcut.

Zero-based storage indexStored value
00
10
2-0
30.2880859375
40
50.2880859375
60
70
8-0
90.14404296875
100
110.14404296875
120.1996612548828125
130
14-0.0390625
150
160.1996612548828125
17-0.0390625
180.399322509765625
190
20-0.078125
210
220.399322509765625
23-0.078125
240
250
26-0
270.216064453125
280
290.216064453125
300
310
32-0
330.072021484375
340
350.072021484375
360.09983062744140625
370
38-0.01953125
390
400.09983062744140625
41-0.01953125
420.29949188232421875
430
44-0.05859375
450
460.29949188232421875
47-0.05859375

adapt_stage_1_readout_Loss

Sample=8 × LossField=9 · float64 · precision 8 · Actual target0,target1,error0,error1,square0,square1,half0,half1,sampleLoss in sample order; each sample loss sums both output half-losses.

Zero-based storage indexStored value
00.5
11
2-0.5
3-0.7119140625
40.25
50.5068216323852539
60.125
70.25341081619262695
80.37841081619262695
90.25
100.5
11-0.25
12-0.35595703125
130.0625
140.12670540809631348
150.03125
160.06335270404815674
170.09460270404815674
180.5
19-0.25
20-0.3003387451171875
210.2109375
220.09020336181856692
230.04449462890625
240.04510168090928346
250.022247314453125
260.06734899536240846
271
28-0.5
29-0.600677490234375
300.421875
310.3608134472742677
320.177978515625
330.18040672363713384
340.0889892578125
350.26939598144963384
360.375
370.75
38-0.375
39-0.533935546875
400.140625
410.2850871682167053
420.0703125
430.14254358410835266
440.21285608410835266
450.125
460.25
47-0.125
48-0.177978515625
490.015625
500.03167635202407837
510.0078125
520.015838176012039185
530.023650676012039185
540.25
55-0.125
56-0.15016937255859375
570.10546875
580.02255084045464173
590.0111236572265625
600.011275420227320865
610.00556182861328125
620.016837248840602115
630.75
64-0.375
65-0.45050811767578125
660.31640625
670.20295756409177557
680.1001129150390625
690.10147878204588778
700.05005645751953125
710.15153523956541903

adapt_stage_1_readout_Reductions

Dataset=2 × DatasetSample=4 × ReductionField=3 · float64 · precision 8 · Actual saved loss, oldSum, sum for each ordered four-sample reduction, training then validation, each initialized at floating positive zero.

Zero-based storage indexStored value
00.37841081619262695
10
20.37841081619262695
30.09460270404815674
40.37841081619262695
50.4730135202407837
60.06734899536240846
70.4730135202407837
80.5403625156031922
90.26939598144963384
100.5403625156031922
110.809758497052826
120.21285608410835266
130
140.21285608410835266
150.023650676012039185
160.21285608410835266
170.23650676012039185
180.016837248840602115
190.23650676012039185
200.25334400896099396
210.15153523956541903
220.25334400896099396
230.404879248526413

adapt_stage_1_readout_Means

Dataset=2 · float64 · precision 8 · Actual independent training and validation means; each divides its own ordered four-sample sum by floating four.

Zero-based storage indexStored value
00.2024396242632065
10.10121981213160325

adapt_stage_1_readout_GradientRows

Coordinate=4 × TrainSample=4 × GradientRowField=5 · float64 · precision 8 · Actual error,feature,contribution,oldSum,sum in coordinate-major then training-row order; each contraction starts at floating positive zero.

Zero-based storage indexStored value
0-0.5
10
2-0
30
40
5-0.25
60
7-0
80
90
10-0.3003387451171875
110.5
12-0.15016937255859375
130
14-0.15016937255859375
15-0.600677490234375
161
17-0.600677490234375
18-0.15016937255859375
19-0.7508468627929688
20-0.5
211
22-0.5
230
24-0.5
25-0.25
260.5
27-0.125
28-0.5
29-0.625
30-0.3003387451171875
310
32-0
33-0.625
34-0.625
35-0.600677490234375
360
37-0
38-0.625
39-0.625
40-0.7119140625
410
42-0
430
440
45-0.35595703125
460
47-0
480
490
500.2109375
510.5
520.10546875
530
540.10546875
550.421875
561
570.421875
580.10546875
590.52734375
60-0.7119140625
611
62-0.7119140625
630
64-0.7119140625
65-0.35595703125
660.5
67-0.177978515625
68-0.7119140625
69-0.889892578125
700.2109375
710
720
73-0.889892578125
74-0.889892578125
750.421875
760
770
78-0.889892578125
79-0.889892578125

adapt_stage_1_readout_MathematicalGradient

Output=2 × Feature=2 · float64 · precision 8 · All four actual derivatives of the current training objective; the final cohort stage is diagnostic only.

Zero-based storage indexStored value
0-0.1877117156982422
1-0.15625
20.1318359375
3-0.22247314453125

adapt_stage_1_readout_EffectiveGradient

Output=2 × Feature=2 · float64 · precision 8 · Actual conditional mathematical-gradient or floating-positive-zero selection, in row-major W order.

Zero-based storage indexStored value
0-0.1877117156982422
1-0.15625
20.1318359375
3-0.22247314453125

adapt_stage_1_readout_Mask

Output=2 × Feature=2 · int32 · precision 0 · Actual numeric zero-or-one selectors in row-major W order; integer values select effective gradients, never rescale features.

Zero-based storage indexStored value
01
11
21
31

adapt_stage_1_GradientRowsA

Rank=1 × Feature=2 × Output=2 × ContractionField=3 · float64 · precision 8 · Actual product,oldSum,sum for B-transpose times the same saved G_W; output0 then output1; scale applied only after each contraction.

Zero-based storage indexStored value
0-0.020880407828371972
10
2-0.020880407828371972
3-0.0102996826171875
4-0.020880407828371972
5-0.031180090445559472
6-0.017380714416503906
70
8-0.017380714416503906
90.017380714416503906
10-0.017380714416503906
110

adapt_stage_1_GradientRowsB

Output=2 × Rank=1 × Feature=2 × ContractionField=3 · float64 · precision 8 · Actual product,oldSum,sum for the same saved G_W times A-transpose; feature0 then feature1; scale applied only after each contraction.

Zero-based storage indexStored value
0-0.1877117156982422
10
2-0.1877117156982422
3-0
4-0.1877117156982422
5-0.1877117156982422
60.1318359375
70
80.1318359375
9-0
100.1318359375
110.1318359375

adapt_stage_1_GradientA

Rank=1 × Feature=2 · float64 · precision 8 · Actual scale*(B-transpose G_W), computed entirely from old factors and saved materialized readout errors.

Zero-based storage indexStored value
0-0.031180090445559472
10

adapt_stage_1_GradientB

Output=2 × Rank=1 · float64 · precision 8 · Actual scale*(G_W A-transpose), computed entirely from the same old factors and readout errors.

Zero-based storage indexStored value
0-0.1877117156982422
10.1318359375

adapt_stage_1_Stats

StageField=4 · float64 · precision 8 · Actual adapter losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors.

Zero-based storage indexStored value
00.2024396242632065
10.10121981213160325
21
30

adapt_StageMetrics

Stage=2 × Dataset=2 · float64 · precision 8 · Only actual adapter stages0..updates; independent training and held-out losses.

Zero-based storage indexStored value
00.23650676012039185
10.11825338006019592
20.2024396242632065
30.10121981213160325

adapt_StageA

Stage=2 × Rank=1 × Feature=2 · float64 · precision 8 · Exact copies of evaluated A at each actual adapter stage, including final diagnostic state.

Zero-based storage indexStored value
01
10
21
30

adapt_StageB

Stage=2 × Output=2 × Rank=1 · float64 · precision 8 · Exact copies of evaluated B at each actual adapter stage; both factor histories reflect simultaneous commits.

Zero-based storage indexStored value
00
10
20.111236572265625
3-0.078125

adapt_StageWeights

Stage=2 × Coordinate=4 · float64 · precision 8 · Actual rematerialized effective readout at each stage in row-major 00,01,10,11 order.

Zero-based storage indexStored value
00.2880859375
10
20
30.2880859375
40.399322509765625
50
6-0.078125
70.2880859375

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 learning a LoRA adapter mean in this lab?
2. Fixed case: rank=1, alpha=1, initialization=0, updates=0, η=0.5. What are A, B and BA shapes and the adapter trainable count compared with full 2×2 tuning?
3. Fixed case: rank=1, alpha=1, initialization=0, updates=1, η=0.5. A=[1,0], B=[0,0], G_W=[−3645/16384,−5/32,+5/32,−3645/16384]. Which simultaneous first update and effective W are correct?
4. Current whole saved root: rank=1, alpha=1, initialization=0, updates=1, η=0.5, c=1. ADAPT training mean 0.23650676012039185 → 0.2024396242632065; held-out mean 0.11825338006019592 → 0.10121981213160325. Adapter stages=2, factor coordinate updates=4, total readout stages=5, frames=163. Which reading is justified? Local inspection does not change this case.
5. Fixed comparison: case A rank=2, alpha=1, initialization=0, updates=1, η=0.5; case B rank=2, alpha=2, initialization=0, updates=1, η=0.5. Which statement respects the scale and rank limits?

Exactly five graded questions accompany this lab. Fixed cases name all five raw inputs; the live question uses the whole current root independently of local inspection. Raw edits, reset and trace navigation clear answers; inspection preserves them. The chapter’s Python panels show the actual four-file source closure.

Keep a base, learn an addition

A parameter is a stored model number. A trainable parameter is one the chosen update rule may replace. A frozen base, written W0W_0, is a matrix copied from the earlier training task and kept fixed during adaptation. Frozen does not mean zero: our base has two nonzero diagonal weights. An adapter is the trainable addition to that base.

Low-Rank Adaptation, abbreviated LoRA, represents the addition as a product of two trainable matrices. A factor is one of the matrices in that product. We call the factors AA and BB, and write

c=α/r,D=BA,ΔW=cD,Weff=W0+ΔW.c=\alpha/r,\qquad D=BA,\qquad \Delta W=cD,\qquad W_{\mathrm{eff}}=W_0+\Delta W.

The symbol Δ\Delta means a change; WeffW_{\mathrm{eff}} is the effective matrix used to make predictions. The rank setting rr chooses the number of intermediate coordinates between the two factors. The positive scale setting α\alpha (alpha) and the quotient cc control the addition’s magnitude. Neither setting is learned by gradient descent here.

A shape states the size of each axis. We use column vectors for one sample. For this two-feature, two-output model, the shapes are as follows.

SymbolMeaningShape, rows by columns
ϕ\phiTwo fixed input features[2,1][2,1]
W0W_0Frozen earlier readout[2,2][2,2]
rrOne or two intermediate coordinatesOne integer
AAMaps two features to rr coordinates[r,2][r,2]
BBMaps those rr coordinates to two outputs[2,r][2,r]
D=BAD=BA, ΔW\Delta W, WeffW_{\mathrm{eff}}Product, scaled addition, effective readoutEach [2,2][2,2]
y^=Weffϕ\widehat y=W_{\mathrm{eff}}\phiPredicted output pair[2,1][2,1]
GW,GA,GBG_W,G_A,G_BLoss gradients with respect to the three matrices[2,2][2,2], [r,2][r,2], [2,r][2,r]

The inner dimensions in [2,r][r,2][2,r][r,2] agree, so BABA is legal and has shape [2,2][2,2]. At r=1r=1, reversing the order gives AB:[1,1]AB:[1,1], which cannot be added to the base. A transpose, written with superscript TT, exchanges rows and columns; it does not mean multiplying by another number. A tensor is an array with named axes; these matrices are two-axis tensors.

There is a useful real-arithmetic picture: AA selects combinations of features and BB turns those combinations into output corrections. The specified numerical calculation first constructs all four entries of WeffW_{\mathrm{eff}}, then uses the unchanged IV55 readout. It does not compute a separate B(Aϕ)B(A\phi) shortcut. Equivalent algebra can round differently on a computer.

The complete small task

A sample has one input xx and a target output pair yy. A feature is a number made from the input. Our features are fixed ReLU values,

ϕ(x)=[max⁡(0,x)max⁡(0,−x)].\phi(x)=\begin{bmatrix}\max(0,x)\\\max(0,-x)\end{bmatrix}.

ReLU means keep a positive argument and replace a negative argument with zero. For example, x=−1/2x=-1/2 gives features (0,1/2)T(0,1/2)^T. Only the first feature is active for positive inputs; only the second is active for negative inputs. We call each fixed feature direction with varying nonnegative magnitude a ray. We never train these features.

The earlier PRE task asks the model to copy ϕ\phi. The later ADAPT task asks for y=Tϕy=T\phi, where

T=[11/2−1/21].T=\begin{bmatrix}1&1/2\\-1/2&1\end{bmatrix}.

Thus y0=ϕ++(1/2)ϕ−y_0=\phi_++(1/2)\phi_- and y1=(−1/2)ϕ++ϕ−y_1=(-1/2)\phi_++\phi_-. The subscripts 0 and 1 name output rows. The eight samples, in their declared order, are:

SampleInput xxϕ\phi and PRE targetADAPT target (y0,y1)(y_0,y_1)
Train 0−1-1(0,1)(0,1)(1/2,1)(1/2,1)
Train 1−1/2-1/2(0,1/2)(0,1/2)(1/4,1/2)(1/4,1/2)
Train 21/21/2(1/2,0)(1/2,0)(1/2,−1/4)(1/2,-1/4)
Train 311(1,0)(1,0)(1,−1/2)(1,-1/2)
Held-out 0−3/4-3/4(0,3/4)(0,3/4)(3/8,3/4)(3/8,3/4)
Held-out 1−1/4-1/4(0,1/4)(0,1/4)(1/8,1/4)(1/8,1/4)
Held-out 21/41/4(1/4,0)(1/4,0)(1/4,−1/8)(1/4,-1/8)
Held-out 33/43/4(3/4,0)(3/4,0)(3/4,−3/8)(3/4,-3/8)

The prediction is y^=Wϕ\widehat y=W\phi. Its error is e=y^−ye=\widehat y-y, prediction minus target. A loss is the scalar penalty we seek to reduce. For sample jj, we square each output error, divide each square by 2, and add the halves:

ℓj=ej02/2+ej12/2,Ltrain=(ℓ0+ℓ1+ℓ2+ℓ3)/4.\ell_j=e_{j0}^2/2+e_{j1}^2/2,\qquad L_{\mathrm{train}}=(\ell_0+\ell_1+\ell_2+\ell_3)/4.

The denominator is four samples, not eight scalar outputs. The held-out mean repeats the same calculation on the four held-out samples. Held-out errors do not contribute to a training gradient. This is two-output numerical regression: there are no tokens, probabilities, classification labels or language-model training.

Obtain the frozen base through two real PRE updates

We start PRE with all four weights at positive zero. A gradient is a collection of derivatives: each entry describes how the training loss changes when one parameter changes slightly. Stochastic gradient descent, abbreviated SGD, subtracts learning rate times gradient. The learning rate, written η\eta (eta), is the multiplier controlling the proposed step size. Here every update uses all four training samples, so it is a full-batch update despite the conventional SGD name.

Write W=wIW=wI for these PRE states, where II is the identity matrix, with ones on its diagonal and zeros elsewhere. On either feature ray, the nonzero error is (w−1)v(w-1)v, where v=∣x∣v=|x|. At PRE stage 0, the diagonal-gradient products for the first feature, in training order, are 0,0,−1/4,−10,0,-1/4,-1. Starting at zero, their running sums are 0,0,−1/4,−5/40,0,-1/4,-5/4; dividing by 4 gives −5/16-5/16. For the second feature the products are −1,−1/4,0,0-1,-1/4,0,0, with sums −1,−5/4,−5/4,−5/4-1,-5/4,-5/4,-5/4, giving the same gradient. Both cross-weight gradients are zero.

Each active feature has squared magnitudes 11 and 1/41/4. Its mean square is (1+1/4)/4=5/16(1+1/4)/4=5/16. Therefore each diagonal gradient is (5/16)(w−1)(5/16)(w-1). The fixed PRE rate is 1/21/2:

wp+1=wp−12516(wp−1)=2732wp+532.w_{p+1}=w_p-\tfrac12\tfrac5{16}(w_p-1) =\tfrac{27}{32}w_p+\tfrac5{32}.

The index pp counts completed PRE updates. The first proposal is 0−(1/2)(−5/16)=5/320-(1/2)(-5/16)=5/32. At that state the nonzero unit-input error is −27/32-27/32. The first-feature products are 0,0,−27/128,−27/320,0,-27/128,-27/32; their sum is −135/128-135/128, and dividing by four gives −135/512-135/512. The second-feature products occur in the opposite feature positions and give the same sum. The second proposal is

5/32−(1/2)(−135/512)=160/1024+135/1024=295/1024.5/32-(1/2)(-135/512)=160/1024+135/1024=295/1024.

All four proposals use the same old matrix and are committed together at each update. The frozen base is a copy of the final evaluated PRE matrix,

W0=[295/102400295/1024].W_0=\begin{bmatrix}295/1024&0\\0&295/1024\end{bmatrix}.
PRE stageDiagonal wwDiagonal error magnitude 1−w1-wTraining lossHeld-out lossEach diagonal gradient
000115/165/165/325/32−5/16-5/16
15/325/3227/3227/323645/163843645/163843645/327683645/32768−135/512-135/512
2295/1024295/1024729/1024729/10242657205/167772162657205/167772162657205/335544322657205/33554432−3645/16384-3645/16384

For any row in this table, its sample half-losses in training order are (1−w)2/2(1-w)^2/2, (1−w)2/8(1-w)^2/8, (1−w)2/8(1-w)^2/8, (1−w)2/2(1-w)^2/2. The running sums have multipliers 4,5,6,104,5,6,10 of (1−w)2/8(1-w)^2/8; divide the last by 4. For held-out order the half-losses have multipliers 9,1,1,99,1,1,9 of (1−w)2/32(1-w)^2/32; running multipliers are 9,10,11,209,10,11,20, again divided by 4. The other output half-loss is zero in PRE. These operations give every loss above, rather than treating the base as a hand-set pretrained matrix. The final gradient is diagnostic: it does not cause a third PRE update.

Differentiate the readout before differentiating its factors

Use oo for output row, ii for feature column and jj for sample. In components,

y^jo=Wo0ϕj0+Wo1ϕj1.\widehat y_{jo}=W_{o0}\phi_{j0}+W_{o1}\phi_{j1}.

A partial derivative varies one coordinate while holding the others fixed. For one output half-loss, the derivative of e2/2e^2/2 with respect to ee is ee. Subtracting a fixed target has derivative 1, and differentiating the prediction with respect to WoiW_{oi} gives ϕji\phi_{ji}. The chain rule multiplies these links:

∂ℓj∂Woi=∂ℓj∂ejo∂ejo∂y^jo∂y^jo∂Woi=ejo⋅1⋅ϕji.\frac{\partial\ell_j}{\partial W_{oi}} =\frac{\partial\ell_j}{\partial e_{jo}} \frac{\partial e_{jo}}{\partial\widehat y_{jo}} \frac{\partial\widehat y_{jo}}{\partial W_{oi}} =e_{jo}\cdot1\cdot\phi_{ji}.

Consequently (GW)oi=14∑j=03ejoϕji(G_W)_{oi}=\frac14\sum_{j=0}^3e_{jo}\phi_{ji}. Form each product, add in sample order from positive zero, and divide the sum by 4. This is the readout derivative even though we will update the factors rather than the base.

Let q=729/1024q=729/1024 abbreviate the base’s diagonal shortfall. At ADAPT stage 0, the errors in training order are (−1/2,−q)(-1/2,-q), (−1/4,−q/2)(-1/4,-q/2), (−q/2,1/4)(-q/2,1/4), (−q,1/2)(-q,1/2). They give the following complete four-coordinate contractions.

CoordinateFour products in training orderFour running sumsDivide final sum by 4
W00W_{00}0,0,−q/4,−q0,0,-q/4,-q0,0,−q/4,−5q/40,0,-q/4,-5q/4−5q/16=−3645/16384-5q/16=-3645/16384
W01W_{01}−1/2,−1/8,0,0-1/2,-1/8,0,0−1/2,−5/8,−5/8,−5/8-1/2,-5/8,-5/8,-5/8−5/32-5/32
W10W_{10}0,0,1/8,1/20,0,1/8,1/20,0,1/8,5/80,0,1/8,5/85/325/32
W11W_{11}−q,−q/4,0,0-q,-q/4,0,0−q,−5q/4,−5q/4,−5q/4-q,-5q/4,-5q/4,-5q/4−3645/16384-3645/16384

Apply the component chain rule to A and B

The intermediate index kk runs from 00 through r−1r-1. Each effective weight is

(Weff)oi=(W0)oi+c∑k=0r−1BokAki.(W_{\mathrm{eff}})_{oi}=(W_0)_{oi}+c\sum_{k=0}^{r-1}B_{ok}A_{ki}.

Vary one AkiA_{ki}. It changes the two output rows in column ii, with derivative cBokcB_{ok} in row oo. Add the two loss contributions. Vary one BokB_{ok} instead: it changes both feature columns in output row oo, with derivative cAkicA_{ki} in column ii. Thus

(GA)ki=c(B0k(GW)0i+B1k(GW)1i),(G_A)_{ki}=c\bigl(B_{0k}(G_W)_{0i}+B_{1k}(G_W)_{1i}\bigr), (GB)ok=c((GW)o0Ak0+(GW)o1Ak1).(G_B)_{ok}=c\bigl((G_W)_{o0}A_{k0}+(G_W)_{o1}A_{k1}\bigr).

In matrix notation these are GA=cBTGWG_A=cB^TG_W and GB=cGWATG_B=cG_WA^T. The shapes check: [r,2][2,2]=[r,2][r,2][2,2]=[r,2] and [2,2][2,r]=[2,r][2,2][2,r]=[2,r]. For each coordinate, compute its two products separately, add from positive zero in the displayed order, then multiply the finished contraction by cc. Moving the scale inside a rounded contraction changes the specified numerical program.

Both gradients use the same old AA, BB, materialized WeffW_{\mathrm{eff}} and saved errors. Calculate every ηGA\eta G_A, every proposed A−ηGAA-\eta G_A, then every ηGB\eta G_B and proposed B−ηGBB-\eta G_B, before publishing both factors together. A partially updated BB must never enter the gradient for AA. This is a simultaneous update, not alternating optimization. There is no optimizer proposal for W0W_0.

The complete default first factor step

The default is r=1r=1, α=1\alpha=1, identity-row initialization, one adapter update, η=1/2\eta=1/2. Identity-row initialization means

A=[10],B=[00],c=1.A=[1\quad0],\qquad B=\begin{bmatrix}0\\0\end{bmatrix},\qquad c=1.

Every product in BABA is zero, so D=0D=0, ΔW=0\Delta W=0 and Weff=W0W_{\mathrm{eff}}=W_0 at adapter stage 0. Both AA derivatives contain zero BB. The two BB contractions select the first column of GWG_W:

CoordinateTwo contraction productsRunning sums from zeroGradient after c=1c=1Update amount ηG\eta GProposed value
A00A_{00}0(−3645/16384), 0(5/32)0(-3645/16384),\ 0(5/32)0,00,0000011
A01A_{01}0(−5/32), 0(−3645/16384)0(-5/32),\ 0(-3645/16384)0,00,0000000
B00B_{00}(−3645/16384)1, (−5/32)0(-3645/16384)1,\ (-5/32)0−3645/16384,−3645/16384-3645/16384,-3645/16384−3645/16384-3645/16384−3645/32768-3645/327683645/327683645/32768
B10B_{10}(5/32)1, (−3645/16384)0(5/32)1,\ (-3645/16384)05/32,5/325/32,5/325/325/325/645/64−5/64-5/64

These zeros are exact real values in this hand table; a signed floating zero still has its own stored word. Commit the proposals together. The new AA remains [1,0][1,0], and

B1=[3645/32768−5/64],D1=[(3645/32768)1(3645/32768)0(−5/64)1(−5/64)0].B_1=\begin{bmatrix}3645/32768\\-5/64\end{bmatrix},\quad D_1=\begin{bmatrix}(3645/32768)1&(3645/32768)0\\(-5/64)1&(-5/64)0\end{bmatrix}.

Scale each product by c=1c=1, then add the corresponding base entry. Since 295/1024=9440/32768295/1024=9440/32768, the new upper-left weight is (9440+3645)/32768=13085/32768(9440+3645)/32768=13085/32768. The other three entries give

Weff,1=[13085/327680−5/64295/1024].W_{\mathrm{eff},1}=\begin{bmatrix}13085/32768&0\\-5/64&295/1024\end{bmatrix}.

Only the first feature column moves on this first update. That is a consequence of the chosen initial row of AA; it is not a rule that rank 1 always changes just one column. After BB becomes nonzero, AA can have nonzero gradients too.

Recompute all outputs and both losses

An update is not a new prediction until we evaluate its committed effective matrix. At x=1x=1, the features are (1,0)(1,0). The four forward products after the first default step are (13085/32768)1(13085/32768)1, 0⋅00\cdot0, (−5/64)1(-5/64)1 and (295/1024)0(295/1024)0. Add the two products within each output row to get (13085/32768,−5/64)(13085/32768,-5/64). Subtract target (1,−1/2)(1,-1/2):

e0=−19683/32768,e1=27/64.e_0=-19683/32768,\qquad e_1=27/64.

The squares are 387420489/1073741824387420489/1073741824 and 729/4096729/4096. Divide each by 2, then add using denominator 21474836482147483648:

ℓ(x=1)=3874204892147483648+1911029762147483648=5785234652147483648.\ell(x=1)=\frac{387420489}{2147483648}+\frac{191102976}{2147483648} =\frac{578523465}{2147483648}.

At x=−1x=-1, the four forward products are (13085/32768)0(13085/32768)0, 0⋅10\cdot1, (−5/64)0(-5/64)0 and (295/1024)1(295/1024)1. Predictions remain (0,295/1024)(0,295/1024), errors are (−1/2,−729/1024)(-1/2,-729/1024), and the half-losses are 1/81/8 and 531441/2097152531441/2097152. Their sum is 793585/2097152793585/2097152. Learning on the first feature column has not improved this other ray on the first step.

For every other row, multiply the unit-ray prediction and error by the input magnitude vv; each half-loss is multiplied by v2v^2. To make that accounting explicit, define

N=(1/2)2+(729/1024)2=793585/1048576,N=(1/2)^2+(729/1024)^2=793585/1048576, P=(19683/32768)2+(27/64)2=578523465/1073741824.P=(19683/32768)^2+(27/64)^2=578523465/1073741824.

Here NN and PP abbreviate squared error sums on the negative and positive unit rays; PP is not a PRE update count. The full first-step output table is:

SamplePrediction (y^0,y^1)(\widehat y_0,\widehat y_1)Error (e0,e1)(e_0,e_1)Sample loss
Train 0(0,295/1024)(0,295/1024)(−1/2,−729/1024)(-1/2,-729/1024)N/2N/2
Train 1(0,295/2048)(0,295/2048)(−1/4,−729/2048)(-1/4,-729/2048)N/8N/8
Train 2(13085/65536,−5/128)(13085/65536,-5/128)(−19683/65536,27/128)(-19683/65536,27/128)P/8P/8
Train 3(13085/32768,−5/64)(13085/32768,-5/64)(−19683/32768,27/64)(-19683/32768,27/64)P/2P/2
Held-out 0(0,885/4096)(0,885/4096)(−3/8,−2187/4096)(-3/8,-2187/4096)9N/329N/32
Held-out 1(0,295/4096)(0,295/4096)(−1/8,−729/4096)(-1/8,-729/4096)N/32N/32
Held-out 2(13085/131072,−5/256)(13085/131072,-5/256)(−19683/131072,27/256)(-19683/131072,27/256)P/32P/32
Held-out 3(39255/131072,−15/256)(39255/131072,-15/256)(−59049/131072,81/256)(-59049/131072,81/256)9P/329P/32

On a negative row the two half-losses are v2/8v^2/8 and q2v2/2q^2v^2/2, with q=729/1024q=729/1024. On a positive row they are (19683/32768)2v2/2(19683/32768)^2v^2/2 and (27/64)2v2/2(27/64)^2v^2/2. Thus neither output’s contribution is dropped by the abbreviations NN and PP.

The ordered training running sums are 4N/84N/8, 5N/85N/8, (5N+P)/8(5N+P)/8 and 5(N+P)/85(N+P)/8. Divide the final sum by 4. The held-out running sums are 9N/329N/32, 10N/3210N/32, (10N+P)/32(10N+P)/32 and 10(N+P)/3210(N+P)/32; independently divide that last sum by 4. Hence

Ltrain,1=532(N+P)=695577252534359738368,Lheldout,1=695577252568719476736.L_{\mathrm{train},1}=\frac5{32}(N+P)=\frac{6955772525}{34359738368}, \qquad L_{\mathrm{heldout},1}=\frac{6955772525}{68719476736}.

For comparison, before the adapter step both rays have squared error sum S0=q2+1/4=793585/1048576S_0=q^2+1/4=793585/1048576. The initial training loss is

L0=516S0=396792516777216,Lheldout,0=396792533554432.L_0=\frac5{16}S_0=\frac{3967925}{16777216}, \qquad L_{\mathrm{heldout},0}=\frac{3967925}{33554432}.

The positive-ray error components each shrink by 27/3227/32 on the first default step; the negative-ray components stay unchanged. Therefore P=(729/1024)S0P=(729/1024)S_0, N=S0N=S_0, and

Ltrain,1L0=1+(27/32)22=17532048.\frac{L_{\mathrm{train},1}}{L_0} =\frac{1+(27/32)^2}{2}=\frac{1753}{2048}.

This ratio explains the reduction; the explicit sample calculation explains what was reduced. The fractions are hand-derived expectations, never inputs to replace an actual forward calculation.

A can start learning after B moves

The evaluated stage after a requested update has gradients too. Those are diagnostic gradients: they describe that state and do not request another transition. In the default experiment there is one transition, so stage 1 is final.

Let d=19683/32768d=19683/32768 and t=27/64t=27/64 describe the positive-ray errors after the first step. The four new readout contractions follow the same ordered sample products: W00W_{00} uses 0,0,−d/4,−d0,0,-d/4,-d; W01W_{01} uses −1/2,−1/8,0,0-1/2,-1/8,0,0; W10W_{10} uses 0,0,t/4,t0,0,t/4,t; W11W_{11} uses −q,−q/4,0,0-q,-q/4,0,0. Sum and divide by four to obtain

GW,1=[−98415/524288−5/32135/1024−3645/16384].G_{W,1}=\begin{bmatrix}-98415/524288&-5/32\\135/1024&-3645/16384\end{bmatrix}.

The current AA is still [1,0][1,0], but the current BB is no longer zero. The two products for (GA)00(G_A)_{00} are

(3645/32768)(−98415/524288)=−35872267517179869184,(3645/32768)(-98415/524288)=\frac{-358722675}{17179869184}, (−5/64)(135/1024)=−17694720017179869184.(-5/64)(135/1024)=\frac{-176947200}{17179869184}.

Starting from zero, add the first product and then the second; scaling by c=1c=1 gives −535669875/17179869184-535669875/17179869184. The other AA coordinate has products −18225/1048576-18225/1048576 and +18225/1048576+18225/1048576, whose sum is zero. The BB contractions still select the first column because the old AA remains [1,0][1,0]:

GA,1=[−535669875/171798691840],GB,1=[−98415/524288135/1024].G_{A,1}=[-535669875/17179869184\quad0],\qquad G_{B,1}=\begin{bmatrix}-98415/524288\\135/1024\end{bmatrix}.

If we separately request two updates at the same rate, the next simultaneous proposals use exactly those old factors and gradients:

A2=[1+535669875/343597383680],B2=[215055/1048576−295/2048].A_2=[1+535669875/34359738368\quad0],\qquad B_2=\begin{bmatrix}215055/1048576\\-295/2048\end{bmatrix}.

For example B00B_{00} becomes (116640+98415)/1048576(116640+98415)/1048576, and B10B_{10} becomes −160/2048−135/2048-160/2048-135/2048. Computing a BB gradient from the already proposed A2A_2 would produce a different procedure. These are exact real proposals explaining the update rule; later-stage rounded trajectories require the complete ordered numerical calculation. No later-stage exact finite-difference claim follows from this illustration.

Separate the rank choice from the scale choice

Changing rr changes both factor shapes. If we keep α\alpha fixed, it changes c=α/rc=\alpha/r as well. At identity-row initialization B=0B=0, the first GAG_A is zero, so A1=A0A_1=A_0. Substituting the BB proposal into the addition gives the exact-real identity

ΔW1=−ηc2GWA0TA0.\Delta W_1=-\eta c^2G_W A_0^TA_0.

The scale appears twice: once in the derivative for BB and once when materializing cBAcBA. This is why halving cc quarters this first effective step, rather than merely halving it. The identity describes this initialization and first step; it is not a general later-step learning-rate formula.

With rank 2, A0=IA_0=I and A0TA0=IA_0^TA_0=I. At α=2\alpha=2, c=1c=1, the first BB gradient is the full GWG_W. Its proposal is

B1=[3645/327685/64−5/643645/32768],Weff,1=[13085/327685/64−5/6413085/32768].B_1=\begin{bmatrix}3645/32768&5/64\\-5/64&3645/32768\end{bmatrix},\qquad W_{\mathrm{eff},1}=\begin{bmatrix}13085/32768&5/64\\-5/64&13085/32768\end{bmatrix}.

This matches the previous chapter’s first full fine-tuning update from the same base. Both columns’ error components shrink by 27/3227/32, so the training loss becomes L0(729/1024)L_0(729/1024).

With rank 2 and α=1\alpha=1, c=1/2c=1/2. First contract GWA0T=GWG_WA_0^T=G_W, then scale it by 1/21/2:

GB,0=[−3645/32768−5/645/64−3645/32768].G_{B,0}=\begin{bmatrix}-3645/32768&-5/64\\5/64&-3645/32768\end{bmatrix}.

Multiplying by η=1/2\eta=1/2 and subtracting from zero gives B1B_1 with diagonals 3645/655363645/65536 and cross entries +5/128,−5/128+5/128,-5/128. Materialization multiplies by c=1/2c=1/2 again, giving ΔW1\Delta W_1 with diagonals 3645/1310723645/131072 and cross entries +5/256,−5/256+5/256,-5/256. Adding the frozen base yields

Weff,1=[41405/1310725/256−5/25641405/131072].W_{\mathrm{eff},1}=\begin{bmatrix}41405/131072&5/256\\-5/256&41405/131072\end{bmatrix}.

The remaining diagonal error is 89667/131072=(123/128)q89667/131072=(123/128)q; the cross error magnitude is 123/256=(123/128)(1/2)123/256=(123/128)(1/2). Both columns therefore have residual multiplier 123/128123/128, giving training loss L0(15129/16384)L_0(15129/16384).

Case, all identity-row initialization, one update, η=1/2\eta=1/2Adapter scale ccTraining loss after updateHeld-out loss after update
r=1,α=1r=1,\alpha=1116955772525/343597383686955772525/343597383686955772525/687194767366955772525/68719476736
r=2,α=2r=2,\alpha=2112892617325/171798691842892617325/171798691842892617325/343597383682892617325/34359738368
r=2,α=1r=2,\alpha=11/21/260030737325/27487790694460030737325/27487790694460030737325/54975581388860030737325/549755813888

To recover all predictions for either rank-2 matrix, name its diagonal aa and upper-right entry bb; the lower-left entry is −b-b. Negative input of magnitude vv gives (bv,av)(bv,av) and errors (−(1/2−b)v,−(1−a)v)(-(1/2-b)v,-(1-a)v). Positive input gives (av,−bv)(av,-bv) and errors (−(1−a)v,(1/2−b)v)(-(1-a)v,(1/2-b)v). For each row, square those two errors, halve each square and add. With S=(1−a)2+(1/2−b)2S=(1-a)^2+(1/2-b)^2, the training sample losses are S/2,S/8,S/8,S/2S/2,S/8,S/8,S/2; held-out sample losses are 9S/32,S/32,S/32,9S/329S/32,S/32,S/32,9S/32. This supplies the intermediate readout arithmetic behind the comparison table.

Choosing α=r\alpha=r holds c=1c=1 in the first two cases. Even then rank 1 initially selects the first feature direction while rank 2 selects both. Choosing α=1\alpha=1 in both ranks changes directions and scale, so it cannot isolate a capacity effect. None of these tiny first-step outcomes establishes a universal ordering of ranks or model quality.

Another allowed scale: rank 1 and alpha 2

Here c=2c=2. The first BB gradient is twice its rank-1 default value, giving B1=(3645/16384,−5/32)TB_1=(3645/16384,-5/32)^T. Materializing 2B1A12B_1A_1 and adding the base yields

Weff,1=[6005/81920−5/16295/1024].W_{\mathrm{eff},1}=\begin{bmatrix}6005/8192&0\\-5/16&295/1024\end{bmatrix}.

The first column’s residual multiplier is 3/83/8 and the other column is unchanged. The first training loss is L0[1+(3/8)2]/2=L0(73/128)L_0[1+(3/8)^2]/2=L_0(73/128). A useful exact hand example does not extend a numerical proof’s scope: this case is outside the initial exact finite-difference domain described below.

Why both factors at zero stall

An all-zero addition is useful at initialization: it starts with the same predictions as the prepared base. But there are two ways to obtain it, and they behave differently under factor SGD.

With identity-row AA and zero BB, GA=0G_A=0 while GBG_B can be nonzero, as the default arithmetic showed. If both factors are zero, every product in BTGWB^TG_W and GWATG_WA^T is zero. Both factor gradients are zero even though the readout gradient above is nonzero. Every requested factor proposal retains zero, so recomputing produces the same effective weights, predictions and loss. Repeating the specified update cannot escape that state.

This is a limitation of the factor parameterization at that starting point. In real arithmetic, changing just one zero factor while keeping the other zero leaves BABA unchanged. Changing both factors together could change the product, but the first derivatives used by this optimizer provide no such move. A stationary factor state therefore need not be the best effective matrix.

Count trainables honestly

For an output-by-input matrix W:[m,n]W:[m,n], full adaptation has mnmn trainable coordinates. The factors have rn+mr=r(m+n)rn+mr=r(m+n) trainable coordinates. Here mm means output count and nn means input-feature count; the frozen base still has mnmn stored coordinates.

Two-by-two adaptationTrainable coordinatesFrozen base coordinates retainedBase plus factors stored
Full adaptation of the readout2⋅2=42\cdot2=4No separate frozen copy required by full adaptationFour readout coordinates
Rank 1 adapter1(2+2)=41(2+2)=44488
Rank 2 adapter2(2+2)=82(2+2)=8441212

The toy rank-1 adapter has equal trainable count to full adaptation; rank 2 has more. Its purpose is to make factor learning inspectable. Materialized weights, gradients and saved traces add storage beyond the last column, so these counts are not memory measurements.

A separate analytical example shows why dimensions matter. For a 40964096-by-40964096 matrix and rank 88, full adaptation has 40962=167772164096^2=16777216 trainable coordinates, while the factors have 8(4096+4096)=655368(4096+4096)=65536. The trainable-count ratio is 256256. The base plus factors still contain 1684275216842752 coordinates before gradients or other storage. This is dimensional arithmetic, not measured bytes, speed, optimizer memory, training quality or language-model performance.

Understand what the rank bound says

The rank of a matrix is the number of independent column directions it can produce. In exact real arithmetic every column of BABA is a combination of the rr columns of BB. Scaling those combinations by cc cannot add a new direction. Therefore the structural rank bound is

rank⁡R(cBA)≤r.\operatorname{rank}_{\mathbb R}(cBA)\le r.

The subscript R\mathbb R says to interpret the expression over the real numbers, at the stored factor values. The bound concerns the addition, not the complete matrix W0+cBAW_0+cBA. A rank-1 addition to a full-rank base need not make the effective matrix rank 1. Nor does the setting rr promise achieved rank exactly rr: zero BB gives an addition of rank zero.

A computer stores a finite selection of real numbers. Binary64 is the floating-point representation used here: its ordinary nonzero values have up to 53 significant binary digits. Operations round their real result to a representable number. Separately rounding the entries of cBAcBA can change the exact algebraic rank of the resulting stored matrix. The structural bound must not be relabeled a measured rank of that rounded matrix.

Optional arithmetic counterexample: a rank-1 expression, rounded entries of rank 2

This is a separate hand example, not a point on the current training trajectory. Set ϵ=2−27\epsilon=2^{-27}, c=1c=1, A=[1,1+ϵ]A=[1,1+\epsilon] and B=ATB=A^T. The exact product is

BA=[11+ϵ1+ϵ1+2ϵ+ϵ2].BA=\begin{bmatrix}1&1+\epsilon\\1+\epsilon&1+2\epsilon+\epsilon^2\end{bmatrix}.

Its columns are proportional. A two-by-two determinant is the scalar ad−bcad-bc for entries arranged as [a,b;c,d][a,b;c,d]; it is zero for this exact product. Between 1 and 2, adjacent binary64 values are separated by 2−522^{-52}. The extra ϵ2=2−54\epsilon^2=2^{-54} in the bottom-right product is smaller than half that spacing, so rounding the separate products gives stored entries

M=[11+ϵ1+ϵ1+2ϵ].M=\begin{bmatrix}1&1+\epsilon\\1+\epsilon&1+2\epsilon\end{bmatrix}.

Treat those four stored numbers as exact real numbers. Their determinant is 1+2ϵ−(1+ϵ)2=−ϵ2=−2−541+2\epsilon-(1+\epsilon)^2=-\epsilon^2=-2^{-54}, which is nonzero: that rounded-entry matrix has rank 2. But a naive floating calculation of ad−bcad-bc rounds the second product to 1+2ϵ1+2\epsilon too, then subtracts equal words and reports positive zero. Thus neither the factor count nor a rounded zero determinant certifies the exact rank of the materialized entries. We need no numerical-rank threshold or extra linear-algebra library to understand this distinction.

Use the five actual experiment controls

The lab has four native selection menus and one number input, in the order shown below. A raw edit recomputes the complete PRE and adapter experiment from its starting inputs; it does not continue from a locally inspected factor. The default raw object is rank=1, alpha=1, initialization=0, updates=1, eta=0.5.

Raw fieldAllowed settingDefaultWhat it determines
rankInteger 1 or 21Factor dimensions and c=α/rc=\alpha/r
alphaInteger 1 or 21The numerator of the fixed scale
initializationNumeric 0 or 100: identity rows in AA, zero BB; 1: both zero
updatesInteger 0 through 31Requested adapter transitions after fixed PRE preparation
etaFinite number in [0,2][0,2]0.50.5Adapter learning rate η\eta

The symbol UU denotes the requested adapter update count. There are evaluated stages 00 through UU, including the final diagnostic. With U=0U=0, the initial adapter state is still evaluated and the two PRE updates still prepare the base. With η=0\eta=0, requested operations still form gradients, rate products, proposals and commits; requesting a transition does not guarantee a numerical change. Binary64 positive and negative zero have different stored signs, so word-level evidence must preserve each rather than normalizing every zero in a copy.

The actual raw labels are Adapter rank r (changes actual factor shapes), Alpha α (scale c=α/r), Factor initialization (numeric 0 or 1), Adapter updates U (PRE always has two) and Adapter learning rate η (eta; from 0 to 2). The rank menu names the actual A/B shapes and four or eight trainables. Alpha choices name scales 1/r or 2/r; initialization choices name identity rows with positive-zero B or both factors positive zero; update choices name stage 0 only or one, two or three simultaneous factor updates. Eta is a number input with any numeric step.

A blank, nonfinite or out-of-range number draft shows an alert and removes the computed projection and graded questions until valid. The draft stays visible; it is not silently clamped into a different experiment. Reset example restores all five defaults. Raw edits and reset return the trace to its first frame and clear answers. Previous step, Calculation step and Next step select an already saved operation and also clear answers. Trace selection performs no new optimizer update.

The four additional menus are Adapter stage (inspection only), Sample (inspection only), Factor (inspection only) and Factor coordinate (inspection only). Their stable IDs are IV-56-stage, IV-56-sample, IV-56-factor and IV-56-coordinate. Stage ranges from 0 through U, sample over the eight saved rows, factor over A/B and coordinate from 0 through 2r-1 in row-major order. All four are bounded before selected lookups, so reducing rank or U cannot select a removed entry. Local inspection preserves raw inputs, trace cursor and answers; it reads the saved root without training or regrading another model.

Try default stage 0, B, coordinate 0: the two products use old readout derivatives and old A entries 1 and 0. The contraction finishes before scaling. Switch to stage 1 and A coordinate 0 to see a nonzero diagnostic A gradient after B has moved. This final stage has no next proposal. Changing the raw update count to 2 requests a second transition by restarting the complete experiment.

At eta=+0 or -0 every requested multiplication, subtraction and commit still occurs; equal magnitudes do not imply identical zero signs. A positive rate as small as Number.MIN_VALUE (the smallest positive binary64 value, shown as 5e-324 in feedback) can underflow in a rate product or produce a proposal that rounds back to its old word. Neither positive eta nor a requested update guarantees strict improvement. Both-zero initialization actually stalls despite nonzero G_W. U=0 still prepares the base and fully evaluates stage 0, with no adapter proposal or commit.

Follow the saved evidence from preparation to commit

The PRE: all three actual states and two updates from zero table retains stages 0, 1 and 2. Frozen base: exact PRE2 copy and every selected-stage copy places PRE initialization, final PRE weights, FrozenBase, selected helper Base, effective weights and readout weights side by side. Final PRE, FrozenBase and selected Base agree word for word. Effective weights can differ after adaptation and their readout copy agrees with them. No adapter optimizer receives a base proposal.

Open Every PRE state: complete readout evidence and both simultaneous transitions for all three complete readouts, both seven-column update tables and full-coordinate commits. Within each PRE stage are further disclosures for all eight forwards/losses, all sixteen training gradient contributions and selected sample/means/mask operands. Open the outer PRE disclosure as well as the desired inner disclosure: an open child is still hidden by a closed parent.

The ADAPT trajectory lists all U+1 evaluated effective matrices and independently computed losses. Both complete factor histories, including the final diagnostic state retains every A/B coordinate at every stage. Selected-stage materialization tables show every old B/A operand, separate product, old partial and new partial, then completed BA, scale, delta and base addition. All four materialization operations and once-per-evaluation scale result includes the actual scale output on materialize_0; other coordinates use its saved word.

Readout tables show all eight data rows, predictions and sample losses. Their nested disclosures expose four forward products, two prediction sums, targets, errors, squares and half-losses, all sixteen training error-feature contributions and old/new partials. Both four-sample loss reductions are retained independently. The ADAPT all-one mask means all four effective-weight derivatives G_W are retained; it does not authorize optimizing W0. Only training rows supply G_W, which feeds the factor chain rule.

The selected factor contraction table shows its two operand pairs, products and partials, followed by the completed contraction and post-contraction scaling. Every A and B chain-rule operation, with both old-factor products exposes all coordinates. If another update follows, both factor tables retain old, gradient, delta, proposed, committed, with one pair commit after both complete arrays exist. A committed column copies the later published proposal; no partially updated factor entered a gradient. The final stage explicitly has no proposal or next commit.

Every table has a named keyboard-focusable scrolling region. The Complete saved operation text fallback: every record in trace order exposes all equations, explanations and operands. The house inspector exposes every scalar alias, text field, tensor axis, dtype, precision, provenance and full storage index from the same root. Rendering, keyboard behavior and accessibility require separate verification.

Read WORD and VALUE without losing zero signs

WORD means the exact 64-bit stored number pattern, including the sign of zero. A floating copy must preserve that pattern instead of replacing -0 with +0 merely because they compare equal. VALUE means an abstract integer selector or count, such as a sample index or update count. Its meaning is the integer rather than a floating zero sign. Identity-factor entries are WORD values even when they are 0 or 1; mask entries are VALUE selectors.

All data, features, targets, arithmetic constants, accumulator zeros, eta, scale, losses, base/factor copies, products, partials and proposals have WORD roles. Rank, alpha, initialization, requested-update counts, dimensions, indices and work counts have VALUE roles. Masks are int32 with precision 0. The floating PRE Update table has one VALUE column, enabled; floating Stats tables have two VALUE entries, diagnosticOnly and hasNextUpdate. Their other entries and all factor-update entries are WORD. Floating tensors use float64 with display precision 8. The UI uses round-trip decimals and explicitly shows -0; display precision never feeds computation.

The equations above derive the real chain rule. In numerical source, products, sums and scales round separately: computed floating gradients are rounded chain-rule approximations using saved intermediates, not derivatives of rounding. Arbitrary later gradient words are not promised to equal the exact-real gradient of an ideal wholly unrounded W0+cBA. Only the separately scoped initial V3 argument below can establish exact identity after complete binding.

Use the five questions as one connected check

The lab contains this chapter’s only five graded questions, with immediate corrective explanations. The first asks what stays frozen and what learns. Two fixed cases fully name all five raw inputs and check rank-1 shapes/counts and the simultaneous default first step. The fourth prints the current whole saved root: raw case, initial/final losses, adapter evaluations, coordinate updates, total readout stages and frames. Its feedback distinguishes U=0, signed-zero eta, the smallest positive rate, both-zero stalling and a later nonzero A gradient. Local inspection does not change its case or correct option.

The fifth fully specifies rank-2 first-step cases at alpha 1 and alpha 2 and asks about the quarter-step scale effect and rounded-rank limit. There are always two factor matrices: rank 1 has four factor entries and rank 2 has eight. The hand derivations explain the answers. No second graded question set is added to the manuscript.

Complete saved helper and tensor inventory

The pure evaluateLora helper returns thirteen fields in this order: base, A, B, rank, alpha, scale, product, delta, weights, readout, gradientA, gradientB, tensors. Its nested readout returns eight: weights, predictions, trainHalfMSE, validationHalfMSE, mathematicalGradient, effectiveGradient, mask, tensors. All ten readout tensors also occur in the helper’s combined twenty-one tensors. The public arrays are detached copies: matching words do not imply shared mutable storage. TypeScript freezes snapshots; the Python reference returns mutable detached copies. loraSGD returns A, B, tensors after the simultaneous pair commit.

Below, p means adapt_stage_s for stage s and q means p_readout. Prefix and suffix are joined with an underscore: p_Base at stage 0 is adapt_stage_0_Base. Named axes give the order of row-major storage. Dataset order is training then validation; readout coordinate order is 00,01,10,11.

Order / tensorShapeNamed axesSaved evidence
1 p_Base[2,2]Output, FeatureFrozen input words
2 p_A[r,2]Rank, FeatureSame old A
3 p_B[2,r]Output, RankSame old B
4 p_ProductRows[2,2,r,3]Output, Feature, Rank, ContractionFieldproduct, oldSum, sum for every BA term
5 p_Product[2,2]Output, FeatureCompleted rounded BA
6 p_Delta[2,2]Output, FeatureScale times completed BA
7 p_Weights[2,2]Output, FeatureBase plus delta before readout
8 q_Weights[2,2]Output, FeatureDetached materialized weight copy
9 q_Predictions[8,2]Sample, OutputTwo predictions per sample
10 q_Forward[8,6]Sample, ForwardFieldproduct00, product01, product10, product11, prediction0, prediction1
11 q_Loss[8,9]Sample, LossFieldtarget0, target1, error0, error1, square0, square1, half0, half1, sampleLoss
12 q_Reductions[2,4,3]Dataset, DatasetSample, ReductionFieldloss, oldSum, sum for both ordered reductions
13 q_Means[2]DatasetIndependently evaluated training and validation means
14 q_GradientRows[4,4,5]Coordinate, TrainSample, GradientRowFielderror, feature, contribution, oldSum, sum
15 q_MathematicalGradient[2,2]Output, FeatureFour same-state training derivatives G_W
16 q_EffectiveGradient[2,2]Output, FeatureDerivatives retained under the all-one mask
17 q_Mask[2,2]Output, FeatureInteger all-one selectors
18 p_GradientRowsA[r,2,2,3]Rank, Feature, Output, ContractionFieldOld-B/G_W product, oldSum, sum
19 p_GradientRowsB[2,r,2,3]Output, Rank, Feature, ContractionFieldG_W/old-A product, oldSum, sum
20 p_GradientA[r,2]Rank, FeatureA contractions scaled after both terms
21 p_GradientB[2,r]Output, RankB contractions scaled after both terms

Each PRE evaluation has the same ten readout tensors with q=pre_stage_s and PRE targets. The wrapper retains the following additional tensors around those evaluations. Transition number t begins at 1. All stage statistics use trainHalfMSE, validationHalfMSE, diagnosticOnly, hasNextUpdate order.

Tensor or familyShape / axesInsertion and content
Data[8,7] / Sample, DataFieldFirst: x, phiPlus, phiMinus, preTarget0, preTarget1, adaptTarget0, adaptTarget1
pre_InitialWeights[2,2] / Output, FeatureFour authored positive zeros
pre_stage_s_Stats[4] / StageFieldAfter each of the three PRE readouts
pre_update_t_Update[4,7] / Coordinate, UpdateFieldAfter PRE stages 0 and 1: old, mathematical, effective, enabled, delta, proposed, committed
pre_StageMetrics[3,2] / Stage, DatasetAll actual PRE means
pre_StageWeights[3,4] / Stage, CoordinateAll actual PRE weights
FrozenBase[2,2] / Output, FeatureCopy of final evaluated PRE2 weights
adapt_InitialA[r,2] / Rank, FeatureActual selected initial A
adapt_InitialB[2,r] / Output, RankPositive-zero B
adapt_stage_s_Stats[4] / StageFieldAfter each 21-tensor adapter evaluation
adapt_update_t_UpdateA[r,2,5] / Rank, Feature, FactorUpdateFieldBefore the next stage: old, gradient, delta, proposed, committed
adapt_update_t_UpdateB[2,r,5] / Output, Rank, FactorUpdateFieldImmediately after UpdateA, same field order
adapt_StageMetrics[U+1,2] / Stage, DatasetFinal trajectory group begins with both actual means
adapt_StageA[U+1,r,2] / Stage, Rank, FeatureEvery evaluated A word
adapt_StageB[U+1,2,r] / Stage, Output, RankEvery evaluated B word
adapt_StageWeights[U+1,4] / Stage, CoordinateEvery rematerialized effective matrix

Each tensor has exactly id, shape, axes, dtype, values, provenance, precision. Each trace frame has id, label, equation, explanation, inputs, outputs. A successful root has status, outputs, steps, tensors, texts; a known-fault root has status, code, reason. Every tensor’s full provenance text and stored values remain available in the house inspector.

The raw boundary requires a complete ordinary or null-prototype own-data object with exactly the five raw fields: no missing fields, extras, getters or coercion. It captures all field descriptors, then validates all five actual finite numbers before any raw domain. Pure helpers differ because rank determines array sizes: finite rank and its 1-or-2 domain come first, then every dependent array’s shape/descriptors, then all array numbers and alpha or eta as finite, then the alpha/eta policy and prefix guard. No U=0 or both-zero branch bypasses validation. Ambient finite helper inputs are allowed; the caller supplies coherent features/targets and gradients. Unknown programming, reflection or observer failures propagate rather than becoming fabricated numerical answers.

Source-derived counts: what the summaries count

The whole-root table retains 76 summary fields, including 43 WORK counts; the record also has 38 text fields, comprising 20 strings and 18 arrays. Its first four summaries are adaptValidationLoss, adaptTrainLoss, adapterTrainableParameters, structuralRankBound. They describe final whole-root results independently of local inspection. Base and final effective-weight summaries copy actual evaluated tensors. After the 76 summaries, every saved step output is copied exactly once as an alias named stepID_outputKey, in trace order and then output insertion order. Inputs are not automatically aliased; copies inherit the original WORD or VALUE role.

With rank r and U requested adapter updates, the current source has 122+4r+U(29+8r) frames, 68+24U tensors and 892+36r+U(171+48r) total scalar outputs including summaries. Step-output aliases alone number 816+36r+U(171+48r). These are manual counts of authored loops and keys, not generated runtime records.

rUFramesTensorsStep-output aliasesTotal outputs
1012668852928
11, default1639210711147
1220011612901366
1323714015091585
2013068888964
211759211551231
2222011614221498
2326514016891765

Alpha, initialization and eta do not change these counts. U+4 readout evaluations each perform eight sample forwards/losses and sixteen training error-feature products. Each adapter evaluation forms four rank-length BA contractions and 4r two-term factor contractions. scaleDivisions counts one wrapper coefficient and one coefficient per adapter evaluation, including the final diagnostic. gradientRowContributions counts four training rows per readout batch; readoutGradientProducts counts all sixteen coordinate-by-row products. Requested transitions alone add coordinate proposals and commits; final evaluations add diagnostic arithmetic without an extra update.

Counts do not measure elapsed time, storage bytes or model quality. The current maximum is 265 frames, 140 tensors and 1765 outputs. Axis and tensor-cell maxima are 9 and 80, within the separate axis-64, tensor-4096-cell and trace-512-frame bounds. There is no total tensor-count cap.

Optional: what a narrowly scoped derivative check can prove

A central finite difference perturbs one factor coordinate θ\theta by +h+h and −h-h, evaluates both complete losses and forms [L(θ+h)−L(θ−h)]/(2h)[L(\theta+h)-L(\theta-h)]/(2h). This approximates the local derivative in general. With the other factor fixed, our real-arithmetic loss is a quadratic function of one coordinate, so the real central-difference truncation error is zero. Rounded computations still need a separate operation-by-operation argument.

The signed prior exactness scope is only adapter stage 0, identity-row initialization, eta positive 1/21/2, h=2−12h=2^{-12}, and (r,α)=(1,1),(2,1),(2,2)(r,\alpha)=(1,1),(2,1),(2,2). A root requesting any UU from 0 to 3 can supply that initial stage. Every AA and BB coordinate is included. At an AA endpoint, the parameter words differ but BB remains zero, so the losses intentionally coincide. At a BB endpoint the selected effective entry moves by ±ch\pm ch, and the losses differ. Distinct losses are required only on that nonflat branch.

The prior proof bounds the integer numerators for ordered endpoint loss operations below 2362^{36} and those for factor-gradient operations below 2342^{34}. These need at most 36 and 34 significant bits respectively, within binary64’s 53 significant bits. Those bounds depend on the prepared base, fixed data, selected scale, initialization and operation order. The actual complete central record and complete endpoint helper returns must be bound before any zero-error verdict. A matching pair of supplied scalar losses is insufficient. The proof alone does not establish such a check result.

The case r=1,α=2r=1,\alpha=2, both-zero initialization, other rates and later stages are outside that zero-error scope. Their rounded calculations still require complete evidence; the coordinate-wise quadratic observation does not grant them an exact numerical finite-difference verdict. The equations differentiate the underlying real expression. Computed gradients approximate that chain rule through separately rounded operations on saved intermediates; they are not derivatives of rounding or a promise of exact ideal-gradient words at arbitrary later states.

What the held-out result does and does not establish

In real arithmetic a fixed effective matrix has error proportional to ∣x∣|x| on each of these two feature rays. Loss is proportional to x2x^2. The training magnitudes have squared sum 1+1/41+1/4 on each ray; the held-out magnitudes have squared sum 9/16+1/169/16+1/16, exactly half as much. This explains why the held-out mean is half the training mean in the hand calculations. The numerical mechanism must nevertheless calculate both means from their own samples, not manufacture validation by halving training loss.

The held-out points test new magnitudes on the same authored rays. They do not establish population generalization, robustness to a new feature direction, production language-model ability, safety or alignment. Full adaptation, rank and scale comparisons here concern a fixed two-output regression task, a particular base and particular initial factors. Smaller trainable count in a different dimensional example would not establish any of those wider claims either.

Python from the actual four-file project

The following four panels display the complete actual files, including comments, metadata and check declarations, in dependency order: transfer_reference.py, iv55.py, lora_reference.py, iv56.py. Each panel imports the repository file as raw text. Nothing is replaced with pseudocode, omitted branches or an ellipsis. Keep all four files adjacent for later use. Python’s standard library and NumPy are external runtime dependencies; they are not hidden fifth project files. Displaying source alone does not establish import, calculation, self-check, parity or rendering results.

NumPy stores shaped arrays, while explicit Python float products, additions, subtractions and divisions implement the declared arithmetic. A list is an ordered collection of values; a dictionary gives names to values. A slice such as A[:] copies a list. deepcopy also detaches nested lists and dictionaries, so changing one returned record cannot change another saved copy. float selects the floating arithmetic role; integer indices and counts stay integers. All numerical primitives round separately and check finiteness. The saved gradients therefore have the rounded-chain-rule meaning explained above.

1. transfer_reference.py: the reused scalar readout

fixed_data() creates the eight-by-seven data and retains each feature/target construction operand. _evaluate stores a two-by-two matrix and explicitly forms all four weight-feature products before the two output sums for each sample. _losses saves both errors, squares, halves and their sum. _mean starts at floating +0 and retains every old/new sum before dividing by four. The same evaluator then forms all four training error-feature contractions, each with four ordered contributions and a final division. Only afterward does it select effective derivatives from the mask.

evaluate_transfer is the guarded ambient-data entry point. _sgd calculates all four old-state proposals before publishing the conditional commits; transfer_sgd also checks shape, finite values, mask/eta policy and WORD consistency of effective gradients. These are the actual mechanisms reused for both PRE transitions and every effective-matrix readout. PRE enables every readout coordinate. During ADAPT the all-one readout mask supplies G_W to the factor chain rule, not an instruction to update W0.

The complete old file also contains _memorize, memorize_transfer, _cohort and its old mechanics_experiment. Those definitions support the previous chapter. IV56 does not call the old whole experiment, fresh ADAPT comparison or memorizer. Showing their source honestly does not add their work to this run.

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.

"""IV55 canonical scalar mechanisms — SOURCE ONLY, ALL EXECUTION UNRUN.

The independent numerical FIRST is retained; the owner-adopted public inventory
is bound by adjacent iv55.py. NumPy stores arrays; Python float primitives do
all arithmetic in declared order, without BLAS, reductions or implicit checks.
"""
from copy import deepcopy
import math
import struct
import sys
from types import MappingProxyType

import numpy as np

RAW_KEYS = ("preUpdates", "updates", "scope", "eta")
DEFAULT_IV55 = MappingProxyType(dict(preUpdates=2, updates=1, scope=0, eta=0.5))


class NumericalFault(ValueError):
    """Only known input/numerical faults become public unavailable records."""

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


def _number(value, label):
    # Arbitrary-size ints are finite; inspect domains before converting to float.
    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):
    """Capture exact dict data, check ALL finite types, then policy domains."""
    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 preUpdates, updates, scope, eta as own fields.")
    saved = {key: value[key] for key in RAW_KEYS}
    for key in RAW_KEYS:
        _number(saved[key], key)
    for key in RAW_KEYS[:2]:
        if not 0 <= saved[key] <= 3 or int(saved[key]) != saved[key]:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer from 0 to 3.")
    if saved["scope"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "scope must be numeric 0 or 1.")
    if not 0.0 <= saved["eta"] <= 2.0:
        raise NumericalFault("INVALID_INPUT", "eta must be between 0 and 2.")
    return dict(preUpdates=int(saved["preUpdates"]), updates=int(saved["updates"]),
                scope=int(saved["scope"]), eta=float(saved["eta"]))


def _vector(value, size, label):
    """Capture every shape before any number or domain consumption."""
    if type(value) is not list:
        raise NumericalFault("INVALID_INPUT", f"{label} must be a dense ordinary array.")
    if len(value) != size:
        raise NumericalFault("SHAPE_MISMATCH", f"{label} requires exactly {size} entries.")
    return value[:]


def _data(value):
    return [_vector(row, 7, f"data[{i}]") for i, row in enumerate(_vector(value, 8, "data"))]


def _numbers(groups):
    for label, values in groups:
        for i, value in enumerate(values):
            _number(value, f"{label}[{i}]")


def _binary64(groups):
    for label, values in groups:
        for value in values:
            if not -sys.float_info.max <= value <= sys.float_info.max:
                raise NumericalFault("NONFINITE", f"{label} requires representable finite binary64 values.")
    return [[float(value) for value in values] for _, values in groups]


def _mask(values):
    for i, value in enumerate(values):
        if value not in (0, 1):
            raise NumericalFault("INVALID_INPUT", f"mask[{i}] must be numeric 0 or 1.")
    return [int(value) for value in values]


def _word(value):
    return struct.pack(">d", value)


def fixed_data():
    """Prepare the fixed features and both target pairs once, before cohorts."""
    xs = np.array([-1.0, -0.5, 0.5, 1.0, -0.75, -0.25, 0.25, 0.75], dtype=np.float64)
    matrix = np.empty((8, 7), dtype=np.float64)
    construction = []
    for i in range(8):
        x = float(xs[i])
        negative = _finite(-x, "negated x")
        plus, minus = max(0.0, x), max(0.0, negative)
        scaled_minus = _finite(0.5 * minus, "scaled negative feature")
        adapt0 = _finite(plus + scaled_minus, "adaptation target 0")
        scaled_plus = _finite(-0.5 * plus, "scaled positive feature")
        adapt1 = _finite(scaled_plus + minus, "adaptation target 1")
        matrix[i] = [x, plus, minus, plus, minus, adapt0, adapt1]
        construction.append(dict(x=x, negativeX=negative, zero=0.0,
                                 phiPlus=plus, phiMinus=minus, preTarget0=plus,
                                 preTarget1=minus, positiveScale=0.5, negativeScale=-0.5,
                                 scaledMinus=scaled_minus, adaptTarget0=adapt0,
                                 scaledPlus=scaled_plus, adaptTarget1=adapt1))
    return dict(data=matrix.tolist(), construction=construction)


def _mean(values):
    total, additions = 0.0, []
    for i, value in enumerate(values):
        old = total
        total = _finite(old + value, "dataset loss sum")
        additions.append(dict(index=i, old=old, value=value, total=total))
    mean = _finite(total / 4.0, "dataset mean")
    return dict(initialSum=0.0, additions=additions, sum=total, divisor=4.0, mean=mean)


def _losses(predictions, data, task):
    rows = []
    target_start = 3 if task == 0 else 5
    for i in range(8):
        p0, p1 = predictions[2 * i:2 * i + 2]
        t0, t1 = data[i][target_start:target_start + 2]
        e0 = _finite(p0 - t0, "output 0 error")
        e1 = _finite(p1 - t1, "output 1 error")
        s0 = _finite(e0 * e0, "output 0 square")
        s1 = _finite(e1 * e1, "output 1 square")
        h0 = _finite(s0 / 2.0, "output 0 half-loss")
        h1 = _finite(s1 / 2.0, "output 1 half-loss")
        sample_loss = _finite(h0 + h1, "sample loss")
        components = [dict(prediction=p0, target=t0, error=e0, square=s0, divisor=2.0, half=h0),
                      dict(prediction=p1, target=t1, error=e1, square=s1, divisor=2.0, half=h1)]
        rows.append(dict(components=components, sampleLoss=sample_loss))
    # Both datasets independently reduce four SAVED sums of two output halves.
    train = _mean([rows[i]["sampleLoss"] for i in range(4)])
    validation = _mean([rows[i]["sampleLoss"] for i in range(4, 8)])
    return dict(rows=rows, train=train, validation=validation)


def _evaluate(weights, data, task, mask):
    """Scalar W:[2,2] times phi:[2,1]; batch storage uses explicit row samples."""
    stored = np.array(weights, dtype=np.float64).reshape((2, 2))
    features = np.array([[row[1], row[2]] for row in data], dtype=np.float64)
    predictions, forwards = [], []
    for i in range(8):
        products = []
        for o in range(2):
            for feature in range(2):
                left, right = float(stored[o, feature]), float(features[i, feature])
                product = _finite(left * right, f"forward product {o}{feature}")
                products.append(dict(weight=left, feature=right, product=product))
        # All four products precede the two sums, just as in the adopted source.
        prediction0 = _finite(products[0]["product"] + products[1]["product"], "prediction 0")
        prediction1 = _finite(products[2]["product"] + products[3]["product"], "prediction 1")
        values = [prediction0, prediction1]
        predictions.extend(values)
        forwards.append(dict(products=products, predictions=values))
    losses = _losses(predictions, data, task)
    mathematical, effective, gradients = [], [], []
    for o in range(2):
        for feature in range(2):
            total, contributions = 0.0, []
            for i in range(4):
                error = losses["rows"][i]["components"][o]["error"]
                phi = float(features[i, feature])
                product = _finite(error * phi, "gradient contribution")
                old = total
                total = _finite(old + product, "gradient sum")
                contributions.append(dict(sample=i, error=error, feature=phi, product=product,
                                          old=old, total=total))
            gradient = _finite(total / 4.0, "mathematical gradient")
            mathematical.append(gradient)
            gradients.append(dict(initialSum=0.0, contributions=contributions,
                                  sum=total, divisor=4.0, mathematical=gradient))
    # Mathematical contractions complete before the conditional optimizer mask.
    for i, gradient in enumerate(gradients):
        used = mathematical[i] if mask[i] else 0.0
        effective.append(used)
        gradient.update(enabled=mask[i], effective=used)
    return dict(weights=weights[:], task=task, mask=mask[:], forwards=forwards,
                predictions=predictions, losses=losses, gradients=gradients,
                trainHalfMSE=losses["train"]["mean"],
                validationHalfMSE=losses["validation"]["mean"],
                mathematicalGradient=mathematical, effectiveGradient=effective)


def evaluate_transfer(weights_value, data_value, task_value, mask_value):
    """Accept ambient finite arrays; numerical coherence remains caller-owned."""
    weights = _vector(weights_value, 4, "weights")
    data = _data(data_value)
    mask = _vector(mask_value, 4, "mask")
    groups = [("weights", weights), *[(f"data[{i}]", row) for i, row in enumerate(data)],
              ("task", [task_value]), ("mask", mask)]
    _numbers(groups)
    if task_value not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "task must be numeric 0 or 1.")
    mask = _mask(mask)
    converted = _binary64(groups)
    return _evaluate(converted[0], converted[1:9], int(task_value), mask)


def _sgd(weights, mathematical, effective, mask, eta):
    rows, proposals = [], []
    for i in range(4):
        delta = _finite(eta * effective[i], "SGD delta")
        proposed = _finite(weights[i] - delta, "SGD proposed")
        proposals.append(proposed)
        rows.append(dict(old=weights[i], mathematical=mathematical[i],
                         effective=effective[i], enabled=mask[i], eta=eta,
                         delta=delta, proposed=proposed))
    # All proposals precede publication. A frozen coordinate copies its OLD WORD.
    committed = [proposals[i] if mask[i] else weights[i] for i in range(4)]
    for i in range(4):
        rows[i]["committed"] = committed[i]
    return dict(weights=committed, coordinates=rows)


def transfer_sgd(weights_value, mathematical_value, effective_value, mask_value, eta_value):
    weights = _vector(weights_value, 4, "weights")
    mathematical = _vector(mathematical_value, 4, "mathematical")
    effective = _vector(effective_value, 4, "effective")
    mask = _vector(mask_value, 4, "mask")
    groups = [("weights", weights), ("mathematical", mathematical), ("effective", effective),
              ("mask", mask), ("eta", [eta_value])]
    _numbers(groups)
    mask = _mask(mask)
    if not 0.0 <= eta_value <= 2.0:
        raise NumericalFault("INVALID_INPUT", "eta must be between 0 and 2.")
    weights, mathematical, effective, _, eta = _binary64(groups)
    eta = eta[0]
    for i in range(4):
        expected = mathematical[i] if mask[i] else 0.0
        if _word(effective[i]) != _word(expected):
            raise NumericalFault("INVALID_INPUT", f"effective[{i}] must match the conditional mathematical gradient.")
    return _sgd(weights, mathematical, effective, mask, eta)


def _memorize(data, prepared_predictions):
    # The actual dictionary has x,target0,target1 columns, hence physical stride3.
    dictionary = [[data[i][0], data[i][5], data[i][6]] for i in range(4)]
    keys = [row[0] for row in dictionary]
    targets = [row[1:3] for row in dictionary]
    predictions, matches, selections = [], [], []
    for i in range(8):
        comparisons, first = [], -1
        for k in range(4):
            equal = data[i][0] == dictionary[k][0]
            old = first
            if equal and first == -1:
                first = k
            comparisons.append(dict(keyIndex=k, x=data[i][0], key=dictionary[k][0],
                                    equal=int(equal), oldMatch=old, match=first))
        kind, source_row = (0, first) if first >= 0 else (1, i)
        index0 = 3 * first + 1 if first >= 0 else 2 * i
        source = dictionary[first][1:3] if first >= 0 else prepared_predictions[2 * i:2 * i + 2]
        predictions.extend(source)
        matches.append(first)
        selections.append(dict(sample=i, comparisons=comparisons, match=first,
                               dictionary=int(first >= 0), sourceRow=source_row,
                               sourceKind=kind, sourceIndex0=index0, sourceIndex1=index0 + 1,
                               sourceValues=source[:], prediction=source[:]))
    losses = _losses(predictions, data, 1)
    return dict(keys=keys, targets=targets, dictionary=dictionary,
                preparedPredictions=prepared_predictions[:], predictions=predictions,
                matches=matches, selections=selections, losses=losses,
                trainHalfMSE=losses["train"]["mean"], validationHalfMSE=losses["validation"]["mean"])


def memorize_transfer(data_value, prepared_predictions_value):
    data = _data(data_value)
    predictions = _vector(prepared_predictions_value, 16, "preparedPredictions")
    groups = [*[(f"data[{i}]", row) for i, row in enumerate(data)], ("preparedPredictions", predictions)]
    _numbers(groups)
    converted = _binary64(groups)
    return _memorize(converted[:8], converted[8])


def _cohort(start, data, task, mask, updates, eta):
    stages, transitions, weights = [], [], start[:]
    for stage in range(updates + 1):
        evaluated = _evaluate(weights, data, task, mask)
        evaluated["stage"] = stage
        evaluated["diagnosticOnly"] = int(stage == updates)
        stages.append(evaluated)
        if stage < updates:
            transition = _sgd(weights, evaluated["mathematicalGradient"], evaluated["effectiveGradient"], mask, eta)
            transitions.append(transition)
            weights = transition["weights"][:]
    return dict(initialWeights=start[:], task=task, mask=mask[:], eta=eta,
                stages=stages, transitions=transitions)


def mechanics_experiment(value):
    """Real PRE, copied-prepared ADAPT, fresh ADAPT and saved-prediction lookup."""
    state = raw_state(value)
    prepared_data = fixed_data()
    data = prepared_data["data"]
    pre = _cohort([0.0, 0.0, 0.0, 0.0], data, 0, [1, 1, 1, 1], state["preUpdates"], 0.5)
    pre_final = pre["stages"][-1]
    copied = pre_final["weights"][:]
    mask = [1, 1, 1, 1] if state["scope"] == 0 else [1, 0, 0, 1]
    prepared = _cohort(copied, data, 1, mask, state["updates"], state["eta"])
    fresh = _cohort([0.0, 0.0, 0.0, 0.0], data, 1, mask, state["updates"], state["eta"])
    memorizer = _memorize(data, pre_final["predictions"])
    return deepcopy(dict(state=state, data=data, construction=prepared_data["construction"],
                         preparedCopy=dict(sourceWeights=pre_final["weights"][:], weights=copied[:]),
                         pre=pre, prepared=prepared, fresh=fresh, memorizer=memorizer))

2. iv55.py: reused readout serializers and declaration identity

This file loads its adjacent mechanism from its own resolved file path. It exposes the same actual NumericalFault class and fixed_data, evaluate_transfer and transfer_sgd functions. A class is the named type used here to distinguish a known numerical failure from an unexpected programming failure. Reusing its identity ensures that a fault raised by the reused readout is recognized by the IV56 wrapper.

_loss_records, _evaluation_records and _update_records project retained operations into named steps and tensors. They do not redo numerical contractions. IV56 reuses these serializers for the unchanged readout and PRE transitions, plus the unchanged data-construction prose. It supplies its own setup, PRE initialization and Stats, adapter metadata, trajectories and finish. It does not substitute the old _cohort_records, whose whole-cohort keys and prose differ from IV56.

The file also contains the previous chapter’s public derivation, memorizer projection, CLI and eight-terminal self-check aggregator. Importing its definitions does not execute the guarded __main__ block. Neither the new ordinary query nor the new nine-terminal aggregator calls that old task-check aggregator. The shared strict_json parser rejects duplicate keys, nonstandard NaN/Infinity constants and malformed/trailing JSON, and retains a literal JSON integer token -0 as floating negative zero.

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.

"""IV55 complete canonical public record — SOURCE ONLY, ALL EXECUTION UNRUN.

Adjacent NumPy storage and scalar mechanisms supply actual retained operands.
This file binds the owner-adopted ordered root, steps, aliases, tensors and texts.
Project closure: exactly iv55.py and adjacent transfer_reference.py.
Import and ordinary queries never run self-checks; explicit --self-check does.
"""
import importlib.util
from pathlib import Path

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

DEFAULT_IV55 = _reference.DEFAULT_IV55
NumericalFault = _reference.NumericalFault
raw_state = _reference.raw_state
fixed_data = _reference.fixed_data
evaluate_transfer = _reference.evaluate_transfer
transfer_sgd = _reference.transfer_sgd
memorize_transfer = _reference.memorize_transfer
mechanics_experiment = _reference.mechanics_experiment


def _same_words(actual, expected):
    assert len(actual) == len(expected)
    for left, right in zip(actual, expected):
        assert type(left) is float and type(right) is float
        assert _reference._word(left) == _reference._word(right)


def _expect_fault(code, operation, *args):
    try:
        operation(*args)
    except NumericalFault as fault:
        assert fault.code == code
    else:
        raise AssertionError(f"Expected {code}")


def check_raw_guards():
    """Finite-before-domain precedence, bool rejection and inactive raw controls."""
    default = dict(DEFAULT_IV55)
    assert tuple(raw_state(default)) == ("preUpdates", "updates", "scope", "eta")
    for bad in (None, [], (), {**default, "extra": 0}, {key: default[key] for key in default if key != "eta"}):
        _expect_fault("INVALID_INPUT", raw_state, bad)
    class DictSubclass(dict):
        pass
    _expect_fault("INVALID_INPUT", raw_state, DictSubclass(default))
    for key in default:
        for bad in (True, False, None, "0", float("nan"), float("inf"), -float("inf")):
            _expect_fault("NONFINITE", raw_state, {**default, key: bad})
        _expect_fault("INVALID_INPUT", raw_state, {**default, key: 10 ** 400})
    for key in ("preUpdates", "updates"):
        for bad in (-1, 4, 0.5):
            _expect_fault("INVALID_INPUT", raw_state, {**default, key: bad})
    for key, bad in (("scope", 2), ("eta", -0.5), ("eta", 2.5)):
        _expect_fault("INVALID_INPUT", raw_state, {**default, key: bad})
    # A late nonfinite wins over an earlier finite-domain defect (even huge int).
    for bad in (4, 10 ** 400):
        _expect_fault("NONFINITE", raw_state, {**default, "preUpdates": bad, "eta": float("nan")})
    _expect_fault("INVALID_INPUT", raw_state, dict(preUpdates=0, updates=0, scope=0, eta=3.0))
    negative_zero = raw_state(dict(preUpdates=0, updates=0, scope=1, eta=-0.0))
    _same_words([negative_zero["eta"]], [-0.0])
    for p in range(4):
        for u in range(4):
            for scope in (0, 1):
                for eta in (0.0, -0.0, 0.5, 2.0):
                    state = raw_state(dict(preUpdates=p, updates=u, scope=scope, eta=eta))
                    assert state["preUpdates"] == p and state["updates"] == u and state["scope"] == scope
                    _same_words([state["eta"]], [eta])


def check_hand_anchors():
    """Literal dyadic expectations derived on paper, never fed to the mechanism."""
    result = mechanics_experiment(dict(DEFAULT_IV55))
    assert result["data"] == [
        [-1.0, 0.0, 1.0, 0.0, 1.0, 0.5, 1.0],
        [-0.5, 0.0, 0.5, 0.0, 0.5, 0.25, 0.5],
        [0.5, 0.5, 0.0, 0.5, 0.0, 0.5, -0.25],
        [1.0, 1.0, 0.0, 1.0, 0.0, 1.0, -0.5],
        [-0.75, 0.0, 0.75, 0.0, 0.75, 0.375, 0.75],
        [-0.25, 0.0, 0.25, 0.0, 0.25, 0.125, 0.25],
        [0.25, 0.25, 0.0, 0.25, 0.0, 0.25, -0.125],
        [0.75, 0.75, 0.0, 0.75, 0.0, 0.75, -0.375],
    ]
    pre = result["pre"]["stages"]
    for stage, diagonal in zip(pre, (0.0, 5.0 / 32.0, 295.0 / 1024.0)):
        _same_words(stage["weights"], [diagonal, 0.0, 0.0, diagonal])
    assert pre[0]["trainHalfMSE"] == 5.0 / 16.0
    assert pre[1]["trainHalfMSE"] == 3645.0 / 16384.0
    assert pre[2]["trainHalfMSE"] == 2657205.0 / 16777216.0
    prepared = result["prepared"]["stages"]
    _same_words(prepared[0]["mathematicalGradient"],
                [-3645.0 / 16384.0, -5.0 / 32.0, 5.0 / 32.0, -3645.0 / 16384.0])
    _same_words(prepared[1]["weights"],
                [13085.0 / 32768.0, 5.0 / 64.0, -5.0 / 64.0, 13085.0 / 32768.0])
    _same_words([row["product"] for row in prepared[0]["gradients"][0]["contributions"]],
                [-0.0, -0.0, -729.0 / 4096.0, -729.0 / 1024.0])
    assert prepared[0]["trainHalfMSE"] == 3967925.0 / 16777216.0
    assert prepared[1]["trainHalfMSE"] == 2892617325.0 / 17179869184.0
    assert prepared[1]["validationHalfMSE"] == 2892617325.0 / 34359738368.0
    fresh = result["fresh"]["stages"]
    assert fresh[0]["trainHalfMSE"] == 25.0 / 64.0
    _same_words(fresh[1]["weights"], [5.0 / 32.0, 5.0 / 64.0, -5.0 / 64.0, 5.0 / 32.0])
    assert fresh[1]["trainHalfMSE"] == 18225.0 / 65536.0
    assert fresh[1]["validationHalfMSE"] == 18225.0 / 131072.0
    diagonal = mechanics_experiment({**dict(DEFAULT_IV55), "scope": 1})["prepared"]["stages"][-1]
    _same_words(diagonal["weights"], [13085.0 / 32768.0, 0.0, 0.0, 13085.0 / 32768.0])
    assert diagonal["trainHalfMSE"] == 3279279725.0 / 17179869184.0
    assert diagonal["validationHalfMSE"] == 3279279725.0 / 34359738368.0
    p3 = mechanics_experiment(dict(preUpdates=3, updates=0, scope=0, eta=0.5))
    _same_words(p3["pre"]["stages"][-1]["weights"],
                [13085.0 / 32768.0, 0.0, 0.0, 13085.0 / 32768.0])


def check_helper_guards_and_words():
    """Ambient states, OLD WORD frozen entries, representability and errors."""
    data, mask, zeros = fixed_data()["data"], [1, 1, 1, 1], [0.0, 0.0, 0.0, 0.0]
    _expect_fault("SHAPE_MISMATCH", evaluate_transfer, zeros[:3], data, 0, mask)
    _expect_fault("SHAPE_MISMATCH", evaluate_transfer, zeros, data[:7], 0, mask)
    _expect_fault("INVALID_INPUT", evaluate_transfer, zeros, data, 2, mask)
    _expect_fault("INVALID_INPUT", evaluate_transfer, zeros, data, 10 ** 400, mask)
    _expect_fault("INVALID_INPUT", evaluate_transfer, zeros, data, 0, [1, 2, 1, 1])
    _expect_fault("INVALID_INPUT", evaluate_transfer, zeros, data, 0, [1, 10 ** 400, 1, 1])
    _expect_fault("NONFINITE", evaluate_transfer, zeros, data, 2, [1, True, 1, 1])
    _expect_fault("NONFINITE", evaluate_transfer, [10 ** 400, 0.0, 0.0, 0.0], data, 0, mask)
    _expect_fault("NONFINITE", evaluate_transfer, [float.fromhex("0x1.fffffffffffffp+1023"), 0.0, 0.0, 0.0], data, 0, mask)
    _expect_fault("INVALID_INPUT", transfer_sgd, zeros, zeros, [-0.0, 0.0, 0.0, 0.0], [0, 0, 0, 0], 0.5)
    _expect_fault("INVALID_INPUT", transfer_sgd, zeros, [1.0] * 4, zeros, mask, 0.5)
    _expect_fault("NONFINITE", transfer_sgd, zeros, zeros, zeros, [2, 1, 1, 1], float("nan"))
    _expect_fault("INVALID_INPUT", transfer_sgd, zeros, zeros, zeros, mask, 10 ** 400)
    _expect_fault("INVALID_INPUT", transfer_sgd, zeros, zeros, zeros, [1, 10 ** 400, 1, 1], 0.5)
    signed = transfer_sgd(zeros, [-0.0, 0.0, 0.0, 0.0], [-0.0, 0.0, 0.0, 0.0], mask, -0.0)
    _same_words([signed["coordinates"][0]["mathematical"], signed["coordinates"][0]["effective"]], [-0.0, -0.0])
    _same_words([signed["coordinates"][0]["eta"], signed["coordinates"][0]["delta"]], [-0.0, 0.0])
    _expect_fault("INVALID_INPUT", transfer_sgd, zeros, [-0.0, 0.0, 0.0, 0.0], zeros, mask, 0.5)
    for eta in (0.0, -0.0, 0.5, 2.0):
        old, mathematical, frozen_mask = [1.25, -0.0, -2.5, 0.0], [2.0, -1.0, 3.0, 0.0], [0, 0, 0, 0]
        transition = transfer_sgd(old, mathematical, zeros, frozen_mask, eta)
        _same_words(transition["weights"], old)
        for i, row in enumerate(transition["coordinates"]):
            _same_words([row["old"], row["committed"], row["effective"]], [old[i], old[i], 0.0])
            _same_words([row["delta"]], [eta * 0.0])
    mixed = transfer_sgd([1.0, 2.0, -0.0, 4.0], [1.0, -2.0, 3.0, 4.0],
                         [1.0, 0.0, 0.0, 4.0], [1, 0, 0, 1], 0.5)
    _same_words(mixed["weights"], [0.5, 2.0, -0.0, 2.0])
    ambient = evaluate_transfer([1.0, 2.0, 3.0, 4.0], data, 1, [0, 0, 0, 0])
    _same_words(ambient["effectiveGradient"], zeros)
    assert any(value != 0.0 for value in ambient["mathematicalGradient"])
    # No origin/coherence assertion: shape-correct ambient rows remain accepted.
    ambient_data = [row[:] for row in data]
    ambient_data[0] = [3.0, 2.0, 3.0, 0.5, -0.5, 1.25, -1.25]
    assert evaluate_transfer([1.0, 2.0, 3.0, 4.0], ambient_data, 1, mask)["predictions"][:2] == [8.0, 18.0]
    captured = evaluate_transfer(zeros, data, 0, mask)
    data[0][1], zeros[0], mask[0] = 123.0, 123.0, 0
    assert captured["weights"][0] == 0.0 and captured["mask"][0] == 1
    assert captured["forwards"][0]["products"][0]["feature"] == 0.0


def check_memorizer():
    result = mechanics_experiment(dict(DEFAULT_IV55))
    memo, pre = result["memorizer"], result["pre"]["stages"][-1]
    assert memo["matches"] == [0, 1, 2, 3, -1, -1, -1, -1]
    assert sum(len(row["comparisons"]) for row in memo["selections"]) == 32
    assert len(memo["keys"]) + sum(len(pair) for pair in memo["targets"]) == 12
    assert memo["trainHalfMSE"] == 0.0
    assert memo["validationHalfMSE"] == 3967925.0 / 33554432.0
    _same_words(memo["preparedPredictions"], pre["predictions"])
    _same_words(memo["predictions"][8:], pre["predictions"][8:])
    for i in range(4):
        _same_words(memo["predictions"][2 * i:2 * i + 2], result["data"][i][5:7])
    data, saved = fixed_data()["data"], [-0.0, 0.0] * 8
    _expect_fault("SHAPE_MISMATCH", memorize_transfer, data, saved[:15])
    _expect_fault("NONFINITE", memorize_transfer, data, [True] + saved[1:])
    _expect_fault("NONFINITE", memorize_transfer, data, [10 ** 400] + saved[1:])
    data[1] = data[0][:]  # coherent duplicate key/feature/target, first index wins
    duplicated = memorize_transfer(data, saved)
    assert duplicated["matches"][:2] == [0, 0]
    assert len(duplicated["selections"][0]["comparisons"]) == 4
    assert duplicated["selections"][0]["comparisons"][1]["equal"] == 1
    _same_words(duplicated["predictions"][8:], saved[8:])
    saved[8], data[0][5] = 17.0, 17.0
    _same_words(duplicated["predictions"][8:10], [-0.0, 0.0])
    assert duplicated["targets"][0][0] == 0.5


def check_controls_and_structure():
    """Every bounded loop count, final diagnostics, eta0 and saved-state isolation."""
    for p in range(4):
        for u in range(4):
            for scope in (0, 1):
                for eta in (0.0, -0.0, 0.5, 2.0):
                    result = mechanics_experiment(dict(preUpdates=p, updates=u, scope=scope, eta=eta))
                    assert len(result["construction"]) == 8
                    for name, updates in (("pre", p), ("prepared", u), ("fresh", u)):
                        cohort = result[name]
                        assert len(cohort["stages"]) == updates + 1 and len(cohort["transitions"]) == updates
                        for stage, evaluated in enumerate(cohort["stages"]):
                            assert evaluated["diagnosticOnly"] == int(stage == updates)
                            assert len(evaluated["forwards"]) == 8 and len(evaluated["predictions"]) == 16
                            assert len(evaluated["gradients"]) == 4
                            for gradient in evaluated["gradients"]:
                                assert len(gradient["contributions"]) == 4
                            for row in evaluated["forwards"]:
                                assert len(row["products"]) == 4
                            for split in ("train", "validation"):
                                assert len(evaluated["losses"][split]["additions"]) == 4
                                assert evaluated["losses"][split]["divisor"] == 4.0
                        for stage, transition in enumerate(cohort["transitions"]):
                            _same_words(transition["weights"], cohort["stages"][stage + 1]["weights"])
                            for i, coordinate in enumerate(transition["coordinates"]):
                                _same_words([coordinate["old"]], [cohort["stages"][stage]["weights"][i]])
                                if not coordinate["enabled"]:
                                    _same_words([coordinate["committed"]], [coordinate["old"]])
                        if name != "pre" and eta == 0.0:
                            # Numeric invariance; enabled zero signs still follow arithmetic.
                            assert cohort["stages"][-1]["weights"] == cohort["stages"][0]["weights"]
                    _same_words(result["prepared"]["initialWeights"], result["pre"]["stages"][-1]["weights"])
                    _same_words(result["fresh"]["initialWeights"], [0.0] * 4)
                    if p == 0:
                        assert result["prepared"]["stages"][0]["weights"] == result["fresh"]["stages"][0]["weights"]
                    assert result["memorizer"]["trainHalfMSE"] == 0.0
    # Independent fresh calls and later mutable records cannot alter earlier states.
    result = mechanics_experiment(dict(preUpdates=3, updates=3, scope=0, eta=0.5))
    original = result["pre"]["stages"][-1]["weights"][:]
    result["prepared"]["initialWeights"][0] = 123.0
    result["prepared"]["stages"][-1]["weights"][0] = 456.0
    _same_words(result["pre"]["stages"][-1]["weights"], original)
    _same_words(result["prepared"]["stages"][0]["weights"], original)
    assert mechanics_experiment(dict(DEFAULT_IV55))["pre"]["stages"][-1]["weights"][0] == 295.0 / 1024.0


def source_self_check():
    """Eight explicit terminal checks; ordinary queries reach none of them."""
    if not __debug__:
        raise RuntimeError("Explicit source checks require assertions enabled.")
    check_raw_guards()
    check_hand_anchors()
    check_helper_guards_and_words()
    check_memorizer()
    check_controls_and_structure()
    check_public_record()
    check_query_check_isolation()
    check_cli_boundary()


# Literal public prose copied from the owner-adopted current sources, not parsed.
_STEP_PROSE = {
    "setup": (
        "Set up a small transfer experiment with two output numbers",
        "W:[2,2]; phi:[2,1]; prediction=W phi:[2,1]; PRE eta=0.5; ADAPT eta=eta; scope0:4 enabled, scope1:2 enabled",
        "Pretraining first learns one numeric target rule. Fine-tuning then changes the desired outputs and updates either all readout entries or just the diagonal. A fresh run supplies a comparison with the same adaptation data and optimizer. These are fixed features with a learned readout, not language-model token probabilities."),
    "data": (
        "Prepare the two fixed features and both target pairs",
        "negatedX=-x; phiPlus=max(0,x); phiMinus=max(0,negatedX); preTarget0=phiPlus; preTarget1=phiMinus; scaledMinus=0.5*phiMinus; adaptTarget0=phiPlus+scaledMinus; scaledPlus=-0.5*phiPlus; adaptTarget1=scaledPlus+phiMinus",
        "A feature is a number supplied to the readout. These ReLU features keep the positive and negative parts of the input separate. Pretraining asks for the features themselves; adaptation changes the desired two outputs. The first four authored inputs train the readout and the last four only evaluate it. Features and targets are prepared once."),
    "initial": (
        "Start this cohort from positive-zero weights",
        "weights=[sourceWeight0,sourceWeight1,sourceWeight2,sourceWeight3]; enabled=mask",
        "All four source weights are positive zero. PRE will learn the feature-copy task; the fresh comparison learns ADAPT directly. Neither start uses hand-set pretrained weights."),
    "prepared": (
        "Copy the actual prepared readout into adaptation",
        "weights=[sourceWeight0,sourceWeight1,sourceWeight2,sourceWeight3]; enabled=mask",
        "These source weights are the genuinely evaluated final PRE weights. Copy every value exactly before any adaptation. The two target columns now change to ADAPT while inputs, fixed features and the squared-error loss form stay the same."),
    "forward": (
        "Read out two numbers from the same fixed feature column",
        "product00=w00*phiPlus; product01=w01*phiMinus; product10=w10*phiPlus; product11=w11*phiMinus; prediction0=product00+product01; prediction1=product10+product11",
        "W has two output rows and two feature columns. Multiplying W:[2,2] by phi:[2,1] gives a two-number column. All four products and both sums are performed, including zero products. Every sample in this evaluation uses these same four weights, with no bias or softmax."),
    "loss": (
        "Measure the two output errors for one sample",
        "error0=prediction0-target0; error1=prediction1-target1; square0=error0*error0; square1=error1*error1; half0=square0/2; half1=square1/2; sampleLoss=half0+half1",
        "Each output is a scalar regression value, so its signed error is a difference of numbers. Squaring makes either error direction costly. Add the two half-losses to obtain one sample loss; the later average counts four samples, not eight output coordinates."),
    "mean": (
        "Average four saved sample losses in their original order",
        "sum starts at +0; sum0=initialSum+loss0; sum1=sum0+loss1; sum2=sum1+loss2; sum3=sum2+loss3; mean=sum3/4",
        "Dataset zero is training; dataset one is held-out validation. Both means are computed independently from their saved sample losses. Validation never contributes a gradient. This ordered average does not divide each output error by eight."),
    "gradient": (
        "Differentiate one readout coordinate using training errors",
        "contribution_j=error_j*feature_j; sum starts at +0 and adds contributions in training-row order; mathematical=sum3/4",
        "A gradient says how the training mean changes when one weight changes slightly. For this linear readout, a weight changes its output in proportion to its feature, giving error times feature. Average the four training contributions. Compute every coordinate even when adaptation will freeze it; final-stage gradients are observations, not extra updates."),
    "mask": (
        "Choose which derivatives the optimizer may use",
        "effective_i=enabled_i==1?mathematical_i:+0",
        "The mathematical derivative describes the loss even for a frozen weight. The effective derivative is the optimizer input: retain that derivative for an enabled weight and select positive zero otherwise. This is a conditional choice, not multiplication by a mask."),
    "stats": (
        "Save this evaluated state and whether an update follows",
        "diagnosticOnly=(stage==requestedUpdates); hasNextUpdate=(stage<requestedUpdates); losses belong to this same saved W",
        "Stage zero is evaluated before any step. Each later point follows a real simultaneous update and a fresh eight-sample evaluation. At the final requested stage, retain all four gradients for inspection but perform no additional optimizer step. Only actual evaluated points appear in the trajectory."),
    "coordinate": (
        "Propose one weight change from the same old state",
        "delta=eta*effective; proposed=old-delta; committed=enabled==1?proposed:old",
        "Subtracting a positive gradient lowers a weight; subtracting a negative one raises it. Every coordinate gets a real multiplication and subtraction, including frozen coordinates. A frozen weight keeps its exact old value and zero sign. All proposals use the unchanged old weights and saved gradients."),
    "commit": (
        "Publish all four proposed coordinates together",
        "nextWeights=[committed0,committed1,committed2,committed3]",
        "This simultaneous publication completes one optimizer step. No coordinate update changes a gradient used for another coordinate. A later stage evaluates the resulting weights again; its final diagnostic gradient causes no additional step."),
    "dictionary": (
        "Copy four training keys and their two desired outputs",
        "dictionary_j=[trainX_j,adaptTarget0_j,adaptTarget1_j], j=0..3",
        "This explicit lookup stores four keys and eight target values, twelve extra numeric slots. It is a constructed counterexample, not a neural network trained by gradient descent. Its fallback will reuse the already saved prepared predictions."),
    "scan": (
        "Compare this input with every stored training key",
        "match starts at -1; for key0..3: equal=(x==keyX); match=(oldMatch==-1 and equal==1)?keyIndex:oldMatch",
        "Perform all four equality comparisons even after finding a match. Keep the first matching index; minus one means none. The fixed eight inputs have four training matches and four held-out misses. If a caller supplies duplicate coherent keys, the first match still wins."),
    "select": (
        "Copy a matched target pair or this sample's saved prepared pair",
        "sourceKind=match==-1?1:0; sourceSample=match==-1?sample:match; sourceIndex0=match==-1?2*sample:3*match+1; sourceIndex1=sourceIndex0+1; source0=match==-1?prepared0:matchedDictionary0; source1=match==-1?prepared1:matchedDictionary1; prediction0=source0; prediction1=source1",
        "Source zero is the dictionary target pair at the first matching training index: in the stored [4,3] dictionary, flat positions 3*match+1 and 3*match+2 skip its x key. Source one is the saved prepared-network prediction at this same sample, at flat positions 2*sample and 2*sample+1 before adaptation. Copy both output values without another neural forward. A perfect lookup fit on training keys says nothing about the missing inputs."),
    "finish": (
        "Compare the final adaptation results and the lookup counterexample",
        "report actual final losses and completed work; final diagnostics add no optimizer steps; dictionary comparisons add no neural forwards",
        "Prepared and fresh losses measure the same ADAPT rule after the same number of adaptation steps. The dictionary can obtain zero training error by copying labels while keeping unadapted predictions on held-out misses. Counts describe this small algorithm, not elapsed time, memory bytes or a general benefit of pretraining."),
}

# Each metadata tuple names the actual row-major table, never an idealized value.
_TENSOR_META = {
    "Data": ([8, 7], ["Sample", "DataField"], "Actual once-prepared authored inputs, features and both target pairs in texts.dataFields order; first four training, last four validation."),
    "AdaptMask": ([2, 2], ["Output", "Feature"], "Actual scope-dependent ADAPT selectors in row-major W order; PRE always enables all four coordinates."),
    "InitialWeights": ([2, 2], ["Output", "Feature"], "Actual cohort initialization: PRE/fresh copy authored positive zeros; prepared ADAPT copies the saved final-PRE weight words."),
    "Weights": ([2, 2], ["Output", "Feature"], "Detached actual same-state W, row-major 00,01,10,11; arbitrary finite represented weights are permitted."),
    "Predictions": ([8, 2], ["Sample", "Output"], "Actual two-output predictions from all four products and both sums per sample, with the same W for all eight rows."),
    "Forward": ([8, 6], ["Sample", "ForwardField"], "Actual product00,product01,product10,product11,prediction0,prediction1; no zero-product shortcut."),
    "Loss": ([8, 9], ["Sample", "LossField"], "Actual target0,target1,error0,error1,square0,square1,half0,half1,sampleLoss in sample order; each sample loss sums both output half-losses."),
    "Reductions": ([2, 4, 3], ["Dataset", "DatasetSample", "ReductionField"], "Actual saved loss, oldSum, sum for each ordered four-sample reduction, training then validation, each initialized at floating positive zero."),
    "Means": ([2], ["Dataset"], "Actual independent training and validation means; each divides its own ordered four-sample sum by floating four."),
    "GradientRows": ([4, 4, 5], ["Coordinate", "TrainSample", "GradientRowField"], "Actual error,feature,contribution,oldSum,sum in coordinate-major then training-row order; each contraction starts at floating positive zero."),
    "MathematicalGradient": ([2, 2], ["Output", "Feature"], "All four actual derivatives of the current training objective; the final cohort stage is diagnostic only."),
    "EffectiveGradient": ([2, 2], ["Output", "Feature"], "Actual conditional mathematical-gradient or floating-positive-zero selection, in row-major W order."),
    "Mask": ([2, 2], ["Output", "Feature"], "Actual numeric zero-or-one selectors in row-major W order; integer values select effective gradients, never rescale features."),
    "Stats": ([4], ["StageField"], "Actual training mean,validation mean,diagnosticOnly,hasNextUpdate in texts.stageFields order; last two positions are integer VALUE selectors."),
    "Update": ([4, 7], ["Coordinate", "UpdateField"], "Actual old,mathematical,effective,enabled,delta,proposed,committed; enabled is an integer VALUE in this mixed float table. Frozen commits copy the old word, including nonzero values and negative zero."),
    "Dictionary": ([4, 3], ["TrainKey", "DictionaryField"], "Actual copied training x,adaptTarget0,adaptTarget1; four keys plus eight target values, twelve extra numeric slots."),
    "Comparisons": ([8, 4, 5], ["Sample", "TrainKey", "ComparisonField"], "Actual x,keyX,equal,oldMatch,match for all 32 comparisons; equal and both match columns are integer VALUE positions in this mixed float table."),
    "Selections": ([8, 9], ["Sample", "SelectionField"], "Actual match,sourceKind,sourceSample,sourceIndex0,sourceIndex1,source0,source1,prediction0,prediction1; first five columns are integer VALUE positions. Source zero indexes target columns at 3*match+1 and 3*match+2 in the flat stored Dictionary:[4,3]; source one indexes 2*sample and 2*sample+1 in the flat saved prepared Predictions:[8,2]."),
    "MemorizerPredictions": ([8, 2], ["Sample", "Output"], "Actual selected two-output values; no new neural forward, gradient or optimizer step."),
    "Matches": ([8], ["Sample"], "Actual first matching training-key index or minus one for every sample; fixed data gives four matches and four misses."),
    "StageMetrics": (None, ["Stage", "Dataset"], "Only actual cohort stages zero through its requested update count; training then independently computed validation mean."),
    "StageWeights": (None, ["Stage", "Coordinate"], "Only actual evaluated cohort weights in row-major 00,01,10,11 order; final weights have a real final evaluation."),
}


def _texts(raw):
    return {
        "trainingScope": "A tiny neural regression readout maps two fixed ReLU features to two scalar outputs. W has four learned entries and no bias. Unlike IV52 text cross-entropy, the loss here measures squared numeric errors; neither hidden features nor a Transformer are trained.",
        "shapePolicy": "For one sample phi=[max(0,x),max(0,-x)]^T:[2,1], W:[2,2], prediction=W phi:[2,1]. Flat W order is 00,01,10,11. With feature rows F:[4,2], batch outputs are F W^T:[4,2]; the transpose explicitly converts column-vector mathematics to row samples.",
        "dataPolicy": "Eight authored nonzero inputs: training [-1,-0.5,0.5,1], held-out [-0.75,-0.25,0.25,0.75]. Features are computed once. PRE targets copy the features; ADAPT targets are T phi with T=[[1,0.5],[-0.5,1]], computed by two half-scalings and two additions. No random sample or unseen test set is implied.",
        "preparationPolicy": "PRE starts at four positive-zero weights and really performs preUpdates full-coordinate steps at fixed learning rate 0.5. Save every evaluated stage from zero through preUpdates. Prepared adaptation copies the final PRE weights exactly; fresh adaptation starts at four positive zeros.",
        "adaptationPolicy": "Both adaptation cohorts use the ADAPT training targets, the same requested updates, learning rate eta and scope. Scope zero enables all four entries; scope one enables only W00 and W11. Inputs, features and loss form stay the same while the target rule changes. Compare actual evaluated states, not fitted curves or ideal optima.",
        "zeroPolicy": "With preUpdates zero, no pretraining has occurred and prepared and fresh starts coincide. With updates zero, both adaptation starts are still evaluated but neither is updated. Eta zero, including negative zero, keeps every requested step and evaluation; multiplication and subtraction still take place.",
        "objectivePolicy": "For each sample compute both predictions, error_o=prediction_o-target_o, square_o=error_o*error_o, half_o=square_o/2, then sampleLoss=half_0+half_1. Each dataset mean adds its four saved sample losses from positive zero in row order and divides by four. This averages samples after summing the two output half-losses; it does not divide by eight.",
        "gradientPolicy": "For each W[o,i], sum the four training products error[o]*phi[i] from positive zero in row order, then divide by four. All four mathematical derivatives belong to the same saved W and objective. Validation never supplies gradients. Each cohort has a final diagnostic gradient with no additional update.",
        "updatePolicy": "Select effective_i=enabled_i?mathematical_i:+0. Compute delta=eta*effective and proposed=old-delta for all four coordinates; commit proposed for enabled entries and the exact old word for frozen entries. Publish all four together. Frozen means preserve the old value, including a nonzero value or negative zero; it never means reset to zero.",
        "memorizerPolicy": "The dictionary copies four training x keys and their eight ADAPT target scalars: twelve extra numeric slots, in addition to the four retained prepared weights. For every input compare all four keys, keeping the first match. Copy a matching target pair or, on a miss, that same sample's saved final-PRE predictions. Compute its losses independently. This constructed lookup is not another neural forward or an SGD-trained network.",
        "evaluationPolicy": "The four held-out inputs have different magnitudes on the same two feature rays. For either homogeneous matrix target and any fixed W, real-arithmetic validation mean equals half the training mean because their feature Gram matrices are 5I/32 and 5I/16. Both means are still computed independently; arbitrary represented arithmetic can round. This grid does not test new directions, nonlinear rules or a population.",
        "transferLimits": "A prepared start can help this adaptation experiment, but this is not a universal transfer benefit. The dictionary fits the four training pairs exactly while retaining unadapted prepared predictions at all four held-out inputs. Perfect training fit alone therefore does not guarantee even this limited held-out performance. These numbers cannot establish LLM cognition, safety or alignment.",
        "computePolicy": "Counts describe actual feature preparation, network evaluations, ordered loss and gradient arithmetic, stored-coordinate proposals and enabled commits. Each gradient batch uses four training rows, counted by gradientRowContributions, and performs sixteen coordinate-by-row multiplications, counted by gradientProducts. Final diagnostics count as gradient work but not optimizer steps. Dictionary comparisons and copies are separate. Counts are not measured seconds, bytes, throughput or hardware savings.",
        "numericPolicy": "Separate finite binary64 additions, subtractions, multiplications and divisions use round-to-nearest ties-to-even, with no fused multiply-add or reordered contraction. Fixed max and comparisons have explicit operands. Raw eta, copied values, products, sums, deltas and proposals retain zero signs; displayed rounding never feeds computation.",
        "diagnosticPolicy": "For eta=positive 0.5, centered differences with h=2^-12 have an exact arithmetic identity only at PRE stages0..preUpdates and prepared/fresh ADAPT stages0..min(1,updates), on enabled coordinates. The first fresh ADAPT state after a step needs the 2^-6 weight grid; the largest selected grid exponent is20. The objective is quadratic in W because features stay fixed. Later ADAPT states and arbitrary eta need complete rounding analysis; zero signs require their own word comparison.",
        "provenance": "Inputs and both target rules are authored examples. Each calculation starts from declared positive-zero weights, actually prepares the PRE state through its requested updates, and copies that state for adaptation. The dictionary is explicitly constructed from training labels; no historical pretrained checkpoint or measured training run is supplied.",
        "rawFields": ["preUpdates", "updates", "scope", "eta"],
        "parameterKeys": ["W00", "W01", "W10", "W11"],
        "cohortKeys": ["pre", "adapt", "fresh"],
        "cohortLabels": ["Pretraining from zero", "Prepared start: no pretraining steps" if raw["preUpdates"] == 0 else "Adaptation from actual pretraining", "Adaptation from fresh zero weights"],
        "taskKeys": ["PRE", "ADAPT"],
        "dataFields": ["x", "phiPlus", "phiMinus", "preTarget0", "preTarget1", "adaptTarget0", "adaptTarget1"],
        "sampleKeys": ["train0", "train1", "train2", "train3", "validation0", "validation1", "validation2", "validation3"],
        "forwardFields": ["product00", "product01", "product10", "product11", "prediction0", "prediction1"],
        "lossFields": ["target0", "target1", "error0", "error1", "square0", "square1", "half0", "half1", "sampleLoss"],
        "datasetKeys": ["training", "validation"],
        "reductionFields": ["loss", "oldSum", "sum"],
        "gradientRowFields": ["error", "feature", "contribution", "oldSum", "sum"],
        "updateFields": ["old", "mathematical", "effective", "enabled", "delta", "proposed", "committed"],
        "stageFields": ["trainHalfMSE", "validationHalfMSE", "diagnosticOnly", "hasNextUpdate"],
        "dictionaryFields": ["x", "adaptTarget0", "adaptTarget1"],
        "comparisonFields": ["x", "keyX", "equal", "oldMatch", "match"],
        "selectionFields": ["match", "sourceKind", "sourceSample", "sourceIndex0", "sourceIndex1", "source0", "source1", "prediction0", "prediction1"],
        "predictionSources": ["dictionary target pair", "same-sample saved prepared prediction pair"],
        "integerValuePolicy": "Mixed float64 tables retain integer values at Update.enabled, Stats.diagnosticOnly/hasNextUpdate, Comparisons.equal/oldMatch/match, and Selections.match/sourceKind/sourceSample/sourceIndex0/sourceIndex1. Masks and matches have int32 dtype and precision zero. These integer selectors and indices are not rounded floating measurements.",
    }


def _step(steps, identifier, family, inputs, outputs):
    label, equation, explanation = _STEP_PROSE[family]
    steps.append(dict(id=identifier, label=label, equation=equation,
                      explanation=explanation, inputs=inputs, outputs=outputs))


def _tensor(identifier, family, values, shape=None):
    fixed_shape, axes, provenance = _TENSOR_META[family]
    integer = family in ("Mask", "AdaptMask", "Matches")
    return dict(id=identifier, shape=list(fixed_shape if shape is None else shape),
                axes=axes[:], dtype="int32" if integer else "float64", values=values[:],
                provenance=provenance, precision=0 if integer else 8)


def _loss_records(evidence, predictions, task, prefix, steps):
    rows, reductions = [], []
    for sample, row in enumerate(evidence["rows"]):
        c0, c1 = row["components"]
        inputs = dict(sample=sample, task=task, prediction0=predictions[2 * sample],
                      prediction1=predictions[2 * sample + 1], target0=c0["target"],
                      target1=c1["target"], divisor=2.0)
        outputs = dict(error0=c0["error"], error1=c1["error"], square0=c0["square"],
                       square1=c1["square"], half0=c0["half"], half1=c1["half"], sampleLoss=row["sampleLoss"])
        _step(steps, f"{prefix}_loss_{sample}", "loss", inputs, outputs)
        rows.extend([c0["target"], c1["target"], *outputs.values()])
    means = []
    for dataset, key in enumerate(("train", "validation")):
        reduced = evidence[key]
        inputs = dict(dataset=dataset, initialSum=reduced["initialSum"], divisor=reduced["divisor"])
        outputs = {}
        for i, addition in enumerate(reduced["additions"]):
            inputs[f"loss{i}"] = addition["value"]
            outputs[f"sum{i}"] = addition["total"]
            reductions.extend([addition["value"], addition["old"], addition["total"]])
        outputs["mean"] = reduced["mean"]
        means.append(reduced["mean"])
        _step(steps, f"{prefix}_mean_{dataset}", "mean", inputs, outputs)
    return [_tensor(f"{prefix}_Loss", "Loss", rows),
            _tensor(f"{prefix}_Reductions", "Reductions", reductions),
            _tensor(f"{prefix}_Means", "Means", means)]


def _evaluation_records(evaluated, data, prefix, steps):
    weights, predictions = evaluated["weights"], evaluated["predictions"]
    forward_rows, gradient_rows = [], []
    for sample, row in enumerate(evaluated["forwards"]):
        inputs = dict(sample=sample, x=data[sample][0], phiPlus=data[sample][1], phiMinus=data[sample][2],
                      w00=weights[0], w01=weights[1], w10=weights[2], w11=weights[3])
        products = [entry["product"] for entry in row["products"]]
        outputs = dict(zip(("product00", "product01", "product10", "product11"), products))
        outputs.update(prediction0=row["predictions"][0], prediction1=row["predictions"][1])
        forward_rows.extend(outputs.values())
        _step(steps, f"{prefix}_forward_{sample}", "forward", inputs, outputs)
    measured = _loss_records(evaluated["losses"], predictions, evaluated["task"], prefix, steps)
    for coordinate, gradient in enumerate(evaluated["gradients"]):
        inputs = dict(coordinate=coordinate, output=coordinate // 2, feature=coordinate % 2,
                      initialSum=gradient["initialSum"], divisor=gradient["divisor"])
        outputs = {}
        for sample, contribution in enumerate(gradient["contributions"]):
            inputs[f"error{sample}"] = contribution["error"]
            inputs[f"feature{sample}"] = contribution["feature"]
            outputs[f"contribution{sample}"] = contribution["product"]
            outputs[f"sum{sample}"] = contribution["total"]
            gradient_rows.extend(contribution[key] for key in ("error", "feature", "product", "old", "total"))
        outputs["mathematical"] = gradient["mathematical"]
        _step(steps, f"{prefix}_gradient_{coordinate}", "gradient", inputs, outputs)
    inputs, outputs = dict(positiveZero=0.0), {}
    for coordinate in range(4):
        inputs[f"mathematical{coordinate}"] = evaluated["mathematicalGradient"][coordinate]
        inputs[f"enabled{coordinate}"] = evaluated["mask"][coordinate]
        outputs[f"effective{coordinate}"] = evaluated["effectiveGradient"][coordinate]
    _step(steps, f"{prefix}_mask", "mask", inputs, outputs)
    return [_tensor(f"{prefix}_Weights", "Weights", weights),
            _tensor(f"{prefix}_Predictions", "Predictions", predictions),
            _tensor(f"{prefix}_Forward", "Forward", forward_rows), *measured,
            _tensor(f"{prefix}_GradientRows", "GradientRows", gradient_rows),
            _tensor(f"{prefix}_MathematicalGradient", "MathematicalGradient", evaluated["mathematicalGradient"]),
            _tensor(f"{prefix}_EffectiveGradient", "EffectiveGradient", evaluated["effectiveGradient"]),
            _tensor(f"{prefix}_Mask", "Mask", evaluated["mask"])]


def _update_records(transition, prefix, steps):
    rows = []
    for coordinate, row in enumerate(transition["coordinates"]):
        inputs = dict(coordinate=coordinate, old=row["old"], mathematical=row["mathematical"],
                      effective=row["effective"], enabled=row["enabled"], eta=row["eta"])
        outputs = {key: row[key] for key in ("delta", "proposed", "committed")}
        _step(steps, f"{prefix}_coordinate_{coordinate}", "coordinate", inputs, outputs)
        rows.extend(row[key] for key in ("old", "mathematical", "effective", "enabled", "delta", "proposed", "committed"))
    _step(steps, f"{prefix}_commit", "commit",
          {f"old{i}": row["old"] for i, row in enumerate(transition["coordinates"])},
          {f"weight{i}": value for i, value in enumerate(transition["weights"])})
    return _tensor(f"{prefix}_Update", "Update", rows)


def _cohort_records(cohort, number, key, data, steps, tensors):
    initial, mask, task = cohort["initialWeights"], cohort["mask"], cohort["task"]
    requested = len(cohort["transitions"])
    inputs = dict(cohort=number, task=task, requestedUpdates=requested, eta=cohort["eta"])
    inputs.update({f"sourceWeight{i}": value for i, value in enumerate(initial)})
    inputs.update({f"mask{i}": value for i, value in enumerate(mask)})
    outputs = {f"weight{i}": value for i, value in enumerate(initial)}
    outputs.update({f"enabled{i}": value for i, value in enumerate(mask)})
    _step(steps, f"{key}_initial", "prepared" if number == 1 else "initial", inputs, outputs)
    tensors.append(_tensor(f"{key}_InitialWeights", "InitialWeights", initial))
    metrics, weights = [], []
    for stage, evaluated in enumerate(cohort["stages"]):
        prefix = f"{key}_stage_{stage}"
        tensors.extend(_evaluation_records(evaluated, data, prefix, steps))
        stats = [evaluated["trainHalfMSE"], evaluated["validationHalfMSE"],
                 int(stage == requested), int(stage < requested)]
        tensors.append(_tensor(f"{prefix}_Stats", "Stats", stats))
        inputs = dict(cohort=number, task=task, stage=stage, requestedUpdates=requested)
        inputs.update({f"weight{i}": value for i, value in enumerate(evaluated["weights"])})
        inputs.update(trainHalfMSE=stats[0], validationHalfMSE=stats[1])
        _step(steps, f"{prefix}_stats", "stats", inputs,
              dict(zip(("trainHalfMSE", "validationHalfMSE", "diagnosticOnly", "hasNextUpdate"), stats)))
        metrics.extend(stats[:2])
        weights.extend(evaluated["weights"])
        if stage < requested:
            tensors.append(_update_records(cohort["transitions"][stage], f"{key}_update_{stage + 1}", steps))
    tensors.extend([_tensor(f"{key}_StageMetrics", "StageMetrics", metrics, [len(cohort["stages"]), 2]),
                    _tensor(f"{key}_StageWeights", "StageWeights", weights, [len(cohort["stages"]), 4])])


def _memorizer_records(memo, steps):
    inputs, outputs, dictionary = {}, {}, []
    for key, row in enumerate(memo["dictionary"]):
        x, pair = row[0], row[1:3]
        inputs.update({f"dataX{key}": x, f"dataTarget{key}_0": pair[0], f"dataTarget{key}_1": pair[1]})
        outputs.update({f"key{key}": x, f"target{key}_0": pair[0], f"target{key}_1": pair[1]})
        dictionary.extend([x, *pair])
    _step(steps, "memorizer_dictionary", "dictionary", inputs, outputs)
    comparisons, selections = [], []
    for sample, selection in enumerate(memo["selections"]):
        inputs = dict(sample=sample, x=selection["comparisons"][0]["x"], noMatch=-1)
        outputs = {}
        for key, comparison in enumerate(selection["comparisons"]):
            inputs[f"key{key}"] = comparison["key"]
            outputs[f"equal{key}"] = comparison["equal"]
            outputs[f"match{key}"] = comparison["match"]
            comparisons.extend(comparison[name] for name in ("x", "key", "equal", "oldMatch", "match"))
        _step(steps, f"memorizer_scan_{sample}", "scan", inputs, outputs)
        match = selection["match"]
        inputs = dict(sample=sample, match=match, prepared0=memo["preparedPredictions"][2 * sample],
                      prepared1=memo["preparedPredictions"][2 * sample + 1])
        if match != -1:
            inputs.update(matchedDictionary0=memo["dictionary"][match][1], matchedDictionary1=memo["dictionary"][match][2])
        # Physical Dictionary[4,3] target positions skip x; fallback uses stride2.
        index0 = selection["sourceIndex0"]
        source0, source1 = selection["sourceValues"]
        outputs = dict(sourceKind=selection["sourceKind"],
                       sourceSample=selection["sourceRow"], sourceIndex0=index0, sourceIndex1=selection["sourceIndex1"],
                       source0=source0, source1=source1,
                       prediction0=selection["prediction"][0], prediction1=selection["prediction"][1])
        selections.extend([match, *outputs.values()])
        _step(steps, f"memorizer_select_{sample}", "select", inputs, outputs)
    measured = _loss_records(memo["losses"], memo["predictions"], 1, "memorizer", steps)
    return [_tensor("memorizer_Dictionary", "Dictionary", dictionary),
            _tensor("memorizer_Comparisons", "Comparisons", comparisons),
            _tensor("memorizer_Selections", "Selections", selections),
            _tensor("memorizer_Predictions", "MemorizerPredictions", memo["predictions"]),
            _tensor("memorizer_Matches", "Matches", memo["matches"]), *measured]


def derive_iv55(value):
    """Bind actual independent scalar evidence to the complete adopted root."""
    try:
        evidence = mechanics_experiment(value)
        raw, data = evidence["state"], evidence["data"]
        pre, adapt, fresh = evidence["pre"], evidence["prepared"], evidence["fresh"]
        memo = evidence["memorizer"]
        trainable = sum(adapt["mask"])
        steps, tensors = [], []
        _step(steps, "setup", "setup", raw.copy(),
              dict(storedParameters=4, trainableAdaptParameters=trainable, fixedFeatures=2,
                   outputsPerSample=2, trainSamples=4, validationSamples=4, preEta=0.5))
        for sample, row in enumerate(evidence["construction"]):
            inputs = dict(sample=sample, training=int(sample < 4), x=row["x"], positiveZero=row["zero"],
                          positiveHalf=row["positiveScale"], negativeHalf=row["negativeScale"])
            outputs = dict(negatedX=row["negativeX"])
            outputs.update({key: row[key] for key in ("phiPlus", "phiMinus", "preTarget0", "preTarget1", "scaledMinus", "adaptTarget0", "scaledPlus", "adaptTarget1")})
            _step(steps, f"data_{sample}", "data", inputs, outputs)
        tensors.extend([_tensor("Data", "Data", [entry for row in data for entry in row]),
                        _tensor("AdaptMask", "AdaptMask", adapt["mask"])])
        for number, (key, cohort) in enumerate((("pre", pre), ("adapt", adapt), ("fresh", fresh))):
            _cohort_records(cohort, number, key, data, steps, tensors)
        tensors.extend(_memorizer_records(memo, steps))
        p, u = raw["preUpdates"], raw["updates"]
        k, s = p + 2 * u, p + 2 * u + 3
        measured = 8 * (s + 1)
        work = dict(
            featureMaps=len(data), featureNegations=len(data), featureMaxSelections=2 * len(data),
            preTargetCopies=2 * len(data), adaptTargetScalings=2 * len(data), adaptTargetAdditions=2 * len(data),
            preparedWeightCopies=len(pre["stages"][-1]["weights"]), pretrainingStages=len(pre["stages"]),
            preparedAdaptStages=len(adapt["stages"]), freshAdaptStages=len(fresh["stages"]),
            stageCount=s, forwardSampleEvaluations=8 * s, forwardProducts=32 * s, forwardSums=16 * s,
            gradientBatches=s, gradientContractions=4 * s, gradientRowContributions=4 * s, gradientProducts=16 * s,
            optimizerBatches=k, usedForUpdateRows=4 * k, storedCoordinateUpdateRecords=4 * k,
            enabledCoordinateUpdates=4 * p + 2 * u * trainable, finalDiagnosticBatches=3,
            lossSampleEvaluations=measured, lossComponentErrors=2 * measured, lossSquares=2 * measured,
            lossHalfDivisions=2 * measured, lossOutputSums=measured, orderedLossAdditions=measured,
            datasetMeanDivisions=2 * (s + 1), memorizerComparisons=len(data) * 4,
            memorizerSelections=len(memo["predictions"]) // 2,
            memorizerMatches=sum(match != -1 for match in memo["matches"]),
            memorizerMisses=sum(match == -1 for match in memo["matches"]),
            dictionaryExtraSlots=12, retainedPreparedWeights=len(pre["stages"][-1]["weights"]),
            memorizerForwardEvaluations=0, memorizerGradientBatches=0, memorizerOptimizerBatches=0)
        pf, af, ff = pre["stages"][-1], adapt["stages"][-1], fresh["stages"][-1]
        metrics = dict(fineTunedValidationLoss=af["validationHalfMSE"], freshValidationLoss=ff["validationHalfMSE"],
                       memorizerValidationLoss=memo["validationHalfMSE"], fineTunedTrainLoss=af["trainHalfMSE"],
                       freshTrainLoss=ff["trainHalfMSE"], memorizerTrainLoss=memo["trainHalfMSE"])
        finish_inputs = {**raw, "trainableAdaptParameters": trainable, **metrics, **work}
        _step(steps, "finish", "finish", finish_inputs, {**metrics, **work})
        outputs = dict(fineTunedValidationLoss=metrics["fineTunedValidationLoss"], freshValidationLoss=metrics["freshValidationLoss"],
                       memorizerValidationLoss=metrics["memorizerValidationLoss"], trainableAdaptParameters=trainable,
                       **raw, storedParameters=4, fixedFeatures=2, outputsPerSample=2, trainSamples=4, validationSamples=4, preEta=0.5,
                       pretrainingTrainLoss=pf["trainHalfMSE"], pretrainingValidationLoss=pf["validationHalfMSE"],
                       preparedInitialTrainLoss=adapt["stages"][0]["trainHalfMSE"],
                       preparedInitialValidationLoss=adapt["stages"][0]["validationHalfMSE"],
                       freshInitialTrainLoss=fresh["stages"][0]["trainHalfMSE"],
                       freshInitialValidationLoss=fresh["stages"][0]["validationHalfMSE"],
                       fineTunedTrainLoss=metrics["fineTunedTrainLoss"], freshTrainLoss=metrics["freshTrainLoss"], memorizerTrainLoss=metrics["memorizerTrainLoss"])
        for prefix, evaluated in (("pre", pf), ("fine", af), ("fresh", ff)):
            outputs.update({f"{prefix}Weight{i}": value for i, value in enumerate(evaluated["weights"])})
        outputs.update(work)
        outputs.update(frames=len(steps), tensorCount=len(tensors))
        for step in steps:
            for key, entry in step["outputs"].items():
                alias = f"{step['id']}_{key}"
                if alias in outputs:
                    raise RuntimeError("IV55 output aliases must be unique.")
                outputs[alias] = entry
        # Repeated evidence is detached too: callers cannot mutate another copy.
        return _reference.deepcopy(dict(status="defined", outputs=outputs, steps=steps, tensors=tensors, texts=_texts(raw)))
    except NumericalFault as fault:
        return dict(status="unavailable", code=fault.code, reason=str(fault))


def strict_json(source):
    """Reject ambiguous JSON objects/constants and retain the word of JSON -0."""
    import json

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

    def constant(_value):
        raise ValueError("Nonfinite JSON constant.")

    def integer(token):
        return -0.0 if token == "-0" else int(token)

    return json.loads(source, object_pairs_hook=pairs, parse_constant=constant, parse_int=integer)


def run():
    """Default/JSON/stdin queries run no checks; --self-check is explicit."""
    import json
    import sys
    args = sys.argv[1:]
    if args == ["--self-check"]:
        source_self_check()  # Deliberate dispatch, outside parse and query catches.
        print("IV55 canonical source self-checks completed (8 terminal checks).")
        return 0
    if len(args) > 1:
        print("Usage: iv55.py [JSON|-|--self-check]", file=sys.stderr)
        return 2
    if not args:
        value = dict(DEFAULT_IV55)
    else:
        source = sys.stdin.read() if args[0] == "-" else args[0]
        try:
            value = strict_json(source)
        except ValueError as fault:
            print(json.dumps(dict(status="unavailable", code="INVALID_INPUT", reason=str(fault)), allow_nan=False))
            return 0
    # No parsing catch encloses semantic evaluation, serialization or self-checks.
    print(json.dumps(derive_iv55(value), allow_nan=False))
    return 0


def check_public_record():
    """Adopted ordering, complete aliases, retained words and physical sources."""
    summaries = (
        "fineTunedValidationLoss freshValidationLoss memorizerValidationLoss trainableAdaptParameters "
        "preUpdates updates scope eta storedParameters fixedFeatures outputsPerSample trainSamples validationSamples preEta "
        "pretrainingTrainLoss pretrainingValidationLoss preparedInitialTrainLoss preparedInitialValidationLoss "
        "freshInitialTrainLoss freshInitialValidationLoss fineTunedTrainLoss freshTrainLoss memorizerTrainLoss "
        "preWeight0 preWeight1 preWeight2 preWeight3 fineWeight0 fineWeight1 fineWeight2 fineWeight3 "
        "freshWeight0 freshWeight1 freshWeight2 freshWeight3 "
        "featureMaps featureNegations featureMaxSelections preTargetCopies adaptTargetScalings adaptTargetAdditions "
        "preparedWeightCopies pretrainingStages preparedAdaptStages freshAdaptStages stageCount forwardSampleEvaluations "
        "forwardProducts forwardSums gradientBatches gradientContractions gradientRowContributions gradientProducts "
        "optimizerBatches usedForUpdateRows storedCoordinateUpdateRecords enabledCoordinateUpdates finalDiagnosticBatches "
        "lossSampleEvaluations lossComponentErrors lossSquares lossHalfDivisions lossOutputSums orderedLossAdditions "
        "datasetMeanDivisions memorizerComparisons memorizerSelections memorizerMatches memorizerMisses "
        "dictionaryExtraSlots retainedPreparedWeights memorizerForwardEvaluations memorizerGradientBatches "
        "memorizerOptimizerBatches frames tensorCount"
    ).split()
    assert len(summaries) == 76
    for p in range(4):
        for u in range(4):
            for scope in (0, 1):
                raw = dict(preUpdates=p, updates=u, scope=scope, eta=0.5)
                record = derive_iv55(raw)
                assert tuple(record) == ("status", "outputs", "steps", "tensors", "texts")
                assert record["status"] == "defined"
                outputs, steps, tensors = record["outputs"], record["steps"], record["tensors"]
                k, s = p + 2 * u, p + 2 * u + 3
                assert len(steps) == outputs["frames"] == 112 + 29 * k
                assert len(tensors) == outputs["tensorCount"] == 52 + 12 * k
                assert len(outputs) == 904 + 174 * k and len(record["texts"]) == 35
                assert list(outputs)[:76] == summaries
                assert outputs["gradientRowContributions"] == 4 * s
                assert outputs["gradientProducts"] == 16 * s
                assert outputs["enabledCoordinateUpdates"] == 4 * p + 2 * u * (4 if scope == 0 else 2)
                assert record["texts"]["cohortLabels"][1] == (
                    "Prepared start: no pretraining steps" if p == 0 else "Adaptation from actual pretraining")
                aliases = []
                for step in steps:
                    assert tuple(step) == ("id", "label", "equation", "explanation", "inputs", "outputs")
                    for key, value in step["outputs"].items():
                        alias = f"{step['id']}_{key}"
                        aliases.append(alias)
                        assert _reference._word(outputs[alias]) == _reference._word(value)
                assert list(outputs)[76:] == aliases and len(set(aliases)) == len(aliases)
                assert len({step["id"] for step in steps}) == len(steps)
                assert len({tensor["id"] for tensor in tensors}) == len(tensors)
                for tensor in tensors:
                    assert tuple(tensor) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
                    assert len(tensor["shape"]) == len(tensor["axes"])
                    cells = 1
                    for dimension in tensor["shape"]:
                        assert 1 <= dimension <= 64
                        cells *= dimension
                    assert len(tensor["values"]) == cells <= 4096
                    integer = tensor["id"] == "AdaptMask" or tensor["id"].endswith(("_Mask", "_Matches"))
                    assert tensor["dtype"] == ("int32" if integer else "float64")
                    assert tensor["precision"] == (0 if integer else 8)
                by_id = {tensor["id"]: tensor for tensor in tensors}
                source_predictions = by_id[f"pre_stage_{p}_Predictions"]["values"]
                dictionary = by_id["memorizer_Dictionary"]["values"]
                for sample in range(8):
                    select = next(step for step in steps if step["id"] == f"memorizer_select_{sample}")
                    assert tuple(select["outputs"]) == ("sourceKind", "sourceSample", "sourceIndex0", "sourceIndex1", "source0", "source1", "prediction0", "prediction1")
                    assert tuple(select["inputs"]) == (("sample", "match", "prepared0", "prepared1", "matchedDictionary0", "matchedDictionary1")
                                                       if sample < 4 else ("sample", "match", "prepared0", "prepared1"))
                    chosen = select["outputs"]
                    assert chosen["sourceIndex0"] == (3 * sample + 1 if sample < 4 else 2 * sample)
                    assert chosen["sourceIndex1"] == chosen["sourceIndex0"] + 1
                    storage = dictionary if sample < 4 else source_predictions
                    _same_words([chosen["source0"], chosen["source1"]],
                                [storage[chosen["sourceIndex0"]], storage[chosen["sourceIndex1"]]])
                for name, requested in (("pre", p), ("adapt", u), ("fresh", u)):
                    stats = [step for step in steps if step["id"].startswith(f"{name}_stage_") and step["id"].endswith("_stats")]
                    assert len(stats) == requested + 1
                    assert sum(step["outputs"]["diagnosticOnly"] for step in stats) == 1
                    for stage, step in enumerate(stats):
                        for field in ("trainHalfMSE", "validationHalfMSE"):
                            _same_words([step["inputs"][field]], [step["outputs"][field]])
                        _same_words([step["inputs"][f"weight{i}"] for i in range(4)],
                                    by_id[f"{name}_stage_{stage}_Weights"]["values"])
                finish = steps[-1]
                for field, value in finish["outputs"].items():
                    assert _reference._word(finish["inputs"][field]) == _reference._word(value)
    for eta in (0.0, -0.0, float.fromhex("0x0.0000000000001p-1022"), 0.1, 2.0):
        record = derive_iv55(dict(preUpdates=3, updates=3, scope=1, eta=eta))
        assert record["status"] == "defined"
        _same_words([record["outputs"]["eta"], record["steps"][0]["inputs"]["eta"], record["steps"][-1]["inputs"]["eta"]], [eta] * 3)
        for step in record["steps"]:
            if "eta" in step["inputs"] and not step["id"].startswith("pre_"):
                _same_words([step["inputs"]["eta"]], [eta])
    record = derive_iv55(dict(DEFAULT_IV55))
    _same_words([record["outputs"]["fineTunedValidationLoss"], record["outputs"]["freshValidationLoss"], record["outputs"]["memorizerValidationLoss"]],
                [2892617325.0 / 34359738368.0, 18225.0 / 131072.0, 3967925.0 / 33554432.0])
    source = record["tensors"][0]["values"][0]
    record["tensors"][0]["values"][0] = 123.0
    assert record["steps"][1]["inputs"]["x"] == source
    record["steps"][0]["outputs"]["storedParameters"] = 123
    assert record["outputs"]["setup_storedParameters"] == 4
    for raw, code, reason in (
            (None, "INVALID_INPUT", "state must be a plain object."),
            ({}, "INVALID_INPUT", "state must have exactly preUpdates, updates, scope, eta as own fields."),
            ({**dict(DEFAULT_IV55), "preUpdates": 4}, "INVALID_INPUT", "preUpdates must be an integer from 0 to 3."),
            ({**dict(DEFAULT_IV55), "updates": 0.5}, "INVALID_INPUT", "updates must be an integer from 0 to 3."),
            ({**dict(DEFAULT_IV55), "scope": 2}, "INVALID_INPUT", "scope must be numeric 0 or 1."),
            ({**dict(DEFAULT_IV55), "updates": 0, "eta": 3}, "INVALID_INPUT", "eta must be between 0 and 2."),
            ({**dict(DEFAULT_IV55), "preUpdates": 10 ** 400, "eta": True}, "NONFINITE", "eta must be an actual finite number.")):
        assert derive_iv55(raw) == dict(status="unavailable", code=code, reason=reason)


def check_query_check_isolation():
    """Import/query graph has no reachable self-check, even through the CLI."""
    import contextlib
    import io
    import sys
    names = ("source_self_check", "check_raw_guards", "check_hand_anchors", "check_helper_guards_and_words",
             "check_memorizer", "check_controls_and_structure", "check_public_record",
             "check_query_check_isolation", "check_cli_boundary")
    saved = {name: globals()[name] for name in names}
    original_argv, original_stdin = sys.argv, sys.stdin

    def forbidden_check(*_args, **_kwargs):
        raise AssertionError("An ordinary query reached a self-check.")

    try:
        for name in names:
            globals()[name] = forbidden_check
        assert derive_iv55(dict(DEFAULT_IV55))["status"] == "defined"
        assert derive_iv55(None)["status"] == "unavailable"
        for args, source in (([], ""), (["{}"], ""), (["-"], '{"preUpdates":0,"updates":0,"scope":1,"eta":-0}'), (["{"], "")):
            sys.argv, sys.stdin = ["iv55.py", *args], io.StringIO(source)
            with contextlib.redirect_stdout(io.StringIO()):
                assert run() == 0
    finally:
        globals().update(saved)
        sys.argv, sys.stdin = original_argv, original_stdin


def check_cli_boundary():
    """Known parse faults return JSON; unexpected semantic/resource errors escape."""
    import contextlib
    import io
    import json
    import sys
    saved_argv, saved_stdin = sys.argv, sys.stdin

    def invoke(args, source=""):
        sys.argv, sys.stdin = ["iv55.py", *args], io.StringIO(source)
        out, err = io.StringIO(), io.StringIO()
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            status = run()
        return status, out.getvalue(), err.getvalue()

    try:
        for args, source in (([], ""), (["-"], '{"preUpdates":0,"updates":0,"scope":1,"eta":-0}'),
                             (['{"preUpdates":2,"updates":1,"scope":0,"eta":0.5}'], "")):
            code, output, error = invoke(args, source)
            assert code == 0 and not error
            value = json.loads(output)
            assert value["status"] == "defined"
            if args == ["-"]:
                _same_words([value["outputs"]["eta"]], [-0.0])
        for source in ("{", "{} {}", '{"eta":0,"eta":1}', "NaN", "Infinity", "-Infinity", "1" * 5000):
            code, output, error = invoke([source])
            assert code == 0 and not error
            result = json.loads(output)
            assert tuple(result) == ("status", "code", "reason")
            assert result["status"] == "unavailable" and result["code"] == "INVALID_INPUT"
        for source in ("{}", "null", "[]", "true", '{"preUpdates":2,"updates":1,"scope":0,"eta":1e999}'):
            code, output, error = invoke([source])
            assert code == 0 and not error and json.loads(output)["status"] == "unavailable"
        code, output, error = invoke(["{}", "{}"])
        assert code == 2 and not output and "Usage:" in error
        original_semantics = globals()["mechanics_experiment"]
        try:
            for fault in (RuntimeError("unexpected semantics"), json.JSONDecodeError("semantic sentinel", "", 0)):
                def broken_semantics(_value):
                    raise fault
                globals()["mechanics_experiment"] = broken_semantics
                try:
                    invoke(["{}"])
                except type(fault) as raised:
                    assert raised is fault
                else:
                    raise AssertionError("Semantic failure was caught as a query result.")
        finally:
            globals()["mechanics_experiment"] = original_semantics
        original_parser = globals()["strict_json"]
        try:
            for fault in (OverflowError("parser sentinel"), RecursionError("parser sentinel")):
                def broken_parser(_source):
                    raise fault
                globals()["strict_json"] = broken_parser
                try:
                    invoke(["{}"])
                except type(fault) as raised:
                    assert raised is fault
                else:
                    raise AssertionError("Unknown parser/resource failure was swallowed.")
        finally:
            globals()["strict_json"] = original_parser
        original_check = globals()["source_self_check"]
        calls = []
        try:
            def explicit_check():
                calls.append("explicit")
            globals()["source_self_check"] = explicit_check
            code, output, error = invoke(["--self-check"])
            assert code == 0 and not error and calls == ["explicit"]
            assert "8 terminal checks" in output
            sentinel = AssertionError("explicit check sentinel")
            def failed_check():
                raise sentinel
            globals()["source_self_check"] = failed_check
            try:
                invoke(["--self-check"])
            except AssertionError as raised:
                assert raised is sentinel
            else:
                raise AssertionError("Self-check failure was swallowed.")
        finally:
            globals()["source_self_check"] = original_check
    finally:
        sys.argv, sys.stdin = saved_argv, saved_stdin


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

3. lora_reference.py: new factor mechanics and public helpers

lora_state captures exactly the five dictionary fields, checks all finite numeric types before domains, and returns integer settings plus floating eta. It rejects bool values even though Python otherwise treats bool as an integer subtype. _rank validates the dimension selector before dependent shapes. _evaluation_inputs captures base4, A2r, B2r and data8-by-7, checks all numbers and binary64 representability before alpha policy. _sgd_inputs does the corresponding work for A/B and both supplied gradients before eta policy. Public prefix validation follows those guards and precedes arithmetic. Huge finite Python integers outside the representable float range are rejected before conversion rather than leaking a conversion overflow.

_evaluate gives A shape [r,2] and B shape [2,r] in NumPy storage. Its output/feature/rank loops keep each old B/A operand, separate product, old accumulator and new accumulator. Scale multiplies each finished contraction, then the base entry is added. Only after all four weights exist does it call the actual old55 ADAPT evaluator. Both factor-gradient loops use that saved G_W and the same old factors; each two-term contraction finishes before scaling. _sgd forms every A then B proposal before publishing either factor. No proposed A can enter a B derivative.

mechanics_experiment prepares data once, actually evaluates PRE stages 0,1,2 with two full eta0.5 transitions, and copies its final evaluated base. It initializes identity-row A with positive-zero B or both-zero factors, then retains adapter stages 0 through U and exactly U transitions. Its richer internal evidence includes materialization/contraction operands and histories. It is not the public thirteen-field helper result.

transfer_trace() provides a structural observer with steps and add; it checks unique nonempty IDs, finite saved operands and the 512-frame bound. A different coherent observer is allowed; unknown observer failures escape. _readout_records, _evaluation_records and _update_records serialize retained evidence without recomputing contractions. Public evaluate_lora(..., trace, prefix) returns thirteen fields with the complete nested eight-field readout and twenty-one combined tensors. Public lora_sgd(..., trace, prefix) returns A, B and two update tensors. The mechanics-only variants are named evaluate_lora_mechanics and lora_sgd_mechanics; their richer evidence is not mislabeled the public schema.

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.

"""IV56 canonical numerical mechanisms and public helpers — ALL EXECUTION UNRUN.

NumPy only stores arrays. Every arithmetic primitive below uses Python floats
in the declared order. Public projections bind the owner-adopted inventory to retained numerical
evidence. Read all four adjacent project files; imports and queries run no checks.
"""
from copy import deepcopy
import importlib.util
import sys
from pathlib import Path
from types import MappingProxyType

import numpy as np

# Load one actual IV55 module, which in turn loads its actual adjacent mechanism.
# Reusing this identity avoids a second NumericalFault class or duplicate loader.
_spec = importlib.util.spec_from_file_location(
    "_p14_iv56_iv55", Path(__file__).resolve().with_name("iv55.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent iv55.py")
_iv55 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_iv55)
_transfer = _iv55._reference
NumericalFault = _iv55.NumericalFault

RAW_KEYS = ("rank", "alpha", "initialization", "updates", "eta")
DEFAULT_IV56 = MappingProxyType(dict(rank=1, alpha=1, initialization=0, updates=1, eta=0.5))


def lora_state(value):
    """Raw five-field replacement: structure, ALL finite numbers, then domains."""
    if type(value) is not dict:
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    if len(value) != 5 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 rank, alpha, initialization, updates, eta as own fields.")
    saved = {key: value[key] for key in RAW_KEYS}
    for key in RAW_KEYS:
        _transfer._number(saved[key], key)
    for key in ("rank", "alpha"):
        if saved[key] not in (1, 2):
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer 1 or 2.")
    if saved["initialization"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "initialization must be numeric 0 or 1.")
    if not 0 <= saved["updates"] <= 3 or int(saved["updates"]) != saved["updates"]:
        raise NumericalFault("INVALID_INPUT", "updates must be an integer from 0 to 3.")
    if not 0.0 <= saved["eta"] <= 2.0:
        raise NumericalFault("INVALID_INPUT", "eta must be between 0 and 2.")
    return dict(rank=int(saved["rank"]), alpha=int(saved["alpha"]),
                initialization=int(saved["initialization"]), updates=int(saved["updates"]),
                eta=float(saved["eta"]))


def _rank(value):
    # Rank is a dimension selector: its finite/domain guards precede ALL shapes.
    _transfer._number(value, "rank")
    if value not in (1, 2):
        raise NumericalFault("INVALID_INPUT", "rank must be an integer 1 or 2.")
    return int(value)


def _evaluate(base, A, B, data, rank, alpha):
    """Materialize RN(W0 + c RN(BA)), then use the actual IV55 ADAPT readout."""
    stored_A = np.array(A, dtype=np.float64).reshape((rank, 2))
    stored_B = np.array(B, dtype=np.float64).reshape((2, rank))
    scale = _transfer._finite(float(alpha) / float(rank), "LoRA scale")
    product, delta, weights, materialization = [], [], [], []
    for output in range(2):
        for feature in range(2):
            total, terms = 0.0, []
            for k in range(rank):
                left, right = float(stored_B[output, k]), float(stored_A[k, feature])
                term = _transfer._finite(left * right, "LoRA product term")
                old = total
                total = _transfer._finite(old + term, "LoRA product sum")
                terms.append(dict(k=k, B=left, A=right, product=term, old=old, total=total))
            scaled = _transfer._finite(scale * total, "LoRA scaled product")
            coordinate = 2 * output + feature
            effective = _transfer._finite(base[coordinate] + scaled, "LoRA effective weight")
            product.append(total)
            delta.append(scaled)
            weights.append(effective)
            materialization.append(dict(coordinate=coordinate, output=output, feature=feature,
                                        initialSum=0.0, terms=terms, product=total, scale=scale,
                                        delta=scaled, base=base[coordinate], weight=effective))
    # This is the accepted mechanism, not W0*phi + c*B*(A*phi).
    readout = _iv55.evaluate_transfer(weights, data, 1, [1, 1, 1, 1])
    G = readout["mathematicalGradient"]
    gradient_A, gradient_B, contractions_A, contractions_B = [], [], [], []
    for k in range(rank):
        for feature in range(2):
            total, terms = 0.0, []
            for output in range(2):
                left, right = float(stored_B[output, k]), G[2 * output + feature]
                term = _transfer._finite(left * right, "LoRA A gradient term")
                old = total
                total = _transfer._finite(old + term, "LoRA A gradient sum")
                terms.append(dict(index=output, left=left, right=right, product=term, old=old, total=total))
            gradient = _transfer._finite(scale * total, "LoRA A gradient")
            gradient_A.append(gradient)
            contractions_A.append(dict(coordinate=2 * k + feature, initialSum=0.0,
                                       terms=terms, sum=total, scale=scale, gradient=gradient))
    for output in range(2):
        for k in range(rank):
            total, terms = 0.0, []
            for feature in range(2):
                left, right = G[2 * output + feature], float(stored_A[k, feature])
                term = _transfer._finite(left * right, "LoRA B gradient term")
                old = total
                total = _transfer._finite(old + term, "LoRA B gradient sum")
                terms.append(dict(index=feature, left=left, right=right, product=term, old=old, total=total))
            gradient = _transfer._finite(scale * total, "LoRA B gradient")
            gradient_B.append(gradient)
            contractions_B.append(dict(coordinate=output * rank + k, initialSum=0.0,
                                       terms=terms, sum=total, scale=scale, gradient=gradient))
    # Real-expression derivatives at saved words, not derivatives of rounding.
    return dict(base=base[:], A=A[:], B=B[:], data=[row[:] for row in data],
                rank=rank, alpha=alpha, scale=scale, product=product, delta=delta,
                weights=weights, readout=readout, gradientA=gradient_A, gradientB=gradient_B,
                materialization=materialization, contractionsA=contractions_A, contractionsB=contractions_B)


def _evaluation_inputs(base_value, A_value, B_value, data_value, rank_value, alpha_value):
    """Ambient coherent finite arrays accepted; no learned-state/origin brand."""
    rank = _rank(rank_value)
    base = _transfer._vector(base_value, 4, "base")
    A = _transfer._vector(A_value, 2 * rank, "A")
    B = _transfer._vector(B_value, 2 * rank, "B")
    data = _transfer._data(data_value)
    groups = [("base", base), ("A", A), ("B", B),
              *[(f"data[{i}]", row) for i, row in enumerate(data)]]
    _transfer._numbers(groups)
    _transfer._number(alpha_value, "alpha")
    # All captured numbers, including representability, precede alpha policy.
    converted = _transfer._binary64(groups)
    if alpha_value not in (1, 2):
        raise NumericalFault("INVALID_INPUT", "alpha must be an integer 1 or 2.")
    return converted[0], converted[1], converted[2], converted[3:], rank, int(alpha_value)


def evaluate_lora_mechanics(base_value, A_value, B_value, data_value, rank_value, alpha_value):
    """Retained FIRST arithmetic after the shared complete input boundary."""
    return _evaluate(*_evaluation_inputs(base_value, A_value, B_value, data_value, rank_value, alpha_value))


def _sgd(A, B, gradient_A, gradient_B, rank, eta):
    rows, proposed_A, proposed_B = [], [], []
    for factor, (old_factor, gradient_factor, proposed) in enumerate(
            ((A, gradient_A, proposed_A), (B, gradient_B, proposed_B))):
        for coordinate in range(2 * rank):
            old, gradient = old_factor[coordinate], gradient_factor[coordinate]
            delta = _transfer._finite(eta * gradient, "LoRA SGD delta")
            value = _transfer._finite(old - delta, "LoRA SGD proposed")
            proposed.append(value)
            rows.append(dict(factor=factor, coordinate=coordinate, old=old, gradient=gradient,
                             eta=eta, delta=delta, proposed=value))
    # Every A AND B proposal is finished before either factor is published.
    committed_A, committed_B = proposed_A[:], proposed_B[:]
    for row in rows:
        row["committed"] = (committed_A if row["factor"] == 0 else committed_B)[row["coordinate"]]
    return dict(A=committed_A, B=committed_B, coordinates=rows)


def _sgd_inputs(A_value, B_value, gradient_A_value, gradient_B_value, rank_value, eta_value):
    """Accept arbitrary finite gradients; coherence belongs to the caller."""
    rank = _rank(rank_value)
    A = _transfer._vector(A_value, 2 * rank, "A")
    B = _transfer._vector(B_value, 2 * rank, "B")
    gradient_A = _transfer._vector(gradient_A_value, 2 * rank, "gradientA")
    gradient_B = _transfer._vector(gradient_B_value, 2 * rank, "gradientB")
    groups = [("A", A), ("B", B), ("gradientA", gradient_A), ("gradientB", gradient_B)]
    _transfer._numbers(groups)
    _transfer._number(eta_value, "eta")
    converted = _transfer._binary64(groups)
    if not 0.0 <= eta_value <= 2.0:
        raise NumericalFault("INVALID_INPUT", "eta must be between 0 and 2.")
    return (*converted, rank, float(eta_value))


def lora_sgd_mechanics(A_value, B_value, gradient_A_value, gradient_B_value, rank_value, eta_value):
    """Retained FIRST simultaneous proposals after the shared input boundary."""
    return _sgd(*_sgd_inputs(A_value, B_value, gradient_A_value, gradient_B_value, rank_value, eta_value))


def mechanics_experiment(value):
    """Actually PRE2 from zero, freeze its copy, then evaluate/update both factors."""
    state = lora_state(value)
    prepared_data = _iv55.fixed_data()
    data = prepared_data["data"]
    weights, pre_stages, pre_transitions = [0.0, 0.0, 0.0, 0.0], [], []
    for stage in range(3):
        evaluated = _iv55.evaluate_transfer(weights, data, 0, [1, 1, 1, 1])
        evaluated.update(stage=stage, diagnosticOnly=int(stage == 2))
        pre_stages.append(evaluated)
        if stage < 2:
            transition = _iv55.transfer_sgd(weights, evaluated["mathematicalGradient"],
                                            evaluated["effectiveGradient"], [1, 1, 1, 1], 0.5)
            pre_transitions.append(transition)
            weights = transition["weights"][:]
    base = pre_stages[-1]["weights"][:]
    rank = state["rank"]
    A, B = [0.0] * (2 * rank), [0.0] * (2 * rank)
    if state["initialization"] == 0:
        for k in range(rank):
            A[2 * k + k] = 1.0
    initial_A, initial_B = A[:], B[:]
    stages, transitions = [], []
    for stage in range(state["updates"] + 1):
        evaluated = evaluate_lora_mechanics(base, A, B, data, rank, state["alpha"])
        evaluated.update(stage=stage, diagnosticOnly=int(stage == state["updates"]))
        stages.append(evaluated)
        if stage < state["updates"]:
            transition = lora_sgd_mechanics(A, B, evaluated["gradientA"], evaluated["gradientB"],
                                           rank, state["eta"])
            transitions.append(transition)
            A, B = transition["A"][:], transition["B"][:]
    pre = dict(initialWeights=[0.0, 0.0, 0.0, 0.0], task=0, mask=[1, 1, 1, 1], eta=0.5,
               stages=pre_stages, transitions=pre_transitions)
    adapter = dict(initialA=initial_A, initialB=initial_B, stages=stages, transitions=transitions)
    return deepcopy(dict(state=state, data=data, construction=prepared_data["construction"], pre=pre,
                         preparedCopy=dict(sourceWeights=pre_stages[-1]["weights"][:], weights=base[:]),
                         base=base, adapter=adapter))


# Exact literal metadata from the adopted model, never parsed from TypeScript.
_STEP_PROSE = {
    "materialize": (
        "Materialize one effective readout coordinate",
        "scale=alpha/rank once before coordinate0; term_k=B[o,k]*A[k,i]; sum starts at +0 and adds term_k in increasing k; product=sum; delta=scale*product; weight=base+delta",
        "Multiply each old factor pair separately, then add in rank order from floating positive zero. Scale the completed contraction and add the frozen base entry. The readout will use this saved matrix, so no alternative factor-forward expression can change the rounding order. The base is copied, never optimized."),
    "gradientA": (
        "Apply the chain rule to one A coordinate",
        "term_o=B[o,k]*G_W[o,i]; sum starts at +0 and adds output0 then output1; contraction=sum; gradient=scale*contraction",
        "Changing A changes the effective matrix through the same old B. Contract the two saved readout derivatives with that B column, then scale once after the sum. These are real-expression derivatives evaluated at the saved words, not derivatives of the rounding map. A zero B makes this contraction zero."),
    "gradientB": (
        "Apply the chain rule to one B coordinate",
        "term_i=G_W[o,i]*A[k,i]; sum starts at +0 and adds feature0 then feature1; contraction=sum; gradient=scale*contraction",
        "Changing B changes the effective matrix through the same old A. Multiply the saved readout derivatives by that A row, add both terms, and only then apply scale. No A proposal has been made. When both old factors are zero, both factor gradients vanish even though the readout derivative can be nonzero."),
    "coordinate": (
        "Propose one factor coordinate from the unchanged old state",
        "delta=eta*gradient; proposed=old-delta; committed=proposed at the later simultaneous factor commit",
        "All A proposals precede all B proposals, but neither factor is published until both are complete. Every multiplication and subtraction takes place even for eta positive or negative zero. W0 has no optimizer proposal; gradients are supplied from one coherent old evaluation."),
    "commit": (
        "Publish both complete factor proposals together",
        "nextA=[all proposed A coordinates]; nextB=[all proposed B coordinates]; publish the pair simultaneously",
        "One optimizer step commits this pair. Neither gradient used an updated factor. The next stage rematerializes the effective matrix and performs a complete new evaluation. The final requested stage has diagnostics and no additional commit."),
}


class _Trace:
    """Canonical structural observer; no origin brand is required by helpers."""
    def __init__(self):
        self.steps = []
        self._ids = set()

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        if type(identifier) is not str or not identifier or identifier in self._ids:
            raise NumericalFault("INVALID_INPUT", "Trace IDs must be nonempty and unique.")
        for key, value in [*inputs.items(), *outputs.items()]:
            if type(value) not in (int, float) or not -sys.float_info.max <= value <= sys.float_info.max:
                raise NumericalFault("NONFINITE", f"{key} must be finite.")
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        self.steps.append(deepcopy(dict(id=identifier, label=label, equation=equation,
                                        explanation=explanation, inputs=inputs, outputs=outputs)))
        self._ids.add(identifier)


def transfer_trace():
    return _Trace()


def _scope(prefix):
    import re
    if type(prefix) is not str or re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", prefix) is None:
        raise NumericalFault("INVALID_INPUT", "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores.")


def _step(trace, identifier, family, inputs, outputs):
    trace.add(identifier, *_STEP_PROSE[family], inputs, outputs)


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


def _readout_records(evaluated, data, prefix, trace):
    steps = []
    tensors = _iv55._evaluation_records(evaluated, data, prefix, steps)
    for step in steps:
        trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    return dict(weights=evaluated["weights"][:], predictions=evaluated["predictions"][:],
                trainHalfMSE=evaluated["trainHalfMSE"], validationHalfMSE=evaluated["validationHalfMSE"],
                mathematicalGradient=evaluated["mathematicalGradient"][:],
                effectiveGradient=evaluated["effectiveGradient"][:], mask=evaluated["mask"][:], tensors=tensors)


def _evaluation_records(evaluated, data, prefix, trace):
    """Project retained FIRST operands; no numerical contraction is recomputed."""
    rank, alpha, scale = evaluated["rank"], evaluated["alpha"], evaluated["scale"]
    product_rows, rows_A, rows_B = [], [], []
    for row in evaluated["materialization"]:
        coordinate = row["coordinate"]
        inputs = dict(coordinate=coordinate, output=row["output"], feature=row["feature"],
                      rank=rank, alpha=alpha, scale=scale, base=row["base"], initialSum=row["initialSum"])
        outputs = dict(scale=scale) if coordinate == 0 else {}
        for k, term in enumerate(row["terms"]):
            inputs[f"b{k}"], inputs[f"a{k}"] = term["B"], term["A"]
            outputs[f"product{k}"], outputs[f"sum{k}"] = term["product"], term["total"]
            product_rows.extend(term[key] for key in ("product", "old", "total"))
        outputs.update(product=row["product"], delta=row["delta"], weight=row["weight"])
        _step(trace, f"{prefix}_materialize_{coordinate}", "materialize", inputs, outputs)
    readout = _readout_records(evaluated["readout"], data, f"{prefix}_readout", trace)
    for factor, rows, stored_rows in (("A", evaluated["contractionsA"], rows_A),
                                      ("B", evaluated["contractionsB"], rows_B)):
        for coordinate, row in enumerate(rows):
            inputs = (dict(coordinate=coordinate, k=coordinate // 2, feature=coordinate % 2)
                      if factor == "A" else dict(coordinate=coordinate, output=coordinate // rank, k=coordinate % rank))
            inputs.update(scale=scale, initialSum=row["initialSum"])
            outputs = {}
            for index, term in enumerate(row["terms"]):
                left, right = ("b", "g") if factor == "A" else ("g", "a")
                inputs[f"{left}{index}"], inputs[f"{right}{index}"] = term["left"], term["right"]
                outputs[f"product{index}"], outputs[f"sum{index}"] = term["product"], term["total"]
                stored_rows.extend(term[key] for key in ("product", "old", "total"))
            outputs.update(contraction=row["sum"], gradient=row["gradient"])
            _step(trace, f"{prefix}_gradient{factor}_{coordinate}", f"gradient{factor}", inputs, outputs)
    tensors = [
        _tensor(f"{prefix}_Base", [2, 2], ["Output", "Feature"], evaluated["base"], "Exact floating-word copy of the frozen base supplied to this evaluation; no base optimizer proposal."),
        _tensor(f"{prefix}_A", [rank, 2], ["Rank", "Feature"], evaluated["A"], "Detached actual old A factor in rank-major then feature order."),
        _tensor(f"{prefix}_B", [2, rank], ["Output", "Rank"], evaluated["B"], "Detached actual old B factor in output-major then rank order."),
        _tensor(f"{prefix}_ProductRows", [2, 2, rank, 3], ["Output", "Feature", "Rank", "ContractionField"], product_rows, "Actual product,oldSum,sum for BA; coordinate-major, increasing rank; every accumulator starts at floating positive zero."),
        _tensor(f"{prefix}_Product", [2, 2], ["Output", "Feature"], evaluated["product"], "Actual separately rounded BA entries after their ordered contractions; no numerical rank certificate."),
        _tensor(f"{prefix}_Delta", [2, 2], ["Output", "Feature"], evaluated["delta"], "Actual scale times completed BA entries; structural exact-real rank(cBA)<=r does not certify the exact rank of these rounded words."),
        _tensor(f"{prefix}_Weights", [2, 2], ["Output", "Feature"], evaluated["weights"], "Actual base+delta entries, materialized before the unchanged IV55 ADAPT evaluation."),
        *deepcopy(readout["tensors"]),
        _tensor(f"{prefix}_GradientRowsA", [rank, 2, 2, 3], ["Rank", "Feature", "Output", "ContractionField"], rows_A, "Actual product,oldSum,sum for B-transpose times the same saved G_W; output0 then output1; scale applied only after each contraction."),
        _tensor(f"{prefix}_GradientRowsB", [2, rank, 2, 3], ["Output", "Rank", "Feature", "ContractionField"], rows_B, "Actual product,oldSum,sum for the same saved G_W times A-transpose; feature0 then feature1; scale applied only after each contraction."),
        _tensor(f"{prefix}_GradientA", [rank, 2], ["Rank", "Feature"], evaluated["gradientA"], "Actual scale*(B-transpose G_W), computed entirely from old factors and saved materialized readout errors."),
        _tensor(f"{prefix}_GradientB", [2, rank], ["Output", "Rank"], evaluated["gradientB"], "Actual scale*(G_W A-transpose), computed entirely from the same old factors and readout errors."),
    ]
    return dict(base=evaluated["base"][:], A=evaluated["A"][:], B=evaluated["B"][:], rank=rank, alpha=alpha,
                scale=scale, product=evaluated["product"][:], delta=evaluated["delta"][:], weights=evaluated["weights"][:],
                readout=readout, gradientA=evaluated["gradientA"][:], gradientB=evaluated["gradientB"][:], tensors=tensors)


def evaluate_lora(base_value, A_value, B_value, data_value, rank_value, alpha_value, trace, prefix):
    """Public thirteen-field helper, with the dimension/numeric/prefix boundary."""
    captured = _evaluation_inputs(base_value, A_value, B_value, data_value, rank_value, alpha_value)
    _scope(prefix)
    return _evaluation_records(_evaluate(*captured), captured[3], prefix, trace)


def _update_records(transition, rank, prefix, trace):
    rows_A, rows_B = [], []
    for row in transition["coordinates"]:
        factor, coordinate = row["factor"], row["coordinate"]
        name = "A" if factor == 0 else "B"
        inputs = {key: row[key] for key in ("factor", "coordinate", "old", "gradient", "eta")}
        outputs = {key: row[key] for key in ("delta", "proposed", "committed")}
        _step(trace, f"{prefix}_{name}_{coordinate}", "coordinate", inputs, outputs)
        (rows_A if factor == 0 else rows_B).extend(row[key] for key in ("old", "gradient", "delta", "proposed", "committed"))
    inputs, outputs = {}, {}
    for factor in ("A", "B"):
        offset = 0 if factor == "A" else 2 * rank
        inputs.update({f"old{factor}{i}": transition["coordinates"][offset + i]["old"] for i in range(2 * rank)})
        outputs.update({f"{factor}{i}": value for i, value in enumerate(transition[factor])})
    _step(trace, f"{prefix}_commit", "commit", inputs, outputs)
    return dict(A=transition["A"][:], B=transition["B"][:], tensors=[
        _tensor(f"{prefix}_UpdateA", [rank, 2, 5], ["Rank", "Feature", "FactorUpdateField"], rows_A, "Actual old,gradient,delta,proposed,committed for every A coordinate; committed copies the proposal published with all B proposals."),
        _tensor(f"{prefix}_UpdateB", [2, rank, 5], ["Output", "Rank", "FactorUpdateField"], rows_B, "Actual old,gradient,delta,proposed,committed for every B coordinate; all gradients belong to the same old A/B pair."),
    ])


def lora_sgd(A_value, B_value, gradient_A_value, gradient_B_value, rank_value, eta_value, trace, prefix):
    """Public three-field update, retaining all proposals and the pair commit."""
    captured = _sgd_inputs(A_value, B_value, gradient_A_value, gradient_B_value, rank_value, eta_value)
    _scope(prefix)
    return _update_records(_sgd(*captured), captured[4], prefix, trace)

4. iv56.py: the complete public result and command line

derive_iv56(value) asks the new mechanics for the actual experiment, then binds retained data, PRE, factors, readouts, contractions, proposals and trajectories to the ordered public record. New56 metadata distinguishes its PRE initialization/Stats from old55’s whole-cohort format. Literal _texts strings and field arrays describe that same record; initialization selects the actual matching policy text. The wrapper retains 76 summaries, all 43 work fields, 38 text fields and every once-only step-output alias. A repeated alias raises an unexpected error rather than overwriting evidence. Detached final copies preserve their floating words, including -0.

Only known NumericalFault instances become status, code, reason unavailable data. Unknown import, semantic, observer, resource or serialization errors escape. A defined root is status, outputs, steps, tensors, texts. evaluate_lora, lora_sgd and transfer_trace are exposed by identity from the actual loaded helper module. DEFAULT_IV56 is an immutable mapping; dict(DEFAULT_IV56) requests a detached complete default object. Passing {} to the derivation does not select defaults.

All project imports resolve adjacent paths from __file__. The actual chain is iv56 → lora_reference → iv55 → transfer_reference. The wrapper’s _legacy is the same actual iv55 module as the helper’s _iv55; _reference._transfer is that legacy module’s mechanism. No cwd project-module shadow, TypeScript parser, independent authority or extra task experiment is part of the intended canonical closure.

The stable zero-argument run() delegates to run_query_cli(derive_iv56). With no command-line arguments, it selects the complete default. One JSON argument or - stdin supplies a full replacement, never a partial merge. These examples are source instructions for use from the Book IV root:

# Complete default public record.
python3 code/python/p14/iv56.py

# Full replacement with no adapter transitions.
python3 code/python/p14/iv56.py '{"rank":2,"alpha":1,"initialization":0,"updates":0,"eta":0.5}'

# Full replacement through stdin, retaining a negative-zero rate.
python3 code/python/p14/iv56.py - <<'JSON'
{"rank":1,"alpha":1,"initialization":1,"updates":1,"eta":-0}
JSON

# Explicit nine-terminal checks only.
python3 code/python/p14/iv56.py --self-check

Defined and known-unavailable queries print JSON with exit status 0. Malformed/duplicate/nonstandard JSON is caught only around strict_json, as ValueError, and becomes INVALID_INPUT JSON with exit 0. A syntactically valid huge exponent instead reaches finite-number validation. More than one argument or an unknown -- option prints usage to stderr and returns 2. Semantic evaluation and JSON serialization are outside the parsing catch; unexpected ValueError, JSONDecodeError, parser resource errors and other unknown failures propagate.

The explicit --self-check branch occurs before all parsing/query catches and calls source_self_check, which requires assertions enabled. It directly calls exactly nine terminal functions in this order: check_raw_guards, check_hand_anchors, check_helper_guards_and_words, check_same_old_factor_graph, check_controls_and_closure, check_cli_and_query_isolation, check_public_helpers, check_public_record, check_public_cli. The literal inventory is still named FIRST_CHECK_DECLARATIONS, but it now lists all nine, not the earlier six. _same_words and _expect_fault are supporting functions, not additional terminal checks. Normal imports and queries call none of these checks.

Those authored checks cover guard precedence, paper anchors, rounded-rank limits, old-factor contractions, control branches and copied history, query/check separation, public helper/root schemas and copies, and the actual zero-argument CLI plus file-relative module/declaration identities. The explicit-check isolation probe uses a sentinel replacement, so it does not recursively invoke the suite. A self-check failure escapes; a success message is printed only after the aggregator returns. The final guarded __main__ dispatch occurs after all declarations exist. These are source facts and intended checks, not nine passing results or an exact-FD verdict for arbitrary states.

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.

"""IV56 complete canonical public record — SOURCE ONLY, ALL CHECKS UNRUN.

Retained independent FIRST arithmetic supplies all values. Public helper/root
projections bind the owner-adopted ordered inventory. Exactly four project files:
transfer_reference.py, iv55.py, lora_reference.py, iv56.py (adjacent/file-relative).
Imports and queries run no checks; --self-check explicitly runs nine terminals.
"""
import importlib.util
from pathlib import Path

_spec = importlib.util.spec_from_file_location(
    "_p14_iv56_lora_reference", Path(__file__).resolve().with_name("lora_reference.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent lora_reference.py")
_reference = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_reference)
_legacy = _reference._iv55

DEFAULT_IV56 = _reference.DEFAULT_IV56
NumericalFault = _reference.NumericalFault
lora_state = _reference.lora_state
evaluate_lora_mechanics = _reference.evaluate_lora_mechanics
lora_sgd_mechanics = _reference.lora_sgd_mechanics
mechanics_experiment = _reference.mechanics_experiment
strict_json = _legacy.strict_json


def _same_words(actual, expected):
    assert len(actual) == len(expected)
    for left, right in zip(actual, expected):
        assert type(left) is float and type(right) is float
        assert _reference._transfer._word(left) == _reference._transfer._word(right)


def _expect_fault(code, reason, operation, *args):
    try:
        operation(*args)
    except NumericalFault as fault:
        assert fault.code == code and str(fault) == reason
    else:
        raise AssertionError(f"Expected {code}: {reason}")


def check_raw_guards():
    default = dict(DEFAULT_IV56)
    assert tuple(lora_state(default)) == ("rank", "alpha", "initialization", "updates", "eta")
    for value in (None, [], (), {**default, "extra": 0}, {k: v for k, v in default.items() if k != "eta"}):
        code = "state must be a plain object." if type(value) is not dict else "state must have exactly rank, alpha, initialization, updates, eta as own fields."
        _expect_fault("INVALID_INPUT", code, lora_state, value)
    class DictSubclass(dict):
        pass
    _expect_fault("INVALID_INPUT", "state must be a plain object.", lora_state, DictSubclass(default))
    for key in default:
        for bad in (True, False, None, "0", float("nan"), float("inf"), -float("inf")):
            _expect_fault("NONFINITE", f"{key} must be an actual finite number.", lora_state, {**default, key: bad})
    for key in ("rank", "alpha"):
        for bad in (0, 3, 1.5, 10 ** 400):
            _expect_fault("INVALID_INPUT", f"{key} must be an integer 1 or 2.", lora_state, {**default, key: bad})
    for bad in (-1, 2, 0.5, 10 ** 400):
        _expect_fault("INVALID_INPUT", "initialization must be numeric 0 or 1.", lora_state, {**default, "initialization": bad})
    for bad in (-1, 4, 1.5, 10 ** 400):
        _expect_fault("INVALID_INPUT", "updates must be an integer from 0 to 3.", lora_state, {**default, "updates": bad})
    for bad in (-0.5, 2.5, 10 ** 400):
        _expect_fault("INVALID_INPUT", "eta must be between 0 and 2.", lora_state, {**default, "eta": bad})
    _expect_fault("NONFINITE", "eta must be an actual finite number.", lora_state,
                  {**default, "rank": 10 ** 400, "updates": 0, "initialization": 1, "eta": float("nan")})
    _same_words([lora_state({**default, "eta": -0.0})["eta"]], [-0.0])
    assert all(type(lora_state(default)[key]) is int for key in ("rank", "alpha", "initialization", "updates"))


def check_hand_anchors():
    """Paper-derived expectations only: none of these numbers initialize PRE."""
    result = mechanics_experiment(dict(DEFAULT_IV56))
    assert len(result["pre"]["stages"]) == 3 and len(result["pre"]["transitions"]) == 2
    for stage, diagonal in zip(result["pre"]["stages"], (0.0, 5.0 / 32.0, 295.0 / 1024.0)):
        _same_words(stage["weights"], [diagonal, 0.0, 0.0, diagonal])
    initial, final = result["adapter"]["stages"]
    _same_words(initial["readout"]["mathematicalGradient"],
                [-3645.0 / 16384.0, -5.0 / 32.0, 5.0 / 32.0, -3645.0 / 16384.0])
    _same_words(initial["gradientA"], [0.0, 0.0])
    _same_words(initial["gradientB"], [-3645.0 / 16384.0, 5.0 / 32.0])
    _same_words(final["A"], [1.0, 0.0])
    _same_words(final["B"], [3645.0 / 32768.0, -5.0 / 64.0])
    _same_words(final["weights"], [13085.0 / 32768.0, 0.0, -5.0 / 64.0, 295.0 / 1024.0])
    initial_loss = 3967925.0 / 16777216.0
    assert initial["readout"]["trainHalfMSE"] == initial_loss
    assert final["readout"]["trainHalfMSE"] == initial_loss * (1753.0 / 2048.0)
    full = mechanics_experiment({**dict(DEFAULT_IV56), "rank": 2, "alpha": 2})
    full_final = full["adapter"]["stages"][-1]
    _same_words(full_final["weights"],
                [13085.0 / 32768.0, 5.0 / 64.0, -5.0 / 64.0, 13085.0 / 32768.0])
    assert full_final["readout"]["trainHalfMSE"] == initial_loss * (729.0 / 1024.0)
    scaled = mechanics_experiment({**dict(DEFAULT_IV56), "rank": 2, "alpha": 1})["adapter"]["stages"][-1]
    _same_words(scaled["weights"],
                [41405.0 / 131072.0, 5.0 / 256.0, -5.0 / 256.0, 41405.0 / 131072.0])
    assert scaled["readout"]["trainHalfMSE"] == initial_loss * (15129.0 / 16384.0)
    # Separate mathematical limit: rounded entries need not retain ideal rank1.
    from fractions import Fraction
    epsilon = 2.0 ** -27
    A, B = [1.0, 1.0 + epsilon], [1.0, 1.0 + epsilon]
    data = result["data"]
    rounded = evaluate_lora_mechanics([0.0] * 4, A, B, data, 1, 1)["product"]
    a, b, c, d = [Fraction.from_float(value) for value in rounded]
    assert a * d - b * c == -Fraction(1, 2 ** 54)
    _same_words([rounded[0] * rounded[3] - rounded[1] * rounded[2]], [0.0])


def check_helper_guards_and_words():
    data = _legacy.fixed_data()["data"]
    base, A, B = [0.0] * 4, [1.0, 0.0], [0.0, 0.0]
    evaluate = evaluate_lora_mechanics
    _expect_fault("NONFINITE", "rank must be an actual finite number.", evaluate, None, None, None, None, True, None)
    _expect_fault("INVALID_INPUT", "rank must be an integer 1 or 2.", evaluate, None, None, None, None, 3, float("nan"))
    _expect_fault("SHAPE_MISMATCH", "B requires exactly 2 entries.", evaluate, [float("nan")] * 4, A, [], data, 1, 3)
    _expect_fault("SHAPE_MISMATCH", "data[7] requires exactly 7 entries.", evaluate, base, A, B, [*data[:7], []], 1, float("nan"))
    _expect_fault("NONFINITE", "base[0] must be an actual finite number.", evaluate, [True, 0.0, 0.0, 0.0], A, B, data, 1, 3)
    _expect_fault("NONFINITE", "alpha must be an actual finite number.", evaluate, base, A, B, data, 1, float("nan"))
    _expect_fault("NONFINITE", "base requires representable finite binary64 values.", evaluate, [10 ** 400] * 4, A, B, data, 1, 3)
    _expect_fault("INVALID_INPUT", "alpha must be an integer 1 or 2.", evaluate, base, A, B, data, 1, 3)
    _expect_fault("NONFINITE", "LoRA product term must be finite.", evaluate, base, [1e308, 0.0], [2.0, 0.0], data, 1, 1)
    sgd = lora_sgd_mechanics
    _expect_fault("SHAPE_MISMATCH", "gradientB requires exactly 2 entries.", sgd, [float("nan"), 0.0], B, B, [], 1, 3.0)
    _expect_fault("NONFINITE", "eta must be an actual finite number.", sgd, A, B, B, B, 1, float("nan"))
    _expect_fault("NONFINITE", "A requires representable finite binary64 values.", sgd, [10 ** 400, 0.0], B, B, B, 1, 3)
    _expect_fault("INVALID_INPUT", "eta must be between 0 and 2.", sgd, A, B, B, B, 1, 3)
    _expect_fault("NONFINITE", "LoRA SGD delta must be finite.", sgd, A, B, [1e308, 0.0], B, 1, 2.0)
    negative = sgd([-0.0, 0.0], B, [0.0, -0.0], B, 1, -0.0)
    _same_words([row["eta"] for row in negative["coordinates"]], [-0.0] * 4)
    _same_words([row["delta"] for row in negative["coordinates"]], [-0.0, 0.0, -0.0, -0.0])
    ambient = evaluate(base, [1.0, 2.0], [3.0, 4.0], data, 1, 1)
    _same_words(ambient["product"], [3.0, 6.0, 4.0, 8.0])
    base[0], A[0], B[0], data[0][1] = 99.0, 99.0, 99.0, 99.0
    assert ambient["base"][0] == 0.0 and ambient["A"][0] == 1.0 and ambient["B"][0] == 3.0
    assert ambient["data"][0][1] == 0.0
    # Unknown semantic failures must propagate through the actual helper call.
    original = _legacy.evaluate_transfer
    sentinel = RuntimeError("readout sentinel")
    try:
        def broken(*_args):
            raise sentinel
        _legacy.evaluate_transfer = broken
        try:
            evaluate([0.0] * 4, [1.0, 0.0], [0.0, 0.0], _legacy.fixed_data()["data"], 1, 1)
        except RuntimeError as fault:
            assert fault is sentinel
        else:
            raise AssertionError("Unknown helper failure was swallowed.")
    finally:
        _legacy.evaluate_transfer = original


def check_same_old_factor_graph():
    """Nonzero factors exercise both contractions, post-contraction c and SGD."""
    data = _legacy.fixed_data()["data"]
    A, B = [1.0, 2.0, -0.5, 0.25], [0.25, -0.5, 0.75, 1.0]
    evaluated = evaluate_lora_mechanics([0.25, 0.0, 0.0, 0.25], A, B, data, 2, 1)
    G = evaluated["readout"]["mathematicalGradient"]
    for name, rows in (("gradientA", evaluated["contractionsA"]), ("gradientB", evaluated["contractionsB"])):
        for coordinate, row in enumerate(rows):
            if name == "gradientA":
                k, feature = coordinate // 2, coordinate % 2
                operands = [(B[2 * o + k], G[2 * o + feature]) for o in range(2)]
            else:
                output, k = coordinate // 2, coordinate % 2
                operands = [(G[2 * output + i], A[2 * k + i]) for i in range(2)]
            total = 0.0
            for saved, (left, right) in zip(row["terms"], operands):
                product = left * right
                _same_words([saved["left"], saved["right"], saved["product"], saved["old"]], [left, right, product, total])
                total = total + product
                _same_words([saved["total"]], [total])
            _same_words([row["gradient"], evaluated[name][coordinate]], [0.5 * total, 0.5 * total])
    transition = lora_sgd_mechanics(A, B, evaluated["gradientA"], evaluated["gradientB"], 2, 0.5)
    for factor, old in enumerate((A, B)):
        gradient = evaluated["gradientA" if factor == 0 else "gradientB"]
        committed = transition["A" if factor == 0 else "B"]
        for coordinate in range(4):
            row = transition["coordinates"][4 * factor + coordinate]
            _same_words([row["old"], row["gradient"], row["delta"], row["proposed"], committed[coordinate]],
                        [old[coordinate], gradient[coordinate], 0.5 * gradient[coordinate],
                         old[coordinate] - 0.5 * gradient[coordinate], old[coordinate] - 0.5 * gradient[coordinate]])
    assert A == [1.0, 2.0, -0.5, 0.25] and B == [0.25, -0.5, 0.75, 1.0]


def check_controls_and_closure():
    """Every raw branch/update bound, frozen base, and exact declaration identities."""
    assert NumericalFault is _legacy.NumericalFault is _reference._transfer.NumericalFault
    assert strict_json is _legacy.strict_json
    assert _legacy.evaluate_transfer is _reference._transfer.evaluate_transfer
    assert _legacy.transfer_sgd is _reference._transfer.transfer_sgd
    assert _legacy.fixed_data is _reference._transfer.fixed_data
    for rank in (1, 2):
        for alpha in (1, 2):
            for initialization in (0, 1):
                for updates in range(4):
                    for eta in (0.0, -0.0, 0.5, 2.0):
                        result = mechanics_experiment(dict(rank=rank, alpha=alpha, initialization=initialization, updates=updates, eta=eta))
                        adapter, base = result["adapter"], result["base"]
                        assert len(adapter["stages"]) == updates + 1 and len(adapter["transitions"]) == updates
                        assert len(result["construction"]) == 8
                        _same_words(base, [295.0 / 1024.0, 0.0, 0.0, 295.0 / 1024.0])
                        for stage, evaluated in enumerate(adapter["stages"]):
                            _same_words(evaluated["base"], base)
                            assert evaluated["diagnosticOnly"] == int(stage == updates)
                            assert len(evaluated["materialization"]) == 4
                            assert len(evaluated["gradientA"]) == len(evaluated["gradientB"]) == 2 * rank
                            assert all(len(row["terms"]) == rank for row in evaluated["materialization"])
                            assert len(evaluated["readout"]["forwards"]) == 8
                            if initialization == 1:
                                _same_words(evaluated["gradientA"], [0.0] * (2 * rank))
                                _same_words(evaluated["gradientB"], [0.0] * (2 * rank))
                                _same_words(evaluated["weights"], base)
                                assert any(g != 0.0 for g in evaluated["readout"]["mathematicalGradient"])
                            if stage < updates:
                                transition = adapter["transitions"][stage]
                                assert len(transition["coordinates"]) == 4 * rank
                                _same_words(transition["A"], adapter["stages"][stage + 1]["A"])
                                _same_words(transition["B"], adapter["stages"][stage + 1]["B"])
                                _same_words([row["eta"] for row in transition["coordinates"]], [eta] * (4 * rank))
                        # Nested history, frozen copies and factors are detached.
                        adapter["stages"][0]["base"][0] = 99.0
                        assert result["base"][0] == 295.0 / 1024.0
                        assert result["preparedCopy"]["weights"][0] == 295.0 / 1024.0
                        adapter["initialA"][0] = 99.0
                        assert adapter["stages"][0]["A"][0] != 99.0


def run_query_cli(query, args=None, stdin=None):
    """Strict CLI boundary shared by run() and explicit boundary checks."""
    import json
    import sys
    args = sys.argv[1:] if args is None else args
    stdin = sys.stdin if stdin is None else stdin
    if args == ["--self-check"]:
        source_self_check()  # Explicit checks outside ALL parsing/query catches.
        print("IV56 canonical source self-checks completed (9 terminal checks).")
        return 0
    if len(args) > 1 or (args and args[0].startswith("--")):
        print("Usage: iv56.py [JSON|-|--self-check]", file=sys.stderr)
        return 2
    if not args:
        value = dict(DEFAULT_IV56)
    else:
        source = stdin.read() if args[0] == "-" else args[0]
        try:
            value = strict_json(source)
        except ValueError as fault:
            print(json.dumps(dict(status="unavailable", code="INVALID_INPUT", reason=str(fault)), allow_nan=False))
            return 0
    # Deliberately no ValueError catch around semantic evaluation or serialization.
    try:
        record = query(value)
    except NumericalFault as fault:
        record = dict(status="unavailable", code=fault.code, reason=str(fault))
    print(json.dumps(record, allow_nan=False))
    return 0


def check_cli_and_query_isolation():
    """Boundary callbacks isolate parser failures; actual public queries are also checked."""
    import contextlib
    import io
    import json
    observed = []
    def query(value):
        observed.append(value)
        return {"received": lora_state(value)}
    def invoke(callback, args, source=""):
        out, err = io.StringIO(), io.StringIO()
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            code = run_query_cli(callback, args, io.StringIO(source))
        return code, out.getvalue(), err.getvalue()
    for args, source in (([], ""), (["-"], '{"rank":1,"alpha":1,"initialization":0,"updates":0,"eta":-0}')):
        code, output, error = invoke(query, args, source)
        assert code == 0 and not error
        if args:
            _same_words([json.loads(output)["received"]["eta"]], [-0.0])
    for source in ("{", "{} {}", '{"eta":0,"eta":1}', "NaN", "Infinity", "-Infinity", "null", "{}"):
        code, output, error = invoke(query, [source])
        assert code == 0 and not error
        assert tuple(json.loads(output)) == ("status", "code", "reason")
    for args in (["{}", "{}"], ["--unknown"]):
        code, output, error = invoke(query, args)
        assert code == 2 and not output and "Usage:" in error
    for sentinel in (ValueError("semantic sentinel"), json.JSONDecodeError("semantic parser class", "", 0), MemoryError("resource sentinel")):
        def broken(_value):
            raise sentinel
        try:
            invoke(broken, ["{}"])
        except type(sentinel) as fault:
            assert fault is sentinel
        else:
            raise AssertionError("Unknown semantic failure was swallowed.")
    original_parser = globals()["strict_json"]
    try:
        for sentinel in (RecursionError("parser sentinel"), OverflowError("parser sentinel")):
            def broken_parser(_source):
                raise sentinel
            globals()["strict_json"] = broken_parser
            try:
                invoke(query, ["{}"])
            except type(sentinel) as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Unknown parser/resource failure was swallowed.")
    finally:
        globals()["strict_json"] = original_parser
    # Patch an explicit list, not reflection/discovery. Same real IV55 identities.
    targets = [(globals(), "source_self_check")]
    targets.extend((globals(), name) for name in FIRST_CHECK_DECLARATIONS)
    targets.extend((_legacy.__dict__, name) for name in ("source_self_check", "check_raw_guards", "check_hand_anchors",
                   "check_helper_guards_and_words", "check_memorizer", "check_controls_and_structure",
                   "check_public_record", "check_query_check_isolation", "check_cli_boundary"))
    saved = [(namespace, name, namespace[name]) for namespace, name in targets]
    try:
        def forbidden():
            raise AssertionError("Implicit check called by a query.")
        for namespace, name, _old in saved:
            namespace[name] = forbidden
        mechanics_experiment(dict(DEFAULT_IV56))
        assert derive_iv56(dict(DEFAULT_IV56))["status"] == "defined"
        assert derive_iv56(None)["status"] == "unavailable"
        invoke(derive_iv56, [])
        invoke(derive_iv56, ["{}"])
        invoke(query, [])
    finally:
        for namespace, name, old in saved:
            namespace[name] = old
    original_check = globals()["source_self_check"]
    calls = []
    try:
        def explicit():
            calls.append("explicit")
        globals()["source_self_check"] = explicit
        code, output, error = invoke(query, ["--self-check"])
        assert code == 0 and not error and calls == ["explicit"]
        assert "9 terminal checks" in output
        sentinel = AssertionError("explicit check sentinel")
        def failed():
            raise sentinel
        globals()["source_self_check"] = failed
        try:
            invoke(query, ["--self-check"])
        except AssertionError as fault:
            assert fault is sentinel
        else:
            raise AssertionError("Explicit check failure was swallowed.")
    finally:
        globals()["source_self_check"] = original_check


# Names are an inventory for review, never used to discover/invoke checks.
FIRST_CHECK_DECLARATIONS = (
    "check_raw_guards", "check_hand_anchors", "check_helper_guards_and_words",
    "check_same_old_factor_graph", "check_controls_and_closure", "check_cli_and_query_isolation",
    "check_public_helpers", "check_public_record", "check_public_cli",
)


def source_self_check():
    """Nine explicit terminal checks; only a deliberate caller may invoke this."""
    if not __debug__:
        raise RuntimeError("Explicit source checks require assertions enabled.")
    check_raw_guards()
    check_hand_anchors()
    check_helper_guards_and_words()
    check_same_old_factor_graph()
    check_controls_and_closure()
    check_cli_and_query_isolation()
    check_public_helpers()
    check_public_record()
    check_public_cli()


# Literal adopted metadata; the independent FIRST arithmetic remains upstream.
_STEP_PROSE = {
    "setup": (
        "Freeze an actual prepared readout and learn additive factors",
        "W_eff=W0+(alpha/r)*BA; A:[r,2]; B:[2,r]; trainable=4r; full=4; PRE updates=2 at eta0.5",
        "First really prepare W0 from zero. Then optimize only the factors of an additive update. Editing any raw field restarts this complete declared experiment. The structural bound describes the exact-real factorization, while the saved effective matrix follows explicit binary64 operations."),
    "pre_initial": (
        "Start actual PRE at positive-zero weights",
        "weights=[+0,+0,+0,+0]",
        "These authored zeros start the feature-copy target task. The next three evaluations and two full-coordinate transitions actually construct the frozen base; no prepared fraction is inserted."),
    "pre_stats": (
        "Save the actual PRE state and its diagnostic status",
        "diagnosticOnly=(stage==2); hasNextUpdate=(stage<2); losses belong to this evaluated W",
        "Stage zero precedes updates. Stages one and two follow complete simultaneous full-coordinate updates. Retain the final PRE gradient without a third step; its evaluated weights become the frozen adapter base."),
    "adapt_initial": (
        "Copy the actual PRE2 base and initialize both factors",
        "base=copy(final evaluated PRE weights); A=initialization0?first r identity rows:positive zeros; B=positive zeros",
        "The four base entries are copied exactly and stay frozen for every adapter stage. Initialization chooses actual factor words and shapes. Identity-row A permits B to learn immediately; both-zero factors stall through the real bilinear chain rule."),
    "adapt_stats": (
        "Save one complete adapter state and whether another step follows",
        "diagnosticOnly=(stage==requestedUpdates); hasNextUpdate=(stage<requestedUpdates); losses and both gradients belong to the saved factor pair",
        "Only actual evaluated states enter the trajectory. Stage zero already has a materialized matrix, eight forwards, two losses and both factor gradients. Final-stage gradients are diagnostic only. Even a stalled or zero-rate run retains all requested arithmetic and states."),
    "finish": (
        "Report the actual final adapter losses and honest parameter counts",
        "report saved final losses; factor trainables=4r versus full4; frozen base4 remains stored; structural exact-real rank bound=r",
        "Compare actual evaluated losses, not fitted curves. Rank one saves no trainable coordinates in this toy and rank two uses more; the frozen base remains stored. Structural rank concerns the real factorization and does not certify rounded-matrix rank. Counts describe source work, not measured time, memory or LLM performance."),
}


def _texts(raw):
    return {
        "trainingScope": "A fixed two-feature neural regression readout predicts two numbers. First train all four readout coordinates on PRE, then freeze that actual prepared base and train only two adapter factors on ADAPT. There is no bias, token probability, Transformer or historical pretrained checkpoint.",
        "shapePolicy": "For one sample phi=[max(0,x),max(0,-x)]^T:[2,1]. W0:[2,2], A:[r,2], B:[2,r], BA:[2,2], scale=alpha/r and W_eff=W0+scale*BA:[2,2]. Prediction=W_eff phi:[2,1]. Batch feature rows F:[4,2] require F W_eff^T:[4,2]. AB has shape[r,r] and is a different multiplication.",
        "dataPolicy": "Prepare the accepted IV55 data once: training inputs [-1,-0.5,0.5,1] and held-out inputs [-0.75,-0.25,0.25,0.75]. PRE copies the two ReLU features; ADAPT targets T phi with T=[[1,0.5],[-0.5,1]]. All eight features and both target pairs are saved; validation never supplies a gradient.",
        "preparationPolicy": "Start PRE at four floating positive-zero weights, evaluate stages0,1,2, and actually perform two full-coordinate simultaneous updates at eta=0.5 using the unchanged IV55 helpers. Copy its final evaluated weights into W0. No discarded full IV55 experiment, fresh adaptation cohort or lookup is computed here.",
        "initializationPolicy": "Initialization zero copies the first r identity rows into A and positive zeros into B. Initial BA is zero and G_A is zero, but the actual identity-row A lets B receive nonzero gradients. This deterministic direction choice is not a random initialization." if raw["initialization"] == 0 else "Initialization one copies positive zeros into BOTH A and B. The actual chain rule then gives both factor gradients zero despite a nonzero readout gradient. Every requested operation is still performed: this is a real stalled branch, not a fabricated curve.",
        "materializationPolicy": "For each effective coordinate in row-major order, multiply B[o,k]*A[k,i] separately and add in increasing k from floating positive zero. Scale the completed sum, then add the frozen base entry. Only then call the actual ADAPT readout helper. W0 phi+scale*B(A phi) is not substituted because its rounding order differs.",
        "objectivePolicy": "Each sample saves two predictions, errors=prediction-target, separate error squares, each square divided by two, and the sum of those two half-losses. Each dataset adds its four saved sample losses in order from positive zero and divides by four. The denominator counts samples, not eight scalar outputs; both dataset means are computed independently.",
        "gradientPolicy": "The accepted readout helper computes every G_W[o,i] by four ordered training error*feature products, a reduction from positive zero, and division by four. G_A=scale*(B^T G_W) and G_B=scale*(G_W A^T) each use two separate products, an ordered reduction from positive zero, and scaling AFTER the contraction. All use the SAME OLD A, B, materialized W_eff and saved errors. They are derivatives of the underlying real expression at stored words, not derivatives of the rounding map.",
        "updatePolicy": "For every A coordinate then every B coordinate, compute delta=eta*gradient and proposed=old-delta using one coherent old evaluation. Publish the two complete proposals simultaneously. W0 is never proposed. Stages0..updates are all evaluated; final gradients are diagnostic only. Eta positive or negative zero still performs all multiplications, subtractions, commits and evaluations.",
        "rankPolicy": "structuralRankBound=r bounds the exact-real factorized expression scale*BA at the stored factor values. Separately rounded materialized entries can have a different exact algebraic rank. No numerical rank, SVD, tolerance or floating determinant certificate is reported.",
        "rankCounterexample": "Separate arithmetic limit, not a trajectory point: epsilon=2^-27, A=[1,1+epsilon], B=A^T and scale1 have exact-real rank1. Rounded BA stores bottom-right 1+2epsilon after losing epsilon squared. The exact determinant of those stored entries is -2^-54, while a naive rounded two-product determinant is positive zero. Neither a factor count nor that floating zero certifies rounded-matrix rank.",
        "parameterPolicy": "Full fine-tuning trains four readout coordinates. The adapter trains 4r: rank1 has four, EQUAL to full fine-tuning; rank2 has eight, MORE. Four frozen base coordinates remain stored, giving 4+4r base-and-factor coordinates before materialized matrices, gradients, optimizer records and trace storage. This toy demonstrates no trainable-count saving.",
        "analyticalCounts": "Separate analytical example only: a 4096 by 4096 readout has 16777216 full trainables; rank8 factors have 65536, a ratio of256. The frozen base still exists. These scalar counts are not measured bytes, memory, elapsed time, speed, quality or hardware evidence.",
        "scalePolicy": "Changing rank with alpha fixed changes scale=alpha/r as well as available directions. With identity-row A and zero B, the first effective step contains scale squared. Rank2/alpha2 has scale1 and matches the first full IV55 adaptation step; rank2/alpha1 has scale0.5 and one quarter of that effective step. Rank1 initially changes only its selected feature column. These finite-step outcomes are not a universal rank-quality ordering.",
        "evaluationPolicy": "Held-out inputs change magnitude on the same two feature rays. In exact real arithmetic their feature Gram matrix is half the training one, so held-out loss is half training loss for any fixed readout and these targets. Both means are still evaluated independently in binary64. This grid does not test new directions, nonlinear rules or population generalization.",
        "numericPolicy": "Every numeric primitive is a separate finite binary64 operation with round-to-nearest ties-to-even; no fused multiply-add or reordered contraction. Constants, accumulator zeros, data, factor and base copies, products, sums, scales and proposals preserve floating words including negative zero. Display precision never feeds computation.",
        "diagnosticPolicy": "A prior zero centered-difference budget is scoped ONLY to initial adapter stage0, initialization0, eta=positive0.5, h=2^-12, rank1/alpha1 or rank2/alpha1 or2, after whole central and complete endpoint binding. Every A and B coordinate participates. Initial A endpoint factor words differ while losses coincide because B stays zero; B endpoint losses differ. Rank1/alpha2, both-zero, other eta and later stages receive no exact finite-difference verdict here.",
        "computePolicy": "Work fields count this source algorithm: once-only data preparation, actual readout evaluations and ordered losses, readout and factor-gradient contractions, materialization and simultaneous coordinate proposals. Final diagnostics add arithmetic but no optimizer steps. scaleDivisions includes the wrapper coefficient and one coefficient per adapter evaluation. These counts do not measure runtime or storage bytes.",
        "provenance": "Self-authored fixed inputs and target rules; actual two-step PRE from positive zeros using readonly IV55 mechanisms; exact final-PRE base copies; deterministic identity-row or both-zero factors; all ADAPT points result from actual saved proposals and complete evaluations. No hand-derived expected fraction is an implementation input.",
        "rawFields": ["rank", "alpha", "initialization", "updates", "eta"],
        "parameterKeys": ["W00", "W01", "W10", "W11"],
        "cohortKeys": ["pre", "adapt"],
        "cohortLabels": ["Actual pretraining from zero", "Adapter on the actual frozen PRE2 base"],
        "taskKeys": ["PRE", "ADAPT"],
        "factorKeys": ["A", "B"],
        "initializationLabels": ["Identity rows in A; positive-zero B", "Both factors positive zero: stalled"],
        "dataFields": ["x", "phiPlus", "phiMinus", "preTarget0", "preTarget1", "adaptTarget0", "adaptTarget1"],
        "sampleKeys": ["train0", "train1", "train2", "train3", "validation0", "validation1", "validation2", "validation3"],
        "forwardFields": ["product00", "product01", "product10", "product11", "prediction0", "prediction1"],
        "lossFields": ["target0", "target1", "error0", "error1", "square0", "square1", "half0", "half1", "sampleLoss"],
        "datasetKeys": ["training", "validation"],
        "reductionFields": ["loss", "oldSum", "sum"],
        "gradientRowFields": ["error", "feature", "contribution", "oldSum", "sum"],
        "preUpdateFields": ["old", "mathematical", "effective", "enabled", "delta", "proposed", "committed"],
        "contractionFields": ["product", "oldSum", "sum"],
        "factorUpdateFields": ["old", "gradient", "delta", "proposed", "committed"],
        "stageFields": ["trainHalfMSE", "validationHalfMSE", "diagnosticOnly", "hasNextUpdate"],
        "integerValuePolicy": "All masks are int32 with precision0. Mixed float tables use integer VALUE roles only for pre Update.enabled and every Stats.diagnosticOnly/hasNextUpdate. Rank, alpha, initialization, requested-update counts, indices, dimensions and work counts are VALUE roles; eta, scale, losses, data, arithmetic constants and all copied factor/base words are WORD roles. Pure floating tables retain every zero sign.",
    }


def _step(trace, identifier, family, inputs, outputs):
    trace.add(identifier, *_STEP_PROSE[family], inputs, outputs)


def derive_iv56(value):
    """Bind the actual independent FIRST history to the full adopted public root."""
    try:
        evidence = mechanics_experiment(value)
        raw, data, pre, adapter = (evidence[key] for key in ("state", "data", "pre", "adapter"))
        rank, alpha, initialization, updates, eta = (raw[key] for key in ("rank", "alpha", "initialization", "updates", "eta"))
        scale = _reference._transfer._finite(float(alpha) / float(rank), "LoRA scale")
        trainable = 4 * rank
        trace, tensors = _reference.transfer_trace(), []
        tensor = _reference._tensor
        _step(trace, "setup", "setup", raw.copy(),
              dict(adapterTrainableParameters=trainable, fullFineTuneParameters=4, frozenBaseParameters=4,
                   storedBaseAndFactors=4 + trainable, structuralRankBound=rank, scale=scale,
                   fixedFeatures=2, outputsPerSample=2, trainSamples=4, validationSamples=4, preUpdates=2, preEta=0.5))
        for sample, row in enumerate(evidence["construction"]):
            inputs = dict(sample=sample, training=int(sample < 4), x=row["x"], positiveZero=row["zero"],
                          positiveHalf=row["positiveScale"], negativeHalf=row["negativeScale"])
            outputs = dict(negatedX=row["negativeX"])
            outputs.update({key: row[key] for key in ("phiPlus", "phiMinus", "preTarget0", "preTarget1", "scaledMinus", "adaptTarget0", "scaledPlus", "adaptTarget1")})
            trace.add(f"data_{sample}", *_legacy._STEP_PROSE["data"], inputs, outputs)
        tensors.append(tensor("Data", [8, 7], ["Sample", "DataField"], [entry for row in data for entry in row], "Actual once-prepared readonly55 data in texts.dataFields order; training rows0..3, held-out rows4..7."))
        initial = pre["initialWeights"]
        _step(trace, "pre_initial", "pre_initial", {f"source{i}": value for i, value in enumerate(initial)},
              {f"weight{i}": value for i, value in enumerate(initial)})
        tensors.append(tensor("pre_InitialWeights", [2, 2], ["Output", "Feature"], initial, "Actual PRE initialization: four authored floating positive zeros."))
        pre_metrics, pre_weights = [], []
        for stage, evaluated in enumerate(pre["stages"]):
            prefix = f"pre_stage_{stage}"
            readout = _reference._readout_records(evaluated, data, prefix, trace)
            stats = [readout["trainHalfMSE"], readout["validationHalfMSE"], int(stage == 2), int(stage < 2)]
            tensors.extend(readout["tensors"])
            tensors.append(tensor(f"{prefix}_Stats", [4], ["StageField"], stats, "Actual PRE losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors."))
            inputs = dict(task=0, stage=stage, requestedUpdates=2)
            inputs.update({f"weight{i}": value for i, value in enumerate(evaluated["weights"])})
            inputs.update(trainHalfMSE=stats[0], validationHalfMSE=stats[1])
            _step(trace, f"{prefix}_stats", "pre_stats", inputs,
                  dict(zip(("trainHalfMSE", "validationHalfMSE", "diagnosticOnly", "hasNextUpdate"), stats)))
            pre_metrics.extend(stats[:2])
            pre_weights.extend(evaluated["weights"])
            if stage < 2:
                steps = []
                tensors.append(_legacy._update_records(pre["transitions"][stage], f"pre_update_{stage + 1}", steps))
                for step in steps:
                    trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
        prepared = pre["stages"][-1]
        tensors.extend([
            tensor("pre_StageMetrics", [3, 2], ["Stage", "Dataset"], pre_metrics, "Actual PRE stages0,1,2; training then independently evaluated held-out loss."),
            tensor("pre_StageWeights", [3, 4], ["Stage", "Coordinate"], pre_weights, "Actual PRE evaluated weights in row-major 00,01,10,11 order; two real updates separate the three states."),
        ])
        base, A, B = evidence["base"], adapter["initialA"], adapter["initialB"]
        inputs = dict(rank=rank, alpha=alpha, initialization=initialization, scale=scale)
        inputs.update({f"base{i}": value for i, value in enumerate(base)})
        outputs = {f"base{i}": value for i, value in enumerate(base)}
        outputs.update({f"A{i}": value for i, value in enumerate(A)})
        outputs.update({f"B{i}": value for i, value in enumerate(B)})
        _step(trace, "adapt_initial", "adapt_initial", inputs, outputs)
        tensors.extend([
            tensor("FrozenBase", [2, 2], ["Output", "Feature"], base, "Exact floating-word copy of final evaluated pre_stage_2_Weights; retained and never proposed during adapter SGD."),
            tensor("adapt_InitialA", [rank, 2], ["Rank", "Feature"], A, "Actual first r identity rows for initialization0, or floating positive zeros for initialization1."),
            tensor("adapt_InitialB", [2, rank], ["Output", "Rank"], B, "Actual floating positive-zero B for either initialization; no randomness."),
        ])
        metrics, As, Bs, weights = [], [], [], []
        for stage, evaluated in enumerate(adapter["stages"]):
            prefix = f"adapt_stage_{stage}"
            public = _reference._evaluation_records(evaluated, data, prefix, trace)
            stats = [public["readout"]["trainHalfMSE"], public["readout"]["validationHalfMSE"], int(stage == updates), int(stage < updates)]
            tensors.extend(public["tensors"])
            tensors.append(tensor(f"{prefix}_Stats", [4], ["StageField"], stats, "Actual adapter losses,diagnosticOnly,hasNextUpdate in texts.stageFields order; final two entries are integer VALUE selectors."))
            _step(trace, f"{prefix}_stats", "adapt_stats",
                  dict(stage=stage, requestedUpdates=updates, rank=rank, alpha=alpha, initialization=initialization,
                       eta=eta, scale=public["scale"], trainHalfMSE=stats[0], validationHalfMSE=stats[1]),
                  dict(zip(("trainHalfMSE", "validationHalfMSE", "diagnosticOnly", "hasNextUpdate"), stats)))
            metrics.extend(stats[:2])
            As.extend(public["A"])
            Bs.extend(public["B"])
            weights.extend(public["weights"])
            if stage < updates:
                tensors.extend(_reference._update_records(adapter["transitions"][stage], rank, f"adapt_update_{stage + 1}", trace)["tensors"])
        adapter_stages, stage_count = updates + 1, updates + 4
        tensors.extend([
            tensor("adapt_StageMetrics", [adapter_stages, 2], ["Stage", "Dataset"], metrics, "Only actual adapter stages0..updates; independent training and held-out losses."),
            tensor("adapt_StageA", [adapter_stages, rank, 2], ["Stage", "Rank", "Feature"], As, "Exact copies of evaluated A at each actual adapter stage, including final diagnostic state."),
            tensor("adapt_StageB", [adapter_stages, 2, rank], ["Stage", "Output", "Rank"], Bs, "Exact copies of evaluated B at each actual adapter stage; both factor histories reflect simultaneous commits."),
            tensor("adapt_StageWeights", [adapter_stages, 4], ["Stage", "Coordinate"], weights, "Actual rematerialized effective readout at each stage in row-major 00,01,10,11 order."),
        ])
        samples, contractions = 8 * stage_count, 4 * rank * adapter_stages
        work = dict(
            featureMaps=len(data), featureNegations=len(data), featureMaxSelections=2 * len(data),
            preTargetCopies=2 * len(data), adaptTargetScalings=2 * len(data), adaptTargetAdditions=2 * len(data),
            preparedWeightCopies=len(base), pretrainingStages=3, adapterStages=adapter_stages, stageCount=stage_count,
            forwardSampleEvaluations=samples, forwardProducts=4 * samples, forwardSums=2 * samples,
            readoutGradientBatches=stage_count, readoutGradientContractions=4 * stage_count, gradientRowContributions=4 * stage_count,
            readoutGradientProducts=16 * stage_count, readoutGradientAdditions=16 * stage_count, readoutGradientDivisions=4 * stage_count,
            preOptimizerBatches=2, preCoordinateUpdates=8,
            adapterEvaluations=adapter_stages, scaleDivisions=1 + adapter_stages, materializationProducts=4 * rank * adapter_stages,
            materializationAdditions=4 * rank * adapter_stages, materializationScalings=4 * adapter_stages, baseAdditions=4 * adapter_stages,
            factorGradientContractions=contractions, factorGradientProducts=2 * contractions,
            factorGradientAdditions=2 * contractions, factorGradientScalings=contractions,
            adapterOptimizerBatches=updates, factorCoordinateUpdates=4 * rank * updates,
            factorUpdateProducts=4 * rank * updates, factorUpdateSubtractions=4 * rank * updates, finalDiagnosticBatches=2,
            lossSampleEvaluations=samples, lossComponentErrors=2 * samples, lossSquares=2 * samples, lossHalfDivisions=2 * samples,
            lossOutputSums=samples, orderedLossAdditions=samples, datasetMeanDivisions=2 * stage_count)
        first, final = adapter["stages"][0], adapter["stages"][-1]
        summaries = dict(adaptValidationLoss=final["readout"]["validationHalfMSE"], adaptTrainLoss=final["readout"]["trainHalfMSE"],
                         adapterTrainableParameters=trainable, structuralRankBound=rank)
        inputs = dict(raw, scale=scale, **summaries, **work)
        _step(trace, "finish", "finish", inputs, dict(summaries, **work))
        outputs = dict(summaries, **raw, scale=scale, fullFineTuneParameters=4, frozenBaseParameters=4,
                       storedBaseAndFactors=4 + trainable, fixedFeatures=2, outputsPerSample=2,
                       trainSamples=4, validationSamples=4, preUpdates=2, preEta=0.5,
                       pretrainingTrainLoss=prepared["trainHalfMSE"], pretrainingValidationLoss=prepared["validationHalfMSE"],
                       adaptInitialTrainLoss=first["readout"]["trainHalfMSE"], adaptInitialValidationLoss=first["readout"]["validationHalfMSE"])
        outputs.update({f"baseWeight{i}": value for i, value in enumerate(base)})
        outputs.update({f"adaptWeight{i}": value for i, value in enumerate(final["weights"])})
        outputs.update(work)
        outputs.update(frames=len(trace.steps), tensorCount=len(tensors))
        for step in trace.steps:
            for key, entry in step["outputs"].items():
                alias = f"{step['id']}_{key}"
                if alias in outputs:
                    raise RuntimeError("IV56 output aliases must be unique.")
                outputs[alias] = entry
        return _reference.deepcopy(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=_texts(raw)))
    except NumericalFault as fault:
        return dict(status="unavailable", code=fault.code, reason=str(fault))


# Public names share the exact four-file loader identities above.
evaluate_lora = _reference.evaluate_lora
lora_sgd = _reference.lora_sgd
transfer_trace = _reference.transfer_trace


def run():
    """Stable zero-argument CLI; complete default, JSON replacement or stdin."""
    return run_query_cli(derive_iv56)



def check_public_helpers():
    """Full helper schema, nested copies, all tensor metadata and zero words."""
    data = _legacy.fixed_data()["data"]
    evaluation_keys = ("base", "A", "B", "rank", "alpha", "scale", "product", "delta", "weights", "readout", "gradientA", "gradientB", "tensors")
    readout_keys = ("weights", "predictions", "trainHalfMSE", "validationHalfMSE", "mathematicalGradient", "effectiveGradient", "mask", "tensors")
    readout_suffixes = ("Weights", "Predictions", "Forward", "Loss", "Reductions", "Means", "GradientRows", "MathematicalGradient", "EffectiveGradient", "Mask")
    for rank in (1, 2):
        A, B = [1.0, -0.0] * rank, [-0.0, 0.25] * rank
        trace = transfer_trace()
        result = evaluate_lora([0.25, -0.0, 0.0, 0.25], A, B, data, rank, 1, trace, "ambient")
        assert tuple(result) == evaluation_keys and tuple(result["readout"]) == readout_keys
        assert len(result["tensors"]) == 21 and len(result["readout"]["tensors"]) == 10
        assert len(trace.steps) == 27 + 4 * rank
        assert sum(len(step["outputs"]) for step in trace.steps) == 167 + 32 * rank
        assert tuple(trace.steps[0]["outputs"])[0] == "scale"
        assert all("scale" not in step["outputs"] for step in trace.steps[1:])
        tensors = result["tensors"]
        expected_ids = [f"ambient_{suffix}" for suffix in ("Base", "A", "B", "ProductRows", "Product", "Delta", "Weights")]
        expected_ids += [f"ambient_readout_{suffix}" for suffix in readout_suffixes]
        expected_ids += [f"ambient_{suffix}" for suffix in ("GradientRowsA", "GradientRowsB", "GradientA", "GradientB")]
        assert [tensor["id"] for tensor in tensors] == expected_ids
        _same_words(result["A"], A)
        _same_words(result["B"], B)
        for key, position in (("base", 0), ("A", 1), ("B", 2), ("product", 4), ("delta", 5), ("weights", 6), ("gradientA", 19), ("gradientB", 20)):
            _same_words(result[key], tensors[position]["values"])
        _same_words(result["weights"], result["readout"]["weights"])
        _same_words(result["weights"], tensors[6]["values"])
        _same_words(result["readout"]["weights"], tensors[7]["values"])
        for combined, nested in zip(tensors[7:17], result["readout"]["tensors"]):
            assert tuple(combined) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
            assert combined == nested and combined is not nested and combined["values"] is not nested["values"]
            if combined["dtype"] == "float64":
                _same_words(combined["values"], nested["values"])
        assert tensors[3]["shape"] == [2, 2, rank, 3]
        assert tensors[17]["shape"] == [rank, 2, 2, 3]
        assert tensors[18]["shape"] == [2, rank, 2, 3]
        assert tensors[16]["dtype"] == "int32" and tensors[16]["precision"] == 0
        # Every retained term/old/new partial is present in the actual public table.
        first = trace.steps[0]
        partial = 0.0
        for k in range(rank):
            term = first["outputs"][f"product{k}"]
            _same_words(tensors[3]["values"][3 * k:3 * k + 3], [term, partial, first["outputs"][f"sum{k}"]])
            partial = first["outputs"][f"sum{k}"]
        updated_trace = transfer_trace()
        updated = lora_sgd(A, B, result["gradientA"], result["gradientB"], rank, -0.0, updated_trace, "step")
        assert tuple(updated) == ("A", "B", "tensors")
        assert len(updated_trace.steps) == 4 * rank + 1 and len(updated["tensors"]) == 2
        assert sum(len(step["outputs"]) for step in updated_trace.steps) == 16 * rank
        assert tuple(updated_trace.steps[-1]["inputs"]) == tuple([f"oldA{i}" for i in range(2 * rank)] + [f"oldB{i}" for i in range(2 * rank)])
        assert tuple(updated_trace.steps[-1]["outputs"]) == tuple([f"A{i}" for i in range(2 * rank)] + [f"B{i}" for i in range(2 * rank)])
        for factor, tensor in enumerate(updated["tensors"]):
            assert tensor["shape"] == ([rank, 2, 5] if factor == 0 else [2, rank, 5])
            assert tensor["dtype"] == "float64" and tensor["precision"] == 8
            for coordinate in range(2 * rank):
                step = updated_trace.steps[factor * 2 * rank + coordinate]
                _same_words([step["inputs"]["eta"]], [-0.0])
                _same_words(tensor["values"][coordinate * 5:coordinate * 5 + 5],
                            [step["inputs"]["old"], step["inputs"]["gradient"], *step["outputs"].values()])
        result["readout"]["tensors"][0]["values"][0] = 99.0
        assert tensors[7]["values"][0] != 99.0 and result["weights"][0] != 99.0
        result["A"][0] = 99.0
        assert A[0] == 1.0 and tensors[1]["values"][0] == 1.0
    prefix_reason = "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores."
    args = ([0.0] * 4, [1.0, 0.0], [0.0, 0.0], data, 1, 1, transfer_trace())
    for prefix in (None, "", "1bad", "bad-prefix", "a\n", "é"):
        _expect_fault("INVALID_INPUT", prefix_reason, evaluate_lora, *args, prefix)
    _expect_fault("INVALID_INPUT", "rank must be an integer 1 or 2.", evaluate_lora, None, None, None, None, 3, 3, None, "bad-prefix")
    _expect_fault("NONFINITE", "alpha must be an actual finite number.", evaluate_lora, *args[:5], float("nan"), None, "bad-prefix")
    _expect_fault("INVALID_INPUT", prefix_reason, lora_sgd, [0.0] * 2, [0.0] * 2, [0.0] * 2, [0.0] * 2, 1, 0.5, None, "bad-prefix")
    sentinel = RuntimeError("observer sentinel")
    class Observer:
        def add(self, *_args):
            raise sentinel
    try:
        evaluate_lora(*args[:6], Observer(), "observer")
    except RuntimeError as fault:
        assert fault is sentinel
    else:
        raise AssertionError("Unknown observer failure was swallowed.")
    for bad in (True, False, None, "0", float("nan"), float("inf"), -float("inf"), 10 ** 400):
        for inputs, outputs in (({"n": bad}, {}), ({}, {"n": bad})):
            rejected_trace = transfer_trace()
            _expect_fault("NONFINITE", "n must be finite.", rejected_trace.add, "bad", "", "", "", inputs, outputs)
            assert rejected_trace.steps == []
    trace = transfer_trace()
    trace.add("same", "label", "equation", "explanation", {}, {})
    _expect_fault("INVALID_INPUT", "Trace IDs must be nonempty and unique.", trace.add, "same", "", "", "", {}, {})
    for index in range(511):
        trace.add(f"s{index}", "", "", "", {}, {})
    _expect_fault("UNSUPPORTED_SIZE", "At most 512 operations are supported.", trace.add, "overflow", "", "", "", {}, {})


def check_public_record():
    """Whole ordered root/steps/tensors/texts, source counts and saved copies."""
    summaries = ("adaptValidationLoss adaptTrainLoss adapterTrainableParameters structuralRankBound "
                 "rank alpha initialization updates eta scale fullFineTuneParameters frozenBaseParameters storedBaseAndFactors "
                 "fixedFeatures outputsPerSample trainSamples validationSamples preUpdates preEta "
                 "pretrainingTrainLoss pretrainingValidationLoss adaptInitialTrainLoss adaptInitialValidationLoss "
                 "baseWeight0 baseWeight1 baseWeight2 baseWeight3 adaptWeight0 adaptWeight1 adaptWeight2 adaptWeight3 "
                 "featureMaps featureNegations featureMaxSelections preTargetCopies adaptTargetScalings adaptTargetAdditions "
                 "preparedWeightCopies pretrainingStages adapterStages stageCount forwardSampleEvaluations forwardProducts forwardSums "
                 "readoutGradientBatches readoutGradientContractions gradientRowContributions readoutGradientProducts readoutGradientAdditions readoutGradientDivisions "
                 "preOptimizerBatches preCoordinateUpdates adapterEvaluations scaleDivisions materializationProducts materializationAdditions materializationScalings baseAdditions "
                 "factorGradientContractions factorGradientProducts factorGradientAdditions factorGradientScalings adapterOptimizerBatches factorCoordinateUpdates "
                 "factorUpdateProducts factorUpdateSubtractions finalDiagnosticBatches lossSampleEvaluations lossComponentErrors lossSquares lossHalfDivisions "
                 "lossOutputSums orderedLossAdditions datasetMeanDivisions frames tensorCount").split()
    text_keys = ("trainingScope shapePolicy dataPolicy preparationPolicy initializationPolicy materializationPolicy objectivePolicy gradientPolicy updatePolicy "
                 "rankPolicy rankCounterexample parameterPolicy analyticalCounts scalePolicy evaluationPolicy numericPolicy diagnosticPolicy computePolicy provenance "
                 "rawFields parameterKeys cohortKeys cohortLabels taskKeys factorKeys initializationLabels dataFields sampleKeys forwardFields lossFields datasetKeys "
                 "reductionFields gradientRowFields preUpdateFields contractionFields factorUpdateFields stageFields integerValuePolicy").split()
    assert len(summaries) == 76 and len(text_keys) == 38
    for rank in (1, 2):
        for alpha in (1, 2):
            for initialization in (0, 1):
                for updates in range(4):
                    for eta in (0.0, -0.0, 0.5, 2.0):
                        raw = dict(rank=rank, alpha=alpha, initialization=initialization, updates=updates, eta=eta)
                        record = derive_iv56(raw)
                        assert tuple(record) == ("status", "outputs", "steps", "tensors", "texts") and record["status"] == "defined"
                        outputs, steps, tensors, texts = (record[key] for key in ("outputs", "steps", "tensors", "texts"))
                        assert list(outputs)[:76] == summaries and list(texts) == text_keys
                        assert sum(type(value) is str for value in texts.values()) == 20
                        assert sum(type(value) is list for value in texts.values()) == 18
                        assert len(steps) == outputs["frames"] == 122 + 4 * rank + updates * (29 + 8 * rank)
                        assert len(tensors) == outputs["tensorCount"] == 68 + 24 * updates
                        assert len(outputs) == 892 + 36 * rank + updates * (171 + 48 * rank)
                        assert outputs["adapterTrainableParameters"] == 4 * rank and outputs["fullFineTuneParameters"] == 4
                        assert outputs["scaleDivisions"] == updates + 2 and outputs["stageCount"] == updates + 4
                        _same_words([outputs["eta"], steps[0]["inputs"]["eta"], steps[-1]["inputs"]["eta"]], [eta] * 3)
                        aliases = []
                        for step in steps:
                            assert tuple(step) == ("id", "label", "equation", "explanation", "inputs", "outputs")
                            assert all(type(step[key]) is str and step[key] for key in ("id", "label", "equation", "explanation"))
                            for key, value in step["outputs"].items():
                                alias = f"{step['id']}_{key}"
                                aliases.append(alias)
                                if type(value) is float:
                                    _same_words([outputs[alias]], [value])
                                else:
                                    assert type(value) is int and type(outputs[alias]) is int and outputs[alias] == value
                        assert list(outputs)[76:] == aliases and len(set(aliases)) == len(aliases)
                        assert len({step["id"] for step in steps}) == len(steps)
                        assert len({tensor["id"] for tensor in tensors}) == len(tensors)
                        by_id = {tensor["id"]: tensor for tensor in tensors}
                        by_step = {step["id"]: step for step in steps}
                        assert tuple(by_step["pre_initial"]["inputs"]) == ("source0", "source1", "source2", "source3")
                        assert by_step["pre_initial"]["equation"] == "weights=[+0,+0,+0,+0]"
                        assert by_id["pre_InitialWeights"]["provenance"] == "Actual PRE initialization: four authored floating positive zeros."
                        expected_steps = ["setup", *[f"data_{i}" for i in range(8)], "pre_initial"]
                        expected_tensors = ["Data", "pre_InitialWeights"]
                        for cohort, requested in (("pre", 2), ("adapt", updates)):
                            if cohort == "adapt":
                                expected_steps.append("adapt_initial")
                                expected_tensors.extend(["FrozenBase", "adapt_InitialA", "adapt_InitialB"])
                            for stage in range(requested + 1):
                                prefix = f"{cohort}_stage_{stage}"
                                readout_prefix = prefix if cohort == "pre" else f"{prefix}_readout"
                                if cohort == "adapt":
                                    expected_steps.extend(f"{prefix}_materialize_{i}" for i in range(4))
                                    expected_tensors.extend(f"{prefix}_{suffix}" for suffix in ("Base", "A", "B", "ProductRows", "Product", "Delta", "Weights"))
                                expected_steps.extend(f"{readout_prefix}_forward_{i}" for i in range(8))
                                expected_steps.extend(f"{readout_prefix}_loss_{i}" for i in range(8))
                                expected_steps.extend(f"{readout_prefix}_mean_{i}" for i in range(2))
                                expected_steps.extend(f"{readout_prefix}_gradient_{i}" for i in range(4))
                                expected_steps.append(f"{readout_prefix}_mask")
                                expected_tensors.extend(f"{readout_prefix}_{suffix}" for suffix in ("Weights", "Predictions", "Forward", "Loss", "Reductions", "Means", "GradientRows", "MathematicalGradient", "EffectiveGradient", "Mask"))
                                if cohort == "adapt":
                                    for factor in ("A", "B"):
                                        expected_steps.extend(f"{prefix}_gradient{factor}_{i}" for i in range(2 * rank))
                                    expected_tensors.extend(f"{prefix}_{suffix}" for suffix in ("GradientRowsA", "GradientRowsB", "GradientA", "GradientB"))
                                    _same_words(by_id[f"{prefix}_Base"]["values"], by_id["FrozenBase"]["values"])
                                expected_steps.append(f"{prefix}_stats")
                                expected_tensors.append(f"{prefix}_Stats")
                                stats = by_id[f"{prefix}_Stats"]["values"]
                                assert stats[2:] == [int(stage == requested), int(stage < requested)]
                                assert all(type(flag) is int for flag in stats[2:])
                                _same_words(stats[:2], by_id[f"{readout_prefix}_Means"]["values"])
                                if stage < requested:
                                    update_prefix = f"{cohort}_update_{stage + 1}"
                                    if cohort == "pre":
                                        expected_steps.extend(f"{update_prefix}_coordinate_{i}" for i in range(4))
                                        expected_tensors.append(f"{update_prefix}_Update")
                                    else:
                                        for factor in ("A", "B"):
                                            expected_steps.extend(f"{update_prefix}_{factor}_{i}" for i in range(2 * rank))
                                        expected_tensors.extend([f"{update_prefix}_UpdateA", f"{update_prefix}_UpdateB"])
                                    expected_steps.append(f"{update_prefix}_commit")
                            expected_tensors.extend([f"{cohort}_StageMetrics"] + (["pre_StageWeights"] if cohort == "pre" else ["adapt_StageA", "adapt_StageB", "adapt_StageWeights"]))
                        expected_steps.append("finish")
                        assert [step["id"] for step in steps] == expected_steps
                        assert [tensor["id"] for tensor in tensors] == expected_tensors
                        for tensor in tensors:
                            assert tuple(tensor) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
                            assert len(tensor["shape"]) == len(tensor["axes"])
                            cells = 1
                            for dimension in tensor["shape"]:
                                assert type(dimension) is int and 1 <= dimension <= 64
                                cells *= dimension
                            assert len(tensor["values"]) == cells <= 4096 and tensor["provenance"]
                            integer = tensor["id"].endswith("_Mask")
                            assert tensor["dtype"] == ("int32" if integer else "float64")
                            assert tensor["precision"] == (0 if integer else 8)
                            for index, value in enumerate(tensor["values"]):
                                mixed = (tensor["id"].endswith("_Stats") and index >= 2) or (tensor["id"].startswith("pre_update_") and index % 7 == 3)
                                assert type(value) is (int if integer or mixed else float)
                        _same_words(by_id["FrozenBase"]["values"], by_id["pre_stage_2_Weights"]["values"])
                        _same_words([outputs[f"baseWeight{i}"] for i in range(4)], by_id["FrozenBase"]["values"])
                        _same_words([outputs[f"adaptWeight{i}"] for i in range(4)], by_id[f"adapt_stage_{updates}_Weights"]["values"])
                        for key, value in steps[-1]["outputs"].items():
                            assert steps[-1]["inputs"][key] == outputs[key] == value
                        assert texts["initializationPolicy"].startswith("Initialization zero" if initialization == 0 else "Initialization one")
    for raw, code, reason in (
            (None, "INVALID_INPUT", "state must be a plain object."),
            ({}, "INVALID_INPUT", "state must have exactly rank, alpha, initialization, updates, eta as own fields."),
            ({**dict(DEFAULT_IV56), "rank": 3}, "INVALID_INPUT", "rank must be an integer 1 or 2."),
            ({**dict(DEFAULT_IV56), "alpha": 3}, "INVALID_INPUT", "alpha must be an integer 1 or 2."),
            ({**dict(DEFAULT_IV56), "initialization": 2}, "INVALID_INPUT", "initialization must be numeric 0 or 1."),
            ({**dict(DEFAULT_IV56), "updates": 4}, "INVALID_INPUT", "updates must be an integer from 0 to 3."),
            ({**dict(DEFAULT_IV56), "eta": 3}, "INVALID_INPUT", "eta must be between 0 and 2."),
            ({**dict(DEFAULT_IV56), "rank": 3, "eta": True}, "NONFINITE", "eta must be an actual finite number.")):
        fault = derive_iv56(raw)
        assert tuple(fault) == ("status", "code", "reason")
        assert fault == dict(status="unavailable", code=code, reason=reason)
    record = derive_iv56(dict(DEFAULT_IV56))
    record["tensors"][0]["values"][0] = 99.0
    assert record["steps"][1]["inputs"]["x"] == -1.0
    record["steps"][0]["outputs"]["scale"] = 99.0
    assert record["outputs"]["setup_scale"] == 1.0


def check_public_cli():
    """Actual zero-argument run(): default/JSON/stdin/fault/usage and isolation."""
    import contextlib
    import io
    import json
    import sys
    saved_argv, saved_stdin = sys.argv, sys.stdin
    def invoke(args, source=""):
        sys.argv, sys.stdin = ["iv56.py", *args], io.StringIO(source)
        out, err = io.StringIO(), io.StringIO()
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            status = run()
        return status, out.getvalue(), err.getvalue()
    try:
        for args, source in (([], ""), ([json.dumps(dict(DEFAULT_IV56))], ""),
                             (["-"], '{"rank":2,"alpha":1,"initialization":1,"updates":0,"eta":-0}')):
            code, output, error = invoke(args, source)
            assert code == 0 and not error
            record = json.loads(output)
            assert tuple(record) == ("status", "outputs", "steps", "tensors", "texts")
            assert record["status"] == "defined"
            if args == ["-"]:
                _same_words([record["outputs"]["eta"]], [-0.0])
                assert record["outputs"]["rank"] == 2 and record["outputs"]["updates"] == 0
            else:
                assert record["outputs"]["frames"] == 163 and len(record["outputs"]) == 1147
        for source in ("{", "{} {}", '{"eta":0,"eta":1}', "NaN", "Infinity", "-Infinity", "1" * 5000,
                       "null", "[]", "true", "{}", '{"rank":3,"alpha":1,"initialization":0,"updates":0,"eta":1e999}'):
            code, output, error = invoke([source])
            assert code == 0 and not error
            fault = json.loads(output)
            assert tuple(fault) == ("status", "code", "reason") and fault["status"] == "unavailable"
        for args in (["{}", "{}"], ["--unknown"]):
            code, output, error = invoke(args)
            assert code == 2 and not output and "Usage:" in error
        original = globals()["mechanics_experiment"]
        try:
            for sentinel in (ValueError("semantic sentinel"), json.JSONDecodeError("semantic class", "", 0), MemoryError("resource sentinel")):
                def broken(_value):
                    raise sentinel
                globals()["mechanics_experiment"] = broken
                try:
                    invoke([])
                except type(sentinel) as fault:
                    assert fault is sentinel
                else:
                    raise AssertionError("Unknown actual public semantic failure was swallowed.")
        finally:
            globals()["mechanics_experiment"] = original
        # Fresh loading uses adjacent absolute paths even with cwd/module shadows.
        import tempfile
        import os
        original_cwd, source_path = Path.cwd(), Path(__file__).resolve()
        with tempfile.TemporaryDirectory() as directory:
            for name in ("iv55", "transfer_reference", "lora_reference"):
                Path(directory, f"{name}.py").write_text('raise AssertionError("cwd shadow imported")\n')
            try:
                os.chdir(directory)
                spec = importlib.util.spec_from_file_location("_iv56_closure_check", source_path)
                module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(module)
                assert module._legacy is module._reference._iv55
                assert module.NumericalFault is module._legacy.NumericalFault is module._reference._transfer.NumericalFault
                assert module.strict_json is module._legacy.strict_json
                assert module.source_self_check.__globals__ is module.__dict__
                assert module.check_public_record.__globals__ is module.__dict__
                assert module._legacy.source_self_check.__globals__ is module._legacy.__dict__
                assert module._legacy.check_public_record.__globals__ is module._legacy.__dict__
                assert module._legacy.check_hand_anchors.__globals__ is module._legacy.__dict__
                assert module._legacy.evaluate_transfer is module._reference._transfer.evaluate_transfer
                assert module._legacy.transfer_sgd is module._reference._transfer.transfer_sgd
                assert module._legacy.fixed_data is module._reference._transfer.fixed_data
                assert [Path(item.__file__).resolve() for item in (module, module._reference, module._legacy, module._reference._transfer)] == [source_path, source_path.with_name("lora_reference.py"), source_path.with_name("iv55.py"), source_path.with_name("transfer_reference.py")]
                assert module._legacy.__name__ == "_p14_iv56_iv55"
                assert module._reference._transfer.__name__ == "_p14_iv55_transfer_reference"
                assert module.derive_iv56(dict(DEFAULT_IV56))["status"] == "defined"
            finally:
                os.chdir(original_cwd)
    finally:
        sys.argv, sys.stdin = saved_argv, saved_stdin


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

Recap and next step

  • Keep the actually prepared W0W_0 fixed; train the factors in Weff=W0+(α/r)BAW_{\mathrm{eff}}=W_0+(\alpha/r)BA.
  • Check shapes before multiplying. A rank-1 addition has four trainable coordinates here, equal to full adaptation; rank 2 has eight.
  • Derive both factor gradients from the same old readout errors and factors, scale after each contraction, and commit all factor proposals together.
  • Identity-row AA with zero BB allows a first BB update. Both factors zero stall even with a nonzero readout gradient.
  • Interpret rank as an exact-real structural bound on the factorized addition. Keep rounded materialization, scale effects and held-out limits explicit.

Return to II.10 — Matrix × matrix as composition to review why the factor order matters, or IV-55 — Pretraining, Fine-Tuning and Transfer to compare the actual full fine-tuning update. The next planned chapter, IV-57 — Preference Data and Optimization Objectives, asks how scored or ranked pairs define an objective. Choosing which parameters may learn, as we did here, does not by itself choose what behavior the objective rewards.