The neural notebook
← All chapters

IV-32 / Part VII · Transformer Blocks

Position-Wise Feed-Forward Networks

Follow each token through shared affine weights, three ReLU hidden features and two output features, calculating every product without mixing token rows.

Review the ideas this chapter uses

Attention can bring information from several positions into one token’s vector. We also need a way to transform the features already at that position. A position-wise feed-forward network applies the same small neural network separately to each token. Sharing the recipe makes the parameters reusable; it does not combine the token rows.

Learning objective: Apply token-independent MLP operations using shared parameters. MLP means multilayer perceptron, a network that composes affine layers and a nonlinear activation.

Review IV-30 — Residual Connections and Gradient Paths for residual addition and IV-09 — Backpropagation Through a Multi-Neuron Layer for nonlinear activations. Book II’s II.9 — Matrix × vector and II.10 — Matrix × matrix as composition explain matrix products and composition; Book III’s III-41 — Composition and Learned Representations motivates composing transformations into representations. Here the weights are hand-set, editable numbers. No learning or parameter update is being performed.

Start with one editable token

Compute it yourself

Position-Wise Feed-Forward Networks

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
B
1
T
3
x000
3
x001
1
x010
2
x011
2
x020
-1
x021
1
x100
1
x101
-1
x110
0
x111
0
x120
-2
x121
3
f100
1
f101
0
f102
1
f110
0
f111
1
f112
-1
fb10
0
fb11
0
fb12
0
f200
0.5
f201
0
f210
0
f211
-0.5
f220
0.25
f221
0.25
fb20
0
fb21
0
f0002
f0010
f0101
f011-1
Input token rows X
FFN weights W1
FFN bias b1
FFN weights W2
FFN bias b2

f000 2. f001 0. f010 1. f011 -1. Validate all position-wise FFN inputs. All 31 stored fields are validated, including inactive token slots. The 17 parameters are shared across every batch and token; sharing does not mix forward token rows.. B 1. T 3. D 2. M 3

Validate all position-wise FFN inputs

D=2; M=3; F=ReLU(X W1+b1) W2+b2

All 31 stored fields are validated, including inactive token slots. The 17 parameters are shared across every batch and token; sharing does not mix forward token rows.

Inputs

B
1
T
3
x000
3
x001
1
x010
2
x011
2
x020
-1
x021
1
x100
1
x101
-1
x110
0
x111
0
x120
-2
x121
3
f100
1
f101
0
f102
1
f110
0
f111
1
f112
-1
fb10
0
fb11
0
fb12
0
f200
0.5
f201
0
f210
0
f211
-0.5
f220
0.25
f221
0.25
fb20
0
fb21
0

Outputs

B
1
T
3
D
2
M
3

One shared feed-forward network, separate token paths

FFN means feed-forward network: two affine layers with a nonlinearity between them. An affine layer multiplies by weights and adds a bias. Here D=2 input/output features expand to M=3 hidden features, then contract to D=2. ReLU, the rectified linear unit, keeps a positive preactivation and sets a nonpositive one to zero. M counts hidden features; it does not count attention heads.

Showing FFN batch 0, token 0, output 0. These selectors change only the view. The live exercise always uses batch 0, token 0, feature 0.

Selected trace operation: setup. Matching operation rows are marked current; every operation remains available in Calculation step above.

Saved ffn_output_0_0_0: hidden products 1.5, 0, 0.5 accumulate from zero to 1.5, 1.5, 2; adding bias 0 gives F[0,0,0]=2.

X: FFN input, batch 0

B=1 × T=3 × D=2 · float64 · precision 8. Active feature-last input rows; D=2.

X: FFN input, batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
031
122
2-11

W1: shared input-to-hidden weights

D=2 × HiddenFeature=3 · float64 · precision 8. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

W1: shared input-to-hidden weights; actual saved binary64 values without display rounding
Input featureHidden feature 0Hidden feature 1Hidden feature 2
0101
101-1

b1: shared hidden bias

HiddenFeature=3 · float64 · precision 8. Shared hidden bias, added after the two products.

b1: shared hidden bias; actual saved binary64 values without display rounding
Bias rowHidden feature 0Hidden feature 1Hidden feature 2
0000

First affine layer: each pair of products, sum, then bias

hidden affines for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput mInput x0Input x1Input w0Input w1Input biasResult product0Result product1Result sumResult preactivation
ffn_hidden_0_0_0000311003033
ffn_hidden_0_0_1001310100111
ffn_hidden_0_0_2002311-103-122

Z: preactivations, batch 0

B=1 × T=3 × HiddenFeature=3 · float64 · precision 8. Hidden preactivations X W1+b1; no batch or token mixing.

Z: preactivations, batch 0; actual saved binary64 values without display rounding
TokenHidden feature 0Hidden feature 1Hidden feature 2
0312
1220
2-11-2

ReLU: apply max(0,z) separately

ReLU for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput mInput preactivationResult activation
ffn_relu_0_0_000033
ffn_relu_0_0_100111
ffn_relu_0_0_200222

Hidden: activations, batch 0

B=1 × T=3 × HiddenFeature=3 · float64 · precision 8. ReLU(Z)=max(0,Z), before the second affine layer.

Hidden: activations, batch 0; actual saved binary64 values without display rounding
TokenHidden feature 0Hidden feature 1Hidden feature 2
0312
1220
2010

W2: shared hidden-to-output weights

