The neural notebook
← All chapters

IV-04 / Part I · Neural Network Foundations

A Trainable MLP Forward Pass

Evaluate two samples through an explicit two-neuron ReLU hidden layer and linear output without pretending the parameters were trained.

Review the ideas this chapter uses

One hidden unit gives one transformed feature. What changes when the hidden layer contains two units and the output combines them? We can answer without training anything: select every parameter explicitly, pass two small samples through the network, and inspect all intermediate values.

This network is trainable because its weights and biases could be adjusted by an optimizer. The current lab performs a forward pass only. Its parameters are self-authored toy values, with no claim that they were fitted or that their predictions are useful.

Compute it yourself

A trainable MLP, evaluated without training

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
w11
1
w12
-1
w21
0.5
w22
1
b1
0
b2
0.5
v1
1
v2
-2
c
0.25
prediction0-5.75
prediction1-1.75
hidden000
hidden013

prediction0 -5.75. prediction1 -1.75. hidden00 0. hidden01 3. Declare row samples and transpose weights. Two original column samples become two batch rows. Weight transposition is explicit.. rowWeight00 1. rowWeight01 0.5. rowWeight10 -1. rowWeight11 1

Declare row samples and transpose weights

X[s,d]=x_s[d,0]; W1_row[d,h]=W1_col[h,d]

Two original column samples become two batch rows. Weight transposition is explicit.

Inputs

x00
1
x01
2
x10
-1
x11
1
w11
1
w12
-1
w21
0.5
w22
1

Outputs

rowWeight00
1
rowWeight01
0.5
rowWeight10
-1
rowWeight11
1

Forward only: X → hidden affine → Z1 → ReLU → A1 → output affine → prediction. Selected operation: Declare row samples and transpose weights.

X: sample=2 × input_feature=2
sample indexinput_feature 0input_feature 1
012
1-11

Authored column samples explicitly arranged as rows.

W1_col: hidden_unit=2 × input_feature=2
hidden_unit indexinput_feature 0input_feature 1
01-1
10.51

Editable first-layer weights; not fitted.

Z1: sample=2 × hidden_unit=2
sample indexhidden_unit 0hidden_unit 1
0-13
1-21

Hidden preactivations before ReLU.

A1: sample=2 × hidden_unit=2
sample indexhidden_unit 0hidden_unit 1
003
101

Elementwise ReLU of Z1.

W2_col: output_feature=1 × hidden_unit=2
output_feature indexhidden_unit 0hidden_unit 1
01-2

Output weight row v1,v2; not fitted.

prediction: sample=2 × output_feature=1
sample indexoutput_feature 0
0-5.75
1-1.75

Linear outputs, with no parameter updates.

Inspect explicit transposes and bias broadcasts
W1_row: input_feature=2 × hidden_unit=2
input_feature indexhidden_unit 0hidden_unit 1
010.5
1-11

Explicit transpose of W1_col.

hidden_bias: hidden_unit=2 × column=1
hidden_unit indexcolumn 0
00
10.5

Hidden bias column: state b1,b2.

hidden_bias_batch: sample=2 × hidden_unit=2
sample indexhidden_unit 0hidden_unit 1
000.5
100.5

Named broadcast of hidden bias column.

W2_row: hidden_unit=2 × output_feature=1
hidden_unit indexoutput_feature 0
01
1-2

Explicit transpose of W2_col, same flat values.

output_bias: output_feature=1 × column=1
output_feature indexcolumn 0
00.25

Output bias c; distinct from state b2, a hidden bias.

output_bias_batch: sample=2 × output_feature=1
sample indexoutput_feature 0
00.25
10.25

Named broadcast of c across samples.

Inspect tensor shapes and full precision

All computed outputs

prediction0
-5.75
prediction1
-1.75
hidden00
0
hidden01
3

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_feature=2 · float64 · display precision 8 · Authored column samples explicitly arranged as rows.

Storage indexValue
01
12
2-1
31

W1_col

hidden_unit=2 × input_feature=2 · float64 · display precision 8 · Editable first-layer weights; not fitted.

Storage indexValue
01
1-1
20.5
31

W1_row

input_feature=2 × hidden_unit=2 · float64 · display precision 8 · Explicit transpose of W1_col.

