The neural notebook
← All chapters

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

Backpropagation Through a Multi-Neuron Layer

Differentiate one real loss through two hidden neurons, inspect the outer-product weight gradient, and accumulate input paths with an explicit transpose.

Review the ideas this chapter uses

A hidden layer can calculate several useful quantities from the same input. Each neuron has its own weights, yet all its outputs may contribute to one prediction and one loss. How should that single loss send feedback to all those weights? And when two neurons both use the same input, how do their effects combine?

We will answer with two input coordinates and two hidden neurons. The numbers are hand-set teaching inputs, not trained measurements. Edit a weight or bias below: the prediction, actual loss, local slopes and full gradients all recompute from the same calculation. There is no parameter update in this chapter.

Compute it yourself

One shared loss, two hidden neurons

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
x0
2
x1
-1
w00
1
w01
0.5
w10
-0.5
w11
1
b0
0.25
b1
2.5
v0
0.5
v1
-1
c
0.25
y
1
loss0.0703125
prediction0.625
dX0-0.375
dX10.28125

loss 0.0703125. prediction 0.625. dX0 -0.375. dX1 0.28125. Hidden neuron 0: dot then bias. W rows enumerate hidden neurons; columns enumerate input coordinates. Bias is added after the two products.. z0Product0 2. z0Product1 -0.5. z0Dot 1.5. z0 1.75

Hidden neuron 0: dot then bias

z_h=W[h,0]*x0+W[h,1]*x1+b_h

W rows enumerate hidden neurons; columns enumerate input coordinates. Bias is added after the two products.

Inputs

w0
1
x0
2
w1
0.5
x1
-1
bias
0.25

Outputs

z0Product0
2
z0Product1
-0.5
z0Dot
1.5
z0
1.75

Forward path

x → W dot products + b → z=[1.75, 0.5] → ReLU → a=[1.75, 0.5] → v dot product + c → prediction=0.625 → half-square loss=0.0703125

Reverse path

error=-0.375 → readout transpose → dA=[-0.1875, 0.375] → slopes=[1, 1] → dZ=[-0.1875, 0.375] → outer-product dW and accumulated dX

Hidden-layer shapes and completed gradients

These tables summarize the completed calculation from the starting inputs. The selected operation above shows its own stored operands and results. Table selectors use a tensor_ prefix, separate from the four primary summary outputs.

W

hidden=2 × input=2. Column-map weights: z=W*x+b.

W: named coordinates, stored binary64 values
hiddeninput 0input 1
010.5
1-0.51

WTranspose

input=2 × hidden=2. Explicit transpose of W, used for dX.

WTranspose: named coordinates, stored binary64 values
inputhidden 0hidden 1
01-0.5
10.51

dV

readout=1 × hidden=2. error*a transpose; same shape as v.

dV: named coordinates, stored binary64 values
readouthidden 0hidden 1
0-0.65625-0.1875

dZ

hidden=2 × column=1. dA elementwise selected slopes.

dZ: named coordinates, stored binary64 values
hiddencolumn 0
0-0.1875
10.375

dW

hidden=2 × input=2. Outer product dZ*x transpose; same axes as W.

dW: named coordinates, stored binary64 values
hiddeninput 0input 1
0-0.3750.1875
10.75-0.375

dXContributions

input=2 × hidden=2. Each input row sums its two hidden-neuron contributions.

dXContributions: named coordinates, stored binary64 values
inputhidden 0hidden 1
0-0.1875-0.1875
1-0.093750.375

dX

input=2 × column=1. W transpose times dZ, accumulating hidden axis.

dX: named coordinates, stored binary64 values
inputcolumn 0
0-0.375
10.28125

outputJacobian

prediction=1 × input=2. v*diag(slopes)*W; selected convention at a kink.

outputJacobian: named coordinates, stored binary64 values
predictioninput 0input 1
01-0.75
Inspect tensor shapes and full precision

All computed outputs

