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.
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
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.
| output | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
WRow
input=2 × output=2. Explicit W transpose for row-batch prediction.
| input | output 0 | output 1 |
|---|---|---|
| 0 | ||
| 1 |
broadcastBias
sample=2 × output=2. Explicit replication of bias across samples.
| sample | output 0 | output 1 |
|---|---|---|
| 0 | ||
| 1 |
P
sample=2 × output=2. X*WRow+broadcastBias.
| sample | output 0 | output 1 |
|---|---|---|
| 0 | ||
| 1 |
E
sample=2 × output=2. P-Y; raw loss seeds before sample reduction.
| sample | output 0 | output 1 |
|---|---|---|
| 0 | ||
| 1 |
sampleLosses
sample=2 × column=1. Half the sum over each sample output axis.
| sample | column 0 |
|---|---|
| 0 | |
| 1 |
perSampleDW
sample=2 × output=2 × input=2. Unreduced E[s,o]*X[s,d], independent of reduction mode.
| sample / output | input 0 | input 1 |
|---|---|---|
| 0 / 0 | ||
| 0 / 1 | ||
| 1 / 0 | ||
| 1 / 1 |
sumDW
output=2 × input=2. Sum perSampleDW across sample axis.
| output | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
dW
output=2 × input=2. reductionFactor*sumDW; same orientation as W.
| output | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
dB
output=2 × column=1. Sum sample contributions, then multiply reductionFactor once.
| output | column 0 |
|---|---|
| 0 | |
| 1 |
dX
sample=2 × input=2. reductionFactor*(E*W), without summing separate input rows.
| sample | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
g
seed_row=1 × output=2. Illustrative output row seed; independent of batch errors.
| seed_row | output 0 | output 1 |
|---|---|---|
| 0 |
vjp
seed_row=1 × input=2. g*J; reverse row VJP.
| seed_row | input 0 | input 1 |
|---|---|---|
| 0 |
vjpColumn
input=2 × column=1. Explicit transpose of the VJP row: J transpose*g transpose.
| input | column 0 |
|---|---|
| 0 | |
| 1 |
v
input=2 × column=1. Illustrative input direction column.
| input | column 0 |
|---|---|
| 0 | |
| 1 |
jvp
output=2 × column=1. J*v; forward directional output change.
| output | column 0 |
|---|---|
| 0 | |
| 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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
| 3 | 1 |
W
output=2 × input=2 · float64 · display precision 8 · Mathematical column-map weights.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
| 3 | 0.5 |
WRow
input=2 × output=2 · float64 · display precision 8 · Explicit W transpose for row-batch prediction.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | -1 |
| 2 | 2 |
| 3 | 0.5 |
b
output=2 × column=1 · float64 · display precision 8 · Bias column before named broadcast.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | -0.25 |
broadcastBias
sample=2 × output=2 · float64 · display precision 8 · Explicit replication of bias across samples.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | -0.25 |
| 2 | 0.5 |
| 3 | -0.25 |
Y
sample=2 × output=2 · float64 · display precision 8 · Two output targets per sample; no feature mean.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 1 |
| 3 | -1 |
P
sample=2 × output=2 · float64 · display precision 8 · X*WRow+broadcastBias.
| Storage index | Value |
|---|---|
| 0 | 5.5 |
| 1 | -0.25 |
| 2 | 1.5 |
| 3 | 1.25 |
E
sample=2 × output=2 · float64 · display precision 8 · P-Y; raw loss seeds before sample reduction.
| Storage index | Value |
|---|---|
| 0 | 5.5 |
| 1 | -1.25 |
| 2 | 0.5 |
| 3 | 2.25 |
sampleLosses
sample=2 × column=1 · float64 · display precision 8 · Half the sum over each sample output axis.
| Storage index | Value |
|---|---|
| 0 | 15.90625 |
| 1 | 2.65625 |
perSampleDW
sample=2 × output=2 × input=2 · float64 · display precision 8 · Unreduced E[s,o]*X[s,d], independent of reduction mode.
| Storage index | Value |
|---|---|
| 0 | 5.5 |
| 1 | 11 |
| 2 | -1.25 |
| 3 | -2.5 |
| 4 | -0.5 |
| 5 | 0.5 |
| 6 | -2.25 |
| 7 | 2.25 |
perSampleDB
sample=2 × output=2 · float64 · display precision 8 · Raw bias gradients before shared-parameter reduction.
| Storage index | Value |
|---|---|
| 0 | 5.5 |
| 1 | -1.25 |
| 2 | 0.5 |
| 3 | 2.25 |
sumDW
output=2 × input=2 · float64 · display precision 8 · Sum perSampleDW across sample axis.
| Storage index | Value |
|---|---|
| 0 | 5 |
| 1 | 11.5 |
| 2 | -3.5 |
| 3 | -0.25 |
dW
output=2 × input=2 · float64 · display precision 8 · reductionFactor*sumDW; same orientation as W.
| Storage index | Value |
|---|---|
| 0 | 2.5 |
| 1 | 5.75 |
| 2 | -1.75 |
| 3 | -0.125 |
dB
output=2 × column=1 · float64 · display precision 8 · Sum sample contributions, then multiply reductionFactor once.
| Storage index | Value |
|---|---|
| 0 | 3 |
| 1 | 0.5 |
sumDX
sample=2 × input=2 · float64 · display precision 8 · E*W; unreduced sum-loss input gradients.
| Storage index | Value |
|---|---|
| 0 | 6.75 |
| 1 | 10.375 |
| 2 | -1.75 |
| 3 | 2.125 |
dX
sample=2 × input=2 · float64 · display precision 8 · reductionFactor*(E*W), without summing separate input rows.
| Storage index | Value |
|---|---|
| 0 | 3.375 |
| 1 | 5.1875 |
| 2 | -0.875 |
| 3 | 1.0625 |
J
output=2 × input=2 · float64 · display precision 8 · Affine forward Jacobian J[o,d]=W[o,d].
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
| 3 | 0.5 |
g
seed_row=1 × output=2 · float64 · display precision 8 · Illustrative output row seed; independent of batch errors.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
vjp
seed_row=1 × input=2 · float64 · display precision 8 · g*J; reverse row VJP.
| Storage index | Value |
|---|---|
| 0 | -1 |
| 1 | 3 |
vjpColumn
input=2 × column=1 · float64 · display precision 8 · Explicit transpose of the VJP row: J transpose*g transpose.
| Storage index | Value |
|---|---|
| 0 | -1 |
| 1 | 3 |
v
input=2 × column=1 · float64 · display precision 8 · Illustrative input direction column.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | -1 |
jvp
output=2 × column=1 · float64 · display precision 8 · J*v; forward directional output change.
| Storage index | Value |
|---|---|
| 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.
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,
There are two input coordinates and two output coordinates. The map’s Jacobian, , is the matrix whose cell means “the derivative of output with respect to input coordinate .” Its rows enumerate outputs and its columns enumerate inputs. Here : 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. and 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 says how the input coordinates move together. Take the column , with shape [input,column]=[2,1]. The Jacobian-vector product, or JVP, is
This result has output rows, shape [2,1]. It describes output changes caused by moving the input in direction . If we move by a small scalar amount , the output change is approximately for a general differentiable map. For this affine map the identity is exact in real arithmetic, even for a finite move.
A direction is not a target, a loss, or a parameter update. Setting 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 specifies how much each output contributes to a scalar combination. Our example uses the row , shape [seed_row,output]=[1,2]. Holding fixed, the scalar combination is .
The vector-Jacobian product, or VJP, multiplies on the left:
Its columns enumerate inputs. For example, the first output contributes to input zero’s sensitivity; the second contributes . They add to .
The corresponding gradient column is . Transposition changes its orientation while preserving the coordinate meanings. It does not turn it into , 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:
Row zero is sample zero; row one is sample one. contains their desired output pairs. The column-map weight must be explicitly transposed for row-batch multiplication:
A broadcast repeats a value over a named axis. We deliberately materialize the bias column into two output rows:
| Record | Shape | Named axes |
|---|---|---|
[2,2] | sample, input | |
[2,2] | output, input | |
[2,2] | input, output | |
[2,1] | output, column | |
| broadcast bias, | [2,2] | sample, output |
| per-sample | [2,2,2] | sample, output, input |
| final | [2,2] | output, input |
| final | [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 and ; 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
For sample one,
Subtract each target from its matching prediction to form the residual or signed error matrix:
Our scalar sample loss is half the sum of its two squared output errors. We do not take an output-feature average:
The sum objective is . The sample-mean objective is . 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 , differentiating its half-square sum gives the output seed row . This is the actual sample-loss seed. It generally differs from the independently editable illustrative row .
Each weight cell receives
These are outer products, using the same output-by-input orientation as . Before any sample averaging, sample zero contributes
Sample one contributes
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 , contributions and partially cancel. For , both contributions are negative and reinforce each other.
Shared parameters accumulate across samples
Both samples use the same . Their parameter derivatives add when their losses add:
For the sample mean, multiply this sum once by :
Bias is also shared. Each sample’s raw bias derivative is its residual row. Reversing the named forward broadcast sums over samples:
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 :
Thus
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 . 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 remain unchanged, because the forward map has not changed. Residuals and objective derivatives generally change. Changing a bias similarly leaves 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 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.