The neural notebook
← All chapters

IV-15 / Part II · Learning, Backpropagation and Optimization

Initialization, Regularization and Gradient Pathologies

Follow a real distinct-weight depth chain, inspect activation and gradient norms, and compare coupled L2 with a first AdamW step from explicit moments.

Review the ideas this chapter uses

A correct chain rule can still deliver a very small gradient to an early parameter. Repeated multiplication may shrink its factors; other choices may amplify them. Before choosing a remedy, we need to see the actual products and distinguish the data-fitting objective from a separate preference for smaller parameters.

This chapter uses a tiny scalar chain so no matrix operation can hide those effects. Each layer has its own independent weight. The controls change depth, starting scale, one selected weight and the activation function; all tables come from the same real forward and reverse calculation. The four optimizer columns are single simultaneous comparisons from that starting point, not a training history.

Compute it yourself

Follow actual gradient paths through distinct scalar weights

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
x
1
y
0
depth
3
alpha
0.5
probeIndex
0
probeDelta
0
activation
0
lambda
0.25
eta
0.125
epsilon
0.125
prediction0.125
dataLoss0.0078125
penalty0.09375
objective0.1015625

prediction 0.125. dataLoss 0.0078125. penalty 0.09375. objective 0.1015625. Initialize distinct scalar parameters. Equal initial values are independent parameters. Alpha is an initializer, not a tied optimizer weight. Probe indices start at zero; displayed layer numbers start at one.. h0 1. w0 0.5. w1 0.5. w2 0.5

Initialize distinct scalar parameters

w_l=alpha+(l==probeIndex ? probeDelta : 0); h0=x

Equal initial values are independent parameters. Alpha is an initializer, not a tied optimizer weight. Probe indices start at zero; displayed layer numbers start at one.

Inputs

alpha
0.5
probeIndex
0
probeDelta
0
x
1

Outputs

h0
1
w0
0.5
w1
0.5
w2
0.5

Starting input h0=1; prediction=0.125; error=0.125. Data loss=0.0078125; L2 penalty=0.09375; total objective=0.1015625. These are three separate quantities.

Computed distinct-weight data-gradient L2 norm: 0.05412658773652741. Total-gradient norm: 0.2706329386826371. Input derivative: 0.015625.

Starting chain: layer l+1 uses independent parameter w[l]; adjoints differentiate data loss
Layer / indexwh previousz producthSlopedH upstreamdZdWdH previousTotal gradient
1 / 00.510.50.510.031250.031250.031250.0156250.15625
2 / 10.50.50.250.2510.06250.06250.031250.031250.15625
3 / 20.50.250.1250.12510.1250.1250.031250.06250.15625

The computed norms use sqrt(sum of squared components). Squaring a tiny nonzero component can underflow to zero, so a displayed zero norm need not mean every stored gradient component is zero. Inspect the components too.

ReLU selects backward slope 0 at zero, where its mathematical derivative is undefined. tanh uses stored binary64 slope 1−h², which may round to 0 at saturation. Equal initialization does not tie the weights together.

Four one-step parameter vectors from the same starting weights and gradients
Weight indexOld wSGD coupled L2SGD decoupledFIRST Adam coupled L2FIRST AdamW
00.50.480468750.480468750.43055555555555560.459375
10.50.480468750.480468750.43055555555555560.459375
20.50.480468750.480468750.43055555555555560.459375

Fresh data losses after full-vector forward recomputation: coupled SGD 0.00615121463398971; first coupled Adam 0.0031852622070397507; first AdamW 0.004698661328074056. These are data losses, not regularized objectives. No general decrease is promised.

Inspect actual first-Adam moment operands

Both branches start at m=v=0, t=1, with beta1=beta2=1/2. Coupled uses data gradient + lambda*w; AdamW uses the data gradient and subtracts old-weight decay separately. The trace records each square, half-moment, correction, root, numerator, denominator and delta; these are evaluated rather than replaced by the real-arithmetic |g| shortcut.

Weight 0

coupledSquare0
0.0244140625
coupledM0
0.078125
coupledV0
0.01220703125
coupledMHat0
0.15625
coupledVHat0
0.0244140625
coupledRoot0
0.15625
coupledNumerator0
0.01953125
coupledDenominator0
0.28125
coupledDelta0
0.06944444444444445
dataSquare0
0.0009765625
dataM0
0.015625
dataV0
0.00048828125
dataMHat0
0.03125
dataVHat0
0.0009765625
dataRoot0
0.03125
dataNumerator0
0.00390625
dataDenominator0
0.15625
dataDelta0
0.025

Weight 1

coupledSquare1
0.0244140625
coupledM1
0.078125
coupledV1
0.01220703125
coupledMHat1
0.15625
coupledVHat1
0.0244140625
coupledRoot1
0.15625
coupledNumerator1
0.01953125
coupledDenominator1
0.28125
coupledDelta1
0.06944444444444445
dataSquare1
0.0009765625
dataM1
0.015625
dataV1
0.00048828125
dataMHat1
0.03125
dataVHat1
0.0009765625
dataRoot1
0.03125
dataNumerator1
0.00390625
dataDenominator1
0.15625
dataDelta1
0.025

