The neural notebook
← All chapters

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

One Training Step: Hand-Derived Backpropagation

Follow every local derivative through a tiny ReLU network, update all four parameters together, and recompute the loss by hand.

Review the ideas this chapter uses

A prediction is a calculation. Learning adds a second job: deciding how to change the numbers that control that calculation. We will do both jobs for one tiny network, with arithmetic small enough to inspect completely. Nothing here calls an automatic differentiation system.

The interaction starts with a solved example. Its initial prediction is −3/4-3/4 for a target of 11. One update with learning rate 1/81/8 changes the prediction to 387/1024387/1024 and reduces the half-squared loss from 49/3249/32 to 405769/2097152405769/2097152. These are results for these particular settings, not a promise about every edit.

Compute it yourself

One real training step: 1 → 1 ReLU → 1

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
2
y
1
w1
1
b1
0
w2
-0.5
b2
0.25
eta
0.125
prediction-0.75
loss1.53125
nextPrediction0.3779296875
nextLoss0.19348573684692383

prediction -0.75. loss 1.53125. nextPrediction 0.3779296875. nextLoss 0.19348573684692383. First affine layer. Multiply the input by the first weight, then add its bias.. firstProduct 2. z1 2

First affine layer

z1 = w1*x + b1

Multiply the input by the first weight, then add its bias.

Inputs

w1
1
x
2
b1
0

Outputs

firstProduct
2
z1
2
Original complete forward path — trace starting state

Selected trace operation: First affine layer. The path below always shows the original calculation; the recomputed values are labeled separately.

  1. Input x

    x = 2

  2. Hidden preactivation z1

    Selected operation

    w1=1, b1=0; (1) × (2) + (0) = 2

  3. Hidden activation a1

    ReLU(z1=2) = 2

  4. Prediction

    w2=-0.5, b2=0.25; (-0.5) × (2) + (0.25) = -0.75

  5. Loss

    Target y=1; error=-1.75; half-squared loss=1.53125

Parameters before and after simultaneous SGD

Every gradient uses the original parameters. The update uses eta=0.125. Scroll the table horizontally if needed, or open its text alternative.

Original parameter, loss gradient, updated parameter
ParameterOriginalGradientUpdated
w111.750.78125
b100.875-0.109375
w2-0.5-3.5-0.0625
b20.25-1.750.46875
Read parameter changes as text
  • w1: original 1; gradient 1.75; updated 0.78125.
  • b1: original 0; gradient 0.875; updated -0.109375.
  • w2: original -0.5; gradient -3.5; updated -0.0625.
  • b2: original 0.25; gradient -1.75; updated 0.46875.

Fresh forward pass with the updated parameters

These values come from recomputing after the simultaneous update, with the same input x=2 and target y=1.

Fresh hidden preactivation
1.453125
Fresh hidden activation
1.453125
Fresh prediction
0.3779296875
Fresh loss
0.19348573684692383
Inspect tensor shapes and full precision

All computed outputs

prediction
-0.75
loss
1.53125
nextPrediction
0.3779296875
nextLoss
0.19348573684692383
z1
2
a1
2
error
-1.75
dPrediction
-1.75
dW1
1.75
dB1
0.875
dW2
-3.5
dB2
-1.75
dA1
0.875
dZ1
0.875
nextW1
0.78125
nextB1
-0.109375
nextW2
-0.0625
nextB2
0.46875
nextZ1
1.453125

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

x

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
02

y

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
01

w1

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
01

b1

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
00

w2

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
0-0.5

b2

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
00.25

eta

row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.

Storage indexValue
00.125

firstProduct

row=1 × column=1 · float64 · display precision 8 · forward-hidden: z1 = w1*x + b1

Storage indexValue
02

z1

row=1 × column=1 · float64 · display precision 8 · forward-hidden: z1 = w1*x + b1

Storage indexValue
02

a1

row=1 × column=1 · float64 · display precision 8 · forward-relu: a1 = max(0, z1)

Storage indexValue
02

secondProduct

row=1 × column=1 · float64 · display precision 8 · forward-output: prediction = w2*a1 + b2

Storage indexValue
0-1

prediction

row=1 × column=1 · float64 · display precision 8 · forward-output: prediction = w2*a1 + b2

Storage indexValue
0-0.75

error

row=1 × column=1 · float64 · display precision 8 · forward-loss: error = prediction-y; loss = error*error/2

Storage indexValue
0-1.75

errorSquared

row=1 × column=1 · float64 · display precision 8 · forward-loss: error = prediction-y; loss = error*error/2

Storage indexValue
03.0625

loss

row=1 × column=1 · float64 · display precision 8 · forward-loss: error = prediction-y; loss = error*error/2

Storage indexValue
01.53125

dLossDError

row=1 × column=1 · float64 · display precision 8 · backward-loss: dL/dError = (1/2)*2*error = error

Storage indexValue
0-1.75

dPrediction

row=1 × column=1 · float64 · display precision 8 · backward-prediction: dPrediction = dLossDError * dErrorDPrediction

Storage indexValue
0-1.75

dW2

row=1 × column=1 · float64 · display precision 8 · backward-w2: dW2 = dPrediction * a1

Storage indexValue
0-3.5

dB2

row=1 × column=1 · float64 · display precision 8 · backward-b2: dB2 = dPrediction * 1