HiddenFeature=3 × D=2 · float64 · precision 8. Shared hidden-to-output weights, f2{m}{d}.

W2: shared hidden-to-output weights; actual saved binary64 values without display rounding
Hidden featureOutput feature 0Output feature 1
00.50
10-0.5
20.250.25

b2: shared output bias

D=2 · float64 · precision 8. Shared output bias, added after all three running sums.

b2: shared output bias; actual saved binary64 values without display rounding
Bias rowOutput feature 0Output feature 1
000

Second affine layer: products and immediate running sums, bias last

output affines for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput h0Input w0Input h1Input w1Input h2Input w2Input biasResult product0Result product1Result product2Result running0Result running1Result running2Result sumResult value
ffn_output_0_0_000030.51020.2501.500.51.51.5222
ffn_output_0_0_1001301-0.520.2500-0.50.50-0.5000

F: outputs, batch 0

B=1 × T=3 × D=2 · float64 · precision 8. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

F: outputs, batch 0; actual saved binary64 values without display rounding
TokenOutput feature 0Output feature 1
020
11-1
20-0.5

Each row uses exactly the same W1,b1,W2,b2. Editing a token row cannot directly change another token's FFN output; editing a shared parameter can affect every row. ReLU can discard information, and equal outputs need not imply equal inputs. Outputs may be negative because the second affine layer has signed weights and bias.

Inspect tensor shapes and full precision

All computed outputs

f000
2
f001
0
f010
1
f011
-1
f020
0
f021
-0.5
B
1
T
3
M
3
pre000
3
pre001
1
pre002
2
pre010
2
pre011
2
pre012
0
pre020
-1
pre021
1
pre022
-2
h000
3
h001
1
h002
2
h010
2
h011
2
h012
0
h020
0
h021
1
h022
0
setup_B
1
setup_T
3
setup_D
2
setup_M
3
ffn_hidden_0_0_0_product0
3
ffn_hidden_0_0_0_product1
0
ffn_hidden_0_0_0_sum
3
ffn_hidden_0_0_0_preactivation
3
ffn_hidden_0_0_1_product0
0
ffn_hidden_0_0_1_product1
1
ffn_hidden_0_0_1_sum
1
ffn_hidden_0_0_1_preactivation
1
ffn_hidden_0_0_2_product0
3
ffn_hidden_0_0_2_product1
-1
ffn_hidden_0_0_2_sum
2
ffn_hidden_0_0_2_preactivation
2
ffn_hidden_0_1_0_product0
2
ffn_hidden_0_1_0_product1
0
ffn_hidden_0_1_0_sum
2
ffn_hidden_0_1_0_preactivation
2
ffn_hidden_0_1_1_product0
0
ffn_hidden_0_1_1_product1
2
ffn_hidden_0_1_1_sum
2
ffn_hidden_0_1_1_preactivation
2
ffn_hidden_0_1_2_product0
2
ffn_hidden_0_1_2_product1
-2
ffn_hidden_0_1_2_sum
0
ffn_hidden_0_1_2_preactivation
0
ffn_hidden_0_2_0_product0
-1
ffn_hidden_0_2_0_product1
0
ffn_hidden_0_2_0_sum
-1
ffn_hidden_0_2_0_preactivation
-1
ffn_hidden_0_2_1_product0
0
ffn_hidden_0_2_1_product1
1
ffn_hidden_0_2_1_sum
1
ffn_hidden_0_2_1_preactivation
1
ffn_hidden_0_2_2_product0
-1
ffn_hidden_0_2_2_product1
-1
ffn_hidden_0_2_2_sum
-2
ffn_hidden_0_2_2_preactivation
-2
ffn_relu_0_0_0_activation
3
ffn_relu_0_0_1_activation
1
ffn_relu_0_0_2_activation
2
ffn_relu_0_1_0_activation
2
ffn_relu_0_1_1_activation
2
ffn_relu_0_1_2_activation
0
ffn_relu_0_2_0_activation
0
ffn_relu_0_2_1_activation
1
ffn_relu_0_2_2_activation
0
ffn_output_0_0_0_product0
1.5
ffn_output_0_0_0_product1
0
ffn_output_0_0_0_product2
0.5
ffn_output_0_0_0_running0
1.5
ffn_output_0_0_0_running1
1.5
ffn_output_0_0_0_running2
2
ffn_output_0_0_0_sum
2
ffn_output_0_0_0_value
2
ffn_output_0_0_1_product0
0
ffn_output_0_0_1_product1
-0.5
ffn_output_0_0_1_product2
0.5
ffn_output_0_0_1_running0
0
ffn_output_0_0_1_running1
-0.5
ffn_output_0_0_1_running2
0
ffn_output_0_0_1_sum
0
ffn_output_0_0_1_value
0
ffn_output_0_1_0_product0
1
ffn_output_0_1_0_product1
0
ffn_output_0_1_0_product2
0
ffn_output_0_1_0_running0
1
ffn_output_0_1_0_running1
1
ffn_output_0_1_0_running2
1
ffn_output_0_1_0_sum
1
ffn_output_0_1_0_value
1
ffn_output_0_1_1_product0
0
ffn_output_0_1_1_product1
-1
ffn_output_0_1_1_product2
0
ffn_output_0_1_1_running0
0
ffn_output_0_1_1_running1
-1
ffn_output_0_1_1_running2
-1
ffn_output_0_1_1_sum
-1
ffn_output_0_1_1_value
-1
ffn_output_0_2_0_product0
0
ffn_output_0_2_0_product1
0
ffn_output_0_2_0_product2
0
ffn_output_0_2_0_running0
0
ffn_output_0_2_0_running1
0
ffn_output_0_2_0_running2
0
ffn_output_0_2_0_sum
0
ffn_output_0_2_0_value
0
ffn_output_0_2_1_product0
0
ffn_output_0_2_1_product1
-0.5
ffn_output_0_2_1_product2
0
ffn_output_0_2_1_running0
0
ffn_output_0_2_1_running1
-0.5
ffn_output_0_2_1_running2
-0.5
ffn_output_0_2_1_sum
-0.5
ffn_output_0_2_1_value
-0.5

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