Weight 2

coupledSquare2
0.0244140625
coupledM2
0.078125
coupledV2
0.01220703125
coupledMHat2
0.15625
coupledVHat2
0.0244140625
coupledRoot2
0.15625
coupledNumerator2
0.01953125
coupledDenominator2
0.28125
coupledDelta2
0.06944444444444445
dataSquare2
0.0009765625
dataM2
0.015625
dataV2
0.00048828125
dataMHat2
0.03125
dataVHat2
0.0009765625
dataRoot2
0.03125
dataNumerator2
0.00390625
dataDenominator2
0.15625
dataDelta2
0.025
Inspect tensor shapes and full precision

All computed outputs

prediction
0.125
dataLoss
0.0078125
penalty
0.09375
objective
0.1015625
x
1
y
0
depth
3
alpha
0.5
probeIndex
0
probeDelta
0
activation
0
lambda
0.25
eta
0.125
epsilon
0.125
h0
1
w0
0.5
w1
0.5
w2
0.5
z0
0.5
h1
0.5
slope0
1
z1
0.25
h2
0.25
slope1
1
z2
0.125
h3
0.125
slope2
1
error
0.125
DataLoss
0.0078125
dH3
0.125
dZ2
0.125
dW2
0.03125
dH2
0.0625
dZ1
0.0625
dW1
0.03125
dH1
0.03125
dZ0
0.03125
dW0
0.03125
dH0
0.015625
totalGradient0
0.15625
penaltyGradient0
0.125
coupledSquare0
0.0244140625
coupledM0
0.078125
coupledV0
0.01220703125
coupledMHat0
0.15625
coupledVHat0
0.0244140625
coupledRoot0
0.15625
coupledDenominator0
0.28125
coupledNumerator0
0.01953125
coupledDelta0
0.06944444444444445
dataSquare0
0.0009765625
dataM0
0.015625
dataV0
0.00048828125
dataMHat0
0.03125
dataVHat0
0.0009765625
dataRoot0
0.03125
dataDenominator0
0.15625
dataNumerator0
0.00390625
dataDelta0
0.025
sgdCoupled0
0.48046875
sgdDecoupled0
0.48046875
adamCoupled0
0.4305555555555556
adamW0
0.459375
totalGradient1
0.15625
penaltyGradient1
0.125
coupledSquare1
0.0244140625
coupledM1
0.078125
coupledV1
0.01220703125
coupledMHat1
0.15625
coupledVHat1
0.0244140625
coupledRoot1
0.15625
coupledDenominator1
0.28125
coupledNumerator1
0.01953125
coupledDelta1
0.06944444444444445
dataSquare1
0.0009765625
dataM1
0.015625
dataV1
0.00048828125
dataMHat1
0.03125
dataVHat1
0.0009765625
dataRoot1
0.03125
dataDenominator1
0.15625
dataNumerator1
0.00390625
dataDelta1
0.025
sgdCoupled1
0.48046875
sgdDecoupled1
0.48046875
adamCoupled1
0.4305555555555556
adamW1
0.459375
totalGradient2
0.15625
penaltyGradient2
0.125
coupledSquare2
0.0244140625
coupledM2
0.078125
coupledV2
0.01220703125
coupledMHat2
0.15625
coupledVHat2
0.0244140625
coupledRoot2
0.15625
coupledDenominator2
0.28125
coupledNumerator2
0.01953125
coupledDelta2
0.06944444444444445
dataSquare2
0.0009765625
dataM2
0.015625
dataV2
0.00048828125
dataMHat2
0.03125
dataVHat2
0.0009765625
dataRoot2
0.03125
dataDenominator2
0.15625
dataNumerator2
0.00390625
dataDelta2
0.025
sgdCoupled2
0.48046875
sgdDecoupled2
0.48046875
adamCoupled2
0.4305555555555556
adamW2
0.459375
dataGradientNorm
0.05412658773652741
totalGradientNorm
0.2706329386826371
inputGradient
0.015625
sgdz0
0.48046875
sgdh1
0.48046875
sgdslope0
1
sgdz1
0.2308502197265625
sgdh2
0.2308502197265625
sgdslope1
1
sgdz2
0.11091631650924683
sgdh3
0.11091631650924683
sgdslope2
1
sgdprediction
0.11091631650924683
sgderror
0.11091631650924683
sgdDataLoss
0.00615121463398971
adamCoupledz0
0.4305555555555556
adamCoupledh1
0.4305555555555556
adamCoupledslope0
1
adamCoupledz1
0.18537808641975312
adamCoupledh2
0.18537808641975312
adamCoupledslope1
1
adamCoupledz2
0.0798155649862826
adamCoupledh3
0.0798155649862826
adamCoupledslope2
1
adamCoupledprediction
0.0798155649862826
adamCouplederror
0.0798155649862826
adamCoupledDataLoss
0.0031852622070397507
adamWz0
0.459375
adamWh1
0.459375
adamWslope0
1
adamWz1
0.21102539062499998
adamWh2
0.21102539062499998
adamWslope1
1
adamWz2
0.09693978881835937
adamWh3
0.09693978881835937
adamWslope2
1
adamWprediction
0.09693978881835937
adamWerror
0.09693978881835937
adamWDataLoss
0.004698661328074056

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