Storage indexValue
0-1.75

dA1

row=1 × column=1 · float64 · display precision 8 · backward-a1: dA1 = dPrediction * w2

Storage indexValue
00.875

dZ1

row=1 × column=1 · float64 · display precision 8 · backward-z1: dZ1 = dA1 * (z1 > 0 ? 1 : 0)

Storage indexValue
00.875

dW1

row=1 × column=1 · float64 · display precision 8 · backward-w1: dW1 = dZ1 * x

Storage indexValue
01.75

dB1

row=1 × column=1 · float64 · display precision 8 · backward-b1: dB1 = dZ1 * 1

Storage indexValue
00.875

deltaW1

row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta

Storage indexValue
00.21875

deltaB1

row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta

Storage indexValue
00.109375

deltaW2

row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta

Storage indexValue
0-0.4375

deltaB2

row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta

Storage indexValue
0-0.21875

nextW1

row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta

Storage indexValue
00.78125

nextB1

row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta

Storage indexValue
0-0.109375

nextW2

row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta

Storage indexValue
0-0.0625

nextB2

row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta

Storage indexValue
00.46875

nextFirstProduct

row=1 × column=1 · float64 · display precision 8 · fresh-hidden: nextZ1 = nextW1*x + nextB1

Storage indexValue
01.5625

nextZ1

row=1 × column=1 · float64 · display precision 8 · fresh-hidden: nextZ1 = nextW1*x + nextB1

Storage indexValue
01.453125

nextA1

row=1 × column=1 · float64 · display precision 8 · fresh-relu: nextA1 = max(0, nextZ1)

Storage indexValue
01.453125

nextSecondProduct

row=1 × column=1 · float64 · display precision 8 · fresh-output: nextPrediction = nextW2*nextA1 + nextB2

Storage indexValue
0-0.0908203125

nextPrediction

row=1 × column=1 · float64 · display precision 8 · fresh-output: nextPrediction = nextW2*nextA1 + nextB2

Storage indexValue
00.3779296875

nextError

row=1 × column=1 · float64 · display precision 8 · fresh-loss: nextError = nextPrediction-y; nextLoss = nextError*nextError/2

Storage indexValue
0-0.6220703125

nextErrorSquared

row=1 × column=1 · float64 · display precision 8 · fresh-loss: nextError = nextPrediction-y; nextLoss = nextError*nextError/2

Storage indexValue
00.38697147369384766

nextLoss

row=1 × column=1 · float64 · display precision 8 · fresh-loss: nextError = nextPrediction-y; nextLoss = nextError*nextError/2

Storage indexValue
00.19348573684692383

diagnostic-w1.minusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.749755859375

diagnostic-w1.plusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.750244140625

diagnostic-w1.minusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5308227837085724

diagnostic-w1.plusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5316772758960724

diagnostic-w1.lossDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.0008544921875

diagnostic-w1.twoH

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.00048828125

diagnostic-w1.centralDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.75

diagnostic-w1.analyticDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-w1.absoluteResidual

row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-b1.minusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.7498779296875

diagnostic-b1.plusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.7501220703125

diagnostic-b1.minusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5310363844037056

diagnostic-b1.plusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5314636304974556

diagnostic-b1.lossDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.00042724609375

diagnostic-b1.twoH

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.00048828125

diagnostic-b1.centralDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.875

diagnostic-b1.analyticDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-b1.absoluteResidual

row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-w2.minusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.75048828125

diagnostic-w2.plusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.74951171875

diagnostic-w2.minusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5321046113967896

diagnostic-w2.plusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5303956270217896

diagnostic-w2.lossDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.001708984375

diagnostic-w2.twoH

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.00048828125

diagnostic-w2.centralDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-3.5

diagnostic-w2.analyticDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-w2.absoluteResidual

row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-b2.minusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.750244140625

diagnostic-b2.plusPrediction

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.749755859375

diagnostic-b2.minusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5316772758960724

diagnostic-b2.plusLoss

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
01.5308227837085724

diagnostic-b2.lossDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-0.0008544921875

diagnostic-b2.twoH

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00.00048828125

diagnostic-b2.centralDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
0-1.75

diagnostic-b2.analyticDifference

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

diagnostic-b2.absoluteResidual

row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)

Storage indexValue
00

Authored toy data, one sample. x → z1=w1*x+b1 → a1=max(0,z1) → prediction=w2*a1+b2. Every tensor is [1,1], with row and column axes. The trace follows every local derivative, then updates all four parameters together. Reset restores the solved fractional example.

Try eta=0 for an unchanged result, eta=2 for overshoot after resetting, or w1=0 and b1=0 for the ReLU kink. At zero the chosen backward subgradient is 0; the mathematical ReLU derivative is undefined there.

Check your understanding

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

1. At these settings dB2 = -1.75. What does dB2 measure?
2. Using x=2, w1=1, b1=0, what is z1 before ReLU?
3. The trace gives dZ1=0.875 and x=2. What is dW1?
4. At the current forward state, suppose eta were strictly positive. In ideal real arithmetic, which way would this SGD step move b2?
5. Compare loss=1.53125 with the freshly recomputed nextLoss=0.19348573684692383. Which statement is supported?

