The neural notebook
← All chapters

IV-33 / Part VII · Transformer Blocks

A Complete Transformer Block

Hand-trace all three tokens through two LayerNorms, real multi-head attention, two residual additions and the shared feed-forward network in pre-norm order.

Review the ideas this chapter uses

A transformer block combines two jobs: exchange information between allowed token positions, then transform the features at each position. Residual additions keep an explicit route for the incoming values around each branch. Normalization prepares the inputs to those branches. The order matters: changing which tensor a branch receives changes the calculation, even when every tensor has the same shape.

Learning objective: Compose attention, residual, normalization and FFN in order. FFN means feed-forward network.

Review IV-29 — Head Concatenation and Output Projection for joining attention heads, IV-30 — Residual Connections and Gradient Paths for residuals, IV-31 — Layer Normalization and RMS Normalization for normalization and IV-32 — Position-Wise Feed-Forward Networks for the shared feed-forward calculation. Book II’s II.10 — Matrix × matrix as composition explains composition, and VIII.3 — Error propagation and conditioning explains numerical conditioning, or sensitivity to input errors. Book III’s III-41 — Composition and Learned Representations connects composition to neural representations. We use hand-set parameters to expose a forward calculation; we do not train a language model here.

Inspect the whole block first

Compute it yourself

A Complete Transformer Block

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
H
2
Dk
1
Dv
1
x000
3
x001
1
x010
2
x011
2
x020
-1
x021
1
x100
1
x101
-1
x110
0
x111
0
x120
-2
x121
3
wq000
1
wq001
0
wq010
0
wq011
1
wq100
0
wq101
1
wq110
1
wq111
0
wk000
1
wk001
0
wk010
0
wk011
1
wk100
0
wk101
1
wk110
1
wk111
0
wv000
1
wv001
0
wv010
0
wv011
1
wv100
0
wv101
1
wv110
1
wv111
0
mode
1
valid0
1
valid1
1
valid2
1
shift
0
wo000
1
wo001
1
wo010
0.5
wo011
0
wo100
1
wo101
-1
wo110
0
wo111
0.5
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
n1gamma0
1
n1gamma1
1
n1beta0
0
n1beta1
0
n1epsilon
3
n2gamma0
1
n2gamma1
1
n2beta0
0
n2beta1
0
n2epsilon
3
y0003.2773500981126147
y0012.138675049056307
y0102
y0112.4285714285714284
Input token rows X
Query projection WQ
Key projection WK
Value projection WV
Output projection WO
FFN weights W1
FFN bias b1
FFN weights W2
FFN bias b2
LN1 feature scales and offsets
LN2 feature scales and offsets

y000 3.2773500981126147. y001 2.138675049056307. y010 2. y011 2.4285714285714284. Validate the complete pre-norm block inputs. All 81 raw fields are validated. LN1 and LN2 are independent feature normalizations; M=3 hidden features differs from H attention heads. Both residuals are always on. Any fully masked attention query makes the entire block unavailable.. B 1. T 3. D 2. H 2. Dk 1. Dv 1. M 3. mode 1. n1epsilon 3. n2epsilon 3

Validate the complete pre-norm block inputs

N1=LN1(X); A=MHA(N1,mask); R1=X+A; N2=LN2(R1); F=FFN(N2); Y=R1+F

All 81 raw fields are validated. LN1 and LN2 are independent feature normalizations; M=3 hidden features differs from H attention heads. Both residuals are always on. Any fully masked attention query makes the entire block unavailable.

Inputs

B
1
T
3
H
2
Dk
1
Dv
1
x000
3
x001
1
x010
2
x011
2
x020
-1
x021
1
x100
1
x101
-1
x110
0
x111
0
x120
-2
x121
3
wq000
1
wq001
0
wq010
0
wq011
1
wq100
0
wq101
1
wq110
1
wq111
0
wk000
1
wk001
0
wk010
0
wk011
1
wk100
0
wk101
1
wk110
1
wk111
0
wv000
1
wv001
0
wv010
0
wv011
1
wv100
0
wv101
1
wv110
1
wv111
0
mode
1
valid0
1
valid1
1
valid2
1
shift
0
wo000
1
wo001
1
wo010
0.5
wo011
0
wo100
1
wo101
-1
wo110
0
wo111
0.5
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
n1gamma0
1
n1gamma1
1
n1beta0
0
n1beta1
0
n1epsilon
3
n2gamma0
1
n2gamma1
1
n2beta0
0
n2beta1
0
n2epsilon
3

Outputs

B
1
T
3
D
2
H
2
Dk
1
Dv
1
M
3
mode
1
n1epsilon
3
n2epsilon
3

The full pre-norm stage flow

Pre-norm means each branch receives normalized features before its main calculation. Multi-head attention (MHA) mixes allowed token values through separate heads. The feed-forward network (FFN) then transforms each token independently. Both residual additions retain their own skip path, always with equal [B,T,2] dimensions and B,T,D axes.

X → LN1 → N1 → MHA → A; R1=X+A → LN2 → N2 → FFN → F; Y=R1+F

Stage flow for batch 0, token 0. Selectors inspect saved values only; the attention and FFN views have independent selectors. The live graded question always uses Y[0,0,0].

Selected trace operation: setup. Matching rows are marked current. The main trace retains every operation in its full block order.

complete stage flow, batch 0, token 0; actual saved binary64 values without display rounding
TensorMeaningShapeFeature 0Feature 1
XOriginal input and first skip[1,3,2]31
N1LN1 output, actual attention input[1,3,2]0.5-0.5
AttnYA: complete MHA including WO[1,3,2]01
R1First residual X+A[1,3,2]32
N2LN2 output, actual FFN input[1,3,2]0.2773500981126146-0.2773500981126146
FFFN output[1,3,2]0.27735009811261460.1386750490563073
YSecond residual R1+F[1,3,2]3.27735009811261472.138675049056307

X

B=1 × T=3 × D=2 · float64 · precision 8. Original raw block input retained on the first residual skip.

X, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
031
122
2-11
LN1 before attention: full feature-only statistics and affine results

Layer normalization (LN) subtracts the mean of this token's two features, divides by sqrt(population variance+epsilon), then applies its own gamma scale and beta offset. LN1 and LN2 have separate parameters and inputs. Neither mixes token rows or uses root-mean-square normalization.

N1 shared feature scales and offsets; actual saved binary64 values without display rounding
FeatureGammaBeta
010
110
N1 statistics and feature affines, batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput x0Input x1Input epsilonInput dInput sourceInput denominatorInput gammaInput betaResult sumResult meanResult centered0Result centered1Result square0Result square1Result squareSumResult varianceResult variancePlusEpsilonResult denominatorResult normalizedResult scaledResult value
n1_0_0_statistics313Not usedNot usedNot usedNot usedNot used421-1112142Not usedNot usedNot used
n1_0_0_feature_0Not usedNot usedNot used01210Not usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot used0.50.50.5
n1_0_0_feature_1Not usedNot usedNot used1-1210Not usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot used-0.5-0.5-0.5

N1Mean

B=1 × T=3 × Statistic=1 · float64 · precision 8. N1 per-token feature mean; no token/batch averaging.

N1Mean, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0
02
12
20

N1Variance

B=1 × T=3 × Statistic=1 · float64 · precision 8. N1 per-token population variance over D=2 features.

N1Variance, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0
01
10
21

N1Denominator

B=1 × T=3 × Statistic=1 · float64 · precision 8. N1 sqrt(variance+n1epsilon).

N1Denominator, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0
02
11.7320508075688772
22

N1Centered

B=1 × T=3 × D=2 · float64 · precision 8. X minus this stage's per-token mean.

N1Centered, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
01-1
100
2-11

N1Normalized

B=1 × T=3 × D=2 · float64 · precision 8. N1 centered features divided by the saved denominator, before gamma/beta.

N1Normalized, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
00.5-0.5
100
2-0.50.5

N1

B=1 × T=3 × D=2 · float64 · precision 8. N1: this stage's feature-only LayerNorm affine output.

N1, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
00.5-0.5
100
2-0.50.5

The saved statistics include both centered squares and their sum, population variance, variance+epsilon and denominator. Gamma/beta can change mean and scale further; normalization alone is no training or gradient-stability guarantee.

Actual attention: Q/K/V, scores, masks, probabilities, head outputs, concatenation and WO

This view shows only the saved attention branch. Its local X is N1 and its local Y is A (AttnY in the full block). Local step names correspond to full trace names with attn_ in front. Its statement that attention adds no residual or normalization describes this branch; the full block adds both residuals and both normalizations in the displayed order.

Projected coordinates, declared layout, real head probabilities and outputs, and output projection

D=2 counts input/output features. H=2 counts heads, Dk=1 counts features per query/key head, and Dv=1 counts features per value head. These weights are hand-set, not trained. Open a matrix control group above before editing its values; inactive stored slots are still validated.

Showing batch 0, head 0, token/query 0, value feature 0, output coordinate 0. Selectors change the view only. Trace navigation selects a saved calculation independently. Matching operation rows are marked as current; use their displayed step IDs in Calculation step.

Selected value coordinate: VHeads[0,0,0,0]=0.5. Saved permute_V_0_0_0_0 copies source flat offset 0 to destination flat offset 0; reshape and permutation do not change this scalar.

X: batch 0

B=1 × T=3 × D=2 · float64. Active token rows; D=2 input features always retained.

X: batch 0; actual stored values without display rounding
TokenInput D 0Input D 1
00.5-0.5
100
2-0.50.5

Q: input products → packed projection → reshape → head-axis permutation

WQ: shared packed weights

D=2 × QueryFeature=2 · float64. Query columns packed by h*Dk+f from wq{d}{h}{f}.

WQ: shared packed weights; actual stored values without display rounding
Input DPacked h*F+f 0Packed h*F+f 1
010
101

QConcat: batch 0

B=1 × T=3 × QueryFeature=2 · float64. XWQ; each packed coordinate has two products and one sum.

QConcat: batch 0; actual stored values without display rounding
TokenPacked h*F+f 0Packed h*F+f 1
00.5-0.5
100
2-0.50.5

QSplit has shape [1,3,2,1], with axes B,T,H,Dk. Its flat values retain QConcat order. Moving to QHeads uses the separate permutation axes [0,2,1,3]; the table gives both real storage offsets and the copied value.

Q projection products, batch 0, head 0; actual stored values without display rounding
Saved stepTokenFeaturex0w0product0x1w1product1Sum
project_Q_0_0_0_0000.510.5-0.5000.5
project_Q_0_1_0_0100100000
project_Q_0_2_0_020-0.51-0.50.500-0.5
Q layout copies, batch 0, head 0; actual stored values without display rounding
Saved step[b,t,h,f] → [b,h,t,f]Packed featureSource flat offsetDestination flat offsetSplit source valueHeads copied value
permute_Q_0_0_0_0[0,0,0,0] → [0,0,0,0]0000.50.5
permute_Q_0_0_1_0[0,1,0,0] → [0,0,1,0]02100
permute_Q_0_0_2_0[0,2,0,0] → [0,0,2,0]042-0.5-0.5

QHeads: batch 0, head 0

B=1 × H=2 × T=3 × Dk=1 · float64. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

QHeads: batch 0, head 0; actual stored values without display rounding
TokenWithin-head feature 0
00.5
10
2-0.5

K: input products → packed projection → reshape → head-axis permutation

WK: shared packed weights

D=2 × KeyFeature=2 · float64. Key columns packed by h*Dk+f from wk{d}{h}{f}.

WK: shared packed weights; actual stored values without display rounding
Input DPacked h*F+f 0Packed h*F+f 1
010
101

KConcat: batch 0

B=1 × T=3 × KeyFeature=2 · float64. XWK; each packed coordinate has two products and one sum.

KConcat: batch 0; actual stored values without display rounding
TokenPacked h*F+f 0Packed h*F+f 1
00.5-0.5
100
2-0.50.5

KSplit has shape [1,3,2,1], with axes B,T,H,Dk. Its flat values retain KConcat order. Moving to KHeads uses the separate permutation axes [0,2,1,3]; the table gives both real storage offsets and the copied value.

K projection products, batch 0, head 0; actual stored values without display rounding
Saved stepTokenFeaturex0w0product0x1w1product1Sum
project_K_0_0_0_0000.510.5-0.5000.5
project_K_0_1_0_0100100000
project_K_0_2_0_020-0.51-0.50.500-0.5
K layout copies, batch 0, head 0; actual stored values without display rounding
Saved step[b,t,h,f] → [b,h,t,f]Packed featureSource flat offsetDestination flat offsetSplit source valueHeads copied value
permute_K_0_0_0_0[0,0,0,0] → [0,0,0,0]0000.50.5
permute_K_0_0_1_0[0,1,0,0] → [0,0,1,0]02100
permute_K_0_0_2_0[0,2,0,0] → [0,0,2,0]042-0.5-0.5

KHeads: batch 0, head 0

B=1 × H=2 × T=3 × Dk=1 · float64. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

KHeads: batch 0, head 0; actual stored values without display rounding
TokenWithin-head feature 0
00.5
10
2-0.5

V: input products → packed projection → reshape → head-axis permutation

WV: shared packed weights

D=2 × ValueFeature=2 · float64. Value columns packed by h*Dv+f from wv{d}{h}{f}.

WV: shared packed weights; actual stored values without display rounding
Input DPacked h*F+f 0Packed h*F+f 1
010
101

VConcat: batch 0

B=1 × T=3 × ValueFeature=2 · float64. XWV; values are projected separately from queries and keys.

VConcat: batch 0; actual stored values without display rounding
TokenPacked h*F+f 0Packed h*F+f 1
00.5-0.5
100
2-0.50.5

VSplit has shape [1,3,2,1], with axes B,T,H,Dv. Its flat values retain VConcat order. Moving to VHeads uses the separate permutation axes [0,2,1,3]; the table gives both real storage offsets and the copied value.

V projection products, batch 0, head 0; actual stored values without display rounding
Saved stepTokenFeaturex0w0product0x1w1product1Sum
project_V_0_0_0_0000.510.5-0.5000.5
project_V_0_1_0_0100100000
project_V_0_2_0_020-0.51-0.50.500-0.5
V layout copies, batch 0, head 0; actual stored values without display rounding
Saved step[b,t,h,f] → [b,h,t,f]Packed featureSource flat offsetDestination flat offsetSplit source valueHeads copied value
permute_V_0_0_0_0[0,0,0,0] → [0,0,0,0]0000.50.5
permute_V_0_0_1_0[0,1,0,0] → [0,0,1,0]02100
permute_V_0_0_2_0[0,2,0,0] → [0,0,2,0]042-0.5-0.5

VHeads: batch 0, head 0

B=1 × H=2 × T=3 × Dv=1 · float64. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

VHeads: batch 0, head 0; actual stored values without display rounding
TokenWithin-head feature 0
00.5
10
2-0.5

Separate score and probability paths

For selected head 0, multiply corresponding Q/K features, add them, then divide by sqrt(Dk). Each probability row normalizes over keys within the same batch and head. Key validity is shared across all B/H slices; padding never removes a query row.

raw: batch 0, head 0