Storage indexValue
01
10.5
2-1
31

hidden_bias

hidden_unit=2 × column=1 · float64 · display precision 8 · Hidden bias column: state b1,b2.

Storage indexValue
00
10.5

hidden_bias_batch

sample=2 × hidden_unit=2 · float64 · display precision 8 · Named broadcast of hidden bias column.

Storage indexValue
00
10.5
20
30.5

Z1

sample=2 × hidden_unit=2 · float64 · display precision 8 · Hidden preactivations before ReLU.

Storage indexValue
0-1
13
2-2
31

A1

sample=2 × hidden_unit=2 · float64 · display precision 8 · Elementwise ReLU of Z1.

Storage indexValue
00
13
20
31

W2_col

output_feature=1 × hidden_unit=2 · float64 · display precision 8 · Output weight row v1,v2; not fitted.

Storage indexValue
01
1-2

W2_row

hidden_unit=2 × output_feature=1 · float64 · display precision 8 · Explicit transpose of W2_col, same flat values.

Storage indexValue
01
1-2

output_bias

output_feature=1 × column=1 · float64 · display precision 8 · Output bias c; distinct from state b2, a hidden bias.

Storage indexValue
00.25

output_bias_batch

sample=2 × output_feature=1 · float64 · display precision 8 · Named broadcast of c across samples.

Storage indexValue
00.25
10.25

prediction

sample=2 × output_feature=1 · float64 · display precision 8 · Linear outputs, with no parameter updates.

Storage indexValue
0-5.75
1-1.75

orient.rowWeight00

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · orient: X[s,d]=x_s[d,0]; W1_row[d,h]=W1_col[h,d]

Storage indexValue
01

orient.rowWeight01

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · orient: X[s,d]=x_s[d,0]; W1_row[d,h]=W1_col[h,d]

Storage indexValue
00.5

orient.rowWeight10

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · orient: X[s,d]=x_s[d,0]; W1_row[d,h]=W1_col[h,d]

Storage indexValue
0-1

orient.rowWeight11

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · orient: X[s,d]=x_s[d,0]; W1_row[d,h]=W1_col[h,d]

Storage indexValue
01

broadcast-hidden.bias00

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-hidden: hiddenBiasBatch[s,h]=hiddenBias[h]

Storage indexValue
00

broadcast-hidden.bias01

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-hidden: hiddenBiasBatch[s,h]=hiddenBias[h]

Storage indexValue
00.5

broadcast-hidden.bias10

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-hidden: hiddenBiasBatch[s,h]=hiddenBias[h]

Storage indexValue
00

broadcast-hidden.bias11

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-hidden: hiddenBiasBatch[s,h]=hiddenBias[h]

Storage indexValue
00.5

hidden-dot-0-0-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-0-0: sum=priorSum+input*weight

Storage indexValue
01

hidden-dot-0-0-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-0-0: sum=priorSum+input*weight

Storage indexValue
01

hidden-dot-0-0-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-0-1: sum=priorSum+input*weight

Storage indexValue
0-2

hidden-dot-0-0-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-0-1: sum=priorSum+input*weight

Storage indexValue
0-1

hidden-relu-0-0.z

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-0-0: z=sum+bias; activation=max(0,z)

Storage indexValue
0-1

hidden-relu-0-0.activation

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-0-0: z=sum+bias; activation=max(0,z)

Storage indexValue
00

hidden-dot-0-1-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-1-0: sum=priorSum+input*weight

Storage indexValue
00.5

hidden-dot-0-1-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-1-0: sum=priorSum+input*weight

Storage indexValue
00.5

hidden-dot-0-1-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-1-1: sum=priorSum+input*weight

Storage indexValue
02

hidden-dot-0-1-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-0-1-1: sum=priorSum+input*weight

Storage indexValue
02.5

hidden-relu-0-1.z

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-0-1: z=sum+bias; activation=max(0,z)

Storage indexValue
03

hidden-relu-0-1.activation

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-0-1: z=sum+bias; activation=max(0,z)

Storage indexValue
03

hidden-dot-1-0-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-0-0: sum=priorSum+input*weight

Storage indexValue
0-1