Start by selecting the first trace step and moving forward. Each backward step shows an incoming loss sensitivity and the local derivative that multiplies it. Reset restores the example used below. Change only the learning rate to zero to see a complete no-op; later, try the deliberately excessive rate of two.

The network path labels its actual operands and highlights the operation selected in the trace with text and a border. It always shows the original complete forward calculation. The parameter table places each original value beside its gradient and updated value; a separate fresh-forward summary shows the recomputed hidden values, prediction and loss. Both displays read the same numerical record as the detailed trace.

Give every number a job

Our authored toy has one input, one hidden unit and one output. A parameter is a number we allow the update to change. A weight multiplies an incoming value; a bias adds an adjustable offset. The four parameters are w1,b1,w2,b2w_1,b_1,w_2,b_2. The input xx, target yy and learning rate η\eta stay fixed during this training step.

Symbol / code nameMeaningDefault
xx / xObserved input22
yy / yDesired output, or target11
w1,b1w_1,b_1 / w1,b1First layer’s weight and bias1,01,0
z1z_1 / z1First weighted sum, before activation22
a1a_1 / a1Hidden value after activation22
w2,b2w_2,b_2 / w2,b2Output layer’s weight and bias−1/2,1/4-1/2,1/4
y^\hat y / predictionComputed output−3/4-3/4
ee / errorPrediction minus target−7/4-7/4
LL / lossHalf-squared error49/3249/32
η\eta / etaLearning rate, or step size1/81/8

A tensor is a collection of numbers with a declared shape. Each quantity here contains one number, stored as a [1,1][1,1] tensor with row and column axes. The input, hidden activation and output each have one feature row and one sample column. Each weight is a one-by-one matrix; each bias is a one-entry column. Thus [1,1][1,1] times [1,1][1,1] gives [1,1][1,1], and adding the bias is legal without broadcasting. Scalar notation keeps that same computation readable.

The learning rate and loss also use one-element inspector records; their row and column labels do not introduce extra samples. We have one sample throughout, so there is no hidden batch average. For more background, revisit matrix–vector multiplication and composition and learned representations.

First, make the prediction

An affine operation means multiply by a weight and add a bias. The hidden layer starts with

z1=w1x+b1=(1)(2)+0=2.z_1=w_1x+b_1=(1)(2)+0=2.

An activation transforms that weighted sum. ReLU, short for rectified linear unit, keeps positive values and replaces negative ones by zero:

a1=max⁡(0,z1)=max⁡(0,2)=2.a_1=\max(0,z_1)=\max(0,2)=2.

The second layer has a linear output, with no second ReLU. A negative prediction is therefore allowed:

y^=w2a1+b2=(−12)(2)+14=−1+14=−34.\hat y=w_2a_1+b_2=\left(-\frac12\right)(2)+\frac14 =-1+\frac14=-\frac34.

The signed error says which side of the target we reached. The loss turns its magnitude into a nonnegative objective:

e=y^−y=−34−1=−74,L=e22=(−7/4)22=4932.e=\hat y-y=-\frac34-1=-\frac74, \qquad L=\frac{e^2}{2}=\frac{(-7/4)^2}{2}=\frac{49}{32}.

The factor 1/21/2 is a convention that simplifies the derivative. Removing it would double every gradient for the same prediction. We must keep the chosen loss definition consistent with the update.

Why derivatives travel backward

A derivative describes how quickly one quantity changes when another changes nearby. The notation ∂L/∂w1\partial L/\partial w_1 asks how loss changes when only w1w_1 changes. The four parameter derivatives together form the gradient. They are local sensitivities, not new parameter values.

The problem is that w1w_1 does not appear directly in the final loss formula. It affects z1z_1, which affects a1a_1, which affects the prediction, which affects loss. The chain rule multiplies the sensitivities along that path. A local derivative belongs to one operation; an accumulated derivative includes the path from that operation to loss.

For example, if changing an intermediate by a small amount changes the prediction by twice that amount, and changing the prediction changes loss by three times that amount, their combined local effect is six times the original change. Signs multiply too. This is why a negative output weight matters even when the hidden activation is positive.

We start at loss, where ∂L/∂L=1\partial L/\partial L=1. Differentiating the half-square and then the subtraction gives

∂L∂e=e=−74,∂e∂y^=1,∂L∂y^=(−74)(1)=−74.\frac{\partial L}{\partial e}=e=-\frac74, \qquad \frac{\partial e}{\partial\hat y}=1, \qquad \frac{\partial L}{\partial\hat y}=\left(-\frac74\right)(1)=-\frac74.

The trace calls this last value dPrediction. Its negative sign means a sufficiently small increase in prediction would lower loss at the current point. It does not mean loss itself is negative.

Every backward multiplication

Consider the output equation y^=w2a1+b2\hat y=w_2a_1+b_2. Holding the other inputs fixed, its local derivatives with respect to w2w_2, b2b_2 and a1a_1 are a1a_1, 11 and w2w_2. Multiply each by the same incoming sensitivity dPrediction:

∂L∂w2=∂L∂y^∂y^∂w2=(−74)(2)=−72,\frac{\partial L}{\partial w_2} =\frac{\partial L}{\partial\hat y}\frac{\partial\hat y}{\partial w_2} =\left(-\frac74\right)(2)=-\frac72, ∂L∂b2=(−74)(1)=−74,∂L∂a1=(−74)(−12)=78.\frac{\partial L}{\partial b_2} =\left(-\frac74\right)(1)=-\frac74, \qquad \frac{\partial L}{\partial a_1} =\left(-\frac74\right)\left(-\frac12\right)=\frac78.

