IV-09 / Part II · Learning, Backpropagation and Optimization
Backpropagation Through a Multi-Neuron Layer
Differentiate one real loss through two hidden neurons, inspect the outer-product weight gradient, and accumulate input paths with an explicit transpose.
Review the ideas this chapter uses
A hidden layer can calculate several useful quantities from the same input. Each neuron has its own weights, yet all its outputs may contribute to one prediction and one loss. How should that single loss send feedback to all those weights? And when two neurons both use the same input, how do their effects combine?
We will answer with two input coordinates and two hidden neurons. The numbers are hand-set teaching inputs, not trained measurements. Edit a weight or bias below: the prediction, actual loss, local slopes and full gradients all recompute from the same calculation. There is no parameter update in this chapter.
One shared loss, two hidden neurons
These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.
Complete results from this trace’s starting inputs
Starting inputs for these results
- x0
- 2
- x1
- -1
- w00
- 1
- w01
- 0.5
- w10
- -0.5
- w11
- 1
- b0
- 0.25
- b1
- 2.5
- v0
- 0.5
- v1
- -1
- c
- 0.25
- y
- 1
loss 0.0703125. prediction 0.625. dX0 -0.375. dX1 0.28125. Hidden neuron 0: dot then bias. W rows enumerate hidden neurons; columns enumerate input coordinates. Bias is added after the two products.. z0Product0 2. z0Product1 -0.5. z0Dot 1.5. z0 1.75
Hidden neuron 0: dot then bias
z_h=W[h,0]*x0+W[h,1]*x1+b_h
W rows enumerate hidden neurons; columns enumerate input coordinates. Bias is added after the two products.
Inputs
- w0
- 1
- x0
- 2
- w1
- 0.5
- x1
- -1
- bias
- 0.25
Outputs
- z0Product0
- 2
- z0Product1
- -0.5
- z0Dot
- 1.5
- z0
- 1.75
Forward path
x → W dot products + b → z=[1.75, 0.5] → ReLU → a=[1.75, 0.5] → v dot product + c → prediction=0.625 → half-square loss=0.0703125
Reverse path
error=-0.375 → readout transpose → dA=[-0.1875, 0.375] → slopes=[1, 1] → dZ=[-0.1875, 0.375] → outer-product dW and accumulated dX
Hidden-layer shapes and completed gradients
These tables summarize the completed calculation from the starting inputs. The selected operation above shows its own stored operands and results. Table selectors use a tensor_ prefix, separate from the four primary summary outputs.
W
hidden=2 × input=2. Column-map weights: z=W*x+b.
| hidden | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
WTranspose
input=2 × hidden=2. Explicit transpose of W, used for dX.
| input | hidden 0 | hidden 1 |
|---|---|---|
| 0 | ||
| 1 |
dV
readout=1 × hidden=2. error*a transpose; same shape as v.
| readout | hidden 0 | hidden 1 |
|---|---|---|
| 0 |
dZ
hidden=2 × column=1. dA elementwise selected slopes.
| hidden | column 0 |
|---|---|
| 0 | |
| 1 |
dW
hidden=2 × input=2. Outer product dZ*x transpose; same axes as W.
| hidden | input 0 | input 1 |
|---|---|---|
| 0 | ||
| 1 |
dXContributions
input=2 × hidden=2. Each input row sums its two hidden-neuron contributions.
| input | hidden 0 | hidden 1 |
|---|---|---|
| 0 | ||
| 1 |
dX
input=2 × column=1. W transpose times dZ, accumulating hidden axis.
| input | column 0 |
|---|---|
| 0 | |
| 1 |
outputJacobian
prediction=1 × input=2. v*diag(slopes)*W; selected convention at a kink.
| prediction | input 0 | input 1 |
|---|---|---|
| 0 |
Inspect tensor shapes and full precision
All computed outputs
- loss
- 0.0703125
- prediction
- 0.625
- dX0
- -0.375
- dX1
- 0.28125
- x0
- 2
- x1
- -1
- w00
- 1
- w01
- 0.5
- w10
- -0.5
- w11
- 1
- b0
- 0.25
- b1
- 2.5
- v0
- 0.5
- v1
- -1
- c
- 0.25
- y
- 1
- z0Product0
- 2
- z0Product1
- -0.5
- z0Dot
- 1.5
- z0
- 1.75
- a0
- 1.75
- slope0
- 1
- z1Product0
- -1
- z1Product1
- -1
- z1Dot
- -2
- z1
- 0.5
- a1
- 0.5
- slope1
- 1
- predictionProduct0
- 0.875
- predictionProduct1
- -0.5
- predictionDot
- 0.375
- error
- -0.375
- errorSquare
- 0.140625
- dC
- -0.375
- dV0
- -0.65625
- dA0
- -0.1875
- dZ0
- -0.1875
- dB0
- -0.1875
- dW00
- -0.375
- dW01
- 0.1875
- dV1
- -0.1875
- dA1
- 0.375
- dZ1
- 0.375
- dB1
- 0.375
- dW10
- 0.75
- dW11
- -0.375
- dX0From0
- -0.1875
- dX0From1
- -0.1875
- jacobian0From0
- 0.5
- jacobian0From1
- 0.5
- jacobian0
- 1
- dX0ViaJacobian
- -0.375
- dX1From0
- -0.09375
- dX1From1
- 0.375
- jacobian1From0
- 0.25
- jacobian1From1
- -1
- jacobian1
- -0.75
- dX1ViaJacobian
- 0.28125
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
x
input=2 × column=1 · float64 · display precision 8 · Authored input column.
| Storage index | Value |
|---|---|
| 0 | 2 |
| 1 | -1 |
W
hidden=2 × input=2 · float64 · display precision 8 · 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 · 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 · 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 · 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 · Elementwise ReLU(z).
| Storage index | Value |
|---|---|
| 0 | 1.75 |
| 1 | 0.5 |
slopes
hidden=2 × column=1 · float64 · display precision 8 · 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 · Readout row: prediction=v*a+c.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | -1 |
dV
readout=1 × hidden=2 · float64 · display precision 8 · 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 · v transpose times error.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | 0.375 |
dZ
hidden=2 × column=1 · float64 · display precision 8 · dA elementwise selected slopes.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | 0.375 |
dW
hidden=2 × input=2 · float64 · display precision 8 · 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 · Bias derivative equals dZ.
| Storage index | Value |
|---|---|
| 0 | -0.1875 |
| 1 | 0.375 |
dXContributions
input=2 × hidden=2 · float64 · display precision 8 · 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 · 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 · 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 · Half-square prediction adjoint; no feature divisor.
| Storage index | Value |
|---|---|
| 0 | -0.375 |
Try b1=0.5 after reset to silence neuron 1. Then try b1=2 for its exact-zero preactivation. All twelve scalar fields are editable; dimensions stay fixed at two inputs and two hidden neurons. No optimizer changes the parameters.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Start with forward_hidden_0, then seek reverse_hidden_0, outer_01 and input_1. The operation panel explains the selected step; the tables summarize the completed calculation. Reset example restores every input. For a review of the scalar reverse pass, use IV-08 — One Training Step: Hand-Derived Backpropagation; matrix shapes are introduced in II.10 — Matrix × matrix as composition.
What the layer stores
A neuron here means a weighted sum, a bias addition and an activation function. A layer collects two such neurons using the same input. Its parameters are adjustable weights and biases. An activation is the value after applying the activation function. Our activation is ReLU, which keeps positive values and replaces negative values with zero.
We use mathematical columns. The input is : two coordinates of one sample, rather than two samples. A superscript means transpose, which exchanges rows and columns. The hidden weights and biases are
Row zero of belongs to hidden neuron zero; row one belongs to neuron one. Its columns identify input coordinates. Indexing begins at zero, so w01 means neuron zero’s weight on input one. The readout row combines both hidden activations into a scalar prediction, with readout bias . The desired scalar target is .
| Quantity | Shape | What the axes count |
|---|---|---|
[2,1] | input coordinate, column | |
[2,2] | hidden neuron, input coordinate | |
[2,1] | hidden neuron, column | |
[1,2] | readout, hidden neuron | |
| prediction, | scalar | one number each |
[2,2] | hidden neuron, input coordinate | |
[2,1] | input coordinate, column |
These dimensions are fixed. All twelve scalar controls accept finite values from through . A missing, malformed or out-of-range input is unavailable; the program does not silently insert defaults, reshape an input or clamp a value.
First compute the real prediction and loss
A preactivation, , is the weighted sum including bias, before ReLU. The forward calculation is
Here is named prediction in code, is error, and is loss. The half-square loss measures error magnitude without its sign. Its derivative with respect to prediction will preserve the signed error.
Expand the hidden rows in the order used by the program:
Both are positive, so and . The readout gives
Therefore , and
This is one scalar target. The two hidden neurons do not introduce a divisor of two into the objective. They are intermediate calculations, not two independently averaged examples.
A backward number measures sensitivity
Write for the loss derivative with respect to activation ; similarly, dW01 means . These code names denote derivatives, not tiny changes already made to the parameters. A gradient collects derivatives for all coordinates of a variable. It describes the local rate of loss change near the current inputs.
The chain rule multiplies sensitivities along a dependency path. Since and , the upstream prediction derivative is
This same number reaches every readout operand through its own local factor. For , that factor is ; for , it is ; for bias , it is one:
For example, . The second hidden activation receives a positive sensitivity because its negative readout weight multiplies the negative error: . A shared loss does not mean all its parameter derivatives have the same sign.
Pass through the local ReLU slopes
Away from zero, ReLU’s slope is one for positive preactivation and zero for negative preactivation. Define as this selected slope. Multiplication is coordinate by coordinate:
Both default slopes are one, so . Hidden bias enters its preactivation with local factor one, giving .
At exactly , ReLU has no unique derivative: approaching from the left gives slope zero and approaching from the right gives slope one. This program chooses backward value zero there. The choice is explicit and reproducible, but it does not establish differentiability. Later numerical gradient checks must exclude both a kink and a perturbation interval crossing one.
Why the weight gradient is an outer product
For a single weight , only preactivation directly contains that weight, multiplied by input . Thus
An outer product forms all pairwise products between a column and a row. Multiplying by fills four cells without summing either of the two meaningful axes:
The first row is . The second is . Each row preserves which hidden neuron received that sensitivity; each column preserves which input multiplied the weight. Consequently has the same hidden-by-input axes as . Replacing it with its transpose would assign derivatives to different parameters, even though both arrays happen to be square.
The repeated value in two cells is incidental. The off-diagonal derivatives and differ, so exchanging them is a detectable error. Always follow axes rather than guessing from a matrix’s visible size.
Inputs collect contributions from both neurons
An input coordinate is used in both hidden rows. Its loss derivative must therefore add both paths:
The explicit arithmetic is
In matrix notation, . The actual transpose is
Its rows now enumerate inputs and its columns enumerate hidden neurons. The inspector keeps W and WTranspose as distinct records. The dXContributions table places inputs in rows and neuron paths in columns, so each row’s sum is visible. Taking only the last neuron contribution would repeat the accumulation mistake from the earlier shared-node graph.
Input derivatives are useful when this layer is connected to an earlier layer. In an isolated supervised example, computing does not imply we should change observed input data. An optimizer’s choice of parameters to update is a separate matter.
Check the forward sensitivity before applying the loss seed
A Jacobian lists output derivatives with respect to input coordinates. Our prediction has one output, so its Jacobian is a row, shape [1,2]. Away from a ReLU kink,
The diagonal matrix places on its diagonal and zero elsewhere. At defaults both slopes are one:
Multiplying this row by prediction’s loss seed gives , the transpose of our input gradient column. This separates a property of the forward prediction from the loss attached to it. Changing only target leaves unchanged while changing the loss seed and generally .
The lab calculates both routes from unrounded operands. For arbitrary decimal controls, rearranged binary64 products can differ in their last bits; an algebraic identity is not a promise of bitwise equality for every evaluation order. At a kink, outputJacobian explicitly records the chosen backward convention rather than asserting that a classical Jacobian exists.
Silence one neuron without silencing the network
Reset and change only from to . Now , so and . Neuron zero is unchanged. Recompute the readout:
The new derivatives are
Notice the distinction between and : the readout is sensitive to a hypothetical activation change, but the locally inactive ReLU blocks changes arriving through its preactivation. A zero gradient for one parameter does not prove zero error, nor does it make every other derivative zero. Setting instead reaches the exact kink, where the declared selected-zero rule applies.
Read the actual NumPy program
The reference below stores true columns and matrices, names every dot product, and fills the outer product explicitly. W.T.copy() performs the input-by-hidden transpose. The loops are small enough to compare directly with the trace; they do not call an automatic differentiation framework. The helper validates input and packages the same numerical record for JSON output.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV09: two hidden ReLU neurons, one loss, explicit outer-product backward pass."""
import numpy as np
from layer_reference import finite, fixed_state, guarded, LayerTrace, tensor, run
DEFAULT_IV09 = {"x0": 2, "x1": -1, "w00": 1, "w01": 0.5, "w10": -0.5, "w11": 1,
"b0": 0.25, "b1": 2.5, "v0": 0.5, "v1": -1, "c": 0.25, "y": 1}
@guarded
def derive_iv09(state):
"""Use mathematical columns; preserve W[hidden,input] throughout backward."""
s = fixed_state(state, DEFAULT_IV09)
trace = LayerTrace(s)
o, add = trace.outputs, trace.add
x = np.array([[s["x0"]], [s["x1"]]], dtype=np.float64)
W = np.array([[s["w00"], s["w01"]], [s["w10"], s["w11"]]], dtype=np.float64)
b = np.array([[s["b0"]], [s["b1"]]], dtype=np.float64)
v = np.array([[s["v0"], s["v1"]]], dtype=np.float64)
z, a, slopes = np.zeros((2, 1)), np.zeros((2, 1)), np.zeros((2, 1))
for h in range(2):
# Two explicit dot products, then bias; no change of vector orientation.
p0 = finite(W[h, 0] * x[0, 0], "hidden product0")
p1 = finite(W[h, 1] * x[1, 0], "hidden product1")
dot = finite(p0 + p1, "hidden dot")
z[h, 0] = finite(dot + b[h, 0], "hidden bias addition")
add(f"forward_hidden_{h}", "z_h=W[h,0]*x0+W[h,1]*x1+b_h",
{"w0": W[h, 0], "x0": x[0, 0], "w1": W[h, 1], "x1": x[1, 0], "bias": b[h, 0]},
{f"z{h}Product0": p0, f"z{h}Product1": p1, f"z{h}Dot": dot, f"z{h}": z[h, 0]})
a[h, 0] = np.maximum(np.float64(0), z[h, 0])
# At zero this is a selected backward rule, not a mathematical derivative.
slopes[h, 0] = 1 if z[h, 0] > 0 else 0
add(f"relu_{h}", "a_h=max(0,z_h); slope_h=1 if z_h>0 else 0", {"z": z[h, 0]},
{f"a{h}": a[h, 0], f"slope{h}": slopes[h, 0]})
p0 = finite(v[0, 0] * a[0, 0], "output product0")
p1 = finite(v[0, 1] * a[1, 0], "output product1")
dot = finite(p0 + p1, "output dot")
add("forward_prediction", "prediction=v*a+c",
{"v0": s["v0"], "a0": o["a0"], "v1": s["v1"], "a1": o["a1"], "c": s["c"]},
{"predictionProduct0": p0, "predictionProduct1": p1, "predictionDot": dot,
"prediction": finite(dot + s["c"], "prediction")})
error = finite(o["prediction"] - s["y"], "error")
square = finite(error * error, "errorSquare")
add("forward_loss", "error=prediction-y; loss=error*error/2", {"prediction": o["prediction"], "y": s["y"]},
{"error": error, "errorSquare": square, "loss": finite(square / 2, "loss"), "dC": error})
dV, dA, dZ, dW = np.zeros((1, 2)), np.zeros((2, 1)), np.zeros((2, 1)), np.zeros((2, 2))
for h in range(2):
dV[0, h] = finite(error * a[h, 0], "dV")
dA[h, 0] = finite(error * v[0, h], "dA")
dZ[h, 0] = finite(dA[h, 0] * slopes[h, 0], "dZ")
add(f"reverse_hidden_{h}", "dV_h=error*a_h; dA_h=v_h*error; dZ_h=dA_h*slope_h; dB_h=dZ_h",
{"error": error, "a": a[h, 0], "v": v[0, h], "slope": slopes[h, 0]},
{f"dV{h}": dV[0, h], f"dA{h}": dA[h, 0], f"dZ{h}": dZ[h, 0], f"dB{h}": dZ[h, 0]})
for d in range(2):
# This is the outer product dZ*x.T, with no axis summed out.
dW[h, d] = finite(dZ[h, 0] * x[d, 0], "dW")
add(f"outer_{h}{d}", "dW[h,d]=dZ[h]*x[d]", {"dZ": dZ[h, 0], "x": x[d, 0]}, {f"dW{h}{d}": dW[h, d]})
WT = W.T.copy() # A real transpose, with input-by-hidden axes.
dX, J = np.zeros((2, 1)), np.zeros((1, 2))
contributions = np.zeros((2, 2))
for d in range(2):
from0 = finite(WT[d, 0] * dZ[0, 0], "input contribution0")
from1 = finite(WT[d, 1] * dZ[1, 0], "input contribution1")
contributions[d] = [from0, from1]
dX[d, 0] = finite(from0 + from1, "dX")
add(f"input_{d}", "dX[d]=W[0,d]*dZ0+W[1,d]*dZ1",
{"w0": W[0, d], "dZ0": dZ[0, 0], "w1": W[1, d], "dZ1": dZ[1, 0]},
{f"dX{d}From0": from0, f"dX{d}From1": from1, f"dX{d}": dX[d, 0]})
j0 = finite(finite(v[0, 0] * slopes[0, 0], "v0 slope0") * W[0, d], "Jacobian contribution0")
j1 = finite(finite(v[0, 1] * slopes[1, 0], "v1 slope1") * W[1, d], "Jacobian contribution1")
J[0, d] = finite(j0 + j1, "outputJacobian")
add(f"jacobian_{d}", "J[0,d]=v0*slope0*W[0,d]+v1*slope1*W[1,d]",
{"v0": s["v0"], "slope0": o["slope0"], "w0": W[0, d], "v1": s["v1"], "slope1": o["slope1"], "w1": W[1, d], "error": error},
{f"jacobian{d}From0": j0, f"jacobian{d}From1": j1, f"jacobian{d}": J[0, d],
f"dX{d}ViaJacobian": finite(error * J[0, d], "seeded Jacobian")})
def col(identifier, values, axis, provenance):
return tensor(identifier, [2, 1], [axis, "column"], values, provenance)
tensors = [col("x", x, "input", "Authored input column."),
tensor("W", [2, 2], ["hidden", "input"], W, "Column-map weights: z=W*x+b."),
tensor("WTranspose", [2, 2], ["input", "hidden"], WT, "Explicit transpose of W, used for dX."),
col("b", b, "hidden", "One bias for each hidden neuron; no batch broadcast."),
col("z", z, "hidden", "Two dot products followed by bias addition."),
col("a", a, "hidden", "Elementwise ReLU(z)."),
col("slopes", slopes, "hidden", "Selected ReLU slopes: 1 for positive z, otherwise 0; undefined derivative at zero."),
tensor("v", [1, 2], ["readout", "hidden"], v, "Readout row: prediction=v*a+c."),
tensor("dV", [1, 2], ["readout", "hidden"], dV, "error*a transpose; same shape as v."),
col("dA", dA, "hidden", "v transpose times error."),
col("dZ", dZ, "hidden", "dA elementwise selected slopes."),
tensor("dW", [2, 2], ["hidden", "input"], dW, "Outer product dZ*x transpose; same axes as W."),
col("dB", dZ, "hidden", "Bias derivative equals dZ."),
tensor("dXContributions", [2, 2], ["input", "hidden"], contributions, "Each input row sums its two hidden-neuron contributions."),
col("dX", dX, "input", "W transpose times dZ, accumulating hidden axis."),
tensor("outputJacobian", [1, 2], ["prediction", "input"], J, "v*diag(slopes)*W; selected convention at a kink."),
tensor("lossSeed", [1, 1], ["seed_row", "prediction"], [error], "Half-square prediction adjoint; no feature divisor.")]
return trace.result({"loss": o["loss"], "prediction": o["prediction"], "dX0": o["dX0"], "dX1": o["dX1"]}, tensors)
if __name__ == "__main__":
run(derive_iv09, DEFAULT_IV09)
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Small JSON/NumPy support for IV09–10; no autodiff and no implicit broadcasting.
Keep this file beside iv09.py and iv10.py. Both chapters display this exact source.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np
class ParseFault(ValueError):
"""Owned JSON syntax/profile failure, separate from numerical validation."""
_JSON_INT = int
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as error:
if type(error) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
# Reject bool (a Python int subclass), strings, complex values and nonfinite data.
if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
number = np.float64(value)
except (OverflowError, ValueError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not np.isfinite(number):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return number
def fixed_state(state, defaults):
if type(state) is not dict:
raise NumericalFault("INVALID_INPUT", "State must be a scalar-field object.")
values = {}
for key in defaults:
if key not in state:
raise NumericalFault("NONFINITE", f"{key} must be an own finite field.")
value = finite(state[key], key)
if value < -20 or value > 20:
raise NumericalFault("INVALID_INPUT", f"{key} must be between -20 and 20.")
values[key] = value
if any(key not in defaults for key in state):
raise NumericalFault("SHAPE_MISMATCH", "Only the declared fixed-width scalar fields are supported.")
return values
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return {"status": "unavailable", "code": error.code, "reason": str(error)}
except (OverflowError, FloatingPointError) as error:
return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
return call
def numbers(values):
return {key: float(finite(value, key)) for key, value in values.items()}
class LayerTrace:
def __init__(self, state):
self.outputs = numbers(state)
self.steps = []
def add(self, identifier, equation, inputs, values):
# Copy operands and results; a later loop iteration cannot rewrite a saved step.
inputs, values = numbers(inputs), numbers(values)
self.outputs.update(values)
self.steps.append({"id": identifier, "label": identifier, "equation": equation,
"explanation": equation, "inputs": inputs, "outputs": values})
def result(self, summary, tensors):
return {"status": "defined", "outputs": {**numbers(summary), **numbers(self.outputs)},
"steps": self.steps, "tensors": tensors}
def tensor(identifier, shape, axes, values, provenance):
# Shapes are lesson-owned constants. Convert only dense, finite NumPy real data.
array = np.asarray(values, dtype=np.float64)
if array.size != int(np.prod(shape)) or len(axes) != len(shape) or len(set(axes)) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match named dimensions.")
return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
"values": [float(finite(value, identifier)) for value in array.reshape(-1)],
"provenance": provenance, "precision": 8}
def run(derive, defaults):
"""CLI: no argument uses defaults; a full JSON object or '-' replaces all fields."""
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
else:
output = derive(state)
else:
state = dict(defaults)
output = derive(state)
print(json.dumps(output, allow_nan=False, separators=(",", ":")))
Keep both files together. No CLI argument selects defaults; a complete JSON object replaces the entire state, and - reads a complete object from standard input.
Carry these rules forward
The weight gradient is an outer product with the same axes as its parameter. The input gradient accumulates all hidden-neuron paths using a genuine transpose. Local activation slopes determine which paths transmit sensitivity, while the scalar loss supplies one upstream seed. Gradients describe local sensitivity; this example performs no learning step.
Next we will replace the scalar readout with a two-output affine map. That lets us distinguish a forward input direction from a reverse output seed, then see how shared parameter gradients add across samples.