weights

layer=3 · float64 · display precision 8 · Independent scalar parameters initialized from alpha and one probe perturbation.

Storage indexValue
00.5
10.5
20.5

activations

input_then_layer=4 · float64 · display precision 8 · h0=x, then the real post-activation at each layer.

Storage indexValue
01
10.5
20.25
30.125

preactivations

layer=3 · float64 · display precision 8 · w_l*h_previous before activation.

Storage indexValue
00.5
10.25
20.125

slopes

layer=3 · float64 · display precision 8 · Selected local slopes, including ReLU-zero=0 and stored binary64 tanh 1-h².

Storage indexValue
01
11
21

dataGradients

layer=3 · float64 · display precision 8 · Distinct parameter partial derivatives of the data half-square.

Storage indexValue
00.03125
10.03125
20.03125

totalGradients

layer=3 · float64 · display precision 8 · Data gradient plus lambda*w for coupled L2.

Storage indexValue
00.15625
10.15625
20.15625

activationAdjoints

input_then_layer=4 · float64 · display precision 8 · Data loss sensitivities to h0 through h_depth; last entry is error.

Storage indexValue
00.015625
10.03125
20.0625
30.125

preactivationAdjoints

layer=3 · float64 · display precision 8 · Data loss sensitivities after local activation slope.

Storage indexValue
00.03125
10.0625
20.125

sgdCoupled

layer=3 · float64 · display precision 8 · One simultaneous update from the starting full vector. Adaptive variants are FIRST steps from zero moments.

Storage indexValue
00.48046875
10.48046875
20.48046875

sgdDecoupled

layer=3 · float64 · display precision 8 · One simultaneous update from the starting full vector. Adaptive variants are FIRST steps from zero moments.

Storage indexValue
00.48046875
10.48046875
20.48046875

adamCoupled

layer=3 · float64 · display precision 8 · One simultaneous update from the starting full vector. Adaptive variants are FIRST steps from zero moments.

Storage indexValue
00.4305555555555556
10.4305555555555556
20.4305555555555556

adamW

layer=3 · float64 · display precision 8 · One simultaneous update from the starting full vector. Adaptive variants are FIRST steps from zero moments.

Storage indexValue
00.459375
10.459375
20.459375

Try alpha=2 and greater linear depth, then switch to tanh or ReLU. Change only probeDelta to inspect one distinct parameter. Reducing depth below the probe index reports an error; fix the index explicitly. Reset restores all defaults and zero first-step moments.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. Weights share an initializer alpha. Which derivative belongs to weight 0?
2. At the displayed first layer dZ0=0.03125 and h0=1. What is dW0?
3. Data loss=0.0078125 and penalty=0.09375. What is the total objective?
4. Reset and change linear depth from 3 to 8 with alpha=1/2 and no probe. What happens to prediction?
5. Which statement about coupled L2 and decoupled weight decay is correct?

Begin with the default linear chain. Seek reverse_2, reverse_1, reverse_0, then norms and penalty_update_0. The table summarizes the complete starting calculation while the selected step explains its operands. Review IV-12 — Gradient Descent, SGD and Mini-Batches for descent, IV-13 — Momentum, Adam and Optimizer State for optimizer memory, and III-12 — Regularization for regularization.

Name the small problem precisely

Initialization means choosing parameter values before updates. A layer here multiplies one scalar activation by one scalar weight, then applies a function. Depth DD counts layers. The input is h0=xh_0=x; for mathematical layer numbers ℓ=1,…,D\ell=1,\ldots,D,

zℓ=wℓhℓ−1,hℓ=f(zℓ),p=hD,e=p−y,Ldata=e2/2.z_\ell=w_\ell h_{\ell-1},\qquad h_\ell=f(z_\ell),\qquad p=h_D,\quad e=p-y,\quad L_{\rm data}=e^2/2.

Here zz means the product before activation, hh the value after activation, pp prediction, yy target, ee signed error and LdataL_{\rm data} data loss. Everything in one layer is scalar. The inspector’s weight vector has shape [D], with a layer axis; the activation vector has shape [D+1], containing input first and then the DD computed activations. These are layers of one example, not samples of a batch.

Code indices start at zero: w0 produces h1, and probeIndex=0 selects mathematical layer one. Every weight starts at initialization scale α\alpha, except the selected probe receives an extra probeDelta. Equal initial values do not make the weights one shared variable. Changing alpha rebuilds their starting values; an optimizer still uses each parameter’s own partial derivative, holding the other weights fixed.