The output weight and bias already have their complete gradients. We also send dA1 back toward the hidden layer. These are three consequences of one output equation, not three separate losses. In particular, we must use the original w2=−1/2w_2=-1/2 in dA1.

At z1=2z_1=2, ReLU is on its positive branch, where a1=z1a_1=z_1. Its local derivative is therefore one:

∂L∂z1=∂L∂a1∂a1∂z1=78⋅1=78.\frac{\partial L}{\partial z_1} =\frac{\partial L}{\partial a_1}\frac{\partial a_1}{\partial z_1} =\frac78\cdot1=\frac78.

Finally, the local derivatives of z1=w1x+b1z_1=w_1x+b_1 with respect to w1w_1 and b1b_1 are xx and one:

∂L∂w1=78⋅2=74,∂L∂b1=78⋅1=78.\frac{\partial L}{\partial w_1}=\frac78\cdot2=\frac74, \qquad \frac{\partial L}{\partial b_1}=\frac78\cdot1=\frac78.

We have now reached every trainable number. The input and target are held fixed, so we do not update them. Read code names such as dW1 as “derivative of loss with respect to w1,” rather than “a new weight.” Every gradient has the same one-by-one shape as its parameter.

Update the four parameters together

Stochastic gradient descent, or SGD, subtracts learning rate times gradient. Here one sample supplies the gradient; we have no momentum, weight decay or optimizer history. Write θ\theta for any one parameter and a prime for its updated value:

θ′=θ−η∂L∂θ.\theta'=\theta-\eta\frac{\partial L}{\partial\theta}.

At η=1/8\eta=1/8, every subtraction is explicit:

ParameterOriginal minus learning rate times gradientUpdated
w1w_11−(1/8)(7/4)=1−7/321-(1/8)(7/4)=1-7/3225/3225/32
b1b_10−(1/8)(7/8)0-(1/8)(7/8)−7/64-7/64
w2w_2−1/2−(1/8)(−7/2)=−8/16+7/16-1/2-(1/8)(-7/2)=-8/16+7/16−1/16-1/16
b2b_21/4−(1/8)(−7/4)=8/32+7/321/4-(1/8)(-7/4)=8/32+7/3215/3215/32

Simultaneous means all gradients describe the same original parameter state. We can store the four new values in any order after computing all gradients. We cannot update w2w_2, use that new value to calculate dA1, and still call the result this same SGD step. That would mix two different evaluation points.

The update frame stores all four new parameters together. Earlier trace frames store the original state. Editing a control from a later frame starts from its displayed parameter state rather than silently returning to the old weights.

Measure the new loss from scratch

A derivative is a local prediction about change. To find the actual outcome of a finite step, run the network again:

z1′=2532⋅2−764=10064−764=9364,a1′=9364.z_1'=\frac{25}{32}\cdot2-\frac7{64} =\frac{100}{64}-\frac7{64}=\frac{93}{64}, \qquad a_1'=\frac{93}{64}. y^′=(−116)(9364)+1532=−931024+4801024=3871024.\hat y'=\left(-\frac1{16}\right)\left(\frac{93}{64}\right)+\frac{15}{32} =-\frac{93}{1024}+\frac{480}{1024}=\frac{387}{1024}. e′=3871024−1=−6371024,L′=(−637/1024)22=4057692097152.e'=\frac{387}{1024}-1=-\frac{637}{1024}, \qquad L'=\frac{(-637/1024)^2}{2}=\frac{405769}{2097152}.

The final loss is approximately 0.193485736846923830.19348573684692383, compared with 1.531251.53125 initially. The fractional equalities are exact. These particular fractions also have finite binary representations, so they are useful reference values for binary64 arithmetic. Arbitrary decimal edits generally involve floating-point rounding. Display precision never feeds back into the model.

Three instructive ways intuition can fail

First, a larger step need not improve more. Reset and set η=2\eta=2. The same original gradients now produce

(w1′,b1′,w2′,b2′)=(−52,−74,132,154).(w_1',b_1',w_2',b_2')= \left(-\frac52,-\frac74,\frac{13}{2},\frac{15}{4}\right).

Then z1′=−27/4z_1'=-27/4, so ReLU returns zero. The prediction becomes 15/415/4 and loss is (11/4)2/2=121/32(11/4)^2/2=121/32, greater than 49/3249/32. This is an actual overshoot, not an error that the interface should hide. At η=0\eta=0, by contrast, all deltas are zero and the fresh loss is unchanged.

Second, an inactive hidden unit does not stop every update. Reset and set w1=−1w_1=-1. Now z1=−2z_1=-2, a1=0a_1=0, and the local ReLU derivative is zero. Both first-layer gradients vanish. The output weight gradient also vanishes because it multiplies a1a_1, but the output bias gradient is −3/4-3/4. Its update can still change the prediction.

Third, at exactly z1=0z_1=0, ReLU has left slope zero and right slope one. There is no unique derivative. Our declared backward convention chooses subgradient zero, so dZ1, dW1 and dB1 use zero. Set w1=b1=0w_1=b_1=0 to inspect that branch. A central finite difference crossing the kink is not evidence for a unique ReLU derivative.

