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.
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 for a target of . One update with learning rate changes the prediction to and reduces the half-squared loss from to . These are results for these particular settings, not a promise about every edit.
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. 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
Selected trace operation: First affine layer. The path below always shows the original calculation; the recomputed values are labeled separately.
- Input x
x = 2
- Hidden preactivation z1
Selected operation
w1=1, b1=0; (1) × (2) + (0) = 2
- Hidden activation a1
ReLU(z1=2) = 2
- Prediction
w2=-0.5, b2=0.25; (-0.5) × (2) + (0.25) = -0.75
- 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.
| Parameter | Original | Gradient | Updated |
|---|---|---|---|
| w1 | 1 | 1.75 | 0.78125 |
| b1 | 0 | 0.875 | -0.109375 |
| w2 | -0.5 | -3.5 | -0.0625 |
| b2 | 0.25 | -1.75 | 0.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 index | Value |
|---|---|
| 0 | 2 |
y
row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.
| Storage index | Value |
|---|---|
| 0 | 1 |
w1
row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.
| Storage index | Value |
|---|---|
| 0 | 1 |
b1
row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.
| Storage index | Value |
|---|---|
| 0 | 0 |
w2
row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.
| Storage index | Value |
|---|---|
| 0 | -0.5 |
b2
row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.
| Storage index | Value |
|---|---|
| 0 | 0.25 |
eta
row=1 × column=1 · float64 · display precision 8 · Authored toy input or original parameter; eta is the step size.
| Storage index | Value |
|---|---|
| 0 | 0.125 |
firstProduct
row=1 × column=1 · float64 · display precision 8 · forward-hidden: z1 = w1*x + b1
| Storage index | Value |
|---|---|
| 0 | 2 |
z1
row=1 × column=1 · float64 · display precision 8 · forward-hidden: z1 = w1*x + b1
| Storage index | Value |
|---|---|
| 0 | 2 |
a1
row=1 × column=1 · float64 · display precision 8 · forward-relu: a1 = max(0, z1)
| Storage index | Value |
|---|---|
| 0 | 2 |
secondProduct
row=1 × column=1 · float64 · display precision 8 · forward-output: prediction = w2*a1 + b2
| Storage index | Value |
|---|---|
| 0 | -1 |
prediction
row=1 × column=1 · float64 · display precision 8 · forward-output: prediction = w2*a1 + b2
| Storage index | Value |
|---|---|
| 0 | -0.75 |
error
row=1 × column=1 · float64 · display precision 8 · forward-loss: error = prediction-y; loss = error*error/2
| Storage index | Value |
|---|---|
| 0 | -1.75 |
errorSquared
row=1 × column=1 · float64 · display precision 8 · forward-loss: error = prediction-y; loss = error*error/2
| Storage index | Value |
|---|---|
| 0 | 3.0625 |
loss
row=1 × column=1 · float64 · display precision 8 · forward-loss: error = prediction-y; loss = error*error/2
| Storage index | Value |
|---|---|
| 0 | 1.53125 |
dLossDError
row=1 × column=1 · float64 · display precision 8 · backward-loss: dL/dError = (1/2)*2*error = error
| Storage index | Value |
|---|---|
| 0 | -1.75 |
dPrediction
row=1 × column=1 · float64 · display precision 8 · backward-prediction: dPrediction = dLossDError * dErrorDPrediction
| Storage index | Value |
|---|---|
| 0 | -1.75 |
dW2
row=1 × column=1 · float64 · display precision 8 · backward-w2: dW2 = dPrediction * a1
| Storage index | Value |
|---|---|
| 0 | -3.5 |
dB2
row=1 × column=1 · float64 · display precision 8 · backward-b2: dB2 = dPrediction * 1
| Storage index | Value |
|---|---|
| 0 | -1.75 |
dA1
row=1 × column=1 · float64 · display precision 8 · backward-a1: dA1 = dPrediction * w2
| Storage index | Value |
|---|---|
| 0 | 0.875 |
dZ1
row=1 × column=1 · float64 · display precision 8 · backward-z1: dZ1 = dA1 * (z1 > 0 ? 1 : 0)
| Storage index | Value |
|---|---|
| 0 | 0.875 |
dW1
row=1 × column=1 · float64 · display precision 8 · backward-w1: dW1 = dZ1 * x
| Storage index | Value |
|---|---|
| 0 | 1.75 |
dB1
row=1 × column=1 · float64 · display precision 8 · backward-b1: dB1 = dZ1 * 1
| Storage index | Value |
|---|---|
| 0 | 0.875 |
deltaW1
row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta
| Storage index | Value |
|---|---|
| 0 | 0.21875 |
deltaB1
row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta
| Storage index | Value |
|---|---|
| 0 | 0.109375 |
deltaW2
row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta
| Storage index | Value |
|---|---|
| 0 | -0.4375 |
deltaB2
row=1 × column=1 · float64 · display precision 8 · sgd-deltas: deltaTheta = eta * dTheta
| Storage index | Value |
|---|---|
| 0 | -0.21875 |
nextW1
row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta
| Storage index | Value |
|---|---|
| 0 | 0.78125 |
nextB1
row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta
| Storage index | Value |
|---|---|
| 0 | -0.109375 |
nextW2
row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta
| Storage index | Value |
|---|---|
| 0 | -0.0625 |
nextB2
row=1 × column=1 · float64 · display precision 8 · sgd-simultaneous: nextTheta = theta - deltaTheta
| Storage index | Value |
|---|---|
| 0 | 0.46875 |
nextFirstProduct
row=1 × column=1 · float64 · display precision 8 · fresh-hidden: nextZ1 = nextW1*x + nextB1
| Storage index | Value |
|---|---|
| 0 | 1.5625 |
nextZ1
row=1 × column=1 · float64 · display precision 8 · fresh-hidden: nextZ1 = nextW1*x + nextB1
| Storage index | Value |
|---|---|
| 0 | 1.453125 |
nextA1
row=1 × column=1 · float64 · display precision 8 · fresh-relu: nextA1 = max(0, nextZ1)
| Storage index | Value |
|---|---|
| 0 | 1.453125 |
nextSecondProduct
row=1 × column=1 · float64 · display precision 8 · fresh-output: nextPrediction = nextW2*nextA1 + nextB2
| Storage index | Value |
|---|---|
| 0 | -0.0908203125 |
nextPrediction
row=1 × column=1 · float64 · display precision 8 · fresh-output: nextPrediction = nextW2*nextA1 + nextB2
| Storage index | Value |
|---|---|
| 0 | 0.3779296875 |
nextError
row=1 × column=1 · float64 · display precision 8 · fresh-loss: nextError = nextPrediction-y; nextLoss = nextError*nextError/2
| Storage index | Value |
|---|---|
| 0 | -0.6220703125 |
nextErrorSquared
row=1 × column=1 · float64 · display precision 8 · fresh-loss: nextError = nextPrediction-y; nextLoss = nextError*nextError/2
| Storage index | Value |
|---|---|
| 0 | 0.38697147369384766 |
nextLoss
row=1 × column=1 · float64 · display precision 8 · fresh-loss: nextError = nextPrediction-y; nextLoss = nextError*nextError/2
| Storage index | Value |
|---|---|
| 0 | 0.19348573684692383 |
diagnostic-w1.minusPrediction
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 1.5308227837085724 |
diagnostic-w1.plusLoss
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 1.5316772758960724 |
diagnostic-w1.lossDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0.0008544921875 |
diagnostic-w1.twoH
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0.00048828125 |
diagnostic-w1.centralDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 1.75 |
diagnostic-w1.analyticDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0 |
diagnostic-w1.absoluteResidual
row=1 × column=1 · float64 · display precision 8 · diagnostic-w1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0 |
diagnostic-b1.minusPrediction
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 1.5310363844037056 |
diagnostic-b1.plusLoss
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 1.5314636304974556 |
diagnostic-b1.lossDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0.00042724609375 |
diagnostic-b1.twoH
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0.00048828125 |
diagnostic-b1.centralDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0.875 |
diagnostic-b1.analyticDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0 |
diagnostic-b1.absoluteResidual
row=1 × column=1 · float64 · display precision 8 · diagnostic-b1: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0 |
diagnostic-w2.minusPrediction
row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 1.5321046113967896 |
diagnostic-w2.plusLoss
row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 1.5303956270217896 |
diagnostic-w2.lossDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 0.00048828125 |
diagnostic-w2.centralDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 0 |
diagnostic-w2.absoluteResidual
row=1 × column=1 · float64 · display precision 8 · diagnostic-w2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0 |
diagnostic-b2.minusPrediction
row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 1.5316772758960724 |
diagnostic-b2.plusLoss
row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 1.5308227837085724 |
diagnostic-b2.lossDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 0.00048828125 |
diagnostic-b2.centralDifference
row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 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 index | Value |
|---|---|
| 0 | 0 |
diagnostic-b2.absoluteResidual
row=1 × column=1 · float64 · display precision 8 · diagnostic-b2: centralDifference = (plusLoss-minusLoss)/(2*h); absoluteResidual = abs(centralDifference-analytic)
| Storage index | Value |
|---|---|
| 0 | 0 |
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.
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 . The input , target and learning rate stay fixed during this training step.
| Symbol / code name | Meaning | Default |
|---|---|---|
/ x | Observed input | |
/ y | Desired output, or target | |
/ w1,b1 | First layer’s weight and bias | |
/ z1 | First weighted sum, before activation | |
/ a1 | Hidden value after activation | |
/ w2,b2 | Output layer’s weight and bias | |
/ prediction | Computed output | |
/ error | Prediction minus target | |
/ loss | Half-squared error | |
/ eta | Learning rate, or step size |
A tensor is a collection of numbers with a declared shape. Each quantity here contains one number, stored as a 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 times gives , 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
An activation transforms that weighted sum. ReLU, short for rectified linear unit, keeps positive values and replaces negative ones by zero:
The second layer has a linear output, with no second ReLU. A negative prediction is therefore allowed:
The signed error says which side of the target we reached. The loss turns its magnitude into a nonnegative objective:
The factor 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 asks how loss changes when only changes. The four parameter derivatives together form the gradient. They are local sensitivities, not new parameter values.
The problem is that does not appear directly in the final loss formula. It affects , which affects , 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 . Differentiating the half-square and then the subtraction gives
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 . Holding the other inputs fixed, its local derivatives with respect to , and are , and . Multiply each by the same incoming sensitivity dPrediction:
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 in dA1.
At , ReLU is on its positive branch, where . Its local derivative is therefore one:
Finally, the local derivatives of with respect to and are and one:
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 for any one parameter and a prime for its updated value:
At , every subtraction is explicit:
| Parameter | Original minus learning rate times gradient | Updated |
|---|---|---|
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 , 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:
The final loss is approximately , compared with 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 . The same original gradients now produce
Then , so ReLU returns zero. The prediction becomes and loss is , greater than . This is an actual overshoot, not an error that the interface should hide. At , 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 . Now , , and the local ReLU derivative is zero. Both first-layer gradients vanish. The output weight gradient also vanishes because it multiplies , but the output bias gradient is . Its update can still change the prediction.
Third, at exactly , 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 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 , fresh forward passes evaluate losses with only that parameter replaced by and , where the fixed dyadic spacing is . The trace shows those operands, nearby predictions and losses, then computes
Here 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 , 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.