B=1 × H=2 × Query=3 × Key=3 · float64. Separate QHeads KHeads transpose products within every batch and head.

raw: batch 0, head 0; actual stored values without display rounding
QueryKey 0Key 1Key 2
00.250-0.25
1000
2-0.2500.25

scores: batch 0, head 0

B=1 × H=2 × Query=3 × Key=3 · float64. raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.

scores: batch 0, head 0; actual stored values without display rounding
QueryKey 0Key 1Key 2
00.250-0.25
1000
2-0.2500.25
score products, batch 0, head 0, query 0; actual stored values without display rounding
Saved stepKeyq0k0product0Rawsqrt(Dk)Score
score_0_0_0_000.50.50.250.2510.25
score_0_0_0_110.500010
score_0_0_0_220.5-0.5-0.25-0.251-0.25

Real probability map for head 0, batch 0

probability heatmap, batch 0, head 0; actual stored values without display rounding
Query / keyKey 0Key 1Key 2
Query 0Allowed: p=1Forbidden: p=0Forbidden: p=0
Query 1Allowed: p=0.5Allowed: p=0.5Forbidden: p=0
Query 2Allowed: p=0.25427521259046565Allowed: p=0.3264958357998367Allowed: p=0.4192289516096977

Real probability map for head 1, batch 0

probability heatmap, batch 0, head 1; actual stored values without display rounding
Query / keyKey 0Key 1Key 2
Query 0Allowed: p=1Forbidden: p=0Forbidden: p=0
Query 1Allowed: p=0.5Allowed: p=0.5Forbidden: p=0
Query 2Allowed: p=0.25427521259046565Allowed: p=0.3264958357998367Allowed: p=0.4192289516096977

Saved row_0_0_0: allowed-key stable softmax

Mode 1: causal: key ≤ query. Common shift 0; allowed maximum 0.25; denominator 1 + 0 + 0 = 1.

stable softmax, batch 0, head 0, query 0; actual stored values without display rounding
KeyAllowed?ScoreLogit=score+shiftAllowed logit−maxExponential termp=term/denominator
0true0.250.250exp(0)=11 / 1 = 1
1false00Forbidden: no subtractionForbidden: 0, no exponential0 / 1 = 0
2false-0.25-0.25Forbidden: no subtractionForbidden: 0, no exponential0 / 1 = 0

The maximum allowed logit has shifted value 0 and exp(0)=1. A fully masked row instead makes the entire result unavailable. Independent heads can produce equal maps; different maps are outcomes of the current weights and inputs, not a requirement. A large common shift preserves real ratios but may change rounded binary64 values.

Actual per-head weighted values

OHeads: batch 0, head 0

B=1 × H=2 × Query=3 × Dv=1 · float64. Actual per-head P times VHeads; every product and running sum is traced.

OHeads: batch 0, head 0; actual stored values without display rounding
QueryValue feature 0
00.5
10.25
2-0.08247686950961602
head_mix_0_0_0_0: real weighted products and running sums; actual stored values without display rounding
KeyThis head’s pThis head’s Vp × VRunning sum from 0
010.50.50.5
10000.5
20-0.500.5

OHeads[0,0,0,0]=0.5. Each product is followed immediately by its running sum, in ascending key order, including actual zero times V for forbidden keys. Value outputs can be signed. There is no second average.

Copy heads into C, then apply WO

Joined coordinate c=h*Dv+f preserves head identity. At Dv=2 the order is head0/feature0, head0/feature1, head1/feature0, head1/feature1. Concatenation copies values; WO then mixes joined coordinates explicitly.

concatenation, batch 0, token 0; actual stored values without display rounding
Saved stepHeadFeatureJoined cSource flat offsetDestination flat offsetOHeads valueC value
concat_0_0_0_0000000.50.5
concat_0_0_1_010131-0.5-0.5

C: batch 0

B=1 × T=3 × JoinedValue=2 · float64. OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged.

C: batch 0; actual stored values without display rounding
TokenJoined c 0Joined c 1
00.5-0.5
10.25-0.25
2-0.082476869509616020.08247686950961602

WO: shared output weights

JoinedValue=2 × D=2 · float64. wo{h}{f}{d} packed in h,f,d order, preserving parameter identity.

WO: shared output weights; actual stored values without display rounding
Joined c=h*Dv+fOutput D 0Output D 1
011
11-1

Y: batch 0

B=1 × T=3 × D=2 · float64. Y=C WO, summing products in ascending joined-feature order from zero; no normalization.

Y: batch 0; actual stored values without display rounding
TokenOutput D 0Output D 1
001
100.5
20-0.16495373901923205
output_0_0_0: all output products and running sums; actual stored values without display rounding
Joined cHead / featureCWO[c,d]ProductRunning sum from 0
00 / 00.510.50.5
11 / 0-0.51-0.50

Y[0,0,0]=0. Its final width is D=2. WO-only edits leave every projection, probability, OHeads and C unchanged. Y is a signed vector, with no output softmax, residual connection or normalization.

First residual: original X plus actual attention output A

first residual additions, batch 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput skipInput branchResult value
r1_0_0_0000303
r1_0_0_1001112
r1_0_1_0010202
r1_0_1_101120.52.5
r1_0_2_0020-10-1
r1_0_2_10211-0.164953739019232050.835046260980768

R1

B=1 × T=3 × D=2 · float64 · precision 8. Exact named-shape addition of X and AttnY; no broadcasting.

R1, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
032
122.5
2-10.835046260980768
LN2 before the FFN: full feature-only statistics and affine results

Layer normalization (LN) subtracts the mean of this token's two features, divides by sqrt(population variance+epsilon), then applies its own gamma scale and beta offset. LN1 and LN2 have separate parameters and inputs. Neither mixes token rows or uses root-mean-square normalization.

N2 shared feature scales and offsets; actual saved binary64 values without display rounding
FeatureGammaBeta
010
110
N2 statistics and feature affines, batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput x0Input x1Input epsilonInput dInput sourceInput denominatorInput gammaInput betaResult sumResult meanResult centered0Result centered1Result square0Result square1Result squareSumResult varianceResult variancePlusEpsilonResult denominatorResult normalizedResult scaledResult value
n2_0_0_statistics323Not usedNot usedNot usedNot usedNot used52.50.5-0.50.250.250.50.253.251.8027756377319946Not usedNot usedNot used
n2_0_0_feature_0Not usedNot usedNot used00.51.802775637731994610Not usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot used0.27735009811261460.27735009811261460.2773500981126146
n2_0_0_feature_1Not usedNot usedNot used1-0.51.802775637731994610Not usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot usedNot used-0.2773500981126146-0.2773500981126146-0.2773500981126146

N2Mean

B=1 × T=3 × Statistic=1 · float64 · precision 8. N2 per-token feature mean; no token/batch averaging.

N2Mean, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0
02.5
12.25
2-0.08247686950961602

N2Variance

B=1 × T=3 × Statistic=1 · float64 · precision 8. N2 per-token population variance over D=2 features.

N2Variance, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0
00.25
10.0625
20.841848694984874

N2Denominator

B=1 × T=3 × Statistic=1 · float64 · precision 8. N2 sqrt(variance+n2epsilon).

N2Denominator, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0
01.8027756377319946
11.75
21.960063441571439

N2Centered

B=1 × T=3 × D=2 · float64 · precision 8. R1 minus this stage's per-token mean.

N2Centered, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
00.5-0.5
1-0.250.25
2-0.91752313049038390.9175231304903839

N2Normalized

B=1 × T=3 × D=2 · float64 · precision 8. N2 centered features divided by the saved denominator, before gamma/beta.

N2Normalized, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
00.2773500981126146-0.2773500981126146
1-0.142857142857142850.14285714285714285
2-0.46810889435026620.4681088943502662

N2

B=1 × T=3 × D=2 · float64 · precision 8. N2: this stage's feature-only LayerNorm affine output.

N2, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
00.2773500981126146-0.2773500981126146
1-0.142857142857142850.14285714285714285
2-0.46810889435026620.4681088943502662

The saved statistics include both centered squares and their sum, population variance, variance+epsilon and denominator. Gamma/beta can change mean and scale further; normalization alone is no training or gradient-stability guarantee.

Actual FFN: all hidden affine, ReLU and output affine records

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 0.1386750490563073, 0, 0.1386750490563073 accumulate from zero to 0.1386750490563073, 0.1386750490563073, 0.2773500981126146; adding bias 0 gives F[0,0,0]=0.2773500981126146.

N2: FFN input, batch 0

B=1 × T=3 × D=2 · float64 · precision 8. N2: this stage's feature-only LayerNorm affine output.

N2: FFN input, batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
00.2773500981126146-0.2773500981126146
1-0.142857142857142850.14285714285714285
2-0.46810889435026620.4681088943502662

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_00000.2773500981126146-0.27735009811261461000.277350098112614600.27735009811261460.2773500981126146
ffn_hidden_0_0_10010.2773500981126146-0.27735009811261460100-0.2773500981126146-0.2773500981126146-0.2773500981126146
ffn_hidden_0_0_20020.2773500981126146-0.27735009811261461-100.27735009811261460.27735009811261460.55470019622522910.5547001962252291

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
00.2773500981126146-0.27735009811261460.5547001962252291
1-0.142857142857142850.14285714285714285-0.2857142857142857
2-0.46810889435026620.4681088943502662-0.9362177887005324

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_00000.27735009811261460.2773500981126146
ffn_relu_0_0_1001-0.27735009811261460
ffn_relu_0_0_20020.55470019622522910.5547001962252291

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
00.277350098112614600.5547001962252291
100.142857142857142850
200.46810889435026620

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_00000.27735009811261460.5000.55470019622522910.2500.138675049056307300.13867504905630730.13867504905630730.13867504905630730.27735009811261460.27735009811261460.2773500981126146
ffn_output_0_0_10010.277350098112614600-0.50.55470019622522910.250000.1386750490563073000.13867504905630730.13867504905630730.1386750490563073

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
00.27735009811261460.1386750490563073
10-0.07142857142857142
20-0.2340544471751331

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.

Second residual: R1 plus actual FFN output F

second residual additions, batch 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput skipInput branchResult value
r2_0_0_000030.27735009811261463.2773500981126147
r2_0_0_100120.13867504905630732.138675049056307
r2_0_1_0010202
r2_0_1_10112.5-0.071428571428571422.4285714285714284
r2_0_2_0020-10-1
r2_0_2_10210.835046260980768-0.23405444717513310.6009918138056348

Y

B=1 × T=3 × D=2 · float64 · precision 8. Exact named-shape addition of R1 and F; no broadcasting.

Y, batch 0; actual saved binary64 values without display rounding
TokenCoordinate 0Coordinate 1
03.27735009811261472.138675049056307
122.4285714285714284
2-10.6009918138056348

The default mask is causal, so a query may use its own token and earlier keys. Other mask modes inspect different allowed sets; key validity is shared across batches and heads and never deletes query rows. A query with no allowed keys makes the entire block unavailable. There is no post-normalization, dropout or output softmax here, and no claim of training stability.

Inspect tensor shapes and full precision

All computed outputs

