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.
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
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: . Total-gradient norm: . Input derivative: .
| Layer / index | w | h previous | z product | h | Slope | dH upstream | dZ | dW | dH previous | Total gradient |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 / 0 | 0.5 | 1 | 0.5 | 0.5 | 1 | 0.03125 | 0.03125 | 0.03125 | 0.015625 | 0.15625 |
| 2 / 1 | 0.5 | 0.5 | 0.25 | 0.25 | 1 | 0.0625 | 0.0625 | 0.03125 | 0.03125 | 0.15625 |
| 3 / 2 | 0.5 | 0.25 | 0.125 | 0.125 | 1 | 0.125 | 0.125 | 0.03125 | 0.0625 | 0.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.
| Weight index | Old w | SGD coupled L2 | SGD decoupled | FIRST Adam coupled L2 | FIRST AdamW |
|---|---|---|---|---|---|
| 0 | 0.5 | 0.48046875 | 0.48046875 | 0.4305555555555556 | 0.459375 |
| 1 | 0.5 | 0.48046875 | 0.48046875 | 0.4305555555555556 | 0.459375 |
| 2 | 0.5 | 0.48046875 | 0.48046875 | 0.4305555555555556 | 0.459375 |
Fresh data losses after full-vector forward recomputation: coupled SGD ; first coupled Adam ; first AdamW . 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 index | Value |
|---|---|
| 0 | 0.5 |
| 1 | 0.5 |
| 2 | 0.5 |
activations
input_then_layer=4 · float64 · display precision 8 · h0=x, then the real post-activation at each layer.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | 0.25 |
| 3 | 0.125 |
preactivations
layer=3 · float64 · display precision 8 · w_l*h_previous before activation.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | 0.25 |
| 2 | 0.125 |
slopes
layer=3 · float64 · display precision 8 · Selected local slopes, including ReLU-zero=0 and stored binary64 tanh 1-h².
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
dataGradients
layer=3 · float64 · display precision 8 · Distinct parameter partial derivatives of the data half-square.
| Storage index | Value |
|---|---|
| 0 | 0.03125 |
| 1 | 0.03125 |
| 2 | 0.03125 |
totalGradients
layer=3 · float64 · display precision 8 · Data gradient plus lambda*w for coupled L2.
| Storage index | Value |
|---|---|
| 0 | 0.15625 |
| 1 | 0.15625 |
| 2 | 0.15625 |
activationAdjoints
input_then_layer=4 · float64 · display precision 8 · Data loss sensitivities to h0 through h_depth; last entry is error.
| Storage index | Value |
|---|---|
| 0 | 0.015625 |
| 1 | 0.03125 |
| 2 | 0.0625 |
| 3 | 0.125 |
preactivationAdjoints
layer=3 · float64 · display precision 8 · Data loss sensitivities after local activation slope.
| Storage index | Value |
|---|---|
| 0 | 0.03125 |
| 1 | 0.0625 |
| 2 | 0.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 index | Value |
|---|---|
| 0 | 0.48046875 |
| 1 | 0.48046875 |
| 2 | 0.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 index | Value |
|---|---|
| 0 | 0.48046875 |
| 1 | 0.48046875 |
| 2 | 0.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 index | Value |
|---|---|
| 0 | 0.4305555555555556 |
| 1 | 0.4305555555555556 |
| 2 | 0.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 index | Value |
|---|---|
| 0 | 0.459375 |
| 1 | 0.459375 |
| 2 | 0.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.
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 counts layers. The input is ; for mathematical layer numbers ,
Here means the product before activation, the value after activation, prediction, target, signed error and 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 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 , 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 and ; depth is an integer from one through eight; alpha and probe delta are between and . 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; is between zero and two, learning rate between zero and one, and between and one. Every field is required and finite. These are teaching bounds, not recommended training hyperparameters.
Work through three distinct linear weights
Defaults are , , , , zero probe delta and the linear activation . Every local activation slope is one. Compute in forward order:
Therefore , and . 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 and similarly . The terminal seed is . Differentiating the product and activation gives
Starting at layer three, , so and . Next , , and . Finally , , and the input derivative is .
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:
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 , keep alpha , and set probe delta to at index zero. The weights are . Prediction is zero and error is . A small change in the first weight still travels through the two later factors, so
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 , prediction is . At target zero, each distinct data gradient is . One factor comes from the loss seed and the others from the forward and backward paths. With alpha , increasing depth from three to eight changes prediction from to and each weight gradient from to . With alpha two, the corresponding powers grow instead. These observations use actual products, not an idealized plotted training curve.
ReLU is . 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 approaches or for large magnitude inputs. Its real derivative is , positive at every finite real argument. Saturation describes the region where the output changes very little with its input. The program stores in binary64 and evaluates the slope as . Stored 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
is the penalty, the total objective and its weight gradient. Lambda controls the penalty’s strength. Its derivative is because differentiating gives . Changing lambda alone does not alter the starting forward graph or data loss.
At the default , sum of squared weights is , so . Thus . Each total gradient is , giving total norm . The data-gradient norm remains . 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:
Both sides use the same old weights and gradients. At every default weight becomes . 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 , and fixed . For whichever gradient that branch uses,
The hats denote bias-corrected moments. Epsilon is added outside the square root, matching IV-13. In real arithmetic this simplifies to . 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 and sets . First AdamW uses and sets
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 , the moments are , , corrected moments and , root , and denominator . The numerator is , so and .
For AdamW, gives , , corrected root and denominator . Its data move is , and old-weight decay is . Hence
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 and for the two adaptive branches. These are data losses, not total regularized objectives.
As another hand check, changing only depth to one gives , . Coupled first Adam yields and first AdamW yields . 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.