hidden-dot-1-0-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-0-0: sum=priorSum+input*weight

Storage indexValue
0-1

hidden-dot-1-0-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-0-1: sum=priorSum+input*weight

Storage indexValue
0-1

hidden-dot-1-0-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-0-1: sum=priorSum+input*weight

Storage indexValue
0-2

hidden-relu-1-0.z

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-1-0: z=sum+bias; activation=max(0,z)

Storage indexValue
0-2

hidden-relu-1-0.activation

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-1-0: z=sum+bias; activation=max(0,z)

Storage indexValue
00

hidden-dot-1-1-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-1-0: sum=priorSum+input*weight

Storage indexValue
0-0.5

hidden-dot-1-1-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-1-0: sum=priorSum+input*weight

Storage indexValue
0-0.5

hidden-dot-1-1-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-1-1: sum=priorSum+input*weight

Storage indexValue
01

hidden-dot-1-1-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-dot-1-1-1: sum=priorSum+input*weight

Storage indexValue
00.5

hidden-relu-1-1.z

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-1-1: z=sum+bias; activation=max(0,z)

Storage indexValue
01

hidden-relu-1-1.activation

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · hidden-relu-1-1: z=sum+bias; activation=max(0,z)

Storage indexValue
01

broadcast-output.outputWeight0

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-output: W2_row[h,0]=W2_col[0,h]; outputBiasBatch[s,0]=c

Storage indexValue
01

broadcast-output.outputWeight1

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-output: W2_row[h,0]=W2_col[0,h]; outputBiasBatch[s,0]=c

Storage indexValue
0-2

broadcast-output.bias0

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-output: W2_row[h,0]=W2_col[0,h]; outputBiasBatch[s,0]=c

Storage indexValue
00.25

broadcast-output.bias1

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast-output: W2_row[h,0]=W2_col[0,h]; outputBiasBatch[s,0]=c

Storage indexValue
00.25

output-dot-0-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-0-0: sum=priorSum+activation*weight

Storage indexValue
00

output-dot-0-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-0-0: sum=priorSum+activation*weight

Storage indexValue
00

output-dot-0-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-0-1: sum=priorSum+activation*weight

Storage indexValue
0-6

output-dot-0-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-0-1: sum=priorSum+activation*weight

Storage indexValue
0-6

output-bias-0.prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-bias-0: prediction=sum+bias

Storage indexValue
0-5.75

output-dot-1-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-1-0: sum=priorSum+activation*weight

Storage indexValue
00

output-dot-1-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-1-0: sum=priorSum+activation*weight

Storage indexValue
00

output-dot-1-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-1-1: sum=priorSum+activation*weight

Storage indexValue
0-2

output-dot-1-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-dot-1-1: sum=priorSum+activation*weight

Storage indexValue
0-2

output-bias-1.prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · output-bias-1: prediction=sum+bias

Storage indexValue
0-1.75

Change one input, then a shared weight. Follow each feature product separately. The two bias controls b1,b2 both belong to hidden units; c alone is the output bias.

Check your understanding

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

1. Current first prediction=-5.75. What does “trainable” establish here?
2. Sample 0, hidden unit 0 has preactivation -1. What is its ReLU activation?
3. Follow both hidden products for sample 0, then add c=0.25. What is its output?
4. You currently use w11=1. What does editing this shared hidden weight affect?
5. Current outputs are -5.75 and -1.75. Which statement about their signs is valid?

Start with the displayed negative predictions. ReLU did run: it constrained the hidden activations, not the final linear output. Change one input and compare the two sample rows. Then change a shared weight and inspect why different samples need not respond equally.

What makes this a multilayer perceptron?

A multilayer perceptron, or MLP, combines affine transformations and activation functions. Here the first layer reads two input features and produces two hidden preactivations. ReLU transforms each hidden value independently. A second affine layer combines the two hidden activations into one output.

The word hidden identifies an intermediate representation rather than a secret calculation. Its values should be inspectable. We write the first-layer preactivation tensor as Z1Z_1 and its activation tensor as A1A_1. The final prediction is y^\hat y. There is no target in this chapter, so there is no loss, gradient or optimizer step.

The two original column samples are