y000
3.2773500981126147
y001
2.138675049056307
y010
2
y011
2.4285714285714284
y020
-1
y021
0.6009918138056348
B
1
T
3
H
2
Dk
1
Dv
1
M
3
n1000
0.5
n1001
-0.5
n1010
0
n1011
0
n1020
-0.5
n1021
0.5
attn_q0000
0.5
attn_q0010
0
attn_q0020
-0.5
attn_q0100
-0.5
attn_q0110
0
attn_q0120
0.5
attn_k0000
0.5
attn_k0010
0
attn_k0020
-0.5
attn_k0100
-0.5
attn_k0110
0
attn_k0120
0.5
attn_v0000
0.5
attn_v0010
0
attn_v0020
-0.5
attn_v0100
-0.5
attn_v0110
0
attn_v0120
0.5
attn_raw0000
0.25
attn_score0000
0.25
attn_raw0001
0
attn_score0001
0
attn_raw0002
-0.25
attn_score0002
-0.25
attn_raw0010
0
attn_score0010
0
attn_raw0011
0
attn_score0011
0
attn_raw0012
0
attn_score0012
0
attn_raw0020
-0.25
attn_score0020
-0.25
attn_raw0021
0
attn_score0021
0
attn_raw0022
0.25
attn_score0022
0.25
attn_raw0100
0.25
attn_score0100
0.25
attn_raw0101
0
attn_score0101
0
attn_raw0102
-0.25
attn_score0102
-0.25
attn_raw0110
0
attn_score0110
0
attn_raw0111
0
attn_score0111
0
attn_raw0112
0
attn_score0112
0
attn_raw0120
-0.25
attn_score0120
-0.25
attn_raw0121
0
attn_score0121
0
attn_raw0122
0.25
attn_score0122
0.25
attn_p0000
1
attn_p0001
0
attn_p0002
0
attn_p0010
0.5
attn_p0011
0.5
attn_p0012
0
attn_p0020
0.25427521259046565
attn_p0021
0.3264958357998367
attn_p0022
0.4192289516096977
attn_p0100
1
attn_p0101
0
attn_p0102
0
attn_p0110
0.5
attn_p0111
0.5
attn_p0112
0
attn_p0120
0.25427521259046565
attn_p0121
0.3264958357998367
attn_p0122
0.4192289516096977
attn_oh0000
0.5
attn_oh0010
0.25
attn_oh0020
-0.08247686950961602
attn_oh0100
-0.5
attn_oh0110
-0.25
attn_oh0120
0.08247686950961602
attn_c000
0.5
attn_c001
-0.5
attn_c010
0.25
attn_c011
-0.25
attn_c020
-0.08247686950961602
attn_c021
0.08247686950961602
attn_y000
0
attn_y001
1
attn_y010
0
attn_y011
0.5
attn_y020
0
attn_y021
-0.16495373901923205
r1000
3
r1001
2
r1010
2
r1011
2.5
r1020
-1
r1021
0.835046260980768
n2000
0.2773500981126146
n2001
-0.2773500981126146
n2010
-0.14285714285714285
n2011
0.14285714285714285
n2020
-0.4681088943502662
n2021
0.4681088943502662
ff_pre000
0.2773500981126146
ff_pre001
-0.2773500981126146
ff_pre002
0.5547001962252291
ff_pre010
-0.14285714285714285
ff_pre011
0.14285714285714285
ff_pre012
-0.2857142857142857
ff_pre020
-0.4681088943502662
ff_pre021
0.4681088943502662
ff_pre022
-0.9362177887005324
ff_h000
0.2773500981126146
ff_h001
0
ff_h002
0.5547001962252291
ff_h010
0
ff_h011
0.14285714285714285
ff_h012
0
ff_h020
0
ff_h021
0.4681088943502662
ff_h022
0
ff_f000
0.2773500981126146
ff_f001
0.1386750490563073
ff_f010
0
ff_f011
-0.07142857142857142
ff_f020
0
ff_f021
-0.2340544471751331
setup_B
1
setup_T
3
setup_D
2
setup_H
2
setup_Dk
1
setup_Dv
1
setup_M
3
setup_mode
1
setup_n1epsilon
3
setup_n2epsilon
3
n1_0_0_statistics_sum
4
n1_0_0_statistics_mean
2
n1_0_0_statistics_centered0
1
n1_0_0_statistics_centered1
-1
n1_0_0_statistics_square0
1
n1_0_0_statistics_square1
1
n1_0_0_statistics_squareSum
2
n1_0_0_statistics_variance
1
n1_0_0_statistics_variancePlusEpsilon
4
n1_0_0_statistics_denominator
2
n1_0_0_feature_0_normalized
0.5
n1_0_0_feature_0_scaled
0.5
n1_0_0_feature_0_value
0.5
n1_0_0_feature_1_normalized
-0.5
n1_0_0_feature_1_scaled
-0.5
n1_0_0_feature_1_value
-0.5
n1_0_1_statistics_sum
4
n1_0_1_statistics_mean
2
n1_0_1_statistics_centered0
0
n1_0_1_statistics_centered1
0
n1_0_1_statistics_square0
0
n1_0_1_statistics_square1
0
n1_0_1_statistics_squareSum
0
n1_0_1_statistics_variance
0
n1_0_1_statistics_variancePlusEpsilon
3
n1_0_1_statistics_denominator
1.7320508075688772
n1_0_1_feature_0_normalized
0
n1_0_1_feature_0_scaled
0
n1_0_1_feature_0_value
0
n1_0_1_feature_1_normalized
0
n1_0_1_feature_1_scaled
0
n1_0_1_feature_1_value
0
n1_0_2_statistics_sum
0
n1_0_2_statistics_mean
0
n1_0_2_statistics_centered0
-1
n1_0_2_statistics_centered1
1
n1_0_2_statistics_square0
1
n1_0_2_statistics_square1
1
n1_0_2_statistics_squareSum
2
n1_0_2_statistics_variance
1
n1_0_2_statistics_variancePlusEpsilon
4
n1_0_2_statistics_denominator
2
n1_0_2_feature_0_normalized
-0.5
n1_0_2_feature_0_scaled
-0.5
n1_0_2_feature_0_value
-0.5
n1_0_2_feature_1_normalized
0.5
n1_0_2_feature_1_scaled
0.5
n1_0_2_feature_1_value
0.5
attn_project_Q_0_0_0_0_product0
0.5
attn_project_Q_0_0_0_0_product1
0
attn_project_Q_0_0_0_0_value
0.5
attn_project_Q_0_0_1_0_product0
0
attn_project_Q_0_0_1_0_product1
-0.5
attn_project_Q_0_0_1_0_value
-0.5
attn_project_Q_0_1_0_0_product0
0
attn_project_Q_0_1_0_0_product1
0
attn_project_Q_0_1_0_0_value
0
attn_project_Q_0_1_1_0_product0
0
attn_project_Q_0_1_1_0_product1
0
attn_project_Q_0_1_1_0_value
0
attn_project_Q_0_2_0_0_product0
-0.5
attn_project_Q_0_2_0_0_product1
0
attn_project_Q_0_2_0_0_value
-0.5
attn_project_Q_0_2_1_0_product0
0
attn_project_Q_0_2_1_0_product1
0.5
attn_project_Q_0_2_1_0_value
0.5
attn_project_K_0_0_0_0_product0
0.5
attn_project_K_0_0_0_0_product1
0
attn_project_K_0_0_0_0_value
0.5
attn_project_K_0_0_1_0_product0
0
attn_project_K_0_0_1_0_product1
-0.5
attn_project_K_0_0_1_0_value
-0.5
attn_project_K_0_1_0_0_product0
0
attn_project_K_0_1_0_0_product1
0
attn_project_K_0_1_0_0_value
0
attn_project_K_0_1_1_0_product0
0
attn_project_K_0_1_1_0_product1
0
attn_project_K_0_1_1_0_value
0
attn_project_K_0_2_0_0_product0
-0.5
attn_project_K_0_2_0_0_product1
0
attn_project_K_0_2_0_0_value
-0.5
attn_project_K_0_2_1_0_product0
0
attn_project_K_0_2_1_0_product1
0.5
attn_project_K_0_2_1_0_value
0.5
attn_project_V_0_0_0_0_product0
0.5
attn_project_V_0_0_0_0_product1
0
attn_project_V_0_0_0_0_value
0.5
attn_project_V_0_0_1_0_product0
0
attn_project_V_0_0_1_0_product1
-0.5
attn_project_V_0_0_1_0_value
-0.5
attn_project_V_0_1_0_0_product0
0
attn_project_V_0_1_0_0_product1
0
attn_project_V_0_1_0_0_value
0
attn_project_V_0_1_1_0_product0
0
attn_project_V_0_1_1_0_product1
0
attn_project_V_0_1_1_0_value
0
attn_project_V_0_2_0_0_product0
-0.5
attn_project_V_0_2_0_0_product1
0
attn_project_V_0_2_0_0_value
-0.5
attn_project_V_0_2_1_0_product0
0
attn_project_V_0_2_1_0_product1
0.5
attn_project_V_0_2_1_0_value
0.5
attn_reshape_Q_elements
6
attn_permute_Q_0_0_0_0_value
0.5
attn_permute_Q_0_0_1_0_value
0
attn_permute_Q_0_0_2_0_value
-0.5
attn_permute_Q_0_1_0_0_value
-0.5
attn_permute_Q_0_1_1_0_value
0
attn_permute_Q_0_1_2_0_value
0.5
attn_reshape_K_elements
6
attn_permute_K_0_0_0_0_value
0.5
attn_permute_K_0_0_1_0_value
0
attn_permute_K_0_0_2_0_value
-0.5
attn_permute_K_0_1_0_0_value
-0.5
attn_permute_K_0_1_1_0_value
0
attn_permute_K_0_1_2_0_value
0.5
attn_reshape_V_elements
6
attn_permute_V_0_0_0_0_value
0.5
attn_permute_V_0_0_1_0_value
0
attn_permute_V_0_0_2_0_value
-0.5
attn_permute_V_0_1_0_0_value
-0.5
attn_permute_V_0_1_1_0_value
0
attn_permute_V_0_1_2_0_value
0.5
attn_score_0_0_0_0_product0
0.25
attn_score_0_0_0_0_raw
0.25
attn_score_0_0_0_0_score
0.25
attn_score_0_0_0_1_product0
0
attn_score_0_0_0_1_raw
0
attn_score_0_0_0_1_score
0
attn_score_0_0_0_2_product0
-0.25
attn_score_0_0_0_2_raw
-0.25
attn_score_0_0_0_2_score
-0.25
attn_score_0_0_1_0_product0
0
attn_score_0_0_1_0_raw
0
attn_score_0_0_1_0_score
0
attn_score_0_0_1_1_product0
0
attn_score_0_0_1_1_raw
0
attn_score_0_0_1_1_score
0
attn_score_0_0_1_2_product0
0
attn_score_0_0_1_2_raw
0
attn_score_0_0_1_2_score
0
attn_score_0_0_2_0_product0
-0.25
attn_score_0_0_2_0_raw
-0.25
attn_score_0_0_2_0_score
-0.25
attn_score_0_0_2_1_product0
0
attn_score_0_0_2_1_raw
0
attn_score_0_0_2_1_score
0
attn_score_0_0_2_2_product0
0.25
attn_score_0_0_2_2_raw
0.25
attn_score_0_0_2_2_score
0.25
attn_score_0_1_0_0_product0
0.25
attn_score_0_1_0_0_raw
0.25
attn_score_0_1_0_0_score
0.25
attn_score_0_1_0_1_product0
0
attn_score_0_1_0_1_raw
0
attn_score_0_1_0_1_score
0
attn_score_0_1_0_2_product0
-0.25
attn_score_0_1_0_2_raw
-0.25
attn_score_0_1_0_2_score
-0.25
attn_score_0_1_1_0_product0
0
attn_score_0_1_1_0_raw
0
attn_score_0_1_1_0_score
0
attn_score_0_1_1_1_product0
0
attn_score_0_1_1_1_raw
0
attn_score_0_1_1_1_score
0
attn_score_0_1_1_2_product0
0
attn_score_0_1_1_2_raw
0
attn_score_0_1_1_2_score
0
attn_score_0_1_2_0_product0
-0.25
attn_score_0_1_2_0_raw
-0.25
attn_score_0_1_2_0_score
-0.25
attn_score_0_1_2_1_product0
0
attn_score_0_1_2_1_raw
0
attn_score_0_1_2_1_score
0
attn_score_0_1_2_2_product0
0.25
attn_score_0_1_2_2_raw
0.25
attn_score_0_1_2_2_score
0.25
attn_row_0_0_0_max
0.25
attn_row_0_0_0_denominator
1
attn_row_0_0_0_shifted0
0
attn_row_0_0_0_term0
1
attn_row_0_0_0_term1
0
attn_row_0_0_0_term2
0
attn_row_0_0_0_p0
1
attn_row_0_0_0_p1
0
attn_row_0_0_0_p2
0
attn_row_0_0_1_max
0
attn_row_0_0_1_denominator
2
attn_row_0_0_1_shifted0
0
attn_row_0_0_1_shifted1
0
attn_row_0_0_1_term0
1
attn_row_0_0_1_term1
1
attn_row_0_0_1_term2
0
attn_row_0_0_1_p0
0.5
attn_row_0_0_1_p1
0.5
attn_row_0_0_1_p2
0
attn_row_0_0_2_max
0.25
attn_row_0_0_2_denominator
2.385331442784038
attn_row_0_0_2_shifted0
-0.5
attn_row_0_0_2_shifted1
-0.25
attn_row_0_0_2_shifted2
0
attn_row_0_0_2_term0
0.6065306597126334
attn_row_0_0_2_term1
0.7788007830714049
attn_row_0_0_2_term2
1
attn_row_0_0_2_p0
0.25427521259046565
attn_row_0_0_2_p1
0.3264958357998367
attn_row_0_0_2_p2
0.4192289516096977
attn_row_0_1_0_max
0.25
attn_row_0_1_0_denominator
1
attn_row_0_1_0_shifted0
0
attn_row_0_1_0_term0
1
attn_row_0_1_0_term1
0
attn_row_0_1_0_term2
0
attn_row_0_1_0_p0
1
attn_row_0_1_0_p1
0
attn_row_0_1_0_p2
0
attn_row_0_1_1_max
0
attn_row_0_1_1_denominator
2
attn_row_0_1_1_shifted0
0
attn_row_0_1_1_shifted1
0
attn_row_0_1_1_term0
1
attn_row_0_1_1_term1
1
attn_row_0_1_1_term2
0
attn_row_0_1_1_p0
0.5
attn_row_0_1_1_p1
0.5
attn_row_0_1_1_p2
0
attn_row_0_1_2_max
0.25
attn_row_0_1_2_denominator
2.385331442784038
attn_row_0_1_2_shifted0
-0.5
attn_row_0_1_2_shifted1
-0.25
attn_row_0_1_2_shifted2
0
attn_row_0_1_2_term0
0.6065306597126334
attn_row_0_1_2_term1
0.7788007830714049
attn_row_0_1_2_term2
1
attn_row_0_1_2_p0
0.25427521259046565
attn_row_0_1_2_p1
0.3264958357998367
attn_row_0_1_2_p2
0.4192289516096977
attn_head_mix_0_0_0_0_product0
0.5
attn_head_mix_0_0_0_0_product1
0
attn_head_mix_0_0_0_0_product2
0
attn_head_mix_0_0_0_0_running0
0.5
attn_head_mix_0_0_0_0_running1
0.5
attn_head_mix_0_0_0_0_running2
0.5
attn_head_mix_0_0_0_0_value
0.5
attn_head_mix_0_0_1_0_product0
0.25
attn_head_mix_0_0_1_0_product1
0
attn_head_mix_0_0_1_0_product2
0
attn_head_mix_0_0_1_0_running0
0.25
attn_head_mix_0_0_1_0_running1
0.25
attn_head_mix_0_0_1_0_running2
0.25
attn_head_mix_0_0_1_0_value
0.25
attn_head_mix_0_0_2_0_product0
0.12713760629523282
attn_head_mix_0_0_2_0_product1
0
attn_head_mix_0_0_2_0_product2
-0.20961447580484885
attn_head_mix_0_0_2_0_running0
0.12713760629523282
attn_head_mix_0_0_2_0_running1
0.12713760629523282
attn_head_mix_0_0_2_0_running2
-0.08247686950961602
attn_head_mix_0_0_2_0_value
-0.08247686950961602
attn_head_mix_0_1_0_0_product0
-0.5
attn_head_mix_0_1_0_0_product1
0
attn_head_mix_0_1_0_0_product2
0
attn_head_mix_0_1_0_0_running0
-0.5
attn_head_mix_0_1_0_0_running1
-0.5
attn_head_mix_0_1_0_0_running2
-0.5
attn_head_mix_0_1_0_0_value
-0.5
attn_head_mix_0_1_1_0_product0
-0.25
attn_head_mix_0_1_1_0_product1
0
attn_head_mix_0_1_1_0_product2
0
attn_head_mix_0_1_1_0_running0
-0.25
attn_head_mix_0_1_1_0_running1
-0.25
attn_head_mix_0_1_1_0_running2
-0.25
attn_head_mix_0_1_1_0_value
-0.25
attn_head_mix_0_1_2_0_product0
-0.12713760629523282
attn_head_mix_0_1_2_0_product1
0
attn_head_mix_0_1_2_0_product2
0.20961447580484885
attn_head_mix_0_1_2_0_running0
-0.12713760629523282
attn_head_mix_0_1_2_0_running1
-0.12713760629523282
attn_head_mix_0_1_2_0_running2
0.08247686950961602
attn_head_mix_0_1_2_0_value
0.08247686950961602
attn_concat_0_0_0_0_value
0.5
attn_concat_0_0_1_0_value
-0.5
attn_concat_0_1_0_0_value
0.25
attn_concat_0_1_1_0_value
-0.25
attn_concat_0_2_0_0_value
-0.08247686950961602
attn_concat_0_2_1_0_value
0.08247686950961602
attn_output_0_0_0_product0
0.5
attn_output_0_0_0_product1
-0.5
attn_output_0_0_0_running0
0.5
attn_output_0_0_0_running1
0
attn_output_0_0_0_value
0
attn_output_0_0_1_product0
0.5
attn_output_0_0_1_product1
0.5
attn_output_0_0_1_running0
0.5
attn_output_0_0_1_running1
1
attn_output_0_0_1_value
1
attn_output_0_1_0_product0
0.25
attn_output_0_1_0_product1
-0.25
attn_output_0_1_0_running0
0.25
attn_output_0_1_0_running1
0
attn_output_0_1_0_value
0
attn_output_0_1_1_product0
0.25
attn_output_0_1_1_product1
0.25
attn_output_0_1_1_running0
0.25
attn_output_0_1_1_running1
0.5
attn_output_0_1_1_value
0.5
attn_output_0_2_0_product0
-0.08247686950961602
attn_output_0_2_0_product1
0.08247686950961602
attn_output_0_2_0_running0
-0.08247686950961602
attn_output_0_2_0_running1
0
attn_output_0_2_0_value
0
attn_output_0_2_1_product0
-0.08247686950961602
attn_output_0_2_1_product1
-0.08247686950961602
attn_output_0_2_1_running0
-0.08247686950961602
attn_output_0_2_1_running1
-0.16495373901923205
attn_output_0_2_1_value
-0.16495373901923205
r1_0_0_0_value
3
r1_0_0_1_value
2
r1_0_1_0_value
2
r1_0_1_1_value
2.5
r1_0_2_0_value
-1
r1_0_2_1_value
0.835046260980768
n2_0_0_statistics_sum
5
n2_0_0_statistics_mean
2.5
n2_0_0_statistics_centered0
0.5
n2_0_0_statistics_centered1
-0.5
n2_0_0_statistics_square0
0.25
n2_0_0_statistics_square1
0.25
n2_0_0_statistics_squareSum
0.5
n2_0_0_statistics_variance
0.25
n2_0_0_statistics_variancePlusEpsilon
3.25
n2_0_0_statistics_denominator
1.8027756377319946
n2_0_0_feature_0_normalized
0.2773500981126146
n2_0_0_feature_0_scaled
0.2773500981126146
n2_0_0_feature_0_value
0.2773500981126146
n2_0_0_feature_1_normalized
-0.2773500981126146
n2_0_0_feature_1_scaled
-0.2773500981126146
n2_0_0_feature_1_value
-0.2773500981126146
n2_0_1_statistics_sum
4.5
n2_0_1_statistics_mean
2.25
n2_0_1_statistics_centered0
-0.25
n2_0_1_statistics_centered1
0.25
n2_0_1_statistics_square0
0.0625
n2_0_1_statistics_square1
0.0625
n2_0_1_statistics_squareSum
0.125
n2_0_1_statistics_variance
0.0625
n2_0_1_statistics_variancePlusEpsilon
3.0625
n2_0_1_statistics_denominator
1.75
n2_0_1_feature_0_normalized
-0.14285714285714285
n2_0_1_feature_0_scaled
-0.14285714285714285
n2_0_1_feature_0_value
-0.14285714285714285
n2_0_1_feature_1_normalized
0.14285714285714285
n2_0_1_feature_1_scaled
0.14285714285714285
n2_0_1_feature_1_value
0.14285714285714285
n2_0_2_statistics_sum
-0.16495373901923205
n2_0_2_statistics_mean
-0.08247686950961602
n2_0_2_statistics_centered0
-0.9175231304903839
n2_0_2_statistics_centered1
0.9175231304903839
n2_0_2_statistics_square0
0.841848694984874
n2_0_2_statistics_square1
0.841848694984874
n2_0_2_statistics_squareSum
1.683697389969748
n2_0_2_statistics_variance
0.841848694984874
n2_0_2_statistics_variancePlusEpsilon
3.841848694984874
n2_0_2_statistics_denominator
1.960063441571439
n2_0_2_feature_0_normalized
-0.4681088943502662
n2_0_2_feature_0_scaled
-0.4681088943502662
n2_0_2_feature_0_value
-0.4681088943502662
n2_0_2_feature_1_normalized
0.4681088943502662
n2_0_2_feature_1_scaled
0.4681088943502662
n2_0_2_feature_1_value
0.4681088943502662
ffn_hidden_0_0_0_product0
0.2773500981126146
ffn_hidden_0_0_0_product1
0
ffn_hidden_0_0_0_sum
0.2773500981126146
ffn_hidden_0_0_0_preactivation
0.2773500981126146
ffn_hidden_0_0_1_product0
0
ffn_hidden_0_0_1_product1
-0.2773500981126146
ffn_hidden_0_0_1_sum
-0.2773500981126146
ffn_hidden_0_0_1_preactivation
-0.2773500981126146
ffn_hidden_0_0_2_product0
0.2773500981126146
ffn_hidden_0_0_2_product1
0.2773500981126146
ffn_hidden_0_0_2_sum
0.5547001962252291
ffn_hidden_0_0_2_preactivation
0.5547001962252291
ffn_hidden_0_1_0_product0
-0.14285714285714285
ffn_hidden_0_1_0_product1
0
ffn_hidden_0_1_0_sum
-0.14285714285714285
ffn_hidden_0_1_0_preactivation
-0.14285714285714285
ffn_hidden_0_1_1_product0
0
ffn_hidden_0_1_1_product1
0.14285714285714285
ffn_hidden_0_1_1_sum
0.14285714285714285
ffn_hidden_0_1_1_preactivation
0.14285714285714285
ffn_hidden_0_1_2_product0
-0.14285714285714285
ffn_hidden_0_1_2_product1
-0.14285714285714285
ffn_hidden_0_1_2_sum
-0.2857142857142857
ffn_hidden_0_1_2_preactivation
-0.2857142857142857
ffn_hidden_0_2_0_product0
-0.4681088943502662
ffn_hidden_0_2_0_product1
0
ffn_hidden_0_2_0_sum
-0.4681088943502662
ffn_hidden_0_2_0_preactivation
-0.4681088943502662
ffn_hidden_0_2_1_product0
0
ffn_hidden_0_2_1_product1
0.4681088943502662
ffn_hidden_0_2_1_sum
0.4681088943502662
ffn_hidden_0_2_1_preactivation
0.4681088943502662
ffn_hidden_0_2_2_product0
-0.4681088943502662
ffn_hidden_0_2_2_product1
-0.4681088943502662
ffn_hidden_0_2_2_sum
-0.9362177887005324
ffn_hidden_0_2_2_preactivation
-0.9362177887005324
ffn_relu_0_0_0_activation
0.2773500981126146
ffn_relu_0_0_1_activation
0
ffn_relu_0_0_2_activation
0.5547001962252291
ffn_relu_0_1_0_activation
0
ffn_relu_0_1_1_activation
0.14285714285714285
ffn_relu_0_1_2_activation
0
ffn_relu_0_2_0_activation
0
ffn_relu_0_2_1_activation
0.4681088943502662
ffn_relu_0_2_2_activation
0
ffn_output_0_0_0_product0
0.1386750490563073
ffn_output_0_0_0_product1
0
ffn_output_0_0_0_product2
0.1386750490563073
ffn_output_0_0_0_running0
0.1386750490563073
ffn_output_0_0_0_running1
0.1386750490563073
ffn_output_0_0_0_running2
0.2773500981126146
ffn_output_0_0_0_sum
0.2773500981126146
ffn_output_0_0_0_value
0.2773500981126146
ffn_output_0_0_1_product0
0
ffn_output_0_0_1_product1
0
ffn_output_0_0_1_product2
0.1386750490563073
ffn_output_0_0_1_running0
0
ffn_output_0_0_1_running1
0
ffn_output_0_0_1_running2
0.1386750490563073
ffn_output_0_0_1_sum
0.1386750490563073
ffn_output_0_0_1_value
0.1386750490563073
ffn_output_0_1_0_product0
0
ffn_output_0_1_0_product1
0
ffn_output_0_1_0_product2
0
ffn_output_0_1_0_running0
0
ffn_output_0_1_0_running1
0
ffn_output_0_1_0_running2
0
ffn_output_0_1_0_sum
0
ffn_output_0_1_0_value
0
ffn_output_0_1_1_product0
0
ffn_output_0_1_1_product1
-0.07142857142857142
ffn_output_0_1_1_product2
0
ffn_output_0_1_1_running0
0
ffn_output_0_1_1_running1
-0.07142857142857142
ffn_output_0_1_1_running2
-0.07142857142857142
ffn_output_0_1_1_sum
-0.07142857142857142
ffn_output_0_1_1_value
-0.07142857142857142
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.2340544471751331
ffn_output_0_2_1_product2
0
ffn_output_0_2_1_running0
0
ffn_output_0_2_1_running1
-0.2340544471751331
ffn_output_0_2_1_running2
-0.2340544471751331
ffn_output_0_2_1_sum
-0.2340544471751331
ffn_output_0_2_1_value
-0.2340544471751331
r2_0_0_0_value
3.2773500981126147
r2_0_0_1_value
2.138675049056307
r2_0_1_0_value
2
r2_0_1_1_value
2.4285714285714284
r2_0_2_0_value
-1
r2_0_2_1_value
0.6009918138056348

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 · Original raw block input retained on the first residual skip.

