The neural notebook
← All chapters

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

Jacobians, VJPs and Batch Gradients

Distinguish a forward JVP from a reverse VJP, materialize per-sample affine gradients, and apply sum or sample-mean reduction exactly once.

Review the ideas this chapter uses

A model can return several numbers for each sample. We might ask how those outputs change when we move the input, or how a particular combination of outputs responds to the input. Those are related questions, but they multiply the derivative matrix on different sides.

Training adds another question: when two samples use the same parameters, how do their loss derivatives combine? We will use one small affine map to separate these ideas. There is no ReLU here, so activation kinks cannot obscure orientation or averaging. Every number below comes from editable, hand-set teaching data.

Compute it yourself

Separate forward directions, reverse seeds, and sample means

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
x00
1
x01
2
x10
-1
x11
1
w00
1
w01
2
w10
-1
w11
0.5
b0
0.5
b1
-0.25
y00
0
y01
1
y10
1
y11
-1
reduction
1
g0
1
g1
2
v0
0.5
v1
-1
loss9.28125
reductionFactor0.5
vjp0-1
jvp0-1.5

loss 9.28125. reductionFactor 0.5. vjp0 -1. jvp0 -1.5. Convert column-map weights to row-batch weights. W and its transpose have equal dimensions here but different axes and different off-diagonal entries.. wRow00 1. wRow01 -1. wRow10 2. wRow11 0.5

Convert column-map weights to row-batch weights

W_row[d,o]=W[o,d]

W and its transpose have equal dimensions here but different axes and different off-diagonal entries.

Inputs

w00
1
w01
2
w10
-1
w11
0.5

Outputs

wRow00
1
wRow01
-1
wRow10
2
wRow11
0.5

Completed general VJP gJ=[-1, 3], shape [1,2] with input columns. Completed general JVP Jv=[-1.5, -1]ᵀ, shape [2,1] with output rows. These independent demos do not seed the batch loss. Its raw seeds are E, and its reduction factor is 0.5.

Batch predictions, raw sample gradients, and reduced 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

output=2 × input=2. Mathematical column-map weights.

W: named coordinates, stored binary64 values
outputinput 0input 1
012
1-10.5

WRow

input=2 × output=2. Explicit W transpose for row-batch prediction.

WRow: named coordinates, stored binary64 values
inputoutput 0output 1
01-1
120.5

broadcastBias

sample=2 × output=2. Explicit replication of bias across samples.

broadcastBias: named coordinates, stored binary64 values
sampleoutput 0output 1
00.5-0.25
10.5-0.25

P

sample=2 × output=2. X*WRow+broadcastBias.

P: named coordinates, stored binary64 values
sampleoutput 0output 1
05.5-0.25
11.51.25

E

sample=2 × output=2. P-Y; raw loss seeds before sample reduction.

E: named coordinates, stored binary64 values
sampleoutput 0output 1
05.5-1.25
10.52.25

sampleLosses

sample=2 × column=1. Half the sum over each sample output axis.

sampleLosses: named coordinates, stored binary64 values
samplecolumn 0
015.90625
12.65625

perSampleDW

sample=2 × output=2 × input=2. Unreduced E[s,o]*X[s,d], independent of reduction mode.

perSampleDW: named coordinates, stored binary64 values
sample / outputinput 0input 1
0 / 05.511
0 / 1-1.25-2.5
1 / 0-0.50.5
1 / 1-2.252.25

sumDW

output=2 × input=2. Sum perSampleDW across sample axis.

sumDW: named coordinates, stored binary64 values
outputinput 0input 1
0511.5
1-3.5-0.25

dW

output=2 × input=2. reductionFactor*sumDW; same orientation as W.

dW: named coordinates, stored binary64 values
outputinput 0input 1
02.55.75
1-1.75-0.125

dB

output=2 × column=1. Sum sample contributions, then multiply reductionFactor once.

dB: named coordinates, stored binary64 values
outputcolumn 0
03
10.5

dX

sample=2 × input=2. reductionFactor*(E*W), without summing separate input rows.

dX: named coordinates, stored binary64 values
sampleinput 0input 1
03.3755.1875
1-0.8751.0625

g

seed_row=1 × output=2. Illustrative output row seed; independent of batch errors.

g: named coordinates, stored binary64 values
seed_rowoutput 0output 1
012

vjp

seed_row=1 × input=2. g*J; reverse row VJP.

vjp: named coordinates, stored binary64 values
seed_rowinput 0input 1
0-13

vjpColumn

input=2 × column=1. Explicit transpose of the VJP row: J transpose*g transpose.

vjpColumn: named coordinates, stored binary64 values
inputcolumn 0
0-1
13

v