X

B=1 × T=3 × D=2 · float64 · display precision 8 · Active feature-last input rows; D=2.

Storage indexValue
03
11
22
32
4-1
51

W1

D=2 × HiddenFeature=3 · float64 · display precision 8 · Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

Storage indexValue
01
10
21
30
41
5-1

b1

HiddenFeature=3 · float64 · display precision 8 · Shared hidden bias, added after the two products.

Storage indexValue
00
10
20

Z

B=1 × T=3 × HiddenFeature=3 · float64 · display precision 8 · Hidden preactivations X W1+b1; no batch or token mixing.

Storage indexValue
03
11
22
32
42
50
6-1
71
8-2

Hidden

B=1 × T=3 × HiddenFeature=3 · float64 · display precision 8 · ReLU(Z)=max(0,Z), before the second affine layer.

Storage indexValue
03
11
22
32
42
50
60
71
80

W2

HiddenFeature=3 × D=2 · float64 · display precision 8 · Shared hidden-to-output weights, f2{m}{d}.

Storage indexValue
00.5
10
20
3-0.5
40.25
50.25

b2

D=2 · float64 · display precision 8 · Shared output bias, added after all three running sums.

Storage indexValue
00
10

F

B=1 × T=3 × D=2 · float64 · display precision 8 · ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Storage indexValue
02
10
21
3-1
40
5-0.5

Open Input token rows X or one of the FFN weight/bias groups to edit it. B and T remain visible; D=2 and M=3 are fixed. All 31 stored fields are validated, including inactive token rows. The native selectors inspect saved token paths without changing the calculation.

At reset the input rows are (3,1),(2,2),(-1,1). W1 maps them to preactivations (3,1,2),(2,2,0),(-1,1,-2). ReLU produces (3,1,2),(2,2,0),(0,1,0). W2 and b2 then give F=(2,0),(1,-1),(0,-0.5). These exact arithmetic values describe the reset example; the tables display the current saved values after edits.

For the first row, output 0 has products 1.5,0,0.5 and running sums 1.5,1.5,2, followed by bias 0. Output 1 has products 0,-0.5,0.5 and running sums 0,-0.5,0, followed by bias 0. The saved tables expose the same sequence for your current inputs. There is no residual addition, training, dropout or output probability distribution inside this FFN.

Check your understanding

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

1. What does position-wise mean in this feed-forward network (FFN)?
2. X has shape [B,T,2]. W1 is [2,3] and W2 is [3,2]. What are the hidden and final shapes?
3. Use the current starting inputs and saved ffn_output_0_0_0. Its three products are 1.5, 0, 0.5; running sums are 1.5, 1.5, 2; bias=0. What is F[0,0,0]?
4. With T≥2, hold every shared parameter and every other input fixed. Edit only x010 (batch 0, token 1, feature 0). What can happen?
5. Set every W2 entry and both b2 entries to zero. What does equality of outputs tell you about different input token rows?

Reset starts with one sequence of three rows: (3,1), (2,2), (−1,1). Inspect the first token’s three hidden features and two output features. Then change only x000, the first input feature of batch zero, token zero. That token’s path can change; the other token rows keep their own results. Reset, then change the shared hidden bias fb10: every active token uses that bias, although ReLU can hide its effect for some inputs.

B and T select how many stored batch/token rows participate. Open Input token rows X, FFN weights W1, FFN bias b1, FFN weights W2 or FFN bias b2 before editing entries; the fields also store a second batch for later inspection. Calculation-step navigation reads saved operands and results. Row selectors choose what you inspect; they do not select which rows compute. The five graded questions use their named coordinates even if you inspect another row.

What the words, symbols and shapes mean

A token is one position’s representation, here just a two-number row without attached text. A feature is one coordinate of that row. A tensor is an array with named axes: X has shape [B,T,D], where B counts sequences, T counts token positions and D=2 counts features. Lowercase b,t,d identify one index, starting at zero. Changing T changes the number of rows, not the width of a row.

FFN means feed-forward network: numbers pass through this calculation from input to output. MLP means multilayer perceptron, a network made from affine transformations separated by a nonlinearity. Affine means multiply by weights and add a bias. A weight controls an input contribution; a bias is an added offset even when the input is zero. Hidden names an intermediate feature, not a secret computation. Here M=3 counts hidden features; m identifies one of them. M is fixed and is distinct from the number of attention heads used in the next chapter.

ReLU, the rectified linear unit, keeps positive numbers and replaces negative numbers with zero: ReLU(z)=max(0,z). In particular ReLU(0)=0. This is a nonlinear operation: its rule changes at zero. The forward value at zero is unambiguous, although its ordinary derivative does not exist at zero. This chapter calculates only forward values.