Storage indexValue
03
11
22
32
4-1
51

N1Gamma

D=2 · float64 · display precision 8 · N1 independent shared per-feature scales.

Storage indexValue
01
11

N1Beta

D=2 · float64 · display precision 8 · N1 independent shared per-feature offsets.

Storage indexValue
00
10

N1Mean

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · N1 per-token feature mean; no token/batch averaging.

Storage indexValue
02
12
20

N1Variance

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · N1 per-token population variance over D=2 features.

Storage indexValue
01
10
21

N1Denominator

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · N1 sqrt(variance+n1epsilon).

Storage indexValue
02
11.7320508075688772
22

N1Centered

B=1 × T=3 × D=2 · float64 · display precision 8 · X minus this stage's per-token mean.

Storage indexValue
01
1-1
20
30
4-1
51

N1Normalized

B=1 × T=3 × D=2 · float64 · display precision 8 · N1 centered features divided by the saved denominator, before gamma/beta.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

N1

B=1 × T=3 × D=2 · float64 · display precision 8 · N1: this stage's feature-only LayerNorm affine output.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnX

B=1 × T=3 × D=2 · float64 · display precision 8 · Active token rows; D=2 input features always retained.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnWQ

D=2 × QueryFeature=2 · float64 · display precision 8 · Query columns packed by h*Dk+f from wq{d}{h}{f}.

Storage indexValue
01
10
20
31

AttnWK

D=2 × KeyFeature=2 · float64 · display precision 8 · Key columns packed by h*Dk+f from wk{d}{h}{f}.

Storage indexValue
01
10
20
31

AttnWV

D=2 × ValueFeature=2 · float64 · display precision 8 · Value columns packed by h*Dv+f from wv{d}{h}{f}.

Storage indexValue
01
10
20
31

AttnQConcat

B=1 × T=3 × QueryFeature=2 · float64 · display precision 8 · XWQ; each packed coordinate has two products and one sum.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnKConcat

B=1 × T=3 × KeyFeature=2 · float64 · display precision 8 · XWK; each packed coordinate has two products and one sum.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnVConcat

B=1 × T=3 × ValueFeature=2 · float64 · display precision 8 · XWV; values are projected separately from queries and keys.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnQSplit

B=1 × T=3 × H=2 × Dk=1 · float64 · display precision 8 · QConcat reshaped without changing flat order; feature=h*F+f.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnQHeads

B=1 × H=2 × T=3 × Dk=1 · float64 · display precision 8 · QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

Storage indexValue
00.5
10
2-0.5
3-0.5
40
50.5

AttnKSplit

B=1 × T=3 × H=2 × Dk=1 · float64 · display precision 8 · KConcat reshaped without changing flat order; feature=h*F+f.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnKHeads

B=1 × H=2 × T=3 × Dk=1 · float64 · display precision 8 · KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

Storage indexValue
00.5
10
2-0.5
3-0.5
40
50.5

AttnVSplit

B=1 × T=3 × H=2 × Dv=1 · float64 · display precision 8 · VConcat reshaped without changing flat order; feature=h*F+f.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

AttnVHeads

B=1 × H=2 × T=3 × Dv=1 · float64 · display precision 8 · VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

Storage indexValue
00.5
10
2-0.5
3-0.5
40
50.5

Attnraw

B=1 × H=2 × Query=3 × Key=3 · float64 · display precision 8 · Separate QHeads KHeads transpose products within every batch and head.

Storage indexValue
00.25
10
2-0.25
30
40
50
6-0.25
70
80.25
90.25
100
11-0.25
120
130
140
15-0.25
160
170.25

Attnscores

B=1 × H=2 × Query=3 × Key=3 · float64 · display precision 8 · raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.

Storage indexValue
00.25
10
2-0.25
30
40
50
6-0.25
70
80.25
90.25
100
11-0.25
120
130
140
15-0.25
160
170.25

Attnallowed

B=1 × H=2 × Query=3 × Key=3 · bool · display precision 8 · Causal and/or valid-key mask; shared validity across B and H; every query retained.

Storage indexValue
0true
1false
2false
3true
4true
5false
6true
7true
8true
9true
10false
11false
12true
13true
14false
15true
16true
17true

Attnlogits

B=1 × H=2 × Query=3 × Key=3 · float64 · display precision 8 · Finite score+shift, including forbidden cells; mask applied separately.

Storage indexValue
00.25
10
2-0.25
30
40
50
6-0.25
70
80.25
90.25
100
11-0.25
120
130
140
15-0.25
160
170.25

Attnprobabilities

B=1 × H=2 × Query=3 × Key=3 · float64 · display precision 8 · Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.

Storage indexValue
01
10
20
30.5
40.5
50
60.25427521259046565
70.3264958357998367
80.4192289516096977
91
100
110
120.5
130.5
140
150.25427521259046565
160.3264958357998367
170.4192289516096977

AttnOHeads

B=1 × H=2 × Query=3 × Dv=1 · float64 · display precision 8 · Actual per-head P times VHeads; every product and running sum is traced.

Storage indexValue
00.5
10.25
2-0.08247686950961602
3-0.5
4-0.25
50.08247686950961602

AttnC

B=1 × T=3 × JoinedValue=2 · float64 · display precision 8 · OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged.

Storage indexValue
00.5
1-0.5
20.25
3-0.25
4-0.08247686950961602
50.08247686950961602

AttnWO

JoinedValue=2 × D=2 · float64 · display precision 8 · wo{h}{f}{d} packed in h,f,d order, preserving parameter identity.

Storage indexValue
01
11
21
3-1

AttnY

B=1 × T=3 × D=2 · float64 · display precision 8 · Y=C WO, summing products in ascending joined-feature order from zero; no normalization.

Storage indexValue
00
11
20
30.5
40
5-0.16495373901923205

R1

B=1 × T=3 × D=2 · float64 · display precision 8 · Exact named-shape addition of X and AttnY; no broadcasting.

Storage indexValue
03
12
22
32.5
4-1
50.835046260980768

N2Gamma

D=2 · float64 · display precision 8 · N2 independent shared per-feature scales.

Storage indexValue
01
11

N2Beta

D=2 · float64 · display precision 8 · N2 independent shared per-feature offsets.

Storage indexValue
00
10

N2Mean

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · N2 per-token feature mean; no token/batch averaging.

Storage indexValue
02.5
12.25
2-0.08247686950961602

N2Variance

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · N2 per-token population variance over D=2 features.

Storage indexValue
00.25
10.0625
20.841848694984874

N2Denominator

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · N2 sqrt(variance+n2epsilon).

Storage indexValue
01.8027756377319946
11.75
21.960063441571439

N2Centered

B=1 × T=3 × D=2 · float64 · display precision 8 · R1 minus this stage's per-token mean.

Storage indexValue
00.5
1-0.5
2-0.25
30.25
4-0.9175231304903839
50.9175231304903839

N2Normalized

B=1 × T=3 × D=2 · float64 · display precision 8 · N2 centered features divided by the saved denominator, before gamma/beta.