loss
0.0703125
prediction
0.625
dX0
-0.375
dX1
0.28125
x0
2
x1
-1
w00
1
w01
0.5
w10
-0.5
w11
1
b0
0.25
b1
2.5
v0
0.5
v1
-1
c
0.25
y
1
z0Product0
2
z0Product1
-0.5
z0Dot
1.5
z0
1.75
a0
1.75
slope0
1
z1Product0
-1
z1Product1
-1
z1Dot
-2
z1
0.5
a1
0.5
slope1
1
predictionProduct0
0.875
predictionProduct1
-0.5
predictionDot
0.375
error
-0.375
errorSquare
0.140625
dC
-0.375
dV0
-0.65625
dA0
-0.1875
dZ0
-0.1875
dB0
-0.1875
dW00
-0.375
dW01
0.1875
dV1
-0.1875
dA1
0.375
dZ1
0.375
dB1
0.375
dW10
0.75
dW11
-0.375
dX0From0
-0.1875
dX0From1
-0.1875
jacobian0From0
0.5
jacobian0From1
0.5
jacobian0
1
dX0ViaJacobian
-0.375
dX1From0
-0.09375
dX1From1
0.375
jacobian1From0
0.25
jacobian1From1
-1
jacobian1
-0.75
dX1ViaJacobian
0.28125

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

x

input=2 × column=1 · float64 · display precision 8 · Authored input column.

Storage indexValue
02
1-1

W

hidden=2 × input=2 · float64 · display precision 8 · Column-map weights: z=W*x+b.

Storage indexValue
01
10.5
2-0.5
31

WTranspose

input=2 × hidden=2 · float64 · display precision 8 · Explicit transpose of W, used for dX.

Storage indexValue
01
1-0.5
20.5
31

b

hidden=2 × column=1 · float64 · display precision 8 · One bias for each hidden neuron; no batch broadcast.

Storage indexValue
00.25
12.5

z

hidden=2 × column=1 · float64 · display precision 8 · Two dot products followed by bias addition.

Storage indexValue
01.75
10.5

a

hidden=2 × column=1 · float64 · display precision 8 · Elementwise ReLU(z).

Storage indexValue
01.75
10.5

slopes

hidden=2 × column=1 · float64 · display precision 8 · Selected ReLU slopes: 1 for positive z, otherwise 0; undefined derivative at zero.

Storage indexValue
01
11

v

readout=1 × hidden=2 · float64 · display precision 8 · Readout row: prediction=v*a+c.

Storage indexValue
00.5
1-1

dV

readout=1 × hidden=2 · float64 · display precision 8 · error*a transpose; same shape as v.

Storage indexValue
0-0.65625
1-0.1875

dA

hidden=2 × column=1 · float64 · display precision 8 · v transpose times error.

Storage indexValue
0-0.1875
10.375

dZ

hidden=2 × column=1 · float64 · display precision 8 · dA elementwise selected slopes.

Storage indexValue
0-0.1875
10.375

dW

hidden=2 × input=2 · float64 · display precision 8 · Outer product dZ*x transpose; same axes as W.

Storage indexValue
0-0.375
10.1875
20.75
3-0.375

dB

hidden=2 × column=1 · float64 · display precision 8 · Bias derivative equals dZ.

Storage indexValue
0-0.1875
10.375

dXContributions

input=2 × hidden=2 · float64 · display precision 8 · Each input row sums its two hidden-neuron contributions.

Storage indexValue
0-0.1875
1-0.1875
2-0.09375
30.375

dX

input=2 × column=1 · float64 · display precision 8 · W transpose times dZ, accumulating hidden axis.

Storage indexValue
0-0.375
10.28125

outputJacobian

prediction=1 × input=2 · float64 · display precision 8 · v*diag(slopes)*W; selected convention at a kink.

Storage indexValue
01
1-0.75

lossSeed

seed_row=1 × prediction=1 · float64 · display precision 8 · Half-square prediction adjoint; no feature divisor.

Storage indexValue
0-0.375

Try b1=0.5 after reset to silence neuron 1. Then try b1=2 for its exact-zero preactivation. All twelve scalar fields are editable; dimensions stay fixed at two inputs and two hidden neurons. No optimizer changes the parameters.

Check your understanding

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

1. What does dW[hidden,input] describe?
2. Currently dZ0=-0.1875, x1=-1. What is dW01?
3. Input 1 receives -0.09375 from neuron 0 and 0.375 from neuron 1. What is dX1?
4. Reset, then change only b1 to 0.5. Which result follows?
5. If a hidden preactivation is exactly zero, what does the recorded slope 0 mean?