RecordShape and axesMeaning
X[B,T,2], B,T,DInput token features
W1[2,3], D,HiddenFeatureTwo input contributions for each hidden feature
b1[3], HiddenFeatureThree shared hidden offsets
Z, Hidden[B,T,3], B,T,HiddenFeaturePreactivations, then ReLU activations
W2[3,2], HiddenFeature,DThree hidden contributions for each output
b2[2], DTwo shared output offsets
F[B,T,2], B,T,DFinal FFN output, before any residual addition

A preactivation z is the affine result before ReLU; its activation h is the result after ReLU. For a single row x=(x₀,x₁), first calculate z=xW1+b1, then h=ReLU(z), then f=hW2+b2. In full-array notation:

Z=XW1+b1,Hact=ReLU⁡(Z),F=HactW2+b2.Z=XW_1+b_1,\qquad H_{\mathrm{act}}=\operatorname{ReLU}(Z),\qquad F=H_{\mathrm{act}}W_2+b_2.

The symbol H_act means the Hidden tensor, not an attention-head count. W₁ and W₂ name the two matrices; b₁ and b₂ name their bias vectors, whereas lowercase b without a subscript indexes a batch. The first matrix product matches two input features; the second matches three hidden features. Biases are applied explicitly to each row, using the same three or two stored numbers every time.

These are row-vector weights. If you remember Book II’s column formula Wx+b, transpose the representation as well as the matrix: (xW1)ᵀ=W1ᵀxᵀ. A row-weight W1[2,3] corresponds to column-weight W1ᵀ[3,2]. Neither convention changes the underlying products.

Why expand, apply ReLU and contract?

The first layer creates three different feature combinations from two inputs. ReLU lets a combination contribute only when its preactivation is positive. The second layer can recombine these three activated features into two signed outputs. Without the nonlinearity, two affine layers collapse to one affine map: (xW1+b1)W2+b2=x(W1W2)+(b1W2+b2). ReLU prevents that collapse across activation changes. It does not guarantee a good representation; useful parameters normally require training elsewhere.

The scalar formulas make the lack of token mixing explicit:

zbtm=Xbt0W1,0m+Xbt1W1,1m+b1,m,hbtm=max⁡(0,zbtm),Fbtd=∑m=02hbtmW2,md+b2,d.z_{btm}=X_{bt0}W_{1,0m}+X_{bt1}W_{1,1m}+b_{1,m},\quad h_{btm}=\max(0,z_{btm}),\quad F_{btd}=\sum_{m=0}^{2}h_{btm}W_{2,md}+b_{2,d}.

The summation sign means add the three hidden contributions in ascending m order. It does not sum over t or b. Identical input rows therefore have identical outputs under identical shared parameters. Different input rows can also have identical outputs, because ReLU can discard information.

Work every default product by hand

The following are exact real arithmetic expressions from the hand-set example, not recorded execution output. Defaults use

W1=[10101−1],b1=(0,0,0),W2=[1200−121414],b2=(0,0).W_1=\begin{bmatrix}1&0&1\\0&1&-1\end{bmatrix},\quad b_1=(0,0,0),\qquad W_2=\begin{bmatrix}\tfrac12&0\\0&-\tfrac12\\\tfrac14&\tfrac14\end{bmatrix},\quad b_2=(0,0).

The first index of W1 identifies its input row, and its second identifies its hidden column. For example f102 stores W1[0,2]=1; f112 stores W1[1,2]=−1. The field f220 stores W2[2,0]=1/4. The fb1m and fb2d fields store the biases. These 6+3+6+2=17 parameters are shared across every active row.

First compute all hidden affines, then all ReLUs, then the outputs. Every hidden affine saves the two products, their sum and the result after bias. All rows below belong to batch zero.

Token t, hidden mproduct0product1sum+ bias → zReLU(z) → h
0,03·1=31·0=03+0=33+0=33
0,13·0=01·1=10+1=11+0=11
0,23·1=31·(−1)=−13−1=22+0=22
1,02·1=22·0=02+0=22+0=22
1,12·0=02·1=20+2=22+0=22
1,22·1=22·(−1)=−22−2=00+0=00
2,0(−1)·1=−11·0=0−1+0=−1−1+0=−10
2,1(−1)·0=01·1=10+1=11+0=11
2,2(−1)·1=−11·(−1)=−1−1−1=−2−2+0=−20

Thus Z rows are (3,1,2),(2,2,0),(−1,1,−2), and Hidden rows are (3,1,2),(2,2,0),(0,1,0). ReLU changes the last row’s negative values; it never normalizes the row or makes its coordinates sum to one.

For each output start a running sum at zero. Calculate product0 and add it immediately, then product1 and add it, then product2 and add it. Only afterward add the output bias. The recorded product fields and running fields below describe that order, even though they are grouped into columns for readability.

Token t, output dproduct0; running0product1; running1product2; running2 = sum+ b2d → F
0,03·1/2=3/2; 0+3/2=3/21·0=0; 3/2+0=3/22·1/4=1/2; 3/2+1/2=22+0=2
0,13·0=0; 0+0=01·(−1/2)=−1/2; 0−1/2=−1/22·1/4=1/2; −1/2+1/2=00+0=0
1,02·1/2=1; 0+1=12·0=0; 1+0=10·1/4=0; 1+0=11+0=1
1,12·0=0; 0+0=02·(−1/2)=−1; 0−1=−10·1/4=0; −1+0=−1−1+0=−1
2,00·1/2=0; 0+0=01·0=0; 0+0=00·1/4=0; 0+0=00+0=0
2,10·0=0; 0+0=01·(−1/2)=−1/2; 0−1/2=−1/20·1/4=0; −1/2+0=−1/2−1/2+0=−1/2