x0=[12],x1=[−11].x_0=\begin{bmatrix}1\\2\end{bmatrix},\qquad x_1=\begin{bmatrix}-1\\1\end{bmatrix}.

Each has shape [2,1][2,1]: two feature rows and one sample column. For batch evaluation we explicitly arrange them as X=[[1,2],[−1,1]]X=[[1,2],[-1,1]], with shape [2,2][2,2] and axes sample,input_feature. Equal dimensions do not make the axes interchangeable.

Give every parameter an owner

The hidden layer has column-convention weights and a bias column:

W1,col=[1−11/21],bhidden=[01/2].W_{1,\mathrm{col}}=\begin{bmatrix}1&-1\\1/2&1\end{bmatrix}, \qquad b_{\mathrm{hidden}}=\begin{bmatrix}0\\1/2\end{bmatrix}.

Each weight row belongs to one hidden unit; its two columns specify how that unit reads the two input features. The four scalar controls w11,w12,w21,w22 follow those row/column positions. Control names use familiar one-based matrix subscripts, while sample and unit indices in trace labels start at zero.

The controls b1 and b2 are the two hidden-unit biases. They do not mean the bias of layer one and the bias of layer two. The inspector therefore names the whole vector hidden_bias. Its broadcast copy is hidden_bias_batch. The output bias is the separate control c, stored as tensor output_bias; its batch copy is output_bias_batch.

Output weights are W2,col=[[1,−2]]:[1,2]W_{2,\mathrm{col}}=[[1,-2]]:[1,2], controlled by v1,v2, and c=1/4c=1/4. There are four hidden weights, two hidden biases, two output weights and one output bias: nine parameters shared by both samples. The four input values are data, not extra trainable weights.

Orient and broadcast before multiplying

For row samples, transpose the hidden weights:

W1,row=W1,colT=[11/2−11].W_{1,\mathrm{row}}=W_{1,\mathrm{col}}^\mathsf T =\begin{bmatrix}1&1/2\\-1&1\end{bmatrix}.

The first affine operation is

Z1=XW1,row+bhidden,batch.Z_1=XW_{1,\mathrm{row}}+b_{\mathrm{hidden,batch}}.

Both XW1,rowXW_{1,\mathrm{row}} and the explicitly broadcast bias have shape [2,2][2,2] with axes sample,hidden_unit. Broadcasting repeats the same hidden bias pair into each sample row; it does not invent four independent biases. The transpose and broadcast are their own named trace operations.

After ReLU, A1A_1 retains shape [2,2][2,2]. The output weights transpose from [1,2][1,2] into [2,1][2,1]. Multiplication A1W2,rowA_1W_{2,\mathrm{row}} therefore contracts the hidden-unit axis and produces shape [2,1][2,1], one output per sample. Adding the repeated scalar bias cc is explicitly another sample-axis broadcast.

All shapes in this lab are constructed from the declared scalar fields. It does not accept a second, hidden arbitrary-matrix input API. Array-valued or nonfinite scalar fields are invalid, and every tensor record verifies its actual dimensions and flat storage.

Evaluate the first sample by hand

For x0=(1,2)x_0=(1,2), hidden unit zero computes its products before adding its bias:

z00=(1)(1)+(2)(−1)+0=1−2=−1.z_{00}=(1)(1)+(2)(-1)+0=1-2=-1.

Hidden unit one reads the same sample through a different weight row:

z01=(1)(1/2)+(2)(1)+1/2=1/2+2+1/2=3.z_{01}=(1)(1/2)+(2)(1)+1/2=1/2+2+1/2=3.

Apply ReLU elementwise: a00=max⁡(0,−1)=0a_{00}=\max(0,-1)=0 and a01=max⁡(0,3)=3a_{01}=\max(0,3)=3. “Elementwise” means each entry is transformed separately, without summing rows or mixing neurons. Rectifying individual products before completing a weighted sum would give a different network.

The output is linear:

y^0=(0)(1)+(3)(−2)+1/4=−6+1/4=−234.\hat y_0=(0)(1)+(3)(-2)+1/4=-6+1/4=-\frac{23}{4}.