Start with forward_hidden_0, then seek reverse_hidden_0, outer_01 and input_1. The operation panel explains the selected step; the tables summarize the completed calculation. Reset example restores every input. For a review of the scalar reverse pass, use IV-08 — One Training Step: Hand-Derived Backpropagation; matrix shapes are introduced in II.10 — Matrix × matrix as composition.

What the layer stores

A neuron here means a weighted sum, a bias addition and an activation function. A layer collects two such neurons using the same input. Its parameters are adjustable weights and biases. An activation is the value after applying the activation function. Our activation is ReLU, which keeps positive values and replaces negative values with zero.

We use mathematical columns. The input is x=[2,−1]Tx=[2,-1]^T: two coordinates of one sample, rather than two samples. A superscript TT means transpose, which exchanges rows and columns. The hidden weights and biases are

W=[11/2−1/21],b=[1/45/2].W=\begin{bmatrix}1&1/2\\-1/2&1\end{bmatrix},\qquad b=\begin{bmatrix}1/4\\5/2\end{bmatrix}.

Row zero of WW belongs to hidden neuron zero; row one belongs to neuron one. Its columns identify input coordinates. Indexing begins at zero, so w01 means neuron zero’s weight on input one. The readout row v=[1/2,−1]v=[1/2,-1] combines both hidden activations into a scalar prediction, with readout bias c=1/4c=1/4. The desired scalar target is y=1y=1.

QuantityShapeWhat the axes count
xx[2,1]input coordinate, column
WW[2,2]hidden neuron, input coordinate
b,z,ab,z,a[2,1]hidden neuron, column
vv[1,2]readout, hidden neuron
prediction, c,y,Lc,y,Lscalarone number each
dWdW[2,2]hidden neuron, input coordinate
dXdX[2,1]input coordinate, column

These dimensions are fixed. All twelve scalar controls accept finite values from −20-20 through 2020. A missing, malformed or out-of-range input is unavailable; the program does not silently insert defaults, reshape an input or clamp a value.

First compute the real prediction and loss

A preactivation, zz, is the weighted sum including bias, before ReLU. The forward calculation is

z=Wx+b,a=ReLU⁡(z),p=va+c,e=p−y,L=e2/2.z=Wx+b,\qquad a=\operatorname{ReLU}(z),\qquad p=va+c,\qquad e=p-y,\qquad L=e^2/2.

Here pp is named prediction in code, ee is error, and LL is loss. The half-square loss measures error magnitude without its sign. Its derivative with respect to prediction will preserve the signed error.

Expand the hidden rows in the order used by the program:

z0=(1)(2)+(1/2)(−1)+1/4=2−1/2+1/4=7/4,z_0=(1)(2)+(1/2)(-1)+1/4=2-1/2+1/4=7/4, z1=(−1/2)(2)+(1)(−1)+5/2=−1−1+5/2=1/2.z_1=(-1/2)(2)+(1)(-1)+5/2=-1-1+5/2=1/2.

Both are positive, so a0=7/4a_0=7/4 and a1=1/2a_1=1/2. The readout gives

p=(1/2)(7/4)+(−1)(1/2)+1/4=7/8−1/2+1/4=5/8.p=(1/2)(7/4)+(-1)(1/2)+1/4 =7/8-1/2+1/4=5/8.

Therefore e=5/8−1=−3/8e=5/8-1=-3/8, and

L=12(−38)2=9128.L=\frac12\left(-\frac38\right)^2=\frac9{128}.

This is one scalar target. The two hidden neurons do not introduce a divisor of two into the objective. They are intermediate calculations, not two independently averaged examples.

A backward number measures sensitivity

Write dAhdA_h for the loss derivative with respect to activation aha_h; similarly, dW01 means ∂L/∂W0,1\partial L/\partial W_{0,1}. These code names denote derivatives, not tiny changes already made to the parameters. A gradient collects derivatives for all coordinates of a variable. It describes the local rate of loss change near the current inputs.