input=2 × column=1. Illustrative input direction column.

v: named coordinates, stored binary64 values
inputcolumn 0
00.5
1-1

jvp

output=2 × column=1. J*v; forward directional output change.

jvp: named coordinates, stored binary64 values
outputcolumn 0
0-1.5
1-1
Inspect tensor shapes and full precision

All computed outputs

loss
9.28125
reductionFactor
0.5
vjp0
-1
jvp0
-1.5
x00
1
x01
2
x10
-1
x11
1
w00
1
w01
2
w10
-1
w11
0.5
b0
0.5
b1
-0.25
y00
0
y01
1
y10
1
y11
-1
reduction
1
g0
1
g1
2
v0
0.5
v1
-1
wRow00
1
wRow01
-1
wRow10
2
wRow11
0.5
broadcastBias00
0.5
broadcastBias01
-0.25
broadcastBias10
0.5
broadcastBias11
-0.25
p00Product0
1
p00Product1
4
p00Dot
5
p00
5.5
e00
5.5
p01Product0
-1
p01Product1
1
p01Dot
0
p01
-0.25
e01
-1.25
errorSquare00
30.25
errorSquare01
1.5625
sampleLoss0
15.90625
sampleDW000
5.5
sampleDW001
11
sampleDW010
-1.25
sampleDW011
-2.5
p10Product0
-1
p10Product1
2
p10Dot
1
p10
1.5
e10
0.5
p11Product0
1
p11Product1
0.5
p11Dot
1.5
p11
1.25
e11
2.25
errorSquare10
0.25
errorSquare11
5.0625
sampleLoss1
2.65625
sampleDW100
-0.5
sampleDW101
0.5
sampleDW110
-2.25
sampleDW111
2.25
lossSum
18.5625
sumDW00
5
dW00
2.5
sumDW01
11.5
dW01
5.75
sumDB0
6
dB0
3
sumDW10
-3.5
dW10
-1.75
sumDW11
-0.25
dW11
-0.125
sumDB1
1
dB1
0.5
dX00From0
5.5
dX00From1
1.25
sumDX00
6.75
dX00
3.375
dX01From0
11
dX01From1
-0.625
sumDX01
10.375
dX01
5.1875
dX10From0
0.5
dX10From1
-2.25
sumDX10
-1.75
dX10
-0.875
dX11From0
1
dX11From1
1.125
sumDX11
2.125
dX11
1.0625
vjp0From0
1
vjp0From1
-2
vjp1From0
2
vjp1From1
1
vjp1
3
jvp0From0
0.5
jvp0From1
-2
jvp1From0
-0.5
jvp1From1
-0.5
jvp1
-1

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

X

sample=2 × input=2 · float64 · display precision 8 · Explicit conversion to two input rows.

Storage indexValue
01
12
2-1
31

W

output=2 × input=2 · float64 · display precision 8 · Mathematical column-map weights.

Storage indexValue
01
12
2-1
30.5

WRow

input=2 × output=2 · float64 · display precision 8 · Explicit W transpose for row-batch prediction.

Storage indexValue
01
1-1
22
30.5

b

output=2 × column=1 · float64 · display precision 8 · Bias column before named broadcast.

Storage indexValue
00.5
1-0.25

broadcastBias

sample=2 × output=2 · float64 · display precision 8 · Explicit replication of bias across samples.

Storage indexValue
00.5
1-0.25
20.5
3-0.25

Y

sample=2 × output=2 · float64 · display precision 8 · Two output targets per sample; no feature mean.

Storage indexValue
00
11
21
3-1

P

sample=2 × output=2 · float64 · display precision 8 · X*WRow+broadcastBias.

Storage indexValue
05.5
1-0.25
21.5
31.25

E

sample=2 × output=2 · float64 · display precision 8 · P-Y; raw loss seeds before sample reduction.

Storage indexValue
05.5
1-1.25
20.5
32.25

sampleLosses

sample=2 × column=1 · float64 · display precision 8 · Half the sum over each sample output axis.

Storage indexValue
015.90625
12.65625

perSampleDW

sample=2 × output=2 × input=2 · float64 · display precision 8 · Unreduced E[s,o]*X[s,d], independent of reduction mode.

Storage indexValue
05.5
111
2-1.25
3-2.5
4-0.5
50.5
6-2.25
72.25

perSampleDB

sample=2 × output=2 · float64 · display precision 8 · Raw bias gradients before shared-parameter reduction.

Storage indexValue
05.5
1-1.25
20.5
32.25

sumDW

output=2 × input=2 · float64 · display precision 8 · Sum perSampleDW across sample axis.

Storage indexValue
05
111.5
2-3.5
3-0.25

dW