The bounds are explicit: input and target are between −10-10 and 1010; depth is an integer from one through eight; alpha and probe delta are between −4-4 and 44. The probe index must be an integer smaller than depth. Reducing depth does not silently move it: repair an invalid index yourself. Activation is exactly linear, ReLU or tanh; λ\lambda is between zero and two, learning rate η\eta between zero and one, and ε\varepsilon between 10−810^{-8} and one. Every field is required and finite. These are teaching bounds, not recommended training hyperparameters.

Work through three distinct linear weights

Defaults are x=1x=1, y=0y=0, D=3D=3, α=1/2\alpha=1/2, zero probe delta and the linear activation f(z)=zf(z)=z. Every local activation slope is one. Compute in forward order:

h0=1,z1=(1/2)(1)=1/2=h1,h_0=1,\quad z_1=(1/2)(1)=1/2=h_1, z2=(1/2)(1/2)=1/4=h2,z3=(1/2)(1/4)=1/8=h3.z_2=(1/2)(1/2)=1/4=h_2,\qquad z_3=(1/2)(1/4)=1/8=h_3.

Therefore p=1/8p=1/8, e=1/8e=1/8 and Ldata=1/128L_{\rm data}=1/128. There is no averaging by depth: intermediate layers do not create extra target examples.

An adjoint is the loss sensitivity carried backward to an intermediate quantity. Write dHℓ=∂Ldata/∂hℓdH_\ell=\partial L_{\rm data}/\partial h_\ell and similarly dZℓdZ_\ell. The terminal seed is dHD=edH_D=e. Differentiating the product and activation gives

dZℓ=dHℓf′(zℓ),gℓ=dWℓ=dZℓhℓ−1,dHℓ−1=dZℓwℓ.dZ_\ell=dH_\ell f'(z_\ell),\quad g_\ell=dW_\ell=dZ_\ell h_{\ell-1},\quad dH_{\ell-1}=dZ_\ell w_\ell.

Starting at layer three, dZ3=1/8dZ_3=1/8, so g3=(1/8)(1/4)=1/32g_3=(1/8)(1/4)=1/32 and dH2=(1/8)(1/2)=1/16dH_2=(1/8)(1/2)=1/16. Next dZ2=1/16dZ_2=1/16, g2=(1/16)(1/2)=1/32g_2=(1/16)(1/2)=1/32, and dH1=1/32dH_1=1/32. Finally dZ1=1/32dZ_1=1/32, g1=(1/32)(1)=1/32g_1=(1/32)(1)=1/32, and the input derivative is dH0=1/64dH_0=1/64.

The identical weight derivatives are a property of this starting case, not a sum imposed by the initializer. The L2 norm measures the vector’s Euclidean length:

∥g∥2=g12+g22+g32=3/32.\|g\|_2=\sqrt{g_1^2+g_2^2+g_3^2}=\sqrt{3}/32.

It is not the mean, the sum of absolute values or the norm of the input derivative. The page computes this from the actual distinct weight derivatives. Trace and table store binary64 numbers; the fractions here state exact mathematical values. The computed norm squares each stored component before summing. Squaring a tiny nonzero component can underflow to zero, so a displayed zero norm alone does not establish that every stored gradient component is zero. Inspect those components as well.

Follow a path through zero instead of dividing by a weight

A tempting linear shortcut is to divide the total prediction by a weight. That fails exactly when the weight is zero. The reverse product rule above never divides and remains meaningful there.

Reset, set y=1y=1, keep alpha 1/21/2, and set probe delta to −1/2-1/2 at index zero. The weights are (0,1/2,1/2)(0,1/2,1/2). Prediction is zero and error is −1-1. A small change in the first weight still travels through the two later factors, so

g=(−1/4,0,0),∂Ldata/∂x=0.g=(-1/4,0,0),\qquad \partial L_{\rm data}/\partial x=0.

The first weight can receive feedback even though its current value is zero. Later weights multiply an already zero activation and receive zero data gradients. A zero prediction therefore does not imply a completely zero gradient. Changing activation to ReLU changes the story again, because the zero preactivation now invokes a selected slope at a kink.

Shrinking, growing and blocked factors

In a linear chain with no probe and x=1x=1, prediction is αD\alpha^D. At target zero, each distinct data gradient is α2D−1\alpha^{2D-1}. One factor comes from the loss seed and the others from the forward and backward paths. With alpha 1/21/2, increasing depth from three to eight changes prediction from 1/81/8 to 1/2561/256 and each weight gradient from 1/321/32 to 1/327681/32768. With alpha two, the corresponding powers grow instead. These observations use actual products, not an idealized plotted training curve.

ReLU is f(z)=max⁡(0,z)f(z)=\max(0,z). Negative preactivation gives local slope zero and blocks that reverse path. At exactly zero the mathematical derivative is undefined; the program chooses backward slope zero. For a negative input with positive weights, the first ReLU can remove the signal, while later exact zeros use this same declared rule. A small gradient may therefore arise from a blocked path rather than merely repeated factors smaller than one.