Storage indexValue
00.2773500981126146
1-0.2773500981126146
2-0.14285714285714285
30.14285714285714285
4-0.4681088943502662
50.4681088943502662

N2

B=1 × T=3 × D=2 · float64 · display precision 8 · N2: this stage's feature-only LayerNorm affine output.

Storage indexValue
00.2773500981126146
1-0.2773500981126146
2-0.14285714285714285
30.14285714285714285
4-0.4681088943502662
50.4681088943502662

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
00.2773500981126146
1-0.2773500981126146
20.5547001962252291
3-0.14285714285714285
40.14285714285714285
5-0.2857142857142857
6-0.4681088943502662
70.4681088943502662
8-0.9362177887005324

Hidden

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

Storage indexValue
00.2773500981126146
10
20.5547001962252291
30
40.14285714285714285
50
60
70.4681088943502662
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
00.2773500981126146
10.1386750490563073
20
3-0.07142857142857142
40
5-0.2340544471751331

Y

B=1 × T=3 × D=2 · float64 · display precision 8 · Exact named-shape addition of R1 and F; no broadcasting.

Storage indexValue
03.2773500981126147
12.138675049056307
22
32.4285714285714284
4-1
50.6009918138056348

B,T,H,Dk,Dv, mask mode, key validity, common score shift and both positive epsilons remain visible. Open native groups for X, WQ/WK/WV/WO, the four FFN parameter groups, or LN1/LN2 scales and offsets. All 81 fields are editable and validated, including inactive slots. D=2 output features and M=3 hidden features are fixed; M is distinct from H attention heads.

The default is a causal pre-norm decoder block. Pre-norm places layer normalization before each branch; the original X bypasses the attention branch and R1 bypasses the FFN branch. The stage flow and expandable attention, normalization and FFN views all read the same saved computation. A fully masked query makes the entire block unavailable, including the final output.

Hand-derived complete default: all three token rows

These exact real expressions are manual mathematics, distinct from the saved binary64 values in the tables. Both epsilons are 3, both gamma vectors are (1,1), and both beta vectors are (0,0). LN1 gives N1=(1/2,-1/2),(0,0),(-1/2,1/2). With H=2 and Dk=Dv=1, head 0 projects the first feature and head 1 the second for Q,K,V.

Head 0 query/key coordinates are (1/2,0,-1/2), giving scaled score rows (1/4,0,-1/4),(0,0,0),(-1/4,0,1/4). Head 1 negates both Q and K, so each score product is unchanged and its probability map coincides. Causality gives allowed probability rows (1,0,0),(1/2,1/2,0),(1,s,s²)/(1+s+s²), where s=exp(1/4). Each head is still computed separately.

Head 0 values are (1/2,0,-1/2). Weighted sums are 1×1/2=1/2; (1/2)×(1/2)+(1/2)×0=1/4; and (1/2+0×s-(1/2)×s²)/(1+s+s²)=a, where a=(1-s²)/(2(1+s+s²)). Head 1 gives the negatives. Concatenation produces C=(1/2,-1/2),(1/4,-1/4),(a,-a). WO rows (1,1),(1,-1) yield A=(0,1),(0,1/2),(0,2a).

The first residual is R1=(3,2),(2,5/2),(-1,1+2a). LN2 has means 5/2,9/4,a; centered rows (1/2,-1/2),(-1/4,1/4),(-1-a,1+a); population variances 1/4,1/16,(1+a)²; denominators sqrt(13)/2,7/4,sqrt((1+a)²+3). Therefore N2=(u,-u),(-1/7,1/7),(-v,v), where u=1/sqrt(13) and v=(1+a)/sqrt((1+a)²+3). Since -1/2<a<1/2, v is positive.

The FFN preactivations are (u,-u,2u),(-1/7,1/7,-2/7),(-v,v,-2v). ReLU gives (u,0,2u),(0,1/7,0),(0,v,0). W2 then gives F=(u/2+0+2u/4,0+0+2u/4)=(u,u/2), (0,-1/14), (0,-v/2), with zero biases. Finally Y=(3+u,2+u/2),(2,17/7),(-1,1+2a-v/2). Different projections need not produce different probability maps: the sign-reversed default Q/K heads are an explicit counterexample.

Check your understanding

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

1. Which order describes this pre-norm transformer block? LN means layer normalization, MHA multi-head attention, and FFN feed-forward network.
2. For the fixed default first token, X[0,0,:]=(3,1) and the complete attention branch gives A[0,0,:]=(0,1). What is R1 before LN2?
3. Use the current starting inputs and saved r2_0_0_0: skip=3, branch=0.2773500981126146. What is Y[0,0,0]?
4. Hold all other inputs fixed and set every active WO entry to zero. Which statement is always valid for a defined block result?
5. Counterexample check: set every W2 entry and both b2 entries to zero while retaining a defined attention computation. What follows?

Reset begins with rows (3,1),(2,2),(−1,1), two attention heads and causal masking. Follow the stage flow from X to Y, then inspect one token’s normalization records, each head’s query/key/value projections, score and probability rows, output projection, residual sums and hidden FFN features. Calculation-step navigation shows saved operands. Changing an inspector selector changes your view; editing a numeric input starts a new computation.

Open the initially closed input, projection and FFN parameter groups before editing their entries. LN1 feature scales and offsets and LN2 feature scales and offsets contain the independent gamma/beta values. Dimensions, mask choices and both epsilons remain visible. Try an output-projection edit and watch the first residual before following the second normalization. Reset before the exact worked example. The lab’s five graded questions use fixed named coordinates, independently of the selected view.

Name the operations before composing them

A token row is a position’s feature vector. A tensor is an array with named axes. X[B,T,D] has B sequences, T token positions and D=2 features. Lowercase b,t,d are zero-based indices. A residual stream is the tensor carried forward by adding a branch result to its incoming tensor; “skip” names the route bypassing that branch.

LN means layer normalization, applied here only over a token’s two features. It subtracts their mean, divides by a stabilized standard deviation, multiplies by per-feature scale gamma and adds per-feature offset beta. Pre-norm means that normalization happens before a branch, while the residual skip keeps the branch’s unnormalized incoming stream. Two independent parameter sets LN₁ and LN₂ are used. Their subscripts identify stages, not tokens.

MHA means multi-head attention: each head forms its own queries Q, keys K and values V. Queries and keys determine scores; normalized scores determine how value rows are combined. H counts heads, Dk counts query/key features per head and Dv counts value features per head. A mask specifies which keys a query may use. A causal mask allows key j only when j≤i for query i. A logit is a score presented to softmax; softmax exponentiates allowed logits and divides by their exponential sum to form probabilities. The softmax is over keys within one batch, head and query, never over heads or batches.

FFN means feed-forward network; here it is a shared MLP, or multilayer perceptron, with two affine layers. An affine layer multiplies features by weights and adds a bias. Its hidden activation is ReLU, the rectified linear unit max(0,z), including ReLU(0)=0. The preactivation z is the affine result before ReLU; its activation is the value afterward. Z stores all preactivations and Hidden stores all activations. M=3 counts hidden features and is unrelated to H heads. These definitions apply locally even if you have not memorized the abbreviations from earlier chapters.

The exact six-stage order is:

N1=LN⁡1(X),A=MHA⁡(N1,mask),R1=X+A,N_1=\operatorname{LN}_1(X),\quad A=\operatorname{MHA}(N_1,\mathrm{mask}),\quad R_1=X+A, N2=LN⁡2(R1),F=FFN⁡(N2),Y=R1+F.N_2=\operatorname{LN}_2(R_1),\quad F=\operatorname{FFN}(N_2),\quad Y=R_1+F.

N₁ and N₂ are the normalized branch inputs. A is the attention branch after joining heads and multiplying by output weights; R₁ is the first residual sum; F is the FFN branch; Y is the block output. A is not the attention probability matrix. No normalization follows the final addition in this declared pre-norm block.

The two residual additions require identical dimensions and named axes [B,T,2], B,T,D. Equal element counts alone do not make tensors addable. There is no implicit broadcasting, head average or hidden output softmax.

Stage recordsShapeMeaning
X, N1, A stored as AttnY, R1, N2, F, Y[B,T,2]Two features per token throughout the residual stream
N1Gamma, N1Beta; N2Gamma, N2Beta[2]Independent shared feature scales and offsets
Each norm’s Mean, Variance, Denominator[B,T,1]Separate statistic per token, axes B,T,Statistic
Each norm’s Centered, Normalized[B,T,2]Feature-wise intermediate values
AttnWQ, AttnWK; AttnWV[2,H*Dk]; [2,H*Dv]Packed head projection weights
AttnQHeads, AttnKHeads; AttnVHeads[B,H,T,Dk]; [B,H,T,Dv]Queries, keys and values separated by head
Attnraw, Attnscores, Attnallowed, Attnlogits, Attnprobabilities[B,H,T,T]Axes B,H,Query,Key; allowed is boolean
AttnOHeads; AttnC; AttnWO[B,H,T,Dv]; [B,T,H*Dv]; [H*Dv,2]Per-head mixtures, concatenation, output projection
W1, b1, Z, Hidden, W2, b2[2,3], [3], [B,T,3], [B,T,3], [3,2], [2]The same FFN expansion and contraction as IV-32

Packed query/key/value arrays also preserve their [B,T,H*width] and [B,T,H,width] layouts before permuting the head axis. Here width is Dk for Q/K and Dv for V. Reshape changes the indexing description without changing flat order; permutation explicitly copies into another axis order; concatenation places all head outputs side by side. None is an average.

How the attention equations extend when you edit head widths

Weights WQ and WK have packed columns h·Dk+f, where h is the head index and f is a query/key feature index. WV instead has columns h·Dv+g, where g is a value feature index. For each token i, the two N1 features multiply the corresponding weight column. For example:

Qbhif=∑d=01N1,bidWQ,d,hDk+f,Kbhjf=∑d=01N1,bjdWK,d,hDk+f.Q_{bhif}=\sum_{d=0}^{1}N_{1,bid}W_{Q,d,hD_k+f},\qquad K_{bhjf}=\sum_{d=0}^{1}N_{1,bjd}W_{K,d,hD_k+f}.

V uses the same two-feature sum with WV and its value-feature index g. The query position is i; the key/value position is j. The raw dot product sums only matching f coordinates within one head, then the score divides by the square root of that head’s query/key width:

scorebhij=∑f=0Dk−1QbhifKbhjfDk.\mathrm{score}_{bhij}=\frac{\sum_{f=0}^{D_k-1}Q_{bhif}K_{bhjf}}{\sqrt{D_k}}.

Add the common editable shift to obtain each logit. The allowed-key mask decides which logits participate in softmax; the worked table below shows the maximum subtraction, exponential terms and division. P names the resulting probability tensor. Each head’s value feature is then

Obhig=∑j=0T−1PbhijVbhjg,Cbi,hDv+g=Obhig,Abid=∑c=0HDv−1CbicWO,cd.O_{bhig}=\sum_{j=0}^{T-1}P_{bhij}V_{bhjg},\qquad C_{bi,hD_v+g}=O_{bhig},\qquad A_{bid}=\sum_{c=0}^{HD_v-1}C_{bic}W_{O,cd}.

Here O is the per-head output, C is the concatenation and c indexes its joined features. T−1, Dk−1 and H·Dv−1 mean the last zero-based index on their respective axes. The summation sign means add the listed contributions in ascending index order. Attention’s O sum mixes allowed token values; its A sum recombines joined head features at the same token. Neither mixes batches. WO maps H·Dv features back to two so A can be added to X. The FFN subsequently transforms N2 as ReLU(N2W1+b1)W2+b2, with no token sum.

The full three-token hand calculation

Everything below is an exact real manual expression, not an observed runtime output. All indices refer to batch zero. Defaults are B=1,T=3,D=2,H=2,Dk=Dv=1; both norms have gamma=(1,1), beta=(0,0), epsilon ε=3. Epsilon sits inside each square root. Three is chosen for hand-friendly arithmetic, not as a production recommendation.

1. First LayerNorm: calculate every token separately

For row x, μ=(x₀+x₁)/2 is the mean; c_d=x_d−μ is a centered feature. Population variance is ν=(c₀²+c₁²)/2, dividing by D=2 rather than the sample-statistic divisor D−1. The denominator is q=√(ν+ε), and the output feature is gamma_d·(c_d/q)+beta_d.

t, XSum → mean μCentered cSquares → sum → variance ν+ ε → denominator qDivide, scale by 1, add 0 → N1
0, (3,1)3+1=4 → 4/2=2(3−2,1−2)=(1,−1)(1·1,(−1)·(−1))=(1,1) → 2 → 11+3=4 → √4=2(1·(1/2)+0,1·(−1/2)+0)=(1/2,−1/2)
1, (2,2)2+2=4 → 4/2=2(0,0)(0·0,0·0)=(0,0) → 0 → 00+3=3 → √3(1·0/√3+0,1·0/√3+0)=(0,0)
2, (−1,1)−1+1=0 → 0/2=0(−1,1)((−1)·(−1),1·1)=(1,1) → 2 → 11+3=4 → √4=2(1·(−1/2)+0,1·(1/2)+0)=(−1/2,1/2)

Each statistic uses one row only. LN₂ will later recompute statistics from R₁, with its own parameters; it cannot reuse these means simply because its shape matches.

2. Actual attention projections, scores and masks

At the default one-feature width, each of WQ, WK and WV is the matrix with rows (1,0),(0,1). Head zero selects N1 feature zero; head one selects feature one. For each role Q,K,V the explicit products are:

tHead 0: two products and sumHead 1: two products and sum
0(1/2)·1+(−1/2)·0=1/2+0=1/2(1/2)·0+(−1/2)·1=0−1/2=−1/2
10·1+0·0=0+0=00·0+0·1=0+0=0
2(−1/2)·1+(1/2)·0=−1/2+0=−1/2(−1/2)·0+(1/2)·1=0+1/2=1/2

This table applies three times because these particular Q/K/V weights coincide. They remain separately editable projections. Denote the head-zero scalar sequence by r=(1/2,0,−1/2). Head one has −r. Each raw score is Q_iK_j, divided by √Dk=√1=1. Both heads’ score maps coincide since (−r_i)(−r_j)=r_ir_j, although their V sequences are opposite.

Query i, key jHead 0 productHead 1 productScore in either head after ÷1Allowed j≤i?
0,0(1/2)(1/2)=1/4(−1/2)(−1/2)=1/41/4yes
0,1(1/2)·0=0(−1/2)·0=00no
0,2(1/2)(−1/2)=−1/4(−1/2)(1/2)=−1/4−1/4no
1,00·(1/2)=00·(−1/2)=00yes
1,10·0=00·0=00yes
1,20·(−1/2)=00·(1/2)=00no
2,0(−1/2)(1/2)=−1/4(1/2)(−1/2)=−1/4−1/4yes
2,1(−1/2)·0=0(1/2)·0=00yes
2,2(−1/2)(−1/2)=1/4(1/2)(1/2)=1/41/4yes