The chain rule multiplies sensitivities along a dependency path. Since L=e2/2L=e^2/2 and e=p−ye=p-y, the upstream prediction derivative is

∂L∂p=e=−3/8.\frac{\partial L}{\partial p}=e=-3/8.

This same number reaches every readout operand through its own local factor. For vhv_h, that factor is aha_h; for aha_h, it is vhv_h; for bias cc, it is one:

dV=e aT=[−21/32−3/16],dC=e=−3/8,dV=e\,a^T=\begin{bmatrix}-21/32&-3/16\end{bmatrix},\qquad dC=e=-3/8, dA=vTe=[−3/163/8].dA=v^T e=\begin{bmatrix}-3/16\\3/8\end{bmatrix}.

For example, dV0=(−3/8)(7/4)=−21/32dV_0=(-3/8)(7/4)=-21/32. The second hidden activation receives a positive sensitivity because its negative readout weight multiplies the negative error: dA1=(−1)(−3/8)=3/8dA_1=(-1)(-3/8)=3/8. A shared loss does not mean all its parameter derivatives have the same sign.

Pass through the local ReLU slopes

Away from zero, ReLU’s slope is one for positive preactivation and zero for negative preactivation. Define shs_h as this selected slope. Multiplication is coordinate by coordinate:

dZh=dAhsh.dZ_h=dA_h s_h.

Both default slopes are one, so dZ=[−3/16,3/8]TdZ=[-3/16,3/8]^T. Hidden bias enters its preactivation with local factor one, giving dB=dZdB=dZ.

At exactly zh=0z_h=0, ReLU has no unique derivative: approaching from the left gives slope zero and approaching from the right gives slope one. This program chooses backward value zero there. The choice is explicit and reproducible, but it does not establish differentiability. Later numerical gradient checks must exclude both a kink and a perturbation interval crossing one.

Why the weight gradient is an outer product

For a single weight Wh,dW_{h,d}, only preactivation zhz_h directly contains that weight, multiplied by input xdx_d. Thus

∂L∂Wh,d=dZhxd.\frac{\partial L}{\partial W_{h,d}}=dZ_h x_d.

An outer product forms all pairwise products between a column and a row. Multiplying dZ:[2,1]dZ:[2,1] by xT:[1,2]x^T:[1,2] fills four cells without summing either of the two meaningful axes:

dW=dZ xT=[−3/163/8][2−1]=[−3/83/163/4−3/8].dW=dZ\,x^T =\begin{bmatrix}-3/16\\3/8\end{bmatrix} \begin{bmatrix}2&-1\end{bmatrix} =\begin{bmatrix}-3/8&3/16\\3/4&-3/8\end{bmatrix}.

The first row is (−3/16)[2,−1](-3/16)[2,-1]. The second is (3/8)[2,−1](3/8)[2,-1]. Each row preserves which hidden neuron received that sensitivity; each column preserves which input multiplied the weight. Consequently dWdW has the same hidden-by-input axes as WW. Replacing it with its transpose would assign derivatives to different parameters, even though both arrays happen to be square.

The repeated value −3/8-3/8 in two cells is incidental. The off-diagonal derivatives 3/163/16 and 3/43/4 differ, so exchanging them is a detectable error. Always follow axes rather than guessing from a matrix’s visible size.

Inputs collect contributions from both neurons

An input coordinate is used in both hidden rows. Its loss derivative must therefore add both paths:

dXd=W0,ddZ0+W1,ddZ1.dX_d=W_{0,d}dZ_0+W_{1,d}dZ_1.

The explicit arithmetic is

dX0=(1)(−3/16)+(−1/2)(3/8)=−3/16−3/16=−3/8,dX_0=(1)(-3/16)+(-1/2)(3/8) =-3/16-3/16=-3/8, dX1=(1/2)(−3/16)+(1)(3/8)=−3/32+12/32=9/32.dX_1=(1/2)(-3/16)+(1)(3/8) =-3/32+12/32=9/32.

In matrix notation, dX=WTdZdX=W^T dZ. The actual transpose is

WT=[1−1/21/21].W^T=\begin{bmatrix}1&-1/2\\1/2&1\end{bmatrix}.