output=2 × input=2 · float64 · display precision 8 · reductionFactor*sumDW; same orientation as W.

Storage indexValue
02.5
15.75
2-1.75
3-0.125

dB

output=2 × column=1 · float64 · display precision 8 · Sum sample contributions, then multiply reductionFactor once.

Storage indexValue
03
10.5

sumDX

sample=2 × input=2 · float64 · display precision 8 · E*W; unreduced sum-loss input gradients.

Storage indexValue
06.75
110.375
2-1.75
32.125

dX

sample=2 × input=2 · float64 · display precision 8 · reductionFactor*(E*W), without summing separate input rows.

Storage indexValue
03.375
15.1875
2-0.875
31.0625

J

output=2 × input=2 · float64 · display precision 8 · Affine forward Jacobian J[o,d]=W[o,d].

Storage indexValue
01
12
2-1
30.5

g

seed_row=1 × output=2 · float64 · display precision 8 · Illustrative output row seed; independent of batch errors.

Storage indexValue
01
12

vjp

seed_row=1 × input=2 · float64 · display precision 8 · g*J; reverse row VJP.

Storage indexValue
0-1
13

vjpColumn

input=2 × column=1 · float64 · display precision 8 · Explicit transpose of the VJP row: J transpose*g transpose.

Storage indexValue
0-1
13

v

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

Storage indexValue
00.5
1-1

jvp

output=2 × column=1 · float64 · display precision 8 · J*v; forward directional output change.

Storage indexValue
0-1.5
1-1

All nineteen fields are editable, with a named selector for reduction. Compare perSampleDW before and after switching sum/mean; then change g or v and inspect the separate VJP/JVP tables. Fixed dimensions prevent accidental sample/feature broadcasting.

Check your understanding

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

1. For J:[output,input] and an output seed row g:[1,2], which product returns input sensitivities?
2. Sample 0, output 1 error=-1.25; its input 0=1. What is raw sampleDW010?
3. Weight [0,1] receives raw sample gradients 11 and 0.5. With factor 0.5, what is dW01?
4. Reset to sample mean, then select sum. What changes?
5. Set both independent VJP seeds g0,g1 to zero. Must the batch gradient dW vanish?

First switch Batch objective reduction between mean and sum. Predictions should remain unchanged while loss and objective gradients change scale. Then edit the independent row seed g0,g1 and column direction v0,v1. Their VJP and JVP are separate demonstrations: changing them does not change batch loss. Reset example restores all nineteen fields.

Review outer products in IV-09 — Backpropagation Through a Multi-Neuron Layer and derivative matrices in III.9 — Jacobian. The selected operation panel shows its actual operands; the expanded tables show the completed calculation from the starting inputs.

Start with a map, before attaching a loss

An affine map multiplies by a matrix and adds a bias. For a single mathematical input column,

f(x)=Wx+b,W=[12−11/2],b=[1/2−1/4].f(x)=Wx+b,\qquad W=\begin{bmatrix}1&2\\-1&1/2\end{bmatrix},\qquad b=\begin{bmatrix}1/2\\-1/4\end{bmatrix}.

There are two input coordinates and two output coordinates. The map’s Jacobian, JJ, is the matrix whose cell Jo,dJ_{o,d} means “the derivative of output oo with respect to input coordinate dd.” Its rows enumerate outputs and its columns enumerate inputs. Here J=WJ=W: bias adds a constant, and the local coefficient of each input is its weight.

This Jacobian describes the forward map before we choose targets or a loss. It does not depend on which of our two samples we evaluate. More complicated maps can have Jacobians depending on the current input; the simplicity here is intentional.

Equal dimensions can conceal mistakes. JJ and JTJ^T are both two by two, yet their off-diagonal values differ. Read axis names along with dimensions. A vector containing two output sensitivities cannot become an input direction just because both have two entries.

A JVP sends an input direction forward

A direction vv says how the input coordinates move together. Take the column v=[1/2,−1]Tv=[1/2,-1]^T, with shape [input,column]=[2,1]. The Jacobian-vector product, or JVP, is

Jv=[12−11/2][1/2−1]=[1/2−2−1/2−1/2]=[−3/2−1].Jv= \begin{bmatrix}1&2\\-1&1/2\end{bmatrix} \begin{bmatrix}1/2\\-1\end{bmatrix} =\begin{bmatrix}1/2-2\\-1/2-1/2\end{bmatrix} =\begin{bmatrix}-3/2\\-1\end{bmatrix}.

This result has output rows, shape [2,1]. It describes output changes caused by moving the input in direction vv. If we move by a small scalar amount tt, the output change is approximately tJvtJv for a general differentiable map. For this affine map the identity f(x+tv)−f(x)=tJvf(x+tv)-f(x)=tJv is exact in real arithmetic, even for a finite move.