The smooth function tanh⁡(z)\tanh(z) approaches −1-1 or 11 for large magnitude inputs. Its real derivative is 1−tanh⁡(z)21-\tanh(z)^2, positive at every finite real argument. Saturation describes the region where the output changes very little with its input. The program stores h=tanh⁡(z)h=\tanh(z) in binary64 and evaluates the slope as 1−h21-h^2. Stored hh may round to an endpoint, making this evaluated slope exactly zero. That is a numerical limit, not proof that the real derivative at a finite argument vanished.

This scalar toy isolates multiplication. Real vector layers also sum paths and depend on width, data statistics, architecture and normalization. No one alpha here is a universal initialization prescription. Inspect the cause of a magnitude change before transferring the observation to a different network.

Add a penalty without renaming the data loss

A regularizer adds a stated preference to the objective. Coupled L2 uses

P(w)=λ2∑ℓ=1Dwℓ2,F=Ldata+P,qℓ=gℓ+λwℓ.P(w)=\frac{\lambda}{2}\sum_{\ell=1}^{D} w_\ell^2, \qquad F=L_{\rm data}+P, \qquad q_\ell=g_\ell+\lambda w_\ell.

PP is the penalty, FF the total objective and qq its weight gradient. Lambda controls the penalty’s strength. Its derivative is λw\lambda w because differentiating w2/2w^2/2 gives ww. Changing lambda alone does not alter the starting forward graph or data loss.

At the default λ=1/4\lambda=1/4, sum of squared weights is 3/43/4, so P=(1/8)(3/4)=3/32P=(1/8)(3/4)=3/32. Thus F=1/128+3/32=13/128F=1/128+3/32=13/128. Each total gradient is 1/32+(1/4)(1/2)=5/321/32+(1/4)(1/2)=5/32, giving total norm 53/325\sqrt{3}/32. The data-gradient norm remains 3/32\sqrt{3}/32. A larger total gradient here partly expresses the penalty; it is not evidence of a larger data error.

For plain SGD, coupled L2 and matching decoupled shrinkage are algebraically equal:

wℓ′=wℓ−η(gℓ+λwℓ)=(1−ηλ)wℓ−ηgℓ.w'_\ell=w_\ell-\eta(g_\ell+\lambda w_\ell) =(1-\eta\lambda)w_\ell-\eta g_\ell.

Both sides use the same old weights and gradients. At η=1/8\eta=1/8 every default weight becomes 1/2−(1/8)(5/32)=123/2561/2-(1/8)(5/32)=123/256. The implementation evaluates both expressions separately; alternate binary64 orders can differ in their last bits without changing this real-arithmetic identity.

Why the first adaptive steps differ

Adam scales a gradient using moving first and second moments. To compare penalty placement without hiding a training engine, we declare only the first step: old moments zero, timestep t=1t=1, and fixed β1=β2=1/2\beta_1=\beta_2=1/2. For whichever gradient aa that branch uses,

m=12a,v=12(a a),m^=m/(1/2),v^=v/(1/2),Δ(a)=ηm^v^+ε.m=\tfrac12a,\quad v=\tfrac12(a\,a),\quad \widehat m=m/(1/2),\quad\widehat v=v/(1/2),\quad \Delta(a)=\frac{\eta\widehat m}{\sqrt{\widehat v}+\varepsilon}.

The hats denote bias-corrected moments. Epsilon is added outside the square root, matching IV-13. In real arithmetic this simplifies to ηa/(∣a∣+ε)\eta a/(|a|+\varepsilon). The code preserves the explicit moment operations: a tiny squared gradient or half-gradient can underflow, so the shortcut is not a universal binary64 identity. The trace exposes all those actual operands.

Coupled first Adam uses a=qa=q and sets w′=w−Δ(q)w'=w-\Delta(q). First AdamW uses a=ga=g and sets

w′=w−Δ(g)−ηλw.w'=w-\Delta(g)-\eta\lambda w.

The decay term uses the old weight. It stays outside the moments. These are distinct update rules, although lambda zero removes this particular difference.

For default coupled q=5/32q=5/32, the moments are m=5/64m=5/64, v=25/2048v=25/2048, corrected moments 5/325/32 and 25/102425/1024, root 5/325/32, and denominator 5/32+1/8=9/325/32+1/8=9/32. The numerator is 5/2565/256, so Δ(q)=5/72\Delta(q)=5/72 and w′=31/72w'=31/72.

For AdamW, g=1/32g=1/32 gives m=1/64m=1/64, v=1/2048v=1/2048, corrected root 1/321/32 and denominator 5/325/32. Its data move is 1/401/40, and old-weight decay is 1/641/64. Hence

wAdamW′=1/2−1/40−1/64=147/320.w'_{\rm AdamW}=1/2-1/40-1/64=147/320.