Define s=exp(1/4), where exp is the exponential function, and E=1+s+s². Both are positive scalars. The default common logit shift is zero. Stable softmax subtracts the maximum allowed logit before exponentiating; forbidden keys get terms and probabilities exactly zero, not exp(0)=1.

Query iAllowed maximumAllowed shifted logitsTerms over keys 0,1,2Ascending term sumProbabilities P over keys 0,1,2
01/4key 0: 1/4−1/4=0(1,0,0)((0+1)+0)+0=1(1,0,0)
10keys 0,1: 0−0=0 each(1,1,0)((0+1)+1)+0=2(1/2,1/2,0)
21/4(−1/2,−1/4,0)(s⁻²,s⁻¹,1)((0+s⁻²)+s⁻¹)+1(1/E,s/E,s²/E)

The last row’s displayed probabilities multiply numerator and denominator of each stable quotient by s². This is an exact algebraic simplification, not a replacement for the implementation’s subtraction/exponential/sum order. P has separate head rows even though their default values coincide.

3. Weighted values, concatenation and output projection

Each head output is the key-weighted sum ∑_j P_ijV_j. Start from zero, multiply and immediately accumulate in ascending key order, including forbidden zero products. Define

a=1−s22(1+s+s2)=1−s22E.a=\frac{1-s^2}{2(1+s+s^2)}=\frac{1-s^2}{2E}.
Head h, token tproduct0; running0product1; running1product2; running2 = head output
0,01·(1/2)=1/2; 1/20·0=0; 1/2+0=1/20·(−1/2)=0; 1/2+0=1/2
0,1(1/2)(1/2)=1/4; 1/4(1/2)·0=0; 1/4+0=1/40·(−1/2)=0; 1/4+0=1/4
0,2(1/E)(1/2)=1/(2E); 1/(2E)(s/E)·0=0; 1/(2E)(s²/E)(−1/2)=−s²/(2E); (1−s²)/(2E)=a
1,01·(−1/2)=−1/2; −1/20·0=0; −1/20·(1/2)=0; −1/2
1,1(1/2)(−1/2)=−1/4; −1/4(1/2)·0=0; −1/40·(1/2)=0; −1/4
1,2(1/E)(−1/2)=−1/(2E); −1/(2E)(s/E)·0=0; −1/(2E)(s²/E)(1/2)=s²/(2E); (s²−1)/(2E)=−a

Concatenation copies the head-zero and head-one scalars into rows C=(1/2,−1/2),(1/4,−1/4),(a,−a). The default output matrix WO has rows (1,1),(1,−1). Thus A=CWO; its two output features are a sum and a difference, not the average of the heads.

t,dFirst product; running0 from 0Second product; running1 = A
0,0(1/2)·1=1/2; 1/2(−1/2)·1=−1/2; 1/2−1/2=0
0,1(1/2)·1=1/2; 1/2(−1/2)(−1)=1/2; 1/2+1/2=1
1,0(1/4)·1=1/4; 1/4(−1/4)·1=−1/4; 1/4−1/4=0
1,1(1/4)·1=1/4; 1/4(−1/4)(−1)=1/4; 1/4+1/4=1/2
2,0a·1=a; a(−a)·1=−a; a−a=0
2,1a·1=a; a(−a)(−1)=a; a+a=2a

4. First residual, then an independent second LayerNorm

Add A to the original X, not N₁. All six residual additions are:

R1,0=(3+0,1+1)=(3,2),R1,1=(2+0,2+12)=(2,52),R1,2=(−1+0,1+2a)=(−1,1+2a).R_{1,0}=(3+0,1+1)=(3,2),\quad R_{1,1}=(2+0,2+\tfrac12)=(2,\tfrac52),\quad R_{1,2}=(-1+0,1+2a)=(-1,1+2a).

The second index here is token position; each parenthesized pair contains feature zero and feature one. LN₂ now takes these new rows. Define u=1/√13 and v=(1+a)/√((1+a)²+3). Since s>1, a is negative; also E>s²−1, so a is greater than −1/2. Consequently 1+a>0, hence u>0 and v>0. These signs determine which FFN features survive ReLU.

t, R1Sum → meanCentered featuresSquared deviations → sum → population variance+3 → denominatorDivide, scale by 1, add 0 → N2
0, (3,2)3+2=5 → 5/2(3−5/2,2−5/2)=(1/2,−1/2)(1/4,1/4) → 1/2 → 1/41/4+3=13/4 → √13/2(1·(1/2)/(√13/2)+0,1·(−1/2)/(√13/2)+0)=(u,−u)
1, (2,5/2)2+5/2=9/2 → 9/4(2−9/4,5/2−9/4)=(−1/4,1/4)(1/16,1/16) → 1/8 → 1/161/16+3=49/16 → 7/4(1·(−1/4)/(7/4)+0,1·(1/4)/(7/4)+0)=(−1/7,1/7)
2, (−1,1+2a)−1+1+2a=2a → a(−1−a,1+a)((1+a)²,(1+a)²) → 2(1+a)² → (1+a)²(1+a)²+3 → √((1+a)²+3)(1·(−1−a)/q+0,1·(1+a)/q+0)=(−v,v), q=√((1+a)²+3)

A normalization changes the branch input without replacing its skip stream. N₂ is therefore (u,−u),(−1/7,1/7),(−v,v), while R₁ remains available for the final addition. Even with gamma one and beta zero, positive epsilon means normalized variance is ν/(ν+ε), generally below one.

5. Full FFN on these normalized rows

Use the same W1 rows (1,0,1),(0,1,−1), W2 rows (1/2,0),(0,−1/2),(1/4,1/4), and all-zero biases as IV-32. All hidden products, sums, bias additions and activations are:

t,mproduct0product1sum + hidden bias → zReLU(z) → h
0,0u·1=u(−u)·0=0(u+0)+0=uu
0,1u·0=0(−u)·1=−u(0−u)+0=−u0
0,2u·1=u(−u)(−1)=u(u+u)+0=2u2u
1,0(−1/7)·1=−1/7(1/7)·0=0(−1/7+0)+0=−1/70
1,1(−1/7)·0=0(1/7)·1=1/7(0+1/7)+0=1/71/7
1,2(−1/7)·1=−1/7(1/7)(−1)=−1/7(−1/7−1/7)+0=−2/70
2,0(−v)·1=−vv·0=0(−v+0)+0=−v0
2,1(−v)·0=0v·1=v(0+v)+0=vv
2,2(−v)·1=−vv·(−1)=−v(−v−v)+0=−2v0

The output loop again starts at zero, adds each hidden contribution immediately in m order and adds b2 last:

t,dproduct0; running0product1; running1product2; running2+ b2 → F
0,0u·1/2=u/2; u/20·0=0; u/2(2u)·1/4=u/2; uu+0=u
0,1u·0=0; 00·(−1/2)=0; 0(2u)·1/4=u/2; u/2u/2+0=u/2
1,00·1/2=0; 0(1/7)·0=0; 00·1/4=0; 00+0=0
1,10·0=0; 0(1/7)(−1/2)=−1/14; −1/140·1/4=0; −1/14−1/14+0=−1/14
2,00·1/2=0; 0v·0=0; 00·1/4=0; 00+0=0
2,10·0=0; 0v·(−1/2)=−v/2; −v/20·1/4=0; −v/2−v/2+0=−v/2

These F rows are (u,u/2),(0,−1/14),(0,−v/2). FFN never sums over another token; the cross-token dependence in this block arrived through attention before LN₂.

6. Final residual: keep the incoming R1

Finally Y=R₁+F. Every final coordinate follows directly:

Y0=(3+u,  2+u/2),Y_0=(3+u,\;2+u/2), Y1=(2+0,  5/2−1/14)=(2,  35/14−1/14)=(2,  17/7),Y_1=(2+0,\;5/2-1/14)=(2,\;35/14-1/14)=(2,\;17/7), Y2=(−1+0,  1+2a−v/2)=(−1,  1+2a−v/2).Y_2=(-1+0,\;1+2a-v/2)=(-1,\;1+2a-v/2).

The second token’s 17/7 comes from the changed residual row (2,5/2) and its own second normalization. Adding F to X instead would give a different answer. This is why operation order is part of the model, not a diagramming preference.

Read the actual Python composition

NumPy is the numerical-array library used to store shaped float64 arrays. Float64, or binary64, stores finite-precision numbers; exact symbolic cancellations above need not imply bit-for-bit symbolic simplification after every floating-point edit. Stored precision metadata controls display, never the arithmetic input.

Start with iv33.py: validate the complete editable state, save setup, and request the full block result. Then read block_reference.py in six-stage order. Its two normalization stages call feature_norm("layer",...) from component_reference.py; both residuals call same_shape_add. It uses the actual project_heads, attend_heads and join_heads functions from head_reference.py, with active input rows replaced by N₁, then calls feed_forward from ffn_reference.py on N₂. The separately displayed iv32.py shows the isolated FFN wrapper from which that component is reused.

Follow each norm’s sum, mean, centered features, squares, population variance, denominator, division, scale and offset. In attention, follow projection products, reshape/permutation copies, score products, allowed keys, exponentials, denominator, probabilities, weighted-value running sums, head concatenation and WO products. The default equal maps arise from sign reversal of Q and K, not from sharing or averaging head outputs.

The saved block records identify attention with attn_ step prefixes and Attn tensor prefixes. AttnX contains the actual N₁ values. Only the child attention setup is omitted because the block already saves its full raw starting state; all arithmetic records remain. r1_0_0_0 and r2_0_0_0 identify the two residual additions at the first feature of the first token. These names help map a displayed record to a source line without asking the view to calculate a second result.

Complete block wrapper

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-33 — A Complete Transformer Block.

Prerequisites: IV-29, IV-30, IV-31, IV-32. This pre-norm decoder uses
N1=LN1(X); A=MHA(N1,mask); R1=X+A; N2=LN2(R1); F=FFN(N2); Y=R1+F.
Each LayerNorm has its own gamma, beta and positive epsilon; masks retain all
queries. A query with no allowed key makes the ENTIRE result unavailable.

Hand default LN1 rows (.5,-.5),(0,0),(-.5,.5). Set s=exp(1/4),
a=(1-s*s)/(2*(1+s+s*s)). The two real heads have opposite values and,
for these defaults only, equal maps: head0 outputs (.5,.25,a), head1
(-.5,-.25,-a). The actual WO produces A=(0,1),(0,.5),(0,2*a).
R1=(3,2),(2,5/2),(-1,1+2*a). With u=1/sqrt(13) and
v=(1+a)/sqrt((1+a)**2+3)>0, N2=(u,-u),(-1/7,1/7),(-v,v),
F=(u,u/2),(0,-1/14),(0,-v/2), and final rows are
(3+u,2+u/2),(2,17/7),(-1,1+2*a-v/2). These are exact real manual
expressions, not observed binary64 outputs. No claim of training stability.
Zero FFN output leaves Y=R1; zero WO leaves R1=X, but FFN can still change Y.