A direction is not a target, a loss, or a parameter update. Setting vv to zero makes the general JVP zero because no input motion is requested. It does not imply the model predicts either target correctly.

A VJP sends an output seed backward

An output seed gg specifies how much each output contributes to a scalar combination. Our example uses the row g=[1,2]g=[1,2], shape [seed_row,output]=[1,2]. Holding gg fixed, the scalar combination is gf(x)=f0(x)+2f1(x)g f(x)=f_0(x)+2f_1(x).

The vector-Jacobian product, or VJP, multiplies on the left:

gJ=[12][12−11/2]=[1−22+1]=[−13].gJ= \begin{bmatrix}1&2\end{bmatrix} \begin{bmatrix}1&2\\-1&1/2\end{bmatrix} =\begin{bmatrix}1-2&2+1\end{bmatrix} =\begin{bmatrix}-1&3\end{bmatrix}.

Its columns enumerate inputs. For example, the first output contributes 1⋅11\cdot1 to input zero’s sensitivity; the second contributes 2⋅(−1)2\cdot(-1). They add to −1-1.

The corresponding gradient column is (gJ)T=JTgT=[−1,3]T(gJ)^T=J^Tg^T=[-1,3]^T. Transposition changes its orientation while preserving the coordinate meanings. It does not turn it into JvJv, whose entries live in output space. The inspector therefore stores g, vjp, vjpColumn, v, and jvp separately.

Name the batch conversion

A batch is a collection of samples evaluated using the same parameters. To store our two samples conveniently, convert input columns into rows:

X=[12−11],Y=[011−1].X=\begin{bmatrix}1&2\\-1&1\end{bmatrix},\qquad Y=\begin{bmatrix}0&1\\1&-1\end{bmatrix}.

Row zero is sample zero; row one is sample one. YY contains their desired output pairs. The column-map weight WW must be explicitly transposed for row-batch multiplication:

Wrow=WT=[1−121/2].W_{\mathrm{row}}=W^T= \begin{bmatrix}1&-1\\2&1/2\end{bmatrix}.

A broadcast repeats a value over a named axis. We deliberately materialize the bias column into two output rows:

Bbroadcast=[1/2−1/41/2−1/4],P=XWrow+Bbroadcast.B_{\mathrm{broadcast}}= \begin{bmatrix}1/2&-1/4\\1/2&-1/4\end{bmatrix},\qquad P=XW_{\mathrm{row}}+B_{\mathrm{broadcast}}.
RecordShapeNamed axes
XX[2,2]sample, input
W=JW=J[2,2]output, input
WrowW_{\mathrm{row}}[2,2]input, output
bb[2,1]output, column
broadcast bias, P,Y,EP,Y,E[2,2]sample, output
per-sample dWdW[2,2,2]sample, output, input
final dWdW[2,2]output, input
final dXdX[2,2]sample, input

The shared dimensions do not authorize exchanging axes. Our state exposes fixed scalar fields rather than accepting arbitrary arrays and guessing their orientation. Inputs must be finite and bounded by −20-20 and 2020; reduction must be exactly sum or sample mean. Invalid fields or unsupported extra shape fields produce an explicit unavailable result.

Work through both prediction rows

For sample zero, the two output contractions are

P0,0=(1)(1)+(2)(2)+1/2=11/2,P_{0,0}=(1)(1)+(2)(2)+1/2=11/2, P0,1=(1)(−1)+(2)(1/2)−1/4=−1/4.P_{0,1}=(1)(-1)+(2)(1/2)-1/4=-1/4.

For sample one,

P1,0=(−1)(1)+(1)(2)+1/2=3/2,P_{1,0}=(-1)(1)+(1)(2)+1/2=3/2, P1,1=(−1)(−1)+(1)(1/2)−1/4=5/4.P_{1,1}=(-1)(-1)+(1)(1/2)-1/4=5/4.

Subtract each target from its matching prediction to form the residual or signed error matrix:

E=P−Y=[11/2−5/41/29/4].E=P-Y=\begin{bmatrix}11/2&-5/4\\1/2&9/4\end{bmatrix}.

Our scalar sample loss is half the sum of its two squared output errors. We do not take an output-feature average:

ℓ0=12[(11/2)2+(−5/4)2]=12[48416+2516]=50932,\ell_0=\frac12\left[(11/2)^2+(-5/4)^2\right] =\frac12\left[\frac{484}{16}+\frac{25}{16}\right]=\frac{509}{32}, ℓ1=12[(1/2)2+(9/4)2]=12[416+8116]=8532.\ell_1=\frac12\left[(1/2)^2+(9/4)^2\right] =\frac12\left[\frac4{16}+\frac{81}{16}\right]=\frac{85}{32}.