Controls accept finite inputs and parameters with absolute value at most 100, and rates from zero through two. Invalid values produce an unavailable result with a reason. Intermediate values and updated parameters are checked for finiteness, not clamped; a large valid step can leave the input bounds. Starting another calculation from such a frame requires returning its parameters to the allowed range.

Optional numerical diagnostic: compare nearby losses

The final four trace entries inspect the original, pre-update parameters, one at a time. They do not change the training step. For a parameter θ\theta, fresh forward passes evaluate losses with only that parameter replaced by θ−h\theta-h and θ+h\theta+h, where the fixed dyadic spacing is h=2−12=1/4096h=2^{-12}=1/4096. The trace shows those operands, nearby predictions and losses, then computes

gcentral=L(θ+h)−L(θ−h)2h,r=∣gcentral−∂L∂θ∣.g_{\mathrm{central}}=\frac{L(\theta+h)-L(\theta-h)}{2h}, \qquad r=\left|g_{\mathrm{central}}-\frac{\partial L}{\partial\theta}\right|.

Here rr is an absolute residual, a numerical difference between two derivative calculations. Smaller residuals alone do not prove correctness: both calculations could share a mistake. No pass/fail threshold or independent-oracle authority is attached to these diagnostics.

In general, smooth central differences have truncation error proportional to h2h^2, while subtracting nearby floating-point losses can amplify roundoff. In this particular network, holding a ReLU branch fixed makes each one-parameter loss quadratic, so that truncation term cancels in exact arithmetic; floating-point cancellation still matters. A fixed spacing is not a full gradient-validation campaign.

If the baseline or either perturbed hidden preactivation is zero or changes sign, that parameter’s entry explicitly skips comparison and has no numeric outputs. It never presents agreement at a kink.

Read the same computation in Python

The source below uses explicit NumPy float64 scalars. firstProduct, z1 and a1 name the first three forward quantities. Each backward assignment multiplies an incoming sensitivity by a named local factor. All deltas precede all next parameters, and the final block recomputes the prediction and loss. The JSON result uses the browser model’s output names and trace operation IDs.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-08: explicit NumPy scalar backpropagation, not autograd.

Later owner-run JSON CLI examples (not executed during the resource hold):
    python code/python/p02/iv08.py
    python code/python/p02/iv08.py '{"x":2,"y":1,"w1":1,"b1":0,"w2":-0.5,"b2":0.25,"eta":0.125}'
    python code/python/p02/iv08.py - < state.json