The three FFN rows are therefore (2,0), (1,−1), (0,−1/2). Notice that ReLU hidden features are nonnegative, yet the output can be negative because W2 contains negative weights. There is no output softmax (conversion to probabilities), residual addition or dropout (randomly omitting activations) in this isolated component.

Read the actual Python, from wrapper to scalar operations

The expandable source is imported directly from the maintained Python files. NumPy, the numerical-array library, stores explicitly shaped float64 arrays; scalar Python floats perform the ordered arithmetic. Float64, also called binary64, is a finite-precision number representation. Fractions above describe exact real values; the inspector shows stored floating-point values with display precision metadata that never feeds back into computation.

Read iv32.py first: it validates the full state, saves the setup record, constructs X and calls the shared FFN helper. In ffn_reference.py, follow the input shape boundary, parameter packing, hidden-affine loops, ReLU loops and output loops. Match x0,x1,w0,w1,bias to the first table; match h0,h1,h2 and product/running fields to the second. component_reference.py supplies finite checks, tensor records, detached trace storage and the wrapper’s unavailable-result boundary. It also contains residual/normalization helpers for neighboring chapters; this FFN does not secretly call a normalization.

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-32 — Position-Wise Feed-Forward Networks.

Prerequisites: IV-30 and IV-09. For EACH token, F=ReLU(X W1+b1) W2+b2,
with X[B,T,2], W1[2,3], b1[3], W2[3,2], b2[2]. M=3 is the hidden-feature
width, not a number of attention heads. Shared parameters do not mix tokens.

Hand default preactivations (3,1,2),(2,2,0),(-1,1,-2) become
(3,1,2),(2,2,0),(0,1,0). First output feature: products (1.5,0,.5),
running sums (1.5,1.5,2), then bias0 -> 2. Second: (0,-.5,.5),
running (0,-.5,0), then bias0 -> 0. Other token outputs are (1,-1),(0,-.5).
These are hand derivations, not executed output. ReLU can discard information;
equal outputs do not establish equal inputs. No residual or training here.
Keep ffn_reference.py and component_reference.py beside this wrapper.
Runtime validation remains deferred.
"""
from types import MappingProxyType
from component_reference import component_trace, guarded, run, tensor
from ffn_reference import FFN_DEFAULTS, feed_forward, ffn_state

DEFAULT_IV32 = MappingProxyType(dict(FFN_DEFAULTS))


@guarded
def derive_iv32(state):
    """Save the input, seven actual FFN tensors and every ordered scalar record."""
    s = ffn_state(state)
    B, T = s["B"], s["T"]
    trace = component_trace()
    trace.add("setup", "Validate the complete position-wise FFN state",
              "D=2; M=3; F=ReLU(X W1+b1) W2+b2",
              "Every inactive X field and every shared parameter is validated before selecting active tokens.",
              s, dict(B=B, T=T, D=2, M=3))
    X = tensor("X", [B, T, 2], ["B", "T", "D"],
               [s[f"x{b}{t}{d}"] for b in range(B) for t in range(T) for d in range(2)],
               "Active token rows; the two features of each token enter its own FFN path.")
    stage = feed_forward(s, X, trace)
    aliases = stage["aliases"]
    summary = {key: value for key, value in aliases.items() if key.startswith("f")}
    summary.update(B=B, T=T, M=3)
    summary.update({key: value for key, value in aliases.items() if not key.startswith("f")})
    return trace.result(summary, [X, *stage["tensors"]])


if __name__ == "__main__":
    run(derive_iv32, DEFAULT_IV32)
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.

"""Part VII position-wise FFN: actual NumPy storage, explicit float order.