Every column updates the full independent vector simultaneously. A subsequent loss is freshly recomputed from that vector and the selected activation; the display never substitutes a predicted reduction from a gradient formula. At defaults the exact new data losses are (31/72)6/2(31/72)^6/2 and (147/320)6/2(147/320)^6/2 for the two adaptive branches. These are data losses, not total regularized objectives.

As another hand check, changing only depth to one gives g=1/2g=1/2, q=5/8q=5/8. Coupled first Adam yields 19/4819/48 and first AdamW yields 123/320123/320. Parameter values can differ even without depth. A single step does not establish which optimizer is better, and an arbitrary learning rate need not lower the data loss.

Read the program and keep its limits visible

The actual NumPy source below validates every field, builds independent weights, records each forward product, and runs the explicit reverse chain. It then constructs the four parameter vectors from the same starting state. Its shared helper, shown next, supplies finite checks, trace packaging and the JSON boundary. Neither file uses autodiff or a numerical-gradient shortcut.

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.

"""IV15: actual distinct-weight scalar chain, explicit reverse pass and first steps.

NumPy binary64 storage; no training loop, numerical differences or autodiff.
"""
import numpy as np
from layer_reference import NumericalFault, finite, fixed_state, guarded, LayerTrace, tensor, run

DEFAULT_IV15 = {"x": 1, "y": 0, "depth": 3, "alpha": 0.5, "probeIndex": 0, "probeDelta": 0,
                "activation": 0, "lambda": 0.25, "eta": 0.125, "epsilon": 0.125}
BOUNDS = {"x": (-10, 10), "y": (-10, 10), "depth": (1, 8), "alpha": (-4, 4),
          "probeIndex": (0, 7), "probeDelta": (-4, 4), "activation": (0, 2),
          "lambda": (0, 2), "eta": (0, 1), "epsilon": (1e-8, 1)}