All seven fields are required when supplying a state. Inputs/parameters have
absolute value at most 100; eta is in [0,2]. Bounds apply to the supplied state,
not to the computed update. All arithmetic uses NumPy float64 scalars.
"""

import argparse
import json
import sys

import numpy as np


DEFAULT_IV08 = {
    "x": 2, "y": 1, "w1": 1, "b1": 0, "w2": -0.5, "b2": 0.25, "eta": 0.125,
}


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 implicit string, boolean and array-to-scalar coercions at the boundary.
    if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = np.float64(value)
    except (OverflowError, ValueError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not np.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def bounded(value, minimum, maximum, label):
    value = finite(value, label)
    if value < minimum or value > maximum:
        raise NumericalFault("INVALID_INPUT", f"{label} must be between {minimum} and {maximum}.")
    return value


def tensor(identifier, value, provenance):
    # A one-element [1,1] record preserves the mathematical column convention.
    return {
        "id": identifier, "shape": [1, 1], "axes": ["row", "column"],
        "dtype": "float64", "values": [float(value)],
        "provenance": provenance, "precision": 8,
    }



# Fresh loss evaluations for the optional diagnostic; no backward values reused.
def diagnostic_forward(state):
    x, y = state["x"], state["y"]
    w1, b1, w2, b2 = state["w1"], state["b1"], state["w2"], state["b2"]
    firstProduct = finite(w1 * x, "diagnostic w1*x")
    z1 = finite(firstProduct + b1, "diagnostic z1")
    a1 = finite(np.float64(z1 if z1 > 0 else 0), "diagnostic a1")
    secondProduct = finite(w2 * a1, "diagnostic w2*a1")
    prediction = finite(secondProduct + b2, "diagnostic prediction")
    error = finite(prediction - y, "diagnostic error")
    errorSquared = finite(error * error, "diagnostic errorSquared")
    loss = finite(errorSquared / np.float64(2), "diagnostic loss")
    return {"z1": z1, "prediction": prediction, "loss": loss}

def derive_iv08(state):
    """Return the same numeric output names and operation IDs as deriveIV08."""
    try:
        values = {}
        for key in DEFAULT_IV08:
            values[key] = bounded(state.get(key), 0 if key == "eta" else -100,
                                  2 if key == "eta" else 100, key)
        x, y = values["x"], values["y"]
        w1, b1, w2, b2 = values["w1"], values["b1"], values["w2"], values["b2"]
        eta = values["eta"]

        # Forward pass: each product and sum is recorded before it is reused.
        firstProduct = finite(w1 * x, "w1*x")
        z1 = finite(firstProduct + b1, "z1")
        a1 = finite(np.float64(z1 if z1 > 0 else 0), "a1")
        secondProduct = finite(w2 * a1, "w2*a1")
        prediction = finite(secondProduct + b2, "prediction")
        error = finite(prediction - y, "error")
        errorSquared = finite(error * error, "errorSquared")
        loss = finite(errorSquared / np.float64(2), "loss")

        # Reverse chain rule: incoming loss sensitivity times the local factor.
        dLossDError = error  # d(error**2/2)/dError = error.
        dErrorDPrediction = np.float64(1)
        dPrediction = finite(dLossDError * dErrorDPrediction, "dPrediction")
        dPredictionDW2 = a1
        dW2 = finite(dPrediction * dPredictionDW2, "dW2")
        dPredictionDB2 = np.float64(1)
        dB2 = finite(dPrediction * dPredictionDB2, "dB2")
        dPredictionDA1 = w2  # Original w2, never the updated output weight.
        dA1 = finite(dPrediction * dPredictionDA1, "dA1")
        # At z1=0 the derivative is undefined; deliberately choose subgradient 0.
        dA1DZ1 = np.float64(1 if z1 > 0 else 0)
        dZ1 = finite(dA1 * dA1DZ1, "dZ1")
        dZ1DW1 = x
        dW1 = finite(dZ1 * dZ1DW1, "dW1")
        dZ1DB1 = np.float64(1)
        dB1 = finite(dZ1 * dZ1DB1, "dB1")

        # Simultaneous SGD: first compute every delta from the original gradient.
        deltaW1 = finite(eta * dW1, "eta*dW1")
        deltaB1 = finite(eta * dB1, "eta*dB1")
        deltaW2 = finite(eta * dW2, "eta*dW2")
        deltaB2 = finite(eta * dB2, "eta*dB2")
        nextW1 = finite(w1 - deltaW1, "nextW1")
        nextB1 = finite(b1 - deltaB1, "nextB1")
        nextW2 = finite(w2 - deltaW2, "nextW2")
        nextB2 = finite(b2 - deltaB2, "nextB2")

        # Fresh forward pass: re-evaluate ReLU rather than reusing a1.
        nextFirstProduct = finite(nextW1 * x, "nextW1*x")
        nextZ1 = finite(nextFirstProduct + nextB1, "nextZ1")
        nextA1 = finite(np.float64(nextZ1 if nextZ1 > 0 else 0), "nextA1")
        nextSecondProduct = finite(nextW2 * nextA1, "nextW2*nextA1")
        nextPrediction = finite(nextSecondProduct + nextB2, "nextPrediction")
        nextError = finite(nextPrediction - y, "nextError")
        nextErrorSquared = finite(nextError * nextError, "nextErrorSquared")
        nextLoss = finite(nextErrorSquared / np.float64(2), "nextLoss")

        outputs = {
            "prediction": prediction, "loss": loss, "nextPrediction": nextPrediction, "nextLoss": nextLoss,
            "z1": z1, "a1": a1, "error": error, "dPrediction": dPrediction,
            "dW1": dW1, "dB1": dB1, "dW2": dW2, "dB2": dB2, "dA1": dA1, "dZ1": dZ1,
            "nextW1": nextW1, "nextB1": nextB1, "nextW2": nextW2, "nextB2": nextB2, "nextZ1": nextZ1,
        }
        steps = [
            {
                "id": "forward-hidden", "label": "First affine layer", "equation": "z1 = w1*x + b1",
                "explanation": "Multiply the input by the first weight, then add its bias.",
                "inputs": {"w1": w1, "x": x, "b1": b1}, "outputs": {"firstProduct": firstProduct, "z1": z1},
            },
            {
                "id": "forward-relu", "label": "Hidden ReLU", "equation": "a1 = max(0, z1)",
                "explanation": "Keep a positive preactivation; replace a nonpositive one by zero.",
                "inputs": {"z1": z1}, "outputs": {"a1": a1},
            },
            {
                "id": "forward-output", "label": "Second affine layer", "equation": "prediction = w2*a1 + b2",
                "explanation": "The output is linear: multiply the hidden activation, then add b2.",
                "inputs": {"w2": w2, "a1": a1, "b2": b2}, "outputs": {"secondProduct": secondProduct, "prediction": prediction},
            },
            {
                "id": "forward-loss", "label": "Error and half-squared loss", "equation": "error = prediction-y; loss = error*error/2",
                "explanation": "Use one sample, with no batch sum or averaging.",
                "inputs": {"prediction": prediction, "y": y}, "outputs": {"error": error, "errorSquared": errorSquared, "loss": loss},
            },
            {
                "id": "backward-loss", "label": "Differentiate the loss", "equation": "dL/dError = (1/2)*2*error = error",
                "explanation": "The incoming derivative dL/dL is 1. The local slope of the half-square is error.",
                "inputs": {"incoming": np.float64(1), "error": error}, "outputs": {"dLossDError": dLossDError},
            },
            {
                "id": "backward-prediction", "label": "Through the subtraction", "equation": "dPrediction = dLossDError * dErrorDPrediction",
                "explanation": "Holding y fixed, the local derivative of prediction-y with respect to prediction is 1.",
                "inputs": {"dLossDError": dLossDError, "dErrorDPrediction": dErrorDPrediction}, "outputs": {"dPrediction": dPrediction},
            },
            {
                "id": "backward-w2", "label": "Output weight gradient", "equation": "dW2 = dPrediction * a1",
                "explanation": "The accumulated loss sensitivity is dPrediction; the local derivative with respect to w2 is a1.",
                "inputs": {"dPrediction": dPrediction, "dPredictionDW2": dPredictionDW2}, "outputs": {"dW2": dW2},
            },
            {
                "id": "backward-b2", "label": "Output bias gradient", "equation": "dB2 = dPrediction * 1",
                "explanation": "Adding b2 has local derivative 1, so the output bias receives the full incoming sensitivity.",
                "inputs": {"dPrediction": dPrediction, "dPredictionDB2": dPredictionDB2}, "outputs": {"dB2": dB2},
            },
            {
                "id": "backward-a1", "label": "Return to the hidden activation", "equation": "dA1 = dPrediction * w2",
                "explanation": "The local derivative with respect to a1 is the original output weight w2.",
                "inputs": {"dPrediction": dPrediction, "dPredictionDA1": dPredictionDA1}, "outputs": {"dA1": dA1},
            },
            {
                "id": "backward-z1", "label": "Through ReLU", "equation": "dZ1 = dA1 * (z1 > 0 ? 1 : 0)",
                "explanation": ("ReLU has no unique derivative at zero. This computation explicitly chooses subgradient 0." if z1 == 0
                                else "The local ReLU derivative is 1 on the positive branch and 0 on the negative branch."),
                "inputs": {"dA1": dA1, "z1": z1, "dA1DZ1": dA1DZ1}, "outputs": {"dZ1": dZ1},
            },
            {
                "id": "backward-w1", "label": "First weight gradient", "equation": "dW1 = dZ1 * x",
                "explanation": "The local derivative of w1*x+b1 with respect to w1 is the fixed input x.",
                "inputs": {"dZ1": dZ1, "dZ1DW1": dZ1DW1}, "outputs": {"dW1": dW1},
            },
            {
                "id": "backward-b1", "label": "First bias gradient", "equation": "dB1 = dZ1 * 1",
                "explanation": "The local derivative with respect to b1 is 1. All four parameter gradients are now available.",
                "inputs": {"dZ1": dZ1, "dZ1DB1": dZ1DB1}, "outputs": {"dB1": dB1},
            },
            {
                "id": "sgd-deltas", "label": "Scale the original gradients", "equation": "deltaTheta = eta * dTheta",
                "explanation": "Compute all four deltas before applying any update; gradients are not recomputed halfway through.",
                "inputs": {"eta": eta, "dW1": dW1, "dB1": dB1, "dW2": dW2, "dB2": dB2},
                "outputs": {"deltaW1": deltaW1, "deltaB1": deltaB1, "deltaW2": deltaW2, "deltaB2": deltaB2},
            },
            {
                "id": "sgd-simultaneous", "label": "Simultaneous SGD", "equation": "nextTheta = theta - deltaTheta",
                "explanation": "Subtract each delta from its original parameter. x, y and eta remain fixed.",
                "inputs": {"w1": w1, "b1": b1, "w2": w2, "b2": b2, "deltaW1": deltaW1, "deltaB1": deltaB1, "deltaW2": deltaW2, "deltaB2": deltaB2},
                "outputs": {"nextW1": nextW1, "nextB1": nextB1, "nextW2": nextW2, "nextB2": nextB2},
            },
            {
                "id": "fresh-hidden", "label": "Fresh first layer", "equation": "nextZ1 = nextW1*x + nextB1",
                "explanation": "Start a new forward pass with the updated parameters and the same input.",
                "inputs": {"nextW1": nextW1, "x": x, "nextB1": nextB1}, "outputs": {"nextFirstProduct": nextFirstProduct, "nextZ1": nextZ1},
            },
            {
                "id": "fresh-relu", "label": "Fresh ReLU", "equation": "nextA1 = max(0, nextZ1)",
                "explanation": "Re-evaluate the branch; the update may have crossed the ReLU kink.",
                "inputs": {"nextZ1": nextZ1}, "outputs": {"nextA1": nextA1},
            },
            {
                "id": "fresh-output", "label": "Fresh prediction", "equation": "nextPrediction = nextW2*nextA1 + nextB2",
                "explanation": "Use both the new hidden activation and the new output parameters.",
                "inputs": {"nextW2": nextW2, "nextA1": nextA1, "nextB2": nextB2}, "outputs": {"nextSecondProduct": nextSecondProduct, "nextPrediction": nextPrediction},
            },
            {
                "id": "fresh-loss", "label": "Fresh loss", "equation": "nextError = nextPrediction-y; nextLoss = nextError*nextError/2",
                "explanation": "Measure the actual new error. A positive learning rate does not guarantee a smaller loss.",
                "inputs": {"nextPrediction": nextPrediction, "y": y}, "outputs": {"nextError": nextError, "nextErrorSquared": nextErrorSquared, "nextLoss": nextLoss},
            },
        ]
        # Convert NumPy scalars at the JSON boundary; never round computational values.
        original_state = {key: float(value) for key, value in values.items()}
        updated_state = dict(original_state, w1=float(nextW1), b1=float(nextB1),
                             w2=float(nextW2), b2=float(nextB2))
        displayed_state = original_state
        h = np.float64(2 ** -12)
        for parameter, analytic in {"w1": dW1, "b1": dB1, "w2": dW2, "b2": dB2}.items():
            minusTheta = finite(values[parameter] - h, "diagnostic theta-h")
            plusTheta = finite(values[parameter] + h, "diagnostic theta+h")
            minus = diagnostic_forward(dict(values, **{parameter: minusTheta}))
            plus = diagnostic_forward(dict(values, **{parameter: plusTheta}))
            smooth = (z1 != 0 and minus["z1"] != 0 and plus["z1"] != 0
                      and (minus["z1"] > 0) == (z1 > 0) and (plus["z1"] > 0) == (z1 > 0))
            diagnostic_outputs = {}
            if smooth:
                lossDifference = finite(plus["loss"] - minus["loss"], "diagnostic lossDifference")
                twoH = finite(np.float64(2) * h, "diagnostic twoH")
                centralDifference = finite(lossDifference / twoH, "diagnostic centralDifference")
                analyticDifference = finite(centralDifference - analytic, "diagnostic analyticDifference")
                absoluteResidual = finite(np.abs(analyticDifference), "diagnostic absoluteResidual")
                diagnostic_outputs = {
                    "minusPrediction": minus["prediction"], "plusPrediction": plus["prediction"],
                    "minusLoss": minus["loss"], "plusLoss": plus["loss"],
                    "lossDifference": lossDifference, "twoH": twoH, "centralDifference": centralDifference,
                    "analyticDifference": analyticDifference, "absoluteResidual": absoluteResidual,
                }
            steps.append({
                "id": f"diagnostic-{parameter}", "label": f"Optional numerical diagnostic: {parameter}",
                "equation": ("centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)"
                             if smooth else "No comparison: ReLU kink reached or crossed"),
                "explanation": ("Original pre-update parameters, with only this parameter perturbed by h=2^-12. Fresh loss evaluations give an approximate derivative and absolute analytic residual. No pass/fail or independent oracle authority is claimed."
                                if smooth else "Skipped: baseline or perturbed hidden preactivation is zero or changes sign. No derivative comparison is made across a ReLU kink. These are the original pre-update parameters."),
                "inputs": dict(original_state, z1=z1, h=h, analytic=analytic, minusTheta=minusTheta,
                               plusTheta=plusTheta, minusZ1=minus["z1"], plusZ1=plus["z1"]),
                "outputs": diagnostic_outputs,
            })
        tensors = [tensor(key, values[key], "Authored toy input or original parameter; eta is the step size.")
                   for key in DEFAULT_IV08]
        for step in steps:
            if step["id"] == "sgd-simultaneous":
                displayed_state = updated_state
            diagnostic = step["id"].startswith("diagnostic-")
            step["state"] = dict(original_state if diagnostic else displayed_state)
            for field in ("inputs", "outputs"):
                step[field] = {key: float(value) for key, value in step[field].items()}
            for key, value in step["outputs"].items():
                tensor_id = f'{step["id"]}.{key}' if diagnostic else key
                tensors.append(tensor(tensor_id, value, f'{step["id"]}: {step["equation"]}'))
        return {"status": "defined", "tensors": tensors, "steps": steps,
                "outputs": {key: float(value) for key, value in outputs.items()}}
    except NumericalFault as error:
        return {"status": "unavailable", "code": error.code, "reason": str(error)}
    except (OverflowError, FloatingPointError):
        return {"status": "unavailable", "code": "NONFINITE", "reason": "Nonfinite scalar arithmetic."}
    except (TypeError, AttributeError) as error:
        return {"status": "unavailable", "code": "UNAVAILABLE", "reason": str(error)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("state", nargs="?", help="Complete JSON state, '-' for stdin, or omit for the default.")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            result = derive_iv08(state)
    else:
        state = dict(DEFAULT_IV08)
        result = derive_iv08(state)
    # Keep the protected derivation and its first required-field fault unchanged.
    if result["status"] == "defined" and any(key not in DEFAULT_IV08 for key in state):
        result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": "Only the declared scalar fields are supported."}
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))


if __name__ == "__main__":
    main()

The validation helpers reject invalid inputs and nonfinite arithmetic instead of manufacturing a number. Tensor records include dimensions, axes, provenance and precision; trace states are detached copies. The CLI accepts a complete JSON state or the default example. This reference source is not an independent oracle. An independent exact-fraction derivation and gradient checks away from kinks provide separate comparisons.

Use the five questions in the lab after changing a parameter: explain a gradient’s meaning, compute the hidden weighted sum, multiply a backward chain factor, predict an update’s direction, and interpret the fresh loss. Feedback uses your current values. If a prediction fails, locate the first trace step where your arithmetic and the computation disagree.

Carry these ideas forward

  • A forward pass evaluates a model; learning additionally changes its parameters.
  • Backpropagation multiplies local derivatives by accumulated loss sensitivities.
  • One simultaneous SGD update uses gradients from one original state.
  • Fresh evaluation establishes what a finite update actually did, including overshoot.
  • ReLU’s zero convention is explicit; it does not create a unique mathematical derivative.

The next chapter, Backpropagation Through a Multi-Neuron Layer, gives the hidden layer several neurons. The same local rules remain, while shared paths require adding contributions and gradients acquire larger matrix shapes.