IV-14 / Part II · Learning, Backpropagation and Optimization
PyTorch Autograd as an Independent Check
Relate a complete hand-derived backward pass to an optional real Torch report, with exact input binding, visible residuals and honest execution provenance.
Review the ideas this chapter uses
A framework can calculate derivatives without our writing a separate backward formula for each parameter. That is useful only if we know which calculation it differentiated. A wrong target, transposed matrix or different loss divisor can produce perfectly consistent derivatives of the wrong problem. Here we keep the complete manual calculation visible and give a framework one small, precisely specified problem to check independently.
The hand-set network below is exactly the two-neuron network from IV-09 — Backpropagation Through a Multi-Neuron Layer. Its manual numerical engine is reused unchanged. The new interaction is an optional local report: the page starts with NOT RUN, and contains no invented framework numbers. Everything about the manual graph and the five exercises remains usable offline without Torch.
Manual gradients first, optional framework comparison second
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
loss 0.0703125. prediction 0.625. dX0 -0.375. dX1 0.28125. Hidden neuron 0: dot then bias. IV-14 manual calculation, reused unchanged from IV-09. 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
IV-14 manual calculation, reused unchanged from IV-09. 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
The complete manual record below reuses unchanged IV-09 mathematics. No imported report changes this graph or its trace.
Manual gradients: same named axes as IV-09
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. IV-14 manual record; unchanged IV-09 mathematics. Column-map weights: z=W*x+b.
| hidden | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
z
hidden=2 × column=1. IV-14 manual record; unchanged IV-09 mathematics. Two dot products followed by bias addition.
| hidden | column 0 |
|---|---|
| 0 | |
| 1 |
a
hidden=2 × column=1. IV-14 manual record; unchanged IV-09 mathematics. Elementwise ReLU(z).
| hidden | column 0 |
|---|---|
| 0 | |
| 1 |
slopes
hidden=2 × column=1. IV-14 manual record; unchanged IV-09 mathematics. Selected ReLU slopes: 1 for positive z, otherwise 0; undefined derivative at zero.
| hidden | column 0 |
|---|---|
| 0 | |
| 1 |
dV
readout=1 × hidden=2. IV-14 manual record; unchanged IV-09 mathematics. error*a transpose; same shape as v.
| readout | hidden 0 | hidden 1 |
|---|---|---|
| 0 |
dZ
hidden=2 × column=1. IV-14 manual record; unchanged IV-09 mathematics. dA elementwise selected slopes.
| hidden | column 0 |
|---|---|
| 0 | |
| 1 |
dW
hidden=2 × input=2. IV-14 manual record; unchanged IV-09 mathematics. Outer product dZ*x transpose; same axes as W.
| hidden | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
dB
hidden=2 × column=1. IV-14 manual record; unchanged IV-09 mathematics. Bias derivative equals dZ.
| hidden | column 0 |
|---|---|
| 0 | |
| 1 |
dX
input=2 × column=1. IV-14 manual record; unchanged IV-09 mathematics. W transpose times dZ, accumulating hidden axis.
| input | column 0 |
|---|---|
| 0 | |
| 1 |
Optional framework report
No framework runs in this page. Choose a local JSON report only after a separate optional Torch run. Producer metadata is a claim supplied by the file, not proof of execution.
The complete twelve inputs must match exactly. Editing any input or using Reset example clears the comparison, even if you later restore the same numbers. Reimport to compare again. The file stays local to this page.
NOT RUN — No current framework comparison is available.
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 · IV-14 manual record; unchanged IV-09 mathematics. Authored input column.
| Storage index | Value |
|---|---|
| 0 | 2 |
| 1 | -1 |
W
hidden=2 × input=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Column-map weights: z=W*x+b.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | -0.5 |
| 3 | 1 |
WTranspose
input=2 × hidden=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Explicit transpose of W, used for dX.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | -0.5 |
| 2 | 0.5 |
| 3 | 1 |
b
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. One bias for each hidden neuron; no batch broadcast.
| Storage index | Value |
|---|---|
| 0 | 0.25 |
| 1 | 2.5 |
z
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Two dot products followed by bias addition.
| Storage index | Value |
|---|---|
| 0 | 1.75 |
| 1 | 0.5 |
a
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Elementwise ReLU(z).
| Storage index | Value |
|---|---|
| 0 | 1.75 |
| 1 | 0.5 |
slopes
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Selected ReLU slopes: 1 for positive z, otherwise 0; undefined derivative at zero.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
v
readout=1 × hidden=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Readout row: prediction=v*a+c.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | -1 |
dV
readout=1 × hidden=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. error*a transpose; same shape as v.
| Storage index | Value |
|---|---|
| 0 | -0.65625 |
| 1 | -0.1875 |
dA
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. v transpose times error.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | 0.375 |
dZ
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. dA elementwise selected slopes.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | 0.375 |
dW
hidden=2 × input=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Outer product dZ*x transpose; same axes as W.
| Storage index | Value |
|---|---|
| 0 | -0.375 |
| 1 | 0.1875 |
| 2 | 0.75 |
| 3 | -0.375 |
dB
hidden=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Bias derivative equals dZ.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | 0.375 |
dXContributions
input=2 × hidden=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Each input row sums its two hidden-neuron contributions.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | -0.1875 |
| 2 | -0.09375 |
| 3 | 0.375 |
dX
input=2 × column=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. W transpose times dZ, accumulating hidden axis.
| Storage index | Value |
|---|---|
| 0 | -0.375 |
| 1 | 0.28125 |
outputJacobian
prediction=1 × input=2 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. v*diag(slopes)*W; selected convention at a kink.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | -0.75 |
lossSeed
seed_row=1 × prediction=1 · float64 · display precision 8 · IV-14 manual record; unchanged IV-09 mathematics. Half-square prediction adjoint; no feature divisor.
| Storage index | Value |
|---|---|
| 0 | -0.375 |
Reset, then try b1=0.5 to block hidden neuron 1, or b1=2 to reach its ReLU kink. The full manual lesson and all five exercises work without Torch or a report.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Seek forward_hidden_0, reverse_hidden_0, outer_01 and input_1 to connect a forward product with its backward factor. Reset restores all twelve fields and clears the optional comparison. Editing also clears it, even if you subsequently restore the old numbers. For independent numerical differences and their limitations, review IV-11 — Gradient Checking and Kinks.
Identify exactly what is being differentiated
A computational graph records operations and their dependencies. A gradient collects the loss sensitivities to the coordinates of one variable. It is a derivative at the current values, not an instruction that has already changed the parameters. Automatic differentiation, often shortened to autodiff, applies local derivative rules to the recorded graph. Reverse mode starts at one scalar loss and propagates sensitivities toward its inputs using the chain rule.
Our two input coordinates form one column , shape [2,1]. They are features of one example, not a batch. A tensor is an array with declared dimensions; a scalar has just one numerical value. The hidden weight matrix is , with hidden neurons in rows and input coordinates in columns. Bias adds one scalar to each hidden neuron. The readout combines hidden activations into a scalar, with bias . The target is fixed scalar data.
The exact default parameters are
A superscript means transpose, exchanging rows and columns. The forward equations are , , , , and . The symbols mean preactivations, activations, prediction, signed error and half-square loss. ReLU keeps positive values and replaces negative ones with zero. There is one loss, with no averaging over hidden neurons.
All twelve scalar fields are required finite numbers between and . Dimensions remain fixed. The program reports invalid input instead of supplying a missing field, coercing a string or silently clipping an out-of-range value. An imported report has to describe this same complete state.
Finish the forward arithmetic before trusting a backward result
Expand each hidden dot product before adding bias:
Both preactivations are positive, so . The readout and loss are
These fractions are exact mathematical values. The page’s numbers are stored binary64 evaluations. Binary64, also called float64 here, gives a 53-bit significand; it represents these power-of-two fractions exactly, while arbitrary decimal edits may round. Displaying more decimal digits does not turn an approximate value into an exact fraction.
Checking the forward result first avoids a common mistake: matching gradients from two programs that happened to implement the same wrong objective. A framework loss of , for example, would suggest an omitted half factor before we even inspect the gradients.
Derive the full manual gradient record
The loss seed is . A local derivative says how an operation’s output changes when one operand changes while the others are held fixed. For the readout product, those local factors are the other operands:
The prefix d in these code names means a loss derivative. Both ReLU slopes are one at the default, so and . The hidden weight derivative keeps the same axes as its parameter:
Each input is used by both hidden neurons, so its derivative adds both paths:
Thus , a column of shape [2,1]. In the JSON report, gradients.x stores its two coordinates as a flat length-two array. Likewise b and v use flat length-two arrays, while W has two explicit rows. This serialization convention does not change the mathematical axes: is a readout row and is a hidden column.
The off-diagonal entries differ, so transposing the gradient is detectable. Checking just the loss or just one repeated value would miss this error. The report comparison includes prediction, loss, both input derivatives and every parameter derivative; it does not request a target derivative.
What a genuine framework reverse pass would do
A leaf tensor is an original tensor created for the calculation rather than the result of a recorded operation. In the optional source below, x, W, b, v and c are fresh float64 leaves with requires_grad=True. This tells Torch to track operations needed for their derivatives. The program forms the same explicit scalar products, uses actual torch.relu calls, constructs one half-square loss and calls loss.backward() once.
Backward reads the graph in reverse dependency order and accumulates the leaf results in .grad. It does not change the leaf values. Intermediate tensors can participate in differentiation without having their .grad retained by default; absence of a displayed intermediate .grad is therefore different from a zero derivative. We read the original leaves, which are exactly the variables named in the report.
Accumulation matters in a training program. Reusing a leaf for another backward pass without clearing its existing gradient can add a new contribution to the old one. That might be intentional for a larger effective batch, but it is a different experiment from a single pass. This source avoids ambiguity by creating fresh leaves for every invocation and performing exactly one backward call. It neither assigns hand-computed .grad values nor imports the manual gradient engine.
At ReLU zero, the mathematical derivative is undefined: the left and right slopes differ. Our manual rule selects zero there, and the optional producer uses Torch’s ReLU operation with that selected backward convention. Matching selected values does not establish a classical derivative. Try b1=2 to reach the kink; use b1=0.5 to enter the genuinely inactive region instead. In that region hidden row one of vanishes, but the other neuron and readout bias can still have nonzero derivatives.
Read the actual sources, including dependencies
The first file is a transparent wrapper. The next two contain the actual reused NumPy mechanism and its validation, trace and JSON helpers. They are shown in full so delegation cannot hide a second implementation or an executable dependency.
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.
"""IV14: reuse the actual IV09 manual NumPy engine, without a second backward pass."""
from iv09 import DEFAULT_IV09, derive_iv09
from layer_reference import run
DEFAULT_IV14 = dict(DEFAULT_IV09)
def derive_iv14(state):
"""Expose the complete manual record; optional Torch reports are separate data."""
result = derive_iv09(state)
if result["status"] == "defined":
# Only explanatory provenance changes; no mathematical value is replaced.
for step in result["steps"]:
step["explanation"] = "IV-14 manual calculation, reused unchanged from IV-09. " + step["explanation"]
for item in result["tensors"]:
item["provenance"] = "IV-14 manual record; unchanged IV-09 mathematics. " + item["provenance"]
return result
if __name__ == "__main__":
run(derive_iv14, DEFAULT_IV14)
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=(",", ":")))
For the manual CLI, omitting the state argument selects defaults. A complete JSON object replaces the entire state; - reads that full object from standard input. Keep the files together so their local imports resolve. The optional file below has the same state interface but produces the framework report schema instead of a manual trace. It requires a separately available Torch installation; the core lesson does not.
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.
"""Optional IV14 report producer. No hand-derived gradient implementation is imported.
This source has not been run during the resource hold. Torch is optional and is
never a browser dependency. Keep the JSON report as a claim about a local run,
not as proof that this source or any particular machine executed it.
"""
import argparse
import json
import math
import sys
DEFAULT_IV14 = {"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}
def derive_iv14_torch(state):
"""Build fresh float64 leaves, one half-square loss, and call backward once."""
if type(state) is not dict or set(state) != set(DEFAULT_IV14):
raise ValueError("Use exactly the twelve IV09 scalar input fields.")
for key, value in state.items():
if type(value) not in (int, float) or not -20 <= value <= 20 or not math.isfinite(value):
raise ValueError(f"{key} must be a finite real number from -20 to 20.")
import torch # Optional local dependency, loaded only when explicitly requested.
s = state
# These are genuine leaf tensors. No .grad field is set by this program.
def leaf(values):
return torch.tensor(values, dtype=torch.float64, requires_grad=True)
x = leaf([[s["x0"]], [s["x1"]]])
W = leaf([[s["w00"], s["w01"]], [s["w10"], s["w11"]]])
b = leaf([[s["b0"]], [s["b1"]]])
v = leaf([[s["v0"], s["v1"]]])
c = leaf(s["c"])
# Expand the tiny dots in the declared order, preserving graph operations.
z0 = (W[0, 0] * x[0, 0] + W[0, 1] * x[1, 0]) + b[0, 0]
z1 = (W[1, 0] * x[0, 0] + W[1, 1] * x[1, 0]) + b[1, 0]
a0, a1 = torch.relu(z0), torch.relu(z1)
prediction = (v[0, 0] * a0 + v[0, 1] * a1) + c
error = prediction - s["y"] # Target is fixed data, not a gradient leaf.
loss = (error * error) / 2
loss.backward() # Exactly ONE reverse pass on a newly constructed graph.
def scalar(value):
number = float(value.detach().item())
if not math.isfinite(number):
raise ValueError("Framework output or gradient is nonfinite; no report emitted.")
return number
# Read actual accumulated .grad values from the fresh leaves.
for name, value in (("x", x), ("W", W), ("b", b), ("v", v), ("c", c)):
if value.grad is None:
raise ValueError(f"Torch did not produce leaf gradient {name}.")
return {"schema": "book-iv-autograd-v1", "model": "IV09-two-neuron-relu-half-square",
"dtype": "float64", "backwardPasses": 1,
"producer": {"library": "torch", "version": str(torch.__version__)},
"inputs": dict(s), "prediction": scalar(prediction), "loss": scalar(loss),
"gradients": {"x": [scalar(x.grad[d, 0]) for d in range(2)],
"W": [[scalar(W.grad[h, d]) for d in range(2)] for h in range(2)],
"b": [scalar(b.grad[h, 0]) for h in range(2)],
"v": [scalar(v.grad[0, h]) for h in range(2)], "c": scalar(c.grad)}}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("state", nargs="?", help="Complete JSON state, or '-' for stdin; omission uses defaults.")
args = parser.parse_args()
try:
state = json.load(sys.stdin) if args.state == "-" else json.loads(args.state) if args.state else dict(DEFAULT_IV14)
output = derive_iv14_torch(state)
except (ImportError, ValueError, OSError, RuntimeError, OverflowError) as error:
output = {"status": "unavailable", "reason": str(error)}
print(json.dumps(output, allow_nan=False, separators=(",", ":")))
if __name__ == "__main__":
main()
These are authored sources, not a record of execution. A missing optional dependency produces an unavailable response rather than a report pretending to contain gradients.
Import a report without confusing a claim with evidence
The labelled local file input accepts at most 64 KiB. It checks complete JSON, exact object keys, schema and model identity, float64, one declared backward pass, nonempty Torch version metadata, dense array shapes and finite real numbers. Booleans, strings, null cells and malformed rows are rejected. Every one of the twelve input values must equal the current manual input; matching just the weights is insufficient because target, biases and observed inputs also affect derivatives.
The status IMPORTED means the file passed these structural and state-binding checks. Producer metadata remains an unauthenticated claim. A user could edit a JSON file, so the page cannot prove which program produced it. A rejected or stale file contributes no values to the comparison. A numerical disagreement remains visible beside the manual value; neither side is overwritten to make agreement appear.
For a nonzero manual value, the illustrative budget is
where is the manual value and the imported value. The residual is . The factor 128 gives a modest margin for a few dozen scalar operations in this short, conditioned toy; it is not a universal error theorem. For an exactly zero manual value, the imported value must also be zero, with positive and negative zero treated equally. Even a tiny nonzero value is shown as a mismatch. Near cancellation, alternate evaluation orders deserve investigation rather than automatic blame or acceptance. Kinks require their separate mathematical explanation.
The independent exact arithmetic and the finite-difference reasoning from IV-11 remain essential authorities. Agreement on one state cannot prove every branch correct, authenticate execution or replace a derivation. The useful outcome is narrower: two separately specified calculations can expose a disagreement, and the full table tells us where to investigate.
Carry the distinction forward
Keep the forward problem, derivative convention and parameter axes explicit. Read leaf gradients as accumulated sensitivities, and distinguish a numerical report from proof of its provenance. A framework can check a complete hand derivation; it does not remove the need to understand it.
Next we will inspect longer chains, where repeated local factors can shrink or amplify gradients, and distinguish a penalty in the objective from separate parameter decay.