The sum objective is Lsum=ℓ0+ℓ1=297/16L_{\mathrm{sum}}=\ell_0+\ell_1=297/16. The sample-mean objective is Lmean=(ℓ0+ℓ1)/2=297/32L_{\mathrm{mean}}=(\ell_0+\ell_1)/2=297/32. The half in each square and the half for averaging two samples have different jobs. Dividing again by the output count would define a different objective.

Materialize each sample’s parameter gradient

For sample ss, differentiating its half-square sum gives the output seed row EsE_s. This is the actual sample-loss seed. It generally differs from the independently editable illustrative row gg.

Each weight cell receives

∂ℓs∂Wo,d=Es,oXs,d.\frac{\partial\ell_s}{\partial W_{o,d}}=E_{s,o}X_{s,d}.

These are outer products, using the same output-by-input orientation as WW. Before any sample averaging, sample zero contributes

G0=[11/2−5/4][12]=[11/211−5/4−5/2].G_0= \begin{bmatrix}11/2\\-5/4\end{bmatrix} \begin{bmatrix}1&2\end{bmatrix} =\begin{bmatrix}11/2&11\\-5/4&-5/2\end{bmatrix}.

Sample one contributes

G1=[1/29/4][−11]=[−1/21/2−9/49/4].G_1= \begin{bmatrix}1/2\\9/4\end{bmatrix} \begin{bmatrix}-1&1\end{bmatrix} =\begin{bmatrix}-1/2&1/2\\-9/4&9/4\end{bmatrix}.

The perSampleDW tensor keeps both matrices with axes [sample,output,input]. This record is useful because a final gradient alone hides which examples reinforced or opposed each other. For weight W0,0W_{0,0}, contributions 11/211/2 and −1/2-1/2 partially cancel. For W1,0W_{1,0}, both contributions are negative and reinforce each other.

Shared parameters accumulate across samples

Both samples use the same WW. Their parameter derivatives add when their losses add:

dWsum=G0+G1=[523/2−7/2−1/4].dW_{\mathrm{sum}}=G_0+G_1 =\begin{bmatrix}5&23/2\\-7/2&-1/4\end{bmatrix}.

For the sample mean, multiply this sum once by 1/21/2:

dWmean=[5/223/4−7/4−1/8].dW_{\mathrm{mean}}= \begin{bmatrix}5/2&23/4\\-7/4&-1/8\end{bmatrix}.

Bias is also shared. Each sample’s raw bias derivative is its residual row. Reversing the named forward broadcast sums over samples:

dBsum=[11/2+1/2−5/4+9/4]=[61],dBmean=[31/2].dB_{\mathrm{sum}}= \begin{bmatrix}11/2+1/2\\-5/4+9/4\end{bmatrix} =\begin{bmatrix}6\\1\end{bmatrix},\qquad dB_{\mathrm{mean}}=\begin{bmatrix}3\\1/2\end{bmatrix}.

The implementation first saves raw sample gradients, then adds them in sample order, then applies reductionFactor. Its value is one for sum and one half for sample mean. Switching the selector cannot alter predictions, residuals or raw sample outer products, because none of those calculations uses the selector.

Input gradients keep their separate sample rows

The parameters are shared, but the two input rows are different variables. Sample zero’s loss depends on its own input, not sample one’s input. Therefore we preserve the sample axis rather than merging input gradients across rows.

For the sum objective, each input row is the reverse product EsJ=EsWE_sJ=E_sW:

(dXsum)0,0=(11/2)(1)+(−5/4)(−1)=27/4,(dX_{\mathrm{sum}})_{0,0}=(11/2)(1)+(-5/4)(-1)=27/4, (dXsum)0,1=(11/2)(2)+(−5/4)(1/2)=83/8,(dX_{\mathrm{sum}})_{0,1}=(11/2)(2)+(-5/4)(1/2)=83/8, (dXsum)1,0=(1/2)(1)+(9/4)(−1)=−7/4,(dX_{\mathrm{sum}})_{1,0}=(1/2)(1)+(9/4)(-1)=-7/4, (dXsum)1,1=(1/2)(2)+(9/4)(1/2)=17/8.(dX_{\mathrm{sum}})_{1,1}=(1/2)(2)+(9/4)(1/2)=17/8.

Thus

dXsum=[27/483/8−7/417/8],dXmean=[27/883/16−7/817/16].dX_{\mathrm{sum}}=\begin{bmatrix}27/4&83/8\\-7/4&17/8\end{bmatrix},\qquad dX_{\mathrm{mean}}=\begin{bmatrix}27/8&83/16\\-7/8&17/16\end{bmatrix}.