A hidden activation of three contributes negative six because its output weight is negative two. Thus nonnegative hidden values do not force the final output to be nonnegative. A final ReLU would change the specified architecture; we do not silently add one to make the prediction look more familiar.

Evaluate the second sample independently

For x1=(−1,1)x_1=(-1,1), the hidden products and biases give

z10=(−1)(1)+(1)(−1)+0=−2,z_{10}=(-1)(1)+(1)(-1)+0=-2, z11=(−1)(1/2)+(1)(1)+1/2=1.z_{11}=(-1)(1/2)+(1)(1)+1/2=1.

Its hidden activation row is (0,1)(0,1). The output becomes

y^1=(0)(1)+(1)(−2)+1/4=−74.\hat y_1=(0)(1)+(1)(-2)+1/4=-\frac74.

Collecting both samples makes the full intermediate record explicit:

Z1=[−13−21],A1=[0301],Y^=[−23/4−7/4].Z_1=\begin{bmatrix}-1&3\\-2&1\end{bmatrix},\qquad A_1=\begin{bmatrix}0&3\\0&1\end{bmatrix},\qquad \hat Y=\begin{bmatrix}-23/4\\-7/4\end{bmatrix}.

These are exact dyadic fractions for the default authored inputs. The repeated use of a weight across samples is visible, but no operation has combined the samples themselves. Each row’s prediction depends on its own input row and the shared parameters.

An edit can be real without changing the output

At the default point, hidden unit zero is inactive for both samples. Editing its output weight v1 alone therefore does not change either prediction: both corresponding products still multiply zero. This is not a fake control; it is a consequence of the current activation state. Changing a hidden bias enough can activate that path and make the weight relevant again.

As another experiment, change only sample zero’s first input from one to two. Its second hidden preactivation becomes 1+2+1/2=7/21+2+1/2=7/2, while its first becomes zero. Its new prediction is −7+1/4=−27/4-7+1/4=-27/4. Sample one’s prediction remains −7/4-7/4 because its input row was unchanged. A shared weight edit, in contrast, enters both rows, although a ReLU can still hide its effect in one of them.

This is why “the parameter changed” and “every displayed output changed” are different claims. Neither claim implies training. Training would additionally need a target, objective, parameter gradients and a disclosed update rule. Hand editing can explore the function without constituting a learned optimization history.

Follow the reference loops

The Python reference first builds the sample rows, explicit transposes and named bias copies. It then loops over samples, hidden units and features. Every product and partial sum is finite-checked. Only after completing a dot product does it add the relevant bias and apply ReLU. A separate output loop combines the resulting hidden activations.

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.

"""IV-04: two row samples through an explicit 2 -> 2 ReLU -> 1 forward pass."""
import numpy as np
from reference import validate, finite, guarded, tensor, step, result, run

DEFAULT_IV04 = {"x00": 1, "x01": 2, "x10": -1, "x11": 1, "w11": 1, "w12": -1,
                "w21": 0.5, "w22": 1, "b1": 0, "b2": 0.5, "v1": 1, "v2": -2, "c": 0.25}