Keep this wrapper, block_reference.py, ffn_reference.py and
component_reference.py in p07, and unchanged head_reference.py in sibling p06.
The head import is relative to the helper file, independent of the process cwd.
Source only; all execution and validation remain deferred.
"""
from types import MappingProxyType
from block_reference import BLOCK_DEFAULTS, block_state, transformer_block
from component_reference import component_trace, guarded, run

DEFAULT_IV33 = MappingProxyType(dict(BLOCK_DEFAULTS))


@guarded
def derive_iv33(state):
    """Save all 48 actual tensors and every scalar operation in pre-norm order."""
    s = block_state(state)
    trace = component_trace()
    trace.add("setup", "Validate the complete pre-norm block state",
              "N1=LN1(X); A=MHA(N1,mask); R1=X+A; N2=LN2(R1); F=FFN(N2); Y=R1+F",
              "Validate all 81 original fields before selecting active dimensions; both residual additions are always on.",
              s, dict(B=s["B"], T=s["T"], D=2, H=s["H"], Dk=s["Dk"], Dv=s["Dv"], M=3,
                      mode=s["mode"], n1epsilon=s["n1epsilon"], n2epsilon=s["n2epsilon"]))
    block = transformer_block(s, trace)
    summary = dict(block["final_aliases"])
    summary.update(B=s["B"], T=s["T"], H=s["H"], Dk=s["Dk"], Dv=s["Dv"], M=3)
    summary.update(block["aliases"])
    return trace.result(summary, block["tensors"])


if __name__ == "__main__":
    run(derive_iv33, DEFAULT_IV33)

Block composition helper

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: actual pre-norm composition, reusing the existing stage kernels.

N1=LN1(X); A=MHA(N1,mask); R1=X+A; N2=LN2(R1); F=FFN(N2); Y=R1+F.
Both residual paths are always on. M=3 hidden features is distinct from H heads.
There is no hidden postnorm, head average, output softmax, dropout or training.
NumPy stores actual intermediate arrays; reused helpers own the arithmetic.
This source has not been imported, executed or runtime-validated.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
import numpy as np
from component_reference import (
    NORM_DEFAULTS, NumericalFault, feature_norm, finite, same_shape_add, tensor,
)
from ffn_reference import FFN_PARAMETERS, feed_forward

# Resolve the unchanged head helper relative to THIS file, never the caller's cwd.
_head_path = Path(__file__).resolve().parent.parent / "p06" / "head_reference.py"
_head_spec = importlib.util.spec_from_file_location("_p07_p06_head_reference", _head_path)
_head = importlib.util.module_from_spec(_head_spec)
_head_spec.loader.exec_module(_head)

_block_defaults = dict(_head.OUTPUT_HEAD_DEFAULTS)
# Replacing existing X values preserves every p06 default's original key position.
_block_defaults.update({key: value for key, value in NORM_DEFAULTS.items() if key.startswith("x")})
_block_defaults.update(FFN_PARAMETERS)
_block_defaults.update(
    n1gamma0=1, n1gamma1=1, n1beta0=0, n1beta1=0, n1epsilon=3,
    n2gamma0=1, n2gamma1=1, n2beta0=0, n2beta1=0, n2epsilon=3,
)
BLOCK_DEFAULTS = MappingProxyType(_block_defaults)
del _block_defaults


def block_state(state):
    """Validate all 81 raw fields once, including every inactive head/X slot."""
    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(BLOCK_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), H=(1, 2), Dk=(1, 2), Dv=(1, 2),
                          mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
    result = {}
    for key in BLOCK_DEFAULTS:
        value = finite(state[key], key)
        low, high = integer_bounds.get(
            key, (-10000, 10000) if key == "shift" else
            (1e-8, 4) if key in ("n1epsilon", "n2epsilon") 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 _norm_stage(s, input_record, trace, name):
    """Use actual width-two feature_norm and save its eight stage-local tensors."""
    B, T = s["B"], s["T"]
    shape, axes = [B, T, 2], ["B", "T", "D"]
    stat_shape, stat_axes = [B, T, 1], ["B", "T", "Statistic"]
    prefix = name.lower()
    X = np.array(input_record["values"], dtype=np.float64).reshape(shape)
    gamma = np.array([s[f"{prefix}gamma{d}"] for d in range(2)], dtype=np.float64)
    beta = np.array([s[f"{prefix}beta{d}"] for d in range(2)], dtype=np.float64)
    mean, variance, denominator = (np.empty(stat_shape, dtype=np.float64) for _ in range(3))
    centered, normalized, output = (np.empty(shape, dtype=np.float64) for _ in range(3))
    aliases = {}
    for b in range(B):
        for t in range(T):
            row = feature_norm("layer", f"{prefix}_{b}_{t}", X[b, t].tolist(),
                               gamma.tolist(), beta.tolist(), s[f"{prefix}epsilon"], trace)
            statistics = row["statistics"]
            mean[b, t, 0], variance[b, t, 0] = statistics["mean"], statistics["variance"]
            denominator[b, t, 0] = statistics["denominator"]
            for d in range(2):
                centered[b, t, d] = statistics[f"centered{d}"]
                normalized[b, t, d] = row["normalized"][d]
                output[b, t, d] = row["values"][d]
                aliases[f"{prefix}{b}{t}{d}"] = row["values"][d]
    tensors = [
        tensor(f"{name}Gamma", [2], ["D"], gamma.tolist(), f"{name} independent learned per-feature scales."),
        tensor(f"{name}Beta", [2], ["D"], beta.tolist(), f"{name} independent learned per-feature offsets."),
        tensor(f"{name}Mean", stat_shape, stat_axes, mean.reshape(-1).tolist(), f"{name} per-token mean across exactly two features."),
        tensor(f"{name}Variance", stat_shape, stat_axes, variance.reshape(-1).tolist(), f"{name} population variance from actual centered squares."),
        tensor(f"{name}Denominator", stat_shape, stat_axes, denominator.reshape(-1).tolist(), f"{name} sqrt(variance+epsilon), using this stage's own positive epsilon."),
        tensor(f"{name}Centered", shape, axes, centered.reshape(-1).tolist(), f"{name} input features minus their own token mean."),
        tensor(f"{name}Normalized", shape, axes, normalized.reshape(-1).tolist(), f"{name} centered features divided by the saved denominator."),
        tensor(name, shape, axes, output.reshape(-1).tolist(), f"{name} normalized features times gamma then plus beta, from feature_norm."),
    ]
    return dict(output=tensors[-1], tensors=tensors, aliases=aliases)


def _attention_stage(s, n1, trace):
    """Copy every real p06 child record, adapting its distinct known fault class."""
    # Raw state was validated already. Derived N1 may exceed [-4,4]: DO NOT head_state it.
    head_input = {key: s[key] for key in _head.OUTPUT_HEAD_DEFAULTS}
    B, T = s["B"], s["T"]
    for b in range(B):
        for t in range(T):
            for d in range(2):
                head_input[f"x{b}{t}{d}"] = n1["values"][(b * T + t) * 2 + d]
    child_trace = _head.head_trace()
    try:
        projected = _head.project_heads(head_input, child_trace)
        attended = _head.attend_heads(head_input, projected, child_trace)
        joined = _head.join_heads(head_input, attended, child_trace)
    except _head.NumericalFault as error:
        # The p07 guarded wrapper catches component faults, not p06's distinct class.
        raise NumericalFault(error.code, str(error)) from error
    for step in child_trace.steps:
        if step["id"] != "setup":
            trace.add(f"attn_{step['id']}", f"Attention: {step['label']}",
                      step["equation"], step["explanation"], step["inputs"], step["outputs"])
    tensors, aliases = [], {}
    for stage in (projected, attended, joined):
        for record in stage["tensors"]:
            # Preserve the real bool allowed mask, precision, axes and flat value order.
            tensors.append({**record, "id": f"Attn{record['id']}", "shape": list(record["shape"]),
                            "axes": list(record["axes"]), "values": list(record["values"])})
        aliases.update({f"attn_{key}": value for key, value in stage["aliases"].items()})
    return dict(output=tensors[-1], tensors=tensors, aliases=aliases)


def _residual_stage(identifier, prefix, left, right, trace):
    """The saved values come from same_shape_add, with no second addition."""
    result = same_shape_add(identifier, left, right)
    B, T, _ = result["shape"]
    aliases = {}
    for b in range(B):
        for t in range(T):
            for d in range(2):
                index = (b * T + t) * 2 + d
                value = result["values"][index]
                trace.add(f"{prefix}_{b}_{t}_{d}", f"{identifier} residual [{b},{t},{d}]",
                          "value=skip+branch",
                          "Actual same-shape addition; both operands have identical B,T,D axes and dimensions.",
                          dict(b=b, t=t, d=d, skip=left["values"][index], branch=right["values"][index]),
                          dict(value=value))
                aliases[f"{identifier.lower()}{b}{t}{d}"] = value
    return dict(output=result, aliases=aliases)


def transformer_block(s, trace):
    """Compose the six declared stages from validated raw state, without partial success."""
    B, T = s["B"], s["T"]
    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)],
               "Original block input retained for the first identity skip.")
    n1 = _norm_stage(s, X, trace, "N1")
    attention = _attention_stage(s, n1["output"], trace)
    r1 = _residual_stage("R1", "r1", X, attention["output"], trace)
    n2 = _norm_stage(s, r1["output"], trace, "N2")
    ffn = feed_forward(s, n2["output"], trace, "ffn")
    y = _residual_stage("Y", "r2", r1["output"], ffn["output"], trace)
    # Semantic aliases follow final outputs/dimensions in the wrapper's summary.
    aliases = {**n1["aliases"], **attention["aliases"], **r1["aliases"], **n2["aliases"],
               **{f"ff_{key}": value for key, value in ffn["aliases"].items()}}
    tensors = [X, *n1["tensors"], *attention["tensors"], r1["output"],
               *n2["tensors"], *ffn["tensors"], y["output"]]
    return dict(output=y["output"], final_aliases=y["aliases"], aliases=aliases, tensors=tensors)

Isolated FFN wrapper and shared FFN helper

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)

Reused normalization/residual and attention 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.

"""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=(",", ":")))
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 VI: real NumPy head arrays with explicit Python-float arithmetic.

The stages are local: project_heads owns projections and layout, attend_heads
owns scores/probabilities/weighted values, join_heads owns concatenation and WO.
Chapter wrappers combine those records explicitly. No Part V helper is imported.
Keep this file beside iv27.py, iv28.py and iv29.py. Source authored under hold;
none of these numerical programs has been executed or runtime-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):
    """Accept numerical scalars, never strings, booleans or nonfinite values."""
    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


# Weight names mean input feature d, head h, feature f WITHIN that head.
_head_defaults = dict(
    B=1, T=3, H=2, Dk=1, Dv=1,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
)
for _prefix in ("wq", "wk", "wv"):
    for _d in range(2):
        for _h in range(2):
            for _f in range(2):
                _head_defaults[f"{_prefix}{_d}{_h}{_f}"] = 1 if _d == (_h + _f) % 2 else 0
HEAD_DEFAULTS = MappingProxyType(_head_defaults)
ATTENTION_HEAD_DEFAULTS = MappingProxyType(dict(
    **HEAD_DEFAULTS, mode=1, valid0=1, valid1=1, valid2=1, shift=0,
))
OUTPUT_HEAD_DEFAULTS = MappingProxyType(dict(
    **ATTENTION_HEAD_DEFAULTS,
    wo000=1, wo001=1, wo010=0.5, wo011=0,
    wo100=1, wo101=-1, wo110=0, wo111=0.5,
))
del _head_defaults, _prefix, _d, _h, _f


def head_state(state, stage):
    """Validate exactly 41/46/54 fields BEFORE selecting any active slots."""
    if type(stage) is not int or stage not in (27, 28, 29):
        raise NumericalFault("INVALID_INPUT", "Use head stage 27, 28 or 29.")
    defaults = {27: HEAD_DEFAULTS, 28: ATTENTION_HEAD_DEFAULTS, 29: OUTPUT_HEAD_DEFAULTS}[stage]
    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 named scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), H=(1, 2), Dk=(1, 2), Dv=(1, 2),
                          mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (-10000, 10000) if key == "shift" 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 {"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: finite(value, key) for key, value in values.items()}


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

    def add(self, identifier, label, equation, explanation, inputs, values):
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        # New finite dictionaries detach records from the caller's mutable state.
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))

    def result(self, summary, tensors):
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def head_trace():
    return HeadTrace()