The sample-mean factor still applies to every input component because the objective itself is divided by two. Sharing determines which contributions accumulate into the same variable; reduction determines the objective’s overall scale. Those are separate rules.

Try changes that distinguish the concepts

Reset and select sum. Every objective gradient doubles from its sample-mean default, including dXdX. If only the displayed loss changed, the backward computation would be inconsistent with the objective.

Next set g0=g1=0. The general VJP becomes zero, but residuals, loss and batch gradients retain their current values. That is a counterexample to treating an arbitrary demonstration seed as the loss seed. Set v0=v1=0 and the general JVP also becomes zero; this still says nothing about prediction quality.

Finally change only a target. The affine Jacobian and the general products gJ,JvgJ,Jv remain unchanged, because the forward map has not changed. Residuals and objective derivatives generally change. Changing a bias similarly leaves J=WJ=W unchanged but affects predictions and loss. A derivative matrix is not a complete record of the model’s outputs or its fit.

Read the actual NumPy source

The program stores X,W,YX,W,Y as dense arrays, performs W.T.copy(), and materializes the named bias broadcast. Short loops expose each multiplication and addition instead of hiding contractions behind a training framework. It saves sample_dW before reduction, then computes independent general VJP/JVP demonstrations from their own operands.

The following blocks are the actual code/python/p02/iv10.py and its sibling layer_reference.py, imported directly as source. Keep the helper beside the lesson file. Defaults, a complete JSON argument and - for JSON stdin are supported. A supplied state replaces all fields; incomplete JSON state is rejected.

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.

"""IV10: an affine two-output map, explicit row batches, VJP, JVP and reductions."""
import numpy as np
from layer_reference import NumericalFault, finite, fixed_state, guarded, LayerTrace, tensor, run

DEFAULT_IV10 = {"x00": 1, "x01": 2, "x10": -1, "x11": 1, "w00": 1, "w01": 2,
                "w10": -1, "w11": 0.5, "b0": 0.5, "b1": -0.25, "y00": 0,
                "y01": 1, "y10": 1, "y11": -1, "reduction": 1,
                "g0": 1, "g1": 2, "v0": 0.5, "v1": -1}