Its rows now enumerate inputs and its columns enumerate hidden neurons. The inspector keeps W and WTranspose as distinct records. The dXContributions table places inputs in rows and neuron paths in columns, so each row’s sum is visible. Taking only the last neuron contribution would repeat the accumulation mistake from the earlier shared-node graph.

Input derivatives are useful when this layer is connected to an earlier layer. In an isolated supervised example, computing dXdX does not imply we should change observed input data. An optimizer’s choice of parameters to update is a separate matter.

Check the forward sensitivity before applying the loss seed

A Jacobian lists output derivatives with respect to input coordinates. Our prediction has one output, so its Jacobian is a row, shape [1,2]. Away from a ReLU kink,

Jp=vdiag⁡(s)W.J_p=v\operatorname{diag}(s)W.

The diagonal matrix places s0,s1s_0,s_1 on its diagonal and zero elsewhere. At defaults both slopes are one:

(Jp)0=(1/2)(1)+(−1)(−1/2)=1,(J_p)_0=(1/2)(1)+(-1)(-1/2)=1, (Jp)1=(1/2)(1/2)+(−1)(1)=−3/4.(J_p)_1=(1/2)(1/2)+(-1)(1)=-3/4.

Multiplying this row by prediction’s loss seed e=−3/8e=-3/8 gives [−3/8,9/32][-3/8,9/32], the transpose of our input gradient column. This separates a property of the forward prediction from the loss attached to it. Changing only target yy leaves JpJ_p unchanged while changing the loss seed and generally dXdX.

The lab calculates both routes from unrounded operands. For arbitrary decimal controls, rearranged binary64 products can differ in their last bits; an algebraic identity is not a promise of bitwise equality for every evaluation order. At a kink, outputJacobian explicitly records the chosen backward convention rather than asserting that a classical Jacobian exists.

Silence one neuron without silencing the network

Reset and change only b1b_1 from 5/25/2 to 1/21/2. Now z1=−1−1+1/2=−3/2z_1=-1-1+1/2=-3/2, so a1=0a_1=0 and s1=0s_1=0. Neuron zero is unchanged. Recompute the readout:

p=7/8+0+1/4=9/8,e=1/8,L=1/128.p=7/8+0+1/4=9/8,\quad e=1/8,\quad L=1/128.

The new derivatives are

dV=[7/32,0],dC=1/8,dA=[1/16,−1/8]T,dZ=[1/16,0]T,dV=[7/32,0],\quad dC=1/8,\quad dA=[1/16,-1/8]^T,\quad dZ=[1/16,0]^T, dW=[1/8−1/1600],dX=[1/161/32].dW=\begin{bmatrix}1/8&-1/16\\0&0\end{bmatrix},\qquad dX=\begin{bmatrix}1/16\\1/32\end{bmatrix}.

Notice the distinction between dA1=−1/8dA_1=-1/8 and dZ1=0dZ_1=0: the readout is sensitive to a hypothetical activation change, but the locally inactive ReLU blocks changes arriving through its preactivation. A zero gradient for one parameter does not prove zero error, nor does it make every other derivative zero. Setting b1=2b_1=2 instead reaches the exact kink, where the declared selected-zero rule applies.

Read the actual NumPy program

The reference below stores true columns and matrices, names every dot product, and fills the outer product explicitly. W.T.copy() performs the input-by-hidden transpose. The loops are small enough to compare directly with the trace; they do not call an automatic differentiation framework. The helper validates input and packages the same numerical record for JSON output.

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.

"""IV09: two hidden ReLU neurons, one loss, explicit outer-product backward pass."""
import numpy as np
from layer_reference import finite, fixed_state, guarded, LayerTrace, tensor, run

DEFAULT_IV09 = {"x0": 2, "x1": -1, "w00": 1, "w01": 0.5, "w10": -0.5, "w11": 1,
                "b0": 0.25, "b1": 2.5, "v0": 0.5, "v1": -1, "c": 0.25, "y": 1}