def tensor(identifier, shape, axes, values, provenance):
    if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    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.")
    array = np.asarray(values)
    if array.shape != tuple(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    boolean = array.dtype == np.dtype(np.bool_)
    flat = [bool(value) for value in array.reshape(-1)] if boolean else [finite(value, identifier) for value in array.reshape(-1)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="bool" if boolean else "float64",
                values=flat, provenance=provenance, precision=8)


def split_heads(identifier, values, B, T, H, F, features, trace):
    """Reshape [B,T,H*F] first; then separately permute axes (0,2,1,3)."""
    for name, value, maximum in (("B", B, 2), ("T", T, 3), ("H", H, 2), ("F", F, 2), ("features", features, 4)):
        value = finite(value, name)
        if not value.is_integer() or not 1 <= value <= maximum:
            raise NumericalFault("INVALID_INPUT", f"{name} must be an integer between 1 and {maximum}.")
    B, T, H, F, features = int(B), int(T), int(H), int(F), int(features)
    if features != H * F:
        raise NumericalFault("SHAPE_MISMATCH", "Projection features must equal H*F; no feature may be discarded.")
    if type(values) is not list or len(values) != B * T * features:
        raise NumericalFault("SHAPE_MISMATCH", "Projection storage must be a dense array of B*T*features values.")
    # Shape/storage errors precede traversal of any numerical element.
    flat = [finite(value, f"{identifier}[{index}]") for index, value in enumerate(values)]
    split = np.array(flat, dtype=np.float64).reshape((B, T, H, F))
    trace.add(f"reshape_{identifier}", f"{identifier}: expose the head and within-head feature axes",
              "[B,T,H*F] -> [B,T,H,F]; the flat value order is unchanged",
              "A reshape changes only the coordinate description. It does not move a token or a head value.",
              dict(B=B, T=T, H=H, F=F, features=features, elements=B*T*H*F), dict(elements=B*T*H*F))
    # This declared permutation is a separate copy, not a disguised reshape.
    heads = np.transpose(split, axes=(0, 2, 1, 3)).copy()
    for b in range(B):
        for h in range(H):
            for t in range(T):
                for f in range(F):
                    feature = h * F + f
                    source_offset = (b * T + t) * (H * F) + feature
                    destination_offset = ((b * H + h) * T + t) * F + f
                    source_value = float(split[b, t, h, f])
                    trace.add(f"permute_{identifier}_{b}_{h}_{t}_{f}", f"{identifier}[{b},{h},{t},{f}]: copy to head-major order",
                              "U[b,h,t,f]=R[b,t,h,f]; axes=(0,2,1,3)",
                              "The source and destination flat offsets differ in general; the indexed value is copied unchanged.",
                              dict(b=b, h=h, t=t, f=f, feature=feature, sourceOffset=source_offset,
                                   destinationOffset=destination_offset, sourceValue=source_value),
                              dict(value=float(heads[b, h, t, f])))
    feature_axis = "Dv" if identifier == "V" else "Dk"
    tensors = [tensor(f"{identifier}Split", [B, T, H, F], ["B", "T", "H", feature_axis], split,
                      "Storage-preserving reshape of the concatenated projection; each feature is h*F+f."),
               tensor(f"{identifier}Heads", [B, H, T, F], ["B", "H", "T", feature_axis], heads,
                      "Separate declared axis permutation (0,2,1,3) from token-major to head-major storage.")]
    return dict(split=split, heads=heads, tensors=tensors)


def project_heads(s, trace):
    """Project Q,K,V in role/b/t/h/f order, then expose each head layout."""
    B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
    X = np.empty((B, T, 2), dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                X[b, t, d] = s[f"x{b}{t}{d}"]
    trace.add("setup", "Validate all scalar inputs and select active dimensions",
              "D=2; X[B,T,D]; WQ,WK[D,H*Dk]; WV[D,H*Dv]",
              "Validate even inactive fields, then pack each named head/feature parameter. Both input rows remain active.",
              s, dict(B=B, T=T, D=2, H=H, Dk=Dk, Dv=Dv))
    stage = dict(X=X)
    for name, prefix, width in (("Q", "wq", Dk), ("K", "wk", Dk), ("V", "wv", Dv)):
        weights = np.empty((2, H * width), dtype=np.float64)
        joined = np.empty((B, T, H * width), dtype=np.float64)
        for d in range(2):
            for h in range(H):
                for f in range(width):
                    weights[d, h * width + f] = s[f"{prefix}{d}{h}{f}"]
        for b in range(B):
            for t in range(T):
                for h in range(H):
                    for f in range(width):
                        x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                        w0, w1 = float(weights[0, h * width + f]), float(weights[1, h * width + f])
                        product0 = finite(x0 * w0, "projection product0")
                        product1 = finite(x1 * w1, "projection product1")
                        value = finite(product0 + product1, "projection value")
                        joined[b, t, h * width + f] = value
                        trace.add(f"project_{name}_{b}_{t}_{h}_{f}", f"{name} token {b},{t}, head {h}, feature {f}",
                                  "product0=x0*w0; product1=x1*w1; value=product0+product1",
                                  "Multiply one input row by the column for this head and feature. The two products precede their sum.",
                                  dict(b=b, t=t, h=h, f=f, x0=x0, x1=x1, w0=w0, w1=w1),
                                  dict(product0=product0, product1=product1, value=value))
        stage[f"W{name}"] = weights
        stage[f"{name}Concat"] = joined
    tensors = [tensor("X", [B, T, 2], ["B", "T", "D"], X, "Active input token rows; both input features are retained.")]
    for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
        tensors.append(tensor(f"W{name}", [2, H*width], ["D", axis], stage[f"W{name}"],
                              "Packed named weights: column h*F+f, retaining both input rows."))
    for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
        tensors.append(tensor(f"{name}Concat", [B, T, H*width], ["B", "T", axis], stage[f"{name}Concat"],
                              "Real two-product projections in token-major, packed-head feature order."))
    aliases = {}
    for name, width in (("Q", Dk), ("K", Dk), ("V", Dv)):
        layout = split_heads(name, stage[f"{name}Concat"].reshape(-1).tolist(), B, T, H, width, H*width, trace)
        stage[f"{name}Split"], stage[f"{name}Heads"] = layout["split"], layout["heads"]
        tensors.extend(layout["tensors"])
        for b in range(B):
            for h in range(H):
                for t in range(T):
                    for f in range(width):
                        aliases[f"{name.lower()}{b}{h}{t}{f}"] = float(layout["heads"][b, h, t, f])
    return dict(X=stage["X"], WQ=stage["WQ"], WK=stage["WK"], WV=stage["WV"],
                QConcat=stage["QConcat"], KConcat=stage["KConcat"], VConcat=stage["VConcat"],
                QSplit=stage["QSplit"], QHeads=stage["QHeads"], KSplit=stage["KSplit"],
                KHeads=stage["KHeads"], VSplit=stage["VSplit"], VHeads=stage["VHeads"],
                aliases=aliases, tensors=tensors)


def stable_softmax(logits, allowed):
    """M1 operation order: allowed max, ascending terms/sum, then quotients."""
    if type(logits) is not list or type(allowed) is not list or not 1 <= len(logits) <= 64 or len(logits) != len(allowed):
        raise NumericalFault("SHAPE_MISMATCH", "A boolean allowed mask must match 1–64 logits.")
    logits = [finite(value, f"logit {j}") for j, value in enumerate(logits)]
    if any(type(value) is not bool for value in allowed):
        raise NumericalFault("INVALID_INPUT", "Every mask entry must be boolean.")
    candidates = [value for j, value in enumerate(logits) if allowed[j]]
    if not candidates:
        raise NumericalFault("FULLY_MASKED_ROW", "This query has no allowed keys; no probability distribution exists.")
    maximum = max(candidates)
    # Match Math.max zero ties without erasing an all-negative-zero maximum.
    if maximum == 0.0 and any(value == 0.0 and math.copysign(1.0, value) > 0.0 for value in candidates):
        maximum = 0.0
    terms = []
    for j, logit in enumerate(logits):
        term = finite(math.exp(finite(logit - maximum, "shifted logit")), "softmax term") if allowed[j] else 0.0
        terms.append(term)
    denominator = 0.0
    for term in terms:
        denominator = finite(denominator + term, "softmax denominator")
    probabilities = [finite(term / denominator, "softmax probability") for term in terms]
    return dict(max=maximum, terms=terms, denominator=denominator, probabilities=probabilities)


def attend_heads(s, projected, trace):
    """Each b,h path scores, masks and mixes independently along the key axis."""
    B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
    Q, K, V = projected["QHeads"], projected["KHeads"], projected["VHeads"]
    shape = (B, H, T, T)
    raw, scores = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    aliases = {}
    divisor = finite(math.sqrt(Dk), "score divisor")
    for b in range(B):
        for h in range(H):
            for i in range(T):
                for j in range(T):
                    q0, k0 = float(Q[b, h, i, 0]), float(K[b, h, j, 0])
                    inputs = dict(b=b, h=h, i=i, j=j, Dk=Dk, divisor=divisor, q0=q0, k0=k0)
                    product0 = finite(q0 * k0, "score product0")
                    values, dot = dict(product0=product0), product0
                    if Dk == 2:
                        q1, k1 = float(Q[b, h, i, 1]), float(K[b, h, j, 1])
                        inputs.update(q1=q1, k1=k1)
                        product1 = finite(q1 * k1, "score product1")
                        values["product1"] = product1
                        dot = finite(product0 + product1, "raw score")
                    scaled = finite(dot / divisor, "scaled score")
                    raw[b, h, i, j], scores[b, h, i, j] = dot, scaled
                    values.update(raw=dot, score=scaled)
                    aliases[f"raw{b}{h}{i}{j}"] = dot
                    aliases[f"score{b}{h}{i}{j}"] = scaled
                    trace.add(f"score_{b}_{h}_{i}_{j}", f"Batch {b}, head {h}: query {i} against key {j}",
                              "product0=q0*k0; raw=product0; score=raw/sqrt(Dk)" if Dk == 1 else
                              "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
                              "Only matching features in this batch and head contribute. The divisor is the per-head key width.", inputs, values)
    allowed = np.empty(shape, dtype=np.bool_)
    logits, probabilities = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    causal, padding = s["mode"] in (1, 3), s["mode"] in (2, 3)
    for b in range(B):
        for h in range(H):
            for i in range(T):
                inputs = dict(b=b, h=h, i=i, mode=s["mode"], shift=s["shift"])
                row_logits, row_allowed = [], []
                for j in range(T):
                    score = float(scores[b, h, i, j])
                    inputs[f"score{j}"] = score
                    permit = (not causal or j <= i) and (not padding or s[f"valid{j}"] == 1)
                    allowed[b, h, i, j] = permit
                    logit = finite(score + s["shift"], "shifted score")
                    logits[b, h, i, j] = logit
                    row_logits.append(logit)
                    row_allowed.append(permit)
                for j in range(T):
                    inputs[f"allowed{j}"] = 1 if row_allowed[j] else 0
                if not any(row_allowed):
                    raise NumericalFault("FULLY_MASKED_ROW", f"Batch {b}, head {h}, query {i} has no allowed keys; the entire result is unavailable.")
                row = stable_softmax(row_logits, row_allowed)
                values = dict(max=row["max"], denominator=row["denominator"])
                for j in range(T):
                    if row_allowed[j]:
                        values[f"shifted{j}"] = finite(row_logits[j] - row["max"], "shifted logit")
                for j in range(T):
                    values[f"term{j}"] = row["terms"][j]
                for j in range(T):
                    p = row["probabilities"][j]
                    probabilities[b, h, i, j] = p
                    values[f"p{j}"] = p
                    aliases[f"p{b}{h}{i}{j}"] = p
                trace.add(f"row_{b}_{h}_{i}", f"Batch {b}, head {h}: masked key softmax for query {i}",
                          "logit_j=score_j+shift; max=max(allowed logits); term_j=allowed_j?exp(logit_j-max):0; denominator=sum_j term_j; p_j=term_j/denominator",
                          "Normalize allowed keys only, in ascending key order. Queries remain; masks are shared across heads/batches. Forbidden probabilities are exactly zero; allowed exponential underflow is distinct.", inputs, values)
    OHeads = np.empty((B, H, T, Dv), dtype=np.float64)
    for b in range(B):
        for h in range(H):
            for i in range(T):
                for f in range(Dv):
                    inputs, products, running = dict(b=b, h=h, i=i, f=f), {}, {}
                    value = 0.0
                    for j in range(T):
                        p, v = float(probabilities[b, h, i, j]), float(V[b, h, j, f])
                        inputs[f"p{j}"], inputs[f"v{j}"] = p, v
                        product = finite(p * v, "head value product")
                        products[f"product{j}"] = product
                        value = finite(value + product, "head value running sum")
                        running[f"running{j}"] = value
                    OHeads[b, h, i, f] = value
                    aliases[f"oh{b}{h}{i}{f}"] = value
                    trace.add(f"head_mix_{b}_{h}_{i}_{f}", f"Head output [{b},{h},{i},{f}]",
                              "product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
                              "Use this head's actual probability row and value feature. Every key contributes its product, including masked 0*V, followed immediately by its running sum.",
                              inputs, {**products, **running, "value": value})
    axes = ["B", "H", "Query", "Key"]
    tensors = [tensor("raw", list(shape), axes, raw, "Per-head query-key products, summed before scaling."),
               tensor("scores", list(shape), axes, scores, "Raw dot products divided by sqrt(Dk)."),
               tensor("allowed", list(shape), axes, allowed, "Boolean allowed-key masks; validity is shared across B and H; queries remain."),
               tensor("logits", list(shape), axes, logits, "Finite score+common shift for every key, including forbidden keys; no infinity sentinel."),
               tensor("probabilities", list(shape), axes, probabilities, "Per-batch/head/query stable softmax along allowed keys only."),
               tensor("OHeads", [B, H, T, Dv], ["B", "H", "Query", "Dv"], OHeads,
                      "Actual per-head weighted values: ascending key products and sequential sums from zero.")]
    return dict(raw=raw, scores=scores, allowed=allowed, logits=logits, probabilities=probabilities,
                OHeads=OHeads, aliases=aliases, tensors=tensors)


def join_heads(s, attended, trace):
    """Copy OHeads into C in head/feature order, then compute every C*WO term."""
    B, T, H, Dv = (s[key] for key in ("B", "T", "H", "Dv"))
    OHeads = attended["OHeads"]
    C = np.empty((B, T, H*Dv), dtype=np.float64)
    aliases = {}
    for b in range(B):
        for t in range(T):
            for h in range(H):
                for f in range(Dv):
                    c = h * Dv + f
                    source_offset = ((b * H + h) * T + t) * Dv + f
                    destination_offset = (b * T + t) * (H * Dv) + c
                    value = finite(OHeads[b, h, t, f], "head output to concatenate")
                    C[b, t, c] = value
                    aliases[f"c{b}{t}{c}"] = value
                    trace.add(f"concat_{b}_{t}_{h}_{f}", f"Joined feature [{b},{t},{c}] from head {h}, feature {f}",
                              "C[b,t,h*Dv+f]=OHeads[b,h,t,f]",
                              "Copy the actual head output unchanged; concatenation rearranges coordinates and never averages heads.",
                              dict(b=b, t=t, h=h, f=f, concatFeature=c, sourceOffset=source_offset,
                                   destinationOffset=destination_offset, sourceValue=value), dict(value=value))
    WO = np.empty((H*Dv, 2), dtype=np.float64)
    for h in range(H):
        for f in range(Dv):
            for d in range(2):
                WO[h*Dv+f, d] = s[f"wo{h}{f}{d}"]
    Y = np.empty((B, T, 2), dtype=np.float64)
    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), {}, {}
                value = 0.0
                for c in range(H*Dv):
                    coordinate, weight = float(C[b, t, c]), float(WO[c, d])
                    inputs[f"c{c}"], inputs[f"w{c}"] = coordinate, weight
                    product = finite(coordinate * weight, "output projection product")
                    products[f"product{c}"] = product
                    value = finite(value + product, "output projection running sum")
                    running[f"running{c}"] = value
                Y[b, t, d] = value
                aliases[f"y{b}{t}{d}"] = value
                trace.add(f"output_{b}_{t}_{d}", f"Output [{b},{t},{d}]: joined values times WO",
                          "product_c=c_c*w_c; running starts at 0; running_c=previous+product_c; value=last running sum",
                          "Pack WO rows by h*Dv+f, retaining parameter identity as Dv changes. Products and immediate running sums follow ascending joined features. Signed output is allowed; no output normalization is added.",
                          inputs, {**products, **running, "value": value})
    tensors = [tensor("C", [B, T, H*Dv], ["B", "T", "JoinedValue"], C, "Head/within-head feature concatenation of actual OHeads, preserving each copied value."),
               tensor("WO", [H*Dv, 2], ["JoinedValue", "D"], WO, "Named output parameters packed in head/feature row order h*Dv+f."),
               tensor("Y", [B, T, 2], ["B", "T", "D"], Y, "C times WO via explicit scalar products and sequential running sums; no output softmax.")]
    return dict(C=C, WO=WO, Y=Y, aliases=aliases, tensors=tensors)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; JSON replaces all fields; '-' 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=(",", ":")))

The complete source set keeps its file-relative attention import rather than assuming a caller’s current directory. The older attention helper has its own NumericalFault exception class. The block adapter catches that known class and preserves its code and reason in the component fault class. In particular, a fully masked query must make the whole block unavailable, never return successful partial results. These listings and import relationships are source descriptions, not runtime evidence.

What an edit can and cannot imply

Setting every W2 output weight and b2 bias to zero makes F=0 and therefore Y=R₁. It does not force Y=X: attention may still have added A. Setting only WO to zero makes A=0 and R₁=X, but LN₂ and the FFN can still change Y. For the default first input (3,1), LN₂(X)=(1/2,−1/2). Its hidden preactivations (1/2,−1/2,1) become (1/2,0,1). The FFN outputs ((1/2)(1/2)+0+1/4,0+0+1/4)=(1/2,1/4), so this WO-zero edit gives Y=(7/2,5/4), not (3,1), in exact real arithmetic. Setting W1 to zero does not necessarily zero F either: nonzero b1 creates hidden activations, and b2 can supply output independently. Specify the full conditions before claiming a branch vanishes.

With the causal mask, editing a later token cannot influence an earlier query through attention. LayerNorm and FFN remain row-local, so they do not reopen that forbidden path. Editing a shared projection or FFN parameter can influence many positions because the same parameter is reused. The default distinct head projections nevertheless yield equal maps; different projection weights do not guarantee different attention probabilities, and those probabilities do not explain model reasoning.

Mask modes allow no mask, causal only, padding only, or both. Padding here removes keys, while retaining all queries; key-validity flags are shared across batches and heads. Combining a causal mask with an invalid first key leaves query zero with no allowed key. There is then no probability distribution, so FULLY_MASKED_ROW replaces the whole block result. A residual route does not repair an undefined attention branch.

All 81 stored inputs are validated, including inactive positions, heads and within-head features. B,H,Dk,Dv are integers from 1 to 2 and T is an integer from 1 to 3; gamma, beta, raw features and weights lie in [−4,4]; each epsilon lies in [10⁻⁸,4]. The finite common logit shift has its own [−10000,10000] bound. Mask mode and validity fields are integer choices. Intermediate N₁ or N₂ values can lie outside raw-editor bounds and must not be clipped: learned affine scales can enlarge normalized values. Shape checks and nonfinite checks remain necessary for derived tensors.

Stable softmax avoids exponentiating large positive shifted logits. It does not eliminate floating-point rounding; very small allowed terms can underflow to zero, which differs from an exactly forbidden key. A large common shift can lose low bits when added to logits before subtraction. Residual paths and positive epsilon do not prove training stability, bounded gradients or learned capability. This block uses LN, not root mean square normalization, has no post-norm, dropout or vocabulary-output probability layer, and supplies no positional encoding or training update.

Five graded exercise outlines

  1. pre-norm-order: Pre-norm order. LN₁ precedes attention; X remains the first skip. LN₂ takes R₁ before the FFN; R₁ remains the second skip. Reusing LN₁ or adding F to X changes the model.
  2. first-residual: Calculate the fixed default first residual. X[0,0,:]=(3,1) and A[0,0,:]=(0,1), so R1=(3+0,1+1)=(3,2). Add to X rather than N1=(1/2,−1/2); LN2 happens only after this addition.
  3. live-block: Live final addition. Read r2_0_0_0, always Y[0,0,0]: add its incoming skip and FFN branch. At reset Y[0,0,0]=3+1/√13; changing an inspector selector does not change this question’s coordinate.
  4. zero-wo: Output-projection edit. Setting every active WO entry to zero kills A, leaving R₁=X, then LN₂/FFN still run. The default first input (3,1) becomes (7/2,5/4) under this edit, proving the full block need not be an identity. Q,K,V and probabilities are upstream of WO and stay fixed. A fully masked query remains unavailable.
  5. zero-ffn: Zero-branch counterexample. Zero all W2 entries and both b2 entries: F=0 and Y=R₁=X+A, which can differ from X. A nonzero attention branch survives the zero FFN: the default first row remains R₁=(3,2), while X=(3,1). Zeroing W1 alone is insufficient when b1 or b2 is nonzero. An entirely masked query instead makes the complete block unavailable.

Use the lab’s immediate feedback to identify the missing operation rather than guessing from a tensor’s name. Fixed counterexamples state their assumptions; the live arithmetic question reads the current saved operands.

Recap and bridge

Normalize the branch input, preserve the skip input, calculate the branch and add it back. Repeat with an independent normalization and the row-local FFN. Attention is the stage that mixes allowed token positions; concatenation, normalization and FFN have different jobs and axes. The complete block output is a feature representation, not a trained model’s next-token prediction. IV-34 — Why Position Matters to Attention next asks what positional information attention needs; this chapter’s causal permission rule does not itself supply every kind of position representation.