@guarded
def derive_iv04(state):
    """Trainable parameters are editable, but no training is performed."""
    s = validate(state, DEFAULT_IV04)
    X = np.array([[s["x00"], s["x01"]], [s["x10"], s["x11"]]], dtype=np.float64)
    W1col = np.array([[s["w11"], s["w12"]], [s["w21"], s["w22"]]], dtype=np.float64)
    W1row = W1col.T.copy()
    hiddenBias = np.array([s["b1"], s["b2"]], dtype=np.float64)
    hiddenBiasBatch = np.array([hiddenBias, hiddenBias], dtype=np.float64)
    W2col = np.array([[s["v1"], s["v2"]]], dtype=np.float64)
    W2row = W2col.T.copy()
    outputBiasBatch = np.array([s["c"], s["c"]], dtype=np.float64)
    steps = [
        step("orient", "Declare row samples and transpose weights", "X[s,d]=x_s[d,0]; W1_row[d,h]=W1_col[h,d]", "Convert sample columns to rows; transpose weights.", {key: s[key] for key in ["x00", "x01", "x10", "x11", "w11", "w12", "w21", "w22"]}, {"rowWeight00": s["w11"], "rowWeight01": s["w21"], "rowWeight10": s["w12"], "rowWeight11": s["w22"]}),
        step("broadcast-hidden", "Broadcast hidden biases across samples", "hiddenBiasBatch[s,h]=hiddenBias[h]", "Repeat the two hidden biases across samples.", {"b1": s["b1"], "b2": s["b2"]}, {"bias00": s["b1"], "bias01": s["b2"], "bias10": s["b1"], "bias11": s["b2"]}),
    ]
    Z1 = np.empty((2, 2), dtype=np.float64)
    A1 = np.empty((2, 2), dtype=np.float64)
    for sample in range(2):
        for hidden in range(2):
            total = np.float64(0)
            for feature in range(2):
                inputValue, weight = X[sample, feature], W1row[feature, hidden]
                product = finite(inputValue * weight, "hidden product")
                priorSum = total
                total = finite(priorSum + product, "hidden sum")
                steps.append(step(f"hidden-dot-{sample}-{hidden}-{feature}", f"Hidden dot: sample {sample}, unit {hidden}, feature {feature}", "sum=priorSum+input*weight", "Accumulate features in index order.", {"input": inputValue, "weight": weight, "priorSum": priorSum}, {"product": product, "sum": total}))
            bias = hiddenBiasBatch[sample, hidden]
            z = finite(total + bias, "hidden preactivation")
            activation = finite(np.float64(z if z > 0 else 0), "hidden activation")
            Z1[sample, hidden], A1[sample, hidden] = z, activation
            steps.append(step(f"hidden-relu-{sample}-{hidden}", f"Hidden bias and ReLU: sample {sample}, unit {hidden}", "z=sum+bias; activation=max(0,z)", "Apply ReLU after bias.", {"sum": total, "bias": bias}, {"z": z, "activation": activation}))
    steps.append(step("broadcast-output", "Transpose output weights and broadcast output bias", "W2_row[h,0]=W2_col[0,h]; outputBiasBatch[s,0]=c", "One output reads both hidden features.", {"v1": s["v1"], "v2": s["v2"], "c": s["c"]}, {"outputWeight0": s["v1"], "outputWeight1": s["v2"], "bias0": s["c"], "bias1": s["c"]}))
    predictions = np.empty((2, 1), dtype=np.float64)
    for sample in range(2):
        total = np.float64(0)
        for hidden in range(2):
            activation, weight = A1[sample, hidden], W2row[hidden, 0]
            product = finite(activation * weight, "output product")
            priorSum = total
            total = finite(priorSum + product, "output sum")
            steps.append(step(f"output-dot-{sample}-{hidden}", f"Output dot: sample {sample}, hidden {hidden}", "sum=priorSum+activation*weight", "Linear output, no output activation.", {"activation": activation, "weight": weight, "priorSum": priorSum}, {"product": product, "sum": total}))
        bias = outputBiasBatch[sample]
        prediction = finite(total + bias, "prediction")
        predictions[sample, 0] = prediction
        steps.append(step(f"output-bias-{sample}", f"Output bias: sample {sample}", "prediction=sum+bias", "No parameter update is performed.", {"sum": total, "bias": bias}, {"prediction": prediction}))
    tensors = [tensor("X", [2, 2], ["sample", "input_feature"], X.ravel(), "Authored samples as rows."),
               tensor("W1_col", [2, 2], ["hidden_unit", "input_feature"], W1col.ravel(), "Editable first-layer weights."),
               tensor("W1_row", [2, 2], ["input_feature", "hidden_unit"], W1row.ravel(), "Explicit transpose."),
               tensor("hidden_bias", [2, 1], ["hidden_unit", "column"], hiddenBias, "State b1,b2, both hidden biases."),
               tensor("hidden_bias_batch", [2, 2], ["sample", "hidden_unit"], hiddenBiasBatch.ravel(), "Explicit sample broadcast."),
               tensor("Z1", [2, 2], ["sample", "hidden_unit"], Z1.ravel(), "Preactivations."),
               tensor("A1", [2, 2], ["sample", "hidden_unit"], A1.ravel(), "ReLU activations."),
               tensor("W2_col", [1, 2], ["output_feature", "hidden_unit"], W2col.ravel(), "State v1,v2."),
               tensor("W2_row", [2, 1], ["hidden_unit", "output_feature"], W2row.ravel(), "Explicit transpose."),
               tensor("output_bias", [1, 1], ["output_feature", "column"], [s["c"]], "State c only."),
               tensor("output_bias_batch", [2, 1], ["sample", "output_feature"], outputBiasBatch, "Explicit sample broadcast."),
               tensor("prediction", [2, 1], ["sample", "output_feature"], predictions.ravel(), "Forward only, not fitted.")]
    return result(tensors, steps, {"prediction0": predictions[0, 0], "prediction1": predictions[1, 0], "hidden00": A1[0, 0], "hidden01": A1[0, 1]})