D=2 input features -> M=3 hidden features -> D=2 output features. Parameters
are shared across tokens/batches; arithmetic never sums over token positions.
NumPy stores shaped float64 arrays, but every arithmetic operation below uses
Python floats, with finite checks and saved operands/results. No BLAS reduction,
broadcast, fused multiply-add, residual, dropout or output softmax is hidden.
Source only: this program has not been imported, executed or validated.
"""
from types import MappingProxyType
import numpy as np
from component_reference import NORM_DEFAULTS, NumericalFault, finite, tensor


FFN_PARAMETERS = MappingProxyType(dict(
    f100=1, f101=0, f102=1, f110=0, f111=1, f112=-1,
    fb10=0, fb11=0, fb12=0,
    f200=0.5, f201=0, f210=0, f211=-0.5, f220=0.25, f221=0.25,
    fb20=0, fb21=0,
))
FFN_DEFAULTS = MappingProxyType(dict(
    B=NORM_DEFAULTS["B"], T=NORM_DEFAULTS["T"],
    **{key: value for key, value in NORM_DEFAULTS.items() if key.startswith("x")},
    **FFN_PARAMETERS,
))


def ffn_state(state):
    """Validate all 31 exact own scalar fields, including inactive X slots."""
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(FFN_DEFAULTS):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    result = {}
    for key in FFN_DEFAULTS:
        value = finite(state[key], key)
        low, high = (1, 2) if key == "B" else (1, 3) if key == "T" else (-4, 4)
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in ("B", "T") and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in ("B", "T") else value
    return result


def feed_forward(s, input_record, trace, prefix="ffn"):
    """Return seven stage tensors and aliases; the caller owns input_record.

    This reusable kernel accepts finite derived inputs beyond raw [-4,4] bounds.
    It requires exact [B,T,2] dimensions/axes and finite values for all parameters.
    """
    dimensions = []
    for key, maximum in (("B", 2), ("T", 3)):
        value = finite(s.get(key), key)
        if not value.is_integer() or not 1 <= value <= maximum:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer between 1 and {maximum}.")
        dimensions.append(int(value))
    B, T = dimensions
    parameters = {key: finite(s.get(key), key) for key in FFN_PARAMETERS}
    if type(input_record) not in (dict, MappingProxyType) or input_record.get("dtype") != "float64":
        raise NumericalFault("INVALID_INPUT", "FFN input must be a float64 tensor.")
    checked = tensor(input_record.get("id"), input_record.get("shape"), input_record.get("axes"),
                     input_record.get("values"), input_record.get("provenance"))
    shape, axes = [B, T, 2], ["B", "T", "D"]
    if checked["shape"] != shape or checked["axes"] != axes:
        raise NumericalFault("SHAPE_MISMATCH", "FFN input needs exact [B,T,2] dimensions and B,T,D axes.")
    # NumPy holds real shaped storage; scalar float reads prevent reordered reductions.
    X = np.array(checked["values"], dtype=np.float64).reshape(shape)
    W1, b1 = np.empty((2, 3), dtype=np.float64), np.empty(3, dtype=np.float64)
    W2, b2 = np.empty((3, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
    for d in range(2):
        for m in range(3):
            W1[d, m] = parameters[f"f1{d}{m}"]
    for m in range(3):
        b1[m] = parameters[f"fb1{m}"]
        for d in range(2):
            W2[m, d] = parameters[f"f2{m}{d}"]
    for d in range(2):
        b2[d] = parameters[f"fb2{d}"]
    hidden_shape, hidden_axes = [B, T, 3], ["B", "T", "HiddenFeature"]
    Z, Hidden = np.empty(hidden_shape, dtype=np.float64), np.empty(hidden_shape, dtype=np.float64)
    F = np.empty(shape, dtype=np.float64)
    # Save ALL hidden affines before any activation, in ascending b/t/m order.
    for b in range(B):
        for t in range(T):
            for m in range(3):
                x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                w0, w1, bias = float(W1[0, m]), float(W1[1, m]), float(b1[m])
                product0 = finite(x0 * w0, "FFN hidden product0")
                product1 = finite(x1 * w1, "FFN hidden product1")
                summed = finite(product0 + product1, "FFN hidden sum")
                preactivation = finite(summed + bias, "FFN hidden preactivation")
                Z[b, t, m] = preactivation
                trace.add(f"{prefix}_hidden_{b}_{t}_{m}", f"Hidden affine [{b},{t},{m}]",
                          "product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
                          "The same input-to-hidden weights and bias are reused at every token; bias is added last.",
                          dict(b=b, t=t, m=m, x0=x0, x1=x1, w0=w0, w1=w1, bias=bias),
                          dict(product0=product0, product1=product1, sum=summed, preactivation=preactivation))
    for b in range(B):
        for t in range(T):
            for m in range(3):
                preactivation = float(Z[b, t, m])
                activation = finite(max(0.0, preactivation), "FFN ReLU")
                Hidden[b, t, m] = activation
                trace.add(f"{prefix}_relu_{b}_{t}_{m}", f"ReLU [{b},{t},{m}]",
                          "activation=max(0,preactivation)",
                          "ReLU keeps positive values and maps negative values and zero to zero; it is not a softmax.",
                          dict(b=b, t=t, m=m, preactivation=preactivation), dict(activation=activation))
    for b in range(B):
        for t in range(T):
            for d in range(2):
                inputs, products, running = dict(b=b, t=t, d=d), {}, {}
                summed = 0.0
                # Each product is immediately accumulated from zero; bias follows all three.
                for m in range(3):
                    h, w = float(Hidden[b, t, m]), float(W2[m, d])
                    inputs[f"h{m}"], inputs[f"w{m}"] = h, w
                    product = finite(h * w, "FFN output product")
                    products[f"product{m}"] = product
                    summed = finite(summed + product, "FFN output running sum")
                    running[f"running{m}"] = summed
                bias = float(b2[d])
                inputs["bias"] = bias
                value = finite(summed + bias, "FFN output")
                F[b, t, d] = value
                trace.add(f"{prefix}_output_{b}_{t}_{d}", f"FFN output [{b},{t},{d}]",
                          "product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
                          "Three hidden features are contracted in ascending order. No token sum, residual or output softmax is added.",
                          inputs, {**products, **running, "sum": summed, "value": value})
    aliases = {}
    for name, values, width in (("pre", Z, 3), ("h", Hidden, 3), ("f", F, 2)):
        for b in range(B):
            for t in range(T):
                for coordinate in range(width):
                    aliases[f"{name}{b}{t}{coordinate}"] = float(values[b, t, coordinate])
    tensors = [
        tensor("W1", [2, 3], ["D", "HiddenFeature"], W1.reshape(-1).tolist(), "Shared row weights from two input features to three hidden features."),
        tensor("b1", [3], ["HiddenFeature"], b1.tolist(), "Shared hidden-feature biases, added after the two input products."),
        tensor("Z", hidden_shape, hidden_axes, Z.reshape(-1).tolist(), "Hidden affine preactivations before ReLU."),
        tensor("Hidden", hidden_shape, hidden_axes, Hidden.reshape(-1).tolist(), "ReLU applied separately to each preactivation, including zero -> zero."),
        tensor("W2", [3, 2], ["HiddenFeature", "D"], W2.reshape(-1).tolist(), "Shared row weights from three hidden features back to two output features."),
        tensor("b2", [2], ["D"], b2.tolist(), "Shared output-feature biases, added after the three hidden products."),
        tensor("F", shape, axes, F.reshape(-1).tolist(), "Position-wise FFN output; each token uses the same parameters without token mixing."),
    ]
    return dict(output=tensors[-1], tensors=tensors, aliases=aliases)
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.

"""Part VII component kernels: real NumPy storage, explicit float operations.