@guarded
def derive_iv09(state):
    """Use mathematical columns; preserve W[hidden,input] throughout backward."""
    s = fixed_state(state, DEFAULT_IV09)
    trace = LayerTrace(s)
    o, add = trace.outputs, trace.add
    x = np.array([[s["x0"]], [s["x1"]]], dtype=np.float64)
    W = np.array([[s["w00"], s["w01"]], [s["w10"], s["w11"]]], dtype=np.float64)
    b = np.array([[s["b0"]], [s["b1"]]], dtype=np.float64)
    v = np.array([[s["v0"], s["v1"]]], dtype=np.float64)
    z, a, slopes = np.zeros((2, 1)), np.zeros((2, 1)), np.zeros((2, 1))
    for h in range(2):
        # Two explicit dot products, then bias; no change of vector orientation.
        p0 = finite(W[h, 0] * x[0, 0], "hidden product0")
        p1 = finite(W[h, 1] * x[1, 0], "hidden product1")
        dot = finite(p0 + p1, "hidden dot")
        z[h, 0] = finite(dot + b[h, 0], "hidden bias addition")
        add(f"forward_hidden_{h}", "z_h=W[h,0]*x0+W[h,1]*x1+b_h",
            {"w0": W[h, 0], "x0": x[0, 0], "w1": W[h, 1], "x1": x[1, 0], "bias": b[h, 0]},
            {f"z{h}Product0": p0, f"z{h}Product1": p1, f"z{h}Dot": dot, f"z{h}": z[h, 0]})
        a[h, 0] = np.maximum(np.float64(0), z[h, 0])
        # At zero this is a selected backward rule, not a mathematical derivative.
        slopes[h, 0] = 1 if z[h, 0] > 0 else 0
        add(f"relu_{h}", "a_h=max(0,z_h); slope_h=1 if z_h>0 else 0", {"z": z[h, 0]},
            {f"a{h}": a[h, 0], f"slope{h}": slopes[h, 0]})
    p0 = finite(v[0, 0] * a[0, 0], "output product0")
    p1 = finite(v[0, 1] * a[1, 0], "output product1")
    dot = finite(p0 + p1, "output dot")
    add("forward_prediction", "prediction=v*a+c",
        {"v0": s["v0"], "a0": o["a0"], "v1": s["v1"], "a1": o["a1"], "c": s["c"]},
        {"predictionProduct0": p0, "predictionProduct1": p1, "predictionDot": dot,
         "prediction": finite(dot + s["c"], "prediction")})
    error = finite(o["prediction"] - s["y"], "error")
    square = finite(error * error, "errorSquare")
    add("forward_loss", "error=prediction-y; loss=error*error/2", {"prediction": o["prediction"], "y": s["y"]},
        {"error": error, "errorSquare": square, "loss": finite(square / 2, "loss"), "dC": error})
    dV, dA, dZ, dW = np.zeros((1, 2)), np.zeros((2, 1)), np.zeros((2, 1)), np.zeros((2, 2))
    for h in range(2):
        dV[0, h] = finite(error * a[h, 0], "dV")
        dA[h, 0] = finite(error * v[0, h], "dA")
        dZ[h, 0] = finite(dA[h, 0] * slopes[h, 0], "dZ")
        add(f"reverse_hidden_{h}", "dV_h=error*a_h; dA_h=v_h*error; dZ_h=dA_h*slope_h; dB_h=dZ_h",
            {"error": error, "a": a[h, 0], "v": v[0, h], "slope": slopes[h, 0]},
            {f"dV{h}": dV[0, h], f"dA{h}": dA[h, 0], f"dZ{h}": dZ[h, 0], f"dB{h}": dZ[h, 0]})
        for d in range(2):
            # This is the outer product dZ*x.T, with no axis summed out.
            dW[h, d] = finite(dZ[h, 0] * x[d, 0], "dW")
            add(f"outer_{h}{d}", "dW[h,d]=dZ[h]*x[d]", {"dZ": dZ[h, 0], "x": x[d, 0]}, {f"dW{h}{d}": dW[h, d]})
    WT = W.T.copy()  # A real transpose, with input-by-hidden axes.
    dX, J = np.zeros((2, 1)), np.zeros((1, 2))
    contributions = np.zeros((2, 2))
    for d in range(2):
        from0 = finite(WT[d, 0] * dZ[0, 0], "input contribution0")
        from1 = finite(WT[d, 1] * dZ[1, 0], "input contribution1")
        contributions[d] = [from0, from1]
        dX[d, 0] = finite(from0 + from1, "dX")
        add(f"input_{d}", "dX[d]=W[0,d]*dZ0+W[1,d]*dZ1",
            {"w0": W[0, d], "dZ0": dZ[0, 0], "w1": W[1, d], "dZ1": dZ[1, 0]},
            {f"dX{d}From0": from0, f"dX{d}From1": from1, f"dX{d}": dX[d, 0]})
        j0 = finite(finite(v[0, 0] * slopes[0, 0], "v0 slope0") * W[0, d], "Jacobian contribution0")
        j1 = finite(finite(v[0, 1] * slopes[1, 0], "v1 slope1") * W[1, d], "Jacobian contribution1")
        J[0, d] = finite(j0 + j1, "outputJacobian")
        add(f"jacobian_{d}", "J[0,d]=v0*slope0*W[0,d]+v1*slope1*W[1,d]",
            {"v0": s["v0"], "slope0": o["slope0"], "w0": W[0, d], "v1": s["v1"], "slope1": o["slope1"], "w1": W[1, d], "error": error},
            {f"jacobian{d}From0": j0, f"jacobian{d}From1": j1, f"jacobian{d}": J[0, d],
             f"dX{d}ViaJacobian": finite(error * J[0, d], "seeded Jacobian")})
    def col(identifier, values, axis, provenance):
        return tensor(identifier, [2, 1], [axis, "column"], values, provenance)
    tensors = [col("x", x, "input", "Authored input column."),
               tensor("W", [2, 2], ["hidden", "input"], W, "Column-map weights: z=W*x+b."),
               tensor("WTranspose", [2, 2], ["input", "hidden"], WT, "Explicit transpose of W, used for dX."),
               col("b", b, "hidden", "One bias for each hidden neuron; no batch broadcast."),
               col("z", z, "hidden", "Two dot products followed by bias addition."),
               col("a", a, "hidden", "Elementwise ReLU(z)."),
               col("slopes", slopes, "hidden", "Selected ReLU slopes: 1 for positive z, otherwise 0; undefined derivative at zero."),
               tensor("v", [1, 2], ["readout", "hidden"], v, "Readout row: prediction=v*a+c."),
               tensor("dV", [1, 2], ["readout", "hidden"], dV, "error*a transpose; same shape as v."),
               col("dA", dA, "hidden", "v transpose times error."),
               col("dZ", dZ, "hidden", "dA elementwise selected slopes."),
               tensor("dW", [2, 2], ["hidden", "input"], dW, "Outer product dZ*x transpose; same axes as W."),
               col("dB", dZ, "hidden", "Bias derivative equals dZ."),
               tensor("dXContributions", [2, 2], ["input", "hidden"], contributions, "Each input row sums its two hidden-neuron contributions."),
               col("dX", dX, "input", "W transpose times dZ, accumulating hidden axis."),
               tensor("outputJacobian", [1, 2], ["prediction", "input"], J, "v*diag(slopes)*W; selected convention at a kink."),
               tensor("lossSeed", [1, 1], ["seed_row", "prediction"], [error], "Half-square prediction adjoint; no feature divisor.")]
    return trace.result({"loss": o["loss"], "prediction": o["prediction"], "dX0": o["dX0"], "dX1": o["dX1"]}, tensors)


if __name__ == "__main__":
    run(derive_iv09, DEFAULT_IV09)
Read the complete executable Python / NumPy source

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

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

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


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


_JSON_INT = int


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


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


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


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


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


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


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


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


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

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

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


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


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

Keep both files together. No CLI argument selects defaults; a complete JSON object replaces the entire state, and - reads a complete object from standard input.

Carry these rules forward

The weight gradient is an outer product with the same axes as its parameter. The input gradient accumulates all hidden-neuron paths using a genuine transpose. Local activation slopes determine which paths transmit sensitivity, while the scalar loss supplies one upstream seed. Gradients describe local sensitivity; this example performs no learning step.

Next we will replace the scalar readout with a two-output affine map. That lets us distinguish a forward input direction from a reverse output seed, then see how shared parameter gradients add across samples.