@guarded
def derive_iv15(state):
    """Every edit starts independent parameters and zero optimizer moments anew."""
    s = fixed_state(state, DEFAULT_IV15)
    for key, (low, high) in BOUNDS.items():
        if not low <= s[key] <= high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
    for key in ("depth", "probeIndex", "activation"):
        if s[key] != np.floor(s[key]):
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
    depth, probe = int(s["depth"]), int(s["probeIndex"])
    if probe >= depth:
        raise NumericalFault("INVALID_INPUT", "probeIndex must be smaller than depth; it is never clamped.")
    trace = LayerTrace(s)
    o, add = trace.outputs, trace.add
    weights = np.array([finite(s["alpha"] + (s["probeDelta"] if l == probe else 0), f"w{l}")
                        for l in range(depth)], dtype=np.float64)
    add("initialize", "w_l=alpha+(l==probeIndex ? probeDelta : 0); h0=x",
        {"alpha": s["alpha"], "probeIndex": probe, "probeDelta": s["probeDelta"], "x": s["x"]},
        {"h0": s["x"], **{f"w{l}": weights[l] for l in range(depth)}})

    def forward(vector, prefix):
        # h[0] is the input; parameter/row index l produces h[l+1].
        h, z, slopes = np.zeros(depth + 1), np.zeros(depth), np.zeros(depth)
        h[0] = s["x"]
        for l in range(depth):
            z[l] = finite(vector[l] * h[l], f"{prefix}z{l}")
            if s["activation"] == 0:
                h[l + 1], slopes[l] = z[l], 1
            elif s["activation"] == 1:
                h[l + 1], slopes[l] = max(0, z[l]), 1 if z[l] > 0 else 0
            else:
                h[l + 1] = finite(np.tanh(z[l]), "tanh activation")
                square = finite(h[l + 1] * h[l + 1], "tanh activation squared")
                slopes[l] = finite(1 - square, "stored binary64 tanh slope")
            finite(h[l + 1], "activation")
            finite(slopes[l], "activation slope")
            add(f"{prefix}forward_{l}", "z_l=w_l*h_previous; h_l=activation(z_l); slope=local selected slope",
                {"weight": vector[l], "previousH": h[l], "activation": s["activation"]},
                {f"{prefix}z{l}": z[l], f"{prefix}h{l + 1}": h[l + 1], f"{prefix}slope{l}": slopes[l]})
        prediction = h[depth]
        error = finite(prediction - s["y"], f"{prefix}error")
        square = finite(error * error, "error square")
        loss = finite(square / 2, "data loss")
        add(f"{prefix}loss", "error=prediction-y; dataLoss=error*error/2", {"prediction": prediction, "y": s["y"]},
            {f"{prefix}prediction": prediction, f"{prefix}error": error, f"{prefix}DataLoss": loss})
        return h, z, slopes, prediction, error, loss

    h, z, slopes, prediction, error, data_loss = forward(weights, "")
    dH, dZ, dW = np.zeros(depth + 1), np.zeros(depth), np.zeros(depth)
    dH[depth] = error  # Loss seed: d(e²/2)/dp = e.
    for l in range(depth - 1, -1, -1):
        # Never divide by w. A zero weight still has a valid local partial.
        dZ[l] = finite(dH[l + 1] * slopes[l], "preactivation adjoint")
        dW[l] = finite(dZ[l] * h[l], "distinct weight gradient")
        dH[l] = finite(dZ[l] * weights[l], "previous activation adjoint")
        add(f"reverse_{l}", "dZ_l=dH_l*slope_l; dW_l=dZ_l*h_previous; dH_previous=dZ_l*w_l",
            {"upstream": dH[l + 1], "slope": slopes[l], "previousH": h[l], "weight": weights[l]},
            {f"dH{l + 1}": dH[l + 1], f"dZ{l}": dZ[l], f"dW{l}": dW[l], f"dH{l}": dH[l]})
    weight_squares = data_squares = total_squares = np.float64(0)
    total, sgd_coupled, sgd_decoupled = np.zeros(depth), np.zeros(depth), np.zeros(depth)
    adam_coupled, adam_w = np.zeros(depth), np.zeros(depth)
    for l in range(depth):
        weight_squares = finite(weight_squares + finite(weights[l] * weights[l], "weight square"), "sum weight squares")
        data_squares = finite(data_squares + finite(dW[l] * dW[l], "data gradient square"), "sum data gradient squares")
        penalty_gradient = finite(s["lambda"] * weights[l], "L2 gradient")
        total[l] = finite(dW[l] + penalty_gradient, "total gradient")
        total_squares = finite(total_squares + finite(total[l] * total[l], "total gradient square"), "sum total gradient squares")
        sgd_delta = finite(s["eta"] * total[l], "SGD coupled delta")
        shrink_factor = finite(1 - finite(s["eta"] * s["lambda"], "eta lambda"), "shrink factor")
        shrunk = finite(shrink_factor * weights[l], "decoupled shrunk weight")
        data_delta = finite(s["eta"] * dW[l], "SGD data delta")
        sgd_coupled[l] = finite(weights[l] - sgd_delta, "SGD coupled parameter")
        sgd_decoupled[l] = finite(shrunk - data_delta, "SGD decoupled parameter")

        def first_adam(g, prefix):
            # Fixed beta1=beta2=.5, t=1, old m=v=0. Preserve IV13 order.
            square = finite(g * g, "gradient square")
            m, v = finite(0.5 * g, "first moment"), finite(0.5 * square, "second moment")
            m_hat, v_hat = finite(m / 0.5, "corrected first moment"), finite(v / 0.5, "corrected second moment")
            root = finite(np.sqrt(v_hat), "sqrt corrected second moment")
            denominator = finite(root + s["epsilon"], "root plus epsilon")
            numerator = finite(s["eta"] * m_hat, "eta times corrected first moment")
            delta = finite(numerator / denominator, "first Adam delta")
            fields = {"square": square, "m": m, "v": v, "mHat": m_hat, "vHat": v_hat,
                      "root": root, "denominator": denominator, "numerator": numerator, "delta": delta}
            records = {f"{prefix}{key[0].upper()}{key[1:]}{l}": value for key, value in fields.items()}
            return delta, records

        coupled_delta, coupled_records = first_adam(total[l], "coupled")
        adaptive_delta, data_records = first_adam(dW[l], "data")
        decay_delta = finite(s["eta"] * penalty_gradient, "AdamW decay delta")
        adam_coupled[l] = finite(weights[l] - coupled_delta, "first Adam coupled parameter")
        adam_w[l] = finite(finite(weights[l] - adaptive_delta, "AdamW after data move") - decay_delta, "first AdamW parameter")
        add(f"penalty_update_{l}", "q=g+lambda*w; SGD=w-eta*q; firstAdam uses explicit moments; AdamW=w-dataDelta-eta*lambda*w",
            {"weight": weights[l], "dataGradient": dW[l], "lambda": s["lambda"], "eta": s["eta"], "epsilon": s["epsilon"]},
            {f"totalGradient{l}": total[l], f"penaltyGradient{l}": penalty_gradient,
             **coupled_records, **data_records,
             f"sgdCoupled{l}": sgd_coupled[l], f"sgdDecoupled{l}": sgd_decoupled[l],
             f"adamCoupled{l}": adam_coupled[l], f"adamW{l}": adam_w[l]})
    penalty = finite(finite(s["lambda"] / 2, "lambda half") * weight_squares, "L2 penalty")
    objective = finite(data_loss + penalty, "total objective")
    data_norm = finite(np.sqrt(data_squares), "data gradient norm")
    total_norm = finite(np.sqrt(total_squares), "total gradient norm")
    add("norms", "penalty=(lambda/2)*sum(w_l²); objective=dataLoss+penalty; norm(g)=sqrt(sum(g_l²))",
        {"lambda": s["lambda"], "weightSquares": weight_squares, "dataSquares": data_squares, "totalSquares": total_squares, "dataLoss": data_loss},
        {"penalty": penalty, "objective": objective, "dataGradientNorm": data_norm, "totalGradientNorm": total_norm, "inputGradient": dH[0]})
    # Each displayed subsequent loss is a new full-vector forward pass.
    after_sgd = forward(sgd_coupled, "sgd")[-1]
    after_adam = forward(adam_coupled, "adamCoupled")[-1]
    after_adam_w = forward(adam_w, "adamW")[-1]
    items = [("weights", weights, "layer", "Independent scalar parameters."),
             ("activations", h, "input_then_layer", "Input h0 then actual layer activations."),
             ("preactivations", z, "layer", "Actual forward products."),
             ("slopes", slopes, "layer", "ReLU-zero=0; tanh slope is stored binary64 1-h²."),
             ("dataGradients", dW, "layer", "Independent data-loss partial derivatives."),
             ("totalGradients", total, "layer", "Data gradient plus lambda*w."),
             ("activationAdjoints", dH, "input_then_layer", "Data adjoints h0 through h_depth."),
             ("preactivationAdjoints", dZ, "layer", "Data adjoints after local slopes."),
             ("sgdCoupled", sgd_coupled, "layer", "One simultaneous coupled SGD step."),
             ("sgdDecoupled", sgd_decoupled, "layer", "One simultaneous decoupled SGD step."),
             ("adamCoupled", adam_coupled, "layer", "FIRST coupled Adam step from zero moments."),
             ("adamW", adam_w, "layer", "FIRST AdamW step from zero moments; old-weight decay.")]
    tensors = [tensor(name, [len(values)], [axis], values, provenance) for name, values, axis, provenance in items]
    return trace.result({"prediction": prediction, "dataLoss": data_loss, "penalty": penalty, "objective": objective,
                         **o, "error": error, "dataGradientNorm": data_norm, "totalGradientNorm": total_norm,
                         "inputGradient": dH[0], "sgdDataLoss": after_sgd,
                         "adamCoupledDataLoss": after_adam, "adamWDataLoss": after_adam_w}, tensors)