@guarded
def derive_iv10(state):
    """Keep sample/output/input axes explicit; reduce the objective exactly once."""
    s = fixed_state(state, DEFAULT_IV10)
    if s["reduction"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "reduction must be 0 (sum) or 1 (sample mean).")
    trace = LayerTrace(s)
    o, add = trace.outputs, trace.add
    X = np.array([[s["x00"], s["x01"]], [s["x10"], s["x11"]]], dtype=np.float64)
    W = np.array([[s["w00"], s["w01"]], [s["w10"], s["w11"]]], dtype=np.float64)
    Y = np.array([[s["y00"], s["y01"]], [s["y10"], s["y11"]]], dtype=np.float64)
    b = np.array([[s["b0"]], [s["b1"]]], dtype=np.float64)
    W_row = W.T.copy()
    add("transpose_weights", "W_row[d,o]=W[o,d]",
        {"w00": s["w00"], "w01": s["w01"], "w10": s["w10"], "w11": s["w11"]},
        {"wRow00": W_row[0, 0], "wRow01": W_row[0, 1], "wRow10": W_row[1, 0], "wRow11": W_row[1, 1]})
    # Materialize the named broadcast, rather than relying on NumPy alignment.
    broadcast = np.array([[b[0, 0], b[1, 0]], [b[0, 0], b[1, 0]]], dtype=np.float64)
    add("broadcast_bias", "broadcastBias[s,o]=b[o] for s=0,1", {"b0": s["b0"], "b1": s["b1"]},
        {"broadcastBias00": broadcast[0, 0], "broadcastBias01": broadcast[0, 1],
         "broadcastBias10": broadcast[1, 0], "broadcastBias11": broadcast[1, 1]})
    P, E, losses = np.zeros((2, 2)), np.zeros((2, 2)), np.zeros((2, 1))
    sample_dW = np.zeros((2, 2, 2))  # [sample, output, input], before reduction.
    for sample in range(2):
        for out in range(2):
            # Explicit contraction order matches the TS trace, without BLAS reordering.
            p0 = finite(X[sample, 0] * W_row[0, out], "batch dot product0")
            p1 = finite(X[sample, 1] * W_row[1, out], "batch dot product1")
            dot = finite(p0 + p1, "batch dot")
            P[sample, out] = finite(dot + broadcast[sample, out], "batch prediction")
            E[sample, out] = finite(P[sample, out] - Y[sample, out], "batch error")
            add(f"forward_{sample}{out}", "P[s,o]=X[s,0]*W_row[0,o]+X[s,1]*W_row[1,o]+broadcastBias[s,o]; E=P-Y",
                {"x0": X[sample, 0], "w0": W_row[0, out], "x1": X[sample, 1], "w1": W_row[1, out], "bias": broadcast[sample, out], "y": Y[sample, out]},
                {f"p{sample}{out}Product0": p0, f"p{sample}{out}Product1": p1,
                 f"p{sample}{out}Dot": dot, f"p{sample}{out}": P[sample, out], f"e{sample}{out}": E[sample, out]})
        sq0 = finite(E[sample, 0] * E[sample, 0], "output error square0")
        sq1 = finite(E[sample, 1] * E[sample, 1], "output error square1")
        losses[sample, 0] = finite(finite(sq0 + sq1, "sample squared-error sum") / 2, "sample loss")
        add(f"sample_loss_{sample}", "sampleLoss[s]=(E[s,0]^2+E[s,1]^2)/2",
            {"e0": E[sample, 0], "e1": E[sample, 1]},
            {f"errorSquare{sample}0": sq0, f"errorSquare{sample}1": sq1, f"sampleLoss{sample}": losses[sample, 0]})
        for out in range(2):
            for d in range(2):
                sample_dW[sample, out, d] = finite(E[sample, out] * X[sample, d], "sampleDW")
                add(f"sample_outer_{sample}{out}{d}", "sampleDW[s,o,d]=E[s,o]*X[s,d]",
                    {"error": E[sample, out], "x": X[sample, d]},
                    {f"sampleDW{sample}{out}{d}": sample_dW[sample, out, d]})
    factor = np.float64(1 if s["reduction"] == 0 else 0.5)
    loss_sum = finite(losses[0, 0] + losses[1, 0], "lossSum")
    add("reduce_loss", "loss=reductionFactor*(sampleLoss0+sampleLoss1)",
        {"sampleLoss0": losses[0, 0], "sampleLoss1": losses[1, 0], "reduction": s["reduction"]},
        {"reductionFactor": factor, "lossSum": loss_sum, "loss": finite(factor * loss_sum, "loss")})
    sum_dW, dW, dB = np.zeros((2, 2)), np.zeros((2, 2)), np.zeros((2, 1))
    for out in range(2):
        for d in range(2):
            sum_dW[out, d] = finite(sample_dW[0, out, d] + sample_dW[1, out, d], "sumDW")
            dW[out, d] = finite(factor * sum_dW[out, d], "dW")
            add(f"reduce_weight_{out}{d}", "sumDW[o,d]=sampleDW[0,o,d]+sampleDW[1,o,d]; dW=reductionFactor*sumDW",
                {"sample0": sample_dW[0, out, d], "sample1": sample_dW[1, out, d], "reductionFactor": factor},
                {f"sumDW{out}{d}": sum_dW[out, d], f"dW{out}{d}": dW[out, d]})
        bias_sum = finite(E[0, out] + E[1, out], "sumDB")
        dB[out, 0] = finite(factor * bias_sum, "dB")
        add(f"reduce_bias_{out}", "sumDB[o]=E[0,o]+E[1,o]; dB=reductionFactor*sumDB",
            {"sample0": E[0, out], "sample1": E[1, out], "reductionFactor": factor},
            {f"sumDB{out}": bias_sum, f"dB{out}": dB[out, 0]})
    sum_dX, dX = np.zeros((2, 2)), np.zeros((2, 2))
    for sample in range(2):
        for d in range(2):
            from0 = finite(E[sample, 0] * W[0, d], "input output0 path")
            from1 = finite(E[sample, 1] * W[1, d], "input output1 path")
            sum_dX[sample, d] = finite(from0 + from1, "sumDX")
            dX[sample, d] = finite(factor * sum_dX[sample, d], "dX")
            add(f"input_{sample}{d}", "sumDX[s,d]=E[s,0]*W[0,d]+E[s,1]*W[1,d]; dX=reductionFactor*sumDX",
                {"e0": E[sample, 0], "w0": W[0, d], "e1": E[sample, 1], "w1": W[1, d], "reductionFactor": factor},
                {f"dX{sample}{d}From0": from0, f"dX{sample}{d}From1": from1,
                 f"sumDX{sample}{d}": sum_dX[sample, d], f"dX{sample}{d}": dX[sample, d]})
    J = W.copy()  # Affine Jacobian: output-by-input, independent of X and b.
    g = np.array([[s["g0"], s["g1"]]], dtype=np.float64)
    direction = np.array([[s["v0"]], [s["v1"]]], dtype=np.float64)
    vjp, jvp = np.zeros((1, 2)), np.zeros((2, 1))
    for d in range(2):
        from0 = finite(g[0, 0] * J[0, d], "VJP product0")
        from1 = finite(g[0, 1] * J[1, d], "VJP product1")
        vjp[0, d] = finite(from0 + from1, "VJP")
        add(f"vjp_{d}", "vjp[d]=g0*J[0,d]+g1*J[1,d]; J=W",
            {"g0": s["g0"], "j0": J[0, d], "g1": s["g1"], "j1": J[1, d]},
            {f"vjp{d}From0": from0, f"vjp{d}From1": from1, f"vjp{d}": vjp[0, d]})
    for out in range(2):
        from0 = finite(J[out, 0] * direction[0, 0], "JVP product0")
        from1 = finite(J[out, 1] * direction[1, 0], "JVP product1")
        jvp[out, 0] = finite(from0 + from1, "JVP")
        add(f"jvp_{out}", "jvp[o]=J[o,0]*v0+J[o,1]*v1; J=W",
            {"j0": J[out, 0], "v0": s["v0"], "j1": J[out, 1], "v1": s["v1"]},
            {f"jvp{out}From0": from0, f"jvp{out}From1": from1, f"jvp{out}": jvp[out, 0]})
    def batch(identifier, values, provenance):
        return tensor(identifier, [2, 2], ["sample", "output"], values, provenance)
    def weight(identifier, values, provenance):
        return tensor(identifier, [2, 2], ["output", "input"], values, provenance)
    tensors = [tensor("X", [2, 2], ["sample", "input"], X, "Explicit conversion to two input rows."),
               weight("W", W, "Mathematical column-map weights."),
               tensor("WRow", [2, 2], ["input", "output"], W_row, "Explicit W transpose for row-batch prediction."),
               tensor("b", [2, 1], ["output", "column"], b, "Bias column before named broadcast."),
               batch("broadcastBias", broadcast, "Explicit replication of bias across samples."),
               batch("Y", Y, "Two output targets per sample; no feature mean."),
               batch("P", P, "X*WRow+broadcastBias."), batch("E", E, "P-Y; raw loss seeds before sample reduction."),
               tensor("sampleLosses", [2, 1], ["sample", "column"], losses, "Half the sum over each sample output axis."),
               tensor("perSampleDW", [2, 2, 2], ["sample", "output", "input"], sample_dW, "Unreduced E[s,o]*X[s,d], independent of reduction mode."),
               batch("perSampleDB", E, "Raw bias gradients before shared-parameter reduction."),
               weight("sumDW", sum_dW, "Sum perSampleDW across sample axis."),
               weight("dW", dW, "reductionFactor*sumDW; same orientation as W."),
               tensor("dB", [2, 1], ["output", "column"], dB, "Sum sample contributions, then multiply reductionFactor once."),
               tensor("sumDX", [2, 2], ["sample", "input"], sum_dX, "E*W; unreduced sum-loss input gradients."),
               tensor("dX", [2, 2], ["sample", "input"], dX, "reductionFactor*(E*W), without summing separate input rows."),
               weight("J", J, "Affine forward Jacobian J[o,d]=W[o,d]."),
               tensor("g", [1, 2], ["seed_row", "output"], g, "Illustrative output row seed; independent of batch errors."),
               tensor("vjp", [1, 2], ["seed_row", "input"], vjp, "g*J; reverse row VJP."),
               tensor("vjpColumn", [2, 1], ["input", "column"], vjp.T.copy(), "Explicit transpose of the VJP row: J transpose*g transpose."),
               tensor("v", [2, 1], ["input", "column"], direction, "Illustrative input direction column."),
               tensor("jvp", [2, 1], ["output", "column"], jvp, "J*v; forward directional output change.")]
    return trace.result({"loss": o["loss"], "reductionFactor": factor, "vjp0": o["vjp0"], "jvp0": o["jvp0"]}, tensors)


if __name__ == "__main__":
    run(derive_iv10, DEFAULT_IV10)
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=(",", ":")))

Arithmetic uses binary64 values, never formatted display text. The exact fractions in this worked example express the hand derivation; arbitrary decimal edits can incur floating-point rounding.

What to remember

A JVP carries an input direction into output space. A VJP carries an output seed into input sensitivities; an explicit transpose gives the gradient column. Per-sample outer products preserve their output-by-input parameter axes. Shared parameter derivatives accumulate over samples, and the declared sample reduction scales every objective gradient exactly once.

We have calculated derivatives without updating parameters or claiming any training improvement. Next, gradient checking will compare analytical sensitivities with changes in actual loss, including the places where finite differences can mislead us.