Keep this file beside iv30.py and iv31.py. NumPy represents actual shaped arrays;
Python floats perform each product/addition/division separately in signed trace
order. No matmul, vector reduction, broadcast, fused multiply-add or hidden norm.
Authored under the resource hold: this source has NOT been executed or validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    """Reject booleans, numeric strings, complex numbers and nonfinite scalars."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


RESIDUAL_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
    w00=0.5, w01=0, w10=0, w11=-0.5, b0=0, b1=0,
    g000=1, g001=2, g010=1, g011=2, g020=1, g021=2,
    g100=1, g101=2, g110=1, g111=2, g120=1, g121=2,
    residual=1,
))
NORM_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=3, x001=1, x010=2, x011=2, x020=-1, x021=1,
    x100=1, x101=-1, x110=0, x111=0, x120=-2, x121=3,
    gamma0=1, gamma1=1, beta0=0, beta1=0, epsilon=3,
))


def component_state(state, stage):
    """Validate all 33/19 own fields, including inactive X/g, before selecting."""
    if type(stage) is not int or stage not in (30, 31):
        raise NumericalFault("INVALID_INPUT", "Use component stage 30 or 31.")
    defaults = RESIDUAL_DEFAULTS if stage == 30 else NORM_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), residual=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (1e-8, 4) if key == "epsilon" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return dict(status="unavailable", code=error.code, reason=str(error))
        except (OverflowError, FloatingPointError) as error:
            return dict(status="unavailable", code="NONFINITE", reason=str(error))
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class ComponentTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        # Finite clones detach each saved operand/result from mutable arrays/state.
        inputs, values = numbers(inputs), numbers(values)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})

    def result(self, summary, tensors):
        # Aliases first, then ALL flattened step outputs in their insertion order.
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def component_trace():
    return ComponentTrace()


def tensor(identifier, shape, axes, values, provenance):
    """Platform-style float64 boundary: explicit named shape and dense flat list."""
    if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if type(values) is not list or len(values) != math.prod(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
    flat = [finite(value, f"{identifier}[{n}]") for n, value in enumerate(values)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64",
                values=flat, provenance=provenance, precision=8)


def same_shape_add(identifier, left, right):
    """Add validated float64 TensorRecords; equal element count is insufficient."""
    checked = []
    for n, record in enumerate((left, right)):
        if type(record) not in (dict, MappingProxyType) or record.get("dtype") != "float64":
            raise NumericalFault("INVALID_INPUT", f"{identifier}: operand {n} must be a float64 tensor.")
        checked.append(tensor(record.get("id"), record.get("shape"), record.get("axes"),
                              record.get("values"), record.get("provenance")))
    a, b = checked
    if a["shape"] != b["shape"] or a["axes"] != b["axes"]:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: addition needs identical dimensions and named axes; no broadcasting.")
    values = [finite(value + b["values"][n], f"{identifier}[{n}]") for n, value in enumerate(a["values"])]
    return tensor(identifier, a["shape"], a["axes"], values,
                  f"Exact named-shape addition of {left['id']} and {right['id']}; no broadcasting.")


def feature_norm(kind, prefix, x, gamma, beta, epsilon, trace):
    """Normalize one width-two token; no chapter bounds on derived IV33 rows.

    Inputs are dense lists, as in the TS kernel. Validate beta even for RMS,
    then deliberately omit it from RMS arithmetic and feature trace inputs.
    """
    if kind not in ("layer", "rms"):
        raise NumericalFault("INVALID_INPUT", "Use layer or rms normalization.")
    checked = []
    for name, values in (("x", x), ("gamma", gamma), ("beta", beta)):
        if type(values) is not list or len(values) != 2:
            raise NumericalFault("SHAPE_MISMATCH", f"{name} needs exactly two dense features.")
        checked.append([finite(value, f"{name}[{d}]") for d, value in enumerate(values)])
    x, gamma, beta = checked
    epsilon = finite(epsilon, "epsilon")
    if epsilon <= 0:
        raise NumericalFault("INVALID_INPUT", "epsilon must be strictly positive.")
    statistics = {}
    if kind == "layer":
        # Population variance: two centered squares, then sum, then divide by 2.
        statistics["sum"] = finite(x[0] + x[1], "feature sum")
        statistics["mean"] = finite(statistics["sum"] / 2, "feature mean")
        statistics["centered0"] = finite(x[0] - statistics["mean"], "centered0")
        statistics["centered1"] = finite(x[1] - statistics["mean"], "centered1")
        statistics["square0"] = finite(statistics["centered0"] * statistics["centered0"], "centered square0")
        statistics["square1"] = finite(statistics["centered1"] * statistics["centered1"], "centered square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "centered square sum")
        statistics["variance"] = finite(statistics["squareSum"] / 2, "population variance")
        statistics["variancePlusEpsilon"] = finite(statistics["variance"] + epsilon, "variance plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["variancePlusEpsilon"]), "LN denominator")
        source = [statistics["centered0"], statistics["centered1"]]
    else:
        # RMS uses original features, with neither mean subtraction nor beta.
        statistics["square0"] = finite(x[0] * x[0], "square0")
        statistics["square1"] = finite(x[1] * x[1], "square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "square sum")
        statistics["meanSquare"] = finite(statistics["squareSum"] / 2, "mean square")
        statistics["meanSquarePlusEpsilon"] = finite(statistics["meanSquare"] + epsilon, "mean square plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["meanSquarePlusEpsilon"]), "RMS denominator")
        source = list(x)
    trace.add(f"{prefix}_statistics", f"{prefix}: feature-only statistics",
              "mean=(x0+x1)/2; variance=(centered0²+centered1²)/2; denominator=sqrt(variance+epsilon)" if kind == "layer" else
              "meanSquare=(x0²+x1²)/2; denominator=sqrt(meanSquare+epsilon)",
              "Only this token's two features contribute. Epsilon stays inside the square root.",
              dict(x0=x[0], x1=x[1], epsilon=epsilon), statistics)
    normalized, values = [], []
    for d in range(2):
        n = finite(source[d] / statistics["denominator"], "normalized feature")
        scaled = finite(gamma[d] * n, "scaled feature")
        value = finite(scaled + beta[d], "LN affine feature") if kind == "layer" else scaled
        normalized.append(n)
        values.append(value)
        inputs = dict(d=d, source=source[d], denominator=statistics["denominator"], gamma=gamma[d])
        if kind == "layer":
            inputs["beta"] = beta[d]
        trace.add(f"{prefix}_feature_{d}", f"{prefix}: affine feature {d}",
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta" if kind == "layer" else
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled",
                  "LayerNorm uses centered features and beta; scale-only RMS uses original features and no beta.",
                  inputs, dict(normalized=n, scaled=scaled, value=value))
    return dict(values=values, normalized=normalized, statistics=statistics)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; one JSON argument replaces all; '-' reads stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    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 fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    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:
            result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

Edits, counterexamples and boundaries

An input edit is local to its row; a shared weight edit is reused for every row. That is dependency, not a guarantee of visible change: a changed negative preactivation may remain negative and ReLU still returns zero. For the default matrices, inputs (−1,0) and (−2,0) both produce hidden (0,0,0) and output (0,0). Equal outputs do not prove equal inputs.

Setting W2 to zero leaves F=b2. Setting W1 to zero leaves Hidden=ReLU(b1), so F can still be nonzero. A claim that “zero weights always zero the network” must specify which weights and biases. In the next chapter, even a completely zero FFN branch leaves its residual stream intact.

B is an integer from 1 to 2 and T from 1 to 3; D=2 and M=3 are fixed. All 12 stored X fields and 17 parameter fields must be finite and between −4 and 4, including inactive rows. The full state has exactly 31 named fields. Invalid shapes, missing/extra fields or nonfinite arithmetic yield an unavailable result rather than clipping or an invented zero output. A later component may feed this helper derived finite inputs outside the raw input range: raw-editor bounds do not constrain the mathematical intermediate to that range.

The Python listings describe source; a listing alone is not runtime evidence.

Five graded exercise outlines

The lab supplies immediate corrective feedback. Use its current saved trace for the live calculation; the fixed examples below remain fixed after edits.

  1. token-wise: Shared parameters and locality. One MLP with W1[2,3] and W2[3,2] is reused per row. Neither B nor T is a summed axis, so sharing parameters does not average tokens.
  2. ffn-shapes: Shape and expansion. The first affine maps two features to three; ReLU preserves [B,T,3]; the second affine contracts back to [B,T,2]. M counts hidden features, not attention heads.
  3. live-ffn: Live output arithmetic. Use ffn_output_0_0_0 for the fixed coordinate F[0,0,0] and its saved products. Accumulate all three products in m order from zero and add b2 last; at reset F[0,0,0]=3/2+0+1/2+0=2.
  4. token-edit: Edit only x010 while T is at least two. This changes feature zero of batch zero, token one. F[0,0,:] stays unchanged because token zero does not read token one; only the edited token’s output row can change. Shared weights stay fixed. A separate shared-parameter edit would be reused across all rows, though ReLU can hide a numerical effect.
  5. equal-outputs: Equal outputs do not identify equal inputs. Set every W2 entry and both b2 entries to zero: all rows then give F=(0,0), however different their inputs. With a nonzero b2, they instead all give that same bias vector. Hidden features can remain nonzero; zero output does not establish a zero hidden vector.

Recap and bridge

The FFN expands two features to three, applies ReLU and projects back to two. Every token uses the same 17 parameters, while its forward computation remains independent of other rows. A nonnegative hidden vector can produce signed outputs, and ReLU can erase input distinctions. IV-33 — A Complete Transformer Block now places this exact component after attention and a second normalization, with a separate residual addition around each branch.