if __name__ == "__main__":
    run(derive_iv15, DEFAULT_IV15)
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.

"""Small JSON/NumPy support for IV09–10; no autodiff and no implicit broadcasting.

Keep this file beside iv09.py and iv10.py. Both chapters display this exact source.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


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


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


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


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


def finite(value, label):
    # Reject bool (a Python int subclass), strings, complex values and nonfinite data.
    if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        number = np.float64(value)
    except (OverflowError, ValueError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not np.isfinite(number):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return number


def fixed_state(state, defaults):
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "State must be a scalar-field object.")
    values = {}
    for key in defaults:
        if key not in state:
            raise NumericalFault("NONFINITE", f"{key} must be an own finite field.")
        value = finite(state[key], key)
        if value < -20 or value > 20:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between -20 and 20.")
        values[key] = value
    if any(key not in defaults for key in state):
        raise NumericalFault("SHAPE_MISMATCH", "Only the declared fixed-width scalar fields are supported.")
    return values


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: float(finite(value, key)) for key, value in values.items()}


class LayerTrace:
    def __init__(self, state):
        self.outputs = numbers(state)
        self.steps = []

    def add(self, identifier, equation, inputs, values):
        # Copy operands and results; a later loop iteration cannot rewrite a saved step.
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update(values)
        self.steps.append({"id": identifier, "label": identifier, "equation": equation,
                           "explanation": equation, "inputs": inputs, "outputs": values})

    def result(self, summary, tensors):
        return {"status": "defined", "outputs": {**numbers(summary), **numbers(self.outputs)},
                "steps": self.steps, "tensors": tensors}


def tensor(identifier, shape, axes, values, provenance):
    # Shapes are lesson-owned constants. Convert only dense, finite NumPy real data.
    array = np.asarray(values, dtype=np.float64)
    if array.size != int(np.prod(shape)) or len(axes) != len(shape) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match named dimensions.")
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
            "values": [float(finite(value, identifier)) for value in array.reshape(-1)],
            "provenance": provenance, "precision": 8}


def run(derive, defaults):
    """CLI: no argument uses defaults; a full JSON object or '-' replaces all fields."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            output = derive(state)
    else:
        state = dict(defaults)
        output = derive(state)
    print(json.dumps(output, allow_nan=False, separators=(",", ":")))

Omitting the CLI state argument uses defaults; a full JSON object replaces every field, and - reads that object from standard input. Keep both files together.

Reset restores all controls and recomputes first steps from zero moments. It does not resume any training history. Use the five exercises in the lab to separate a parameter partial from initializer sensitivity, reconstruct a gradient cell and objective, predict a depth edit, and distinguish SGD algebra from adaptive decay placement.

The key habits are concrete: follow actual forward and reverse factors, measure the norm of the specified vector, keep data loss separate from penalty, and declare optimizer state and arithmetic order. In Part III, the same discipline will explain how a discrete token ID selects a vector row and how a real gradient can update that selected embedding.