if __name__ == "__main__":
    run(derive_iv04, DEFAULT_IV04)
Read the validation and JSON helpers
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 serialization/validation helpers for the five standalone references.

Run each ivNN.py from its path; this sibling module is then on Python's import
path. This module supplies no neuron, matrix multiplication or loss algorithm.
"""
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):
    if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = np.float64(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not np.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def validate(state, defaults, bounds=None):
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "State must be a scalar-field object.")
    values = {}
    for key in defaults:
        minimum, maximum = (bounds or {}).get(key, (-100, 100))
        value = finite(state.get(key), key)
        if value < minimum or value > maximum:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {minimum} and {maximum}.")
        values[key] = value
    if any(key not in defaults for key in state):
        raise NumericalFault("INVALID_INPUT", "Only the declared scalar fields are supported.")
    return values


def choice(value, allowed, label):
    if not float(value).is_integer() or value not in allowed:
        raise NumericalFault("INVALID_INPUT", f"{label} must be one of {allowed}.")


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)}
        except (TypeError, AttributeError) as error:
            return {"status": "unavailable", "code": "UNAVAILABLE", "reason": str(error)}
    return call


def tensor(identifier, shape, axes, values, provenance):
    if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or any(not isinstance(axis, str) or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each axis uniquely.")
    count = 1
    for dimension in shape:
        if isinstance(dimension, bool) or not isinstance(dimension, int) or not 1 <= dimension <= 64:
            raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: invalid dimension.")
        count *= dimension
    if count > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: at most 4096 elements are supported.")
    if count != len(values):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match shape.")
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
            "values": [float(finite(value, identifier)) for value in values],
            "provenance": provenance, "precision": 8}


def step(identifier, label, equation, explanation, inputs, outputs, state=None):
    record = {"id": identifier, "label": label, "equation": equation, "explanation": explanation,
              "inputs": {key: float(value) for key, value in inputs.items()},
              "outputs": {key: float(finite(value, key)) for key, value in outputs.items()}}
    if state is not None:
        record["state"] = {key: float(value) for key, value in state.items()}
    return record


def result(tensors, steps, outputs):
    for operation in steps:
        for key, value in operation["outputs"].items():
            tensors.append(tensor(f'{operation["id"]}.{key}', [1, 1], ["scalar_row", "scalar_column"],
                                  [value], f'{operation["id"]}: {operation["equation"]}'))
    return {"status": "defined", "tensors": tensors, "steps": steps,
            "outputs": {key: float(value) for key, value in outputs.items()}}


def run(derive, defaults):
    """Later owner CLI: ivNN.py [complete JSON state | - for stdin]."""
    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=(",", ":")))

The helper file supplies records and bounded validation; it is not a neural-network engine. The reference uses no matrix training framework or autograd. All scalar controls are finite and bounded in magnitude by one hundred. Intermediate outputs are checked rather than clamped.

The five questions revisit trainable versus trained, a hidden activation, the real first prediction, parameter sharing, and negative output signs. Background on composing learned representations is available through the earlier composition chapter; the local prerequisites are tensor shapes and activations.

  • Samples share parameters while retaining separate activation rows.
  • Bias additions and nonlinearities occur at specified points in the computation.
  • A hidden ReLU does not constrain the sign of a later linear output.
  • Trainable architecture alone is not evidence of trained parameters.

We now have predictions but no rule for judging them. The next chapter supplies targets, task-specific losses and an explicit way to combine losses across samples.