The neural notebook
← All chapters

IV-29 / Part VI · Multi-Head Attention

Head Concatenation and Output Projection

Join the actual head messages in head/feature order, follow every output-matrix product and running sum, and distinguish signed outputs from attention probabilities.

Review the ideas this chapter uses

We now have a message from each attention head for every query position. Keeping only one head would discard the other path’s contribution, while averaging would force a particular combination before we could choose its weights. Instead, we place all the message coordinates beside one another, then calculate an explicit linear transformation. You will see exactly which head supplied every coordinate and which weight turns it into each final output feature.

Learning objective: Concatenate real head outputs and apply an explicit output matrix.

Use IV-28 — Independent Attention Heads for the messages being assembled, and Book II’s II.10 — Matrix × matrix as composition for matrix composition. I.8 — Indexed quantities and summation reviews indexed sums. Book III’s III-41 — Composition and Learned Representations explains composing representations; this small forward calculation uses hand-set parameters and does not establish learning or a useful language model.

Follow one real token to its output

Compute it yourself

Head Concatenation and Output Projection

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
1
x001
0
x010
0
x011
1
x020
1
x021
1
x100
1
x101
1
x110
-1
x111
0
x120
0
x121
2
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
B1
T3
H2
Dk1
Input token rows X
Query projection WQ
Key projection WK
Value projection WV
Output projection WO

B 1. T 3. H 2. Dk 1. Validate every scalar slot, then select active dimensions. All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights.. B 1. T 3. D 2. H 2. Dk 1. Dv 1

Validate every scalar slot, then select active dimensions

D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv]

All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights.

Inputs

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
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

Outputs

B
1
T
3
D
2
H
2
Dk
1
Dv
1

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]=1. 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.

Selected trace operation: setup. Its operands and results are displayed above; the tables below identify the same saved records. A selected operation in another batch/head/query remains visible in the main trace.

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
010
101
211

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
010
101
211

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_0001110001
project_Q_0_1_0_0100101000
project_Q_0_2_0_0201111001
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]00011
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]04211

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
01
10
21

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
010
101
211

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_0001110001
project_K_0_1_0_0100101000
project_K_0_2_0_0201111001
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]00011
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]04211

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
01
10
21

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
010
101
211

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_0001110001
project_V_0_1_0_0100101000
project_V_0_2_0_0201111001
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]00011
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]04211

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
01
10
21

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
0101
1000
2101

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
0101
1000
2101
score products, batch 0, head 0, query 0; actual stored values without display rounding
Saved stepKeyq0k0product0Rawsqrt(Dk)Score
score_0_0_0_00111111
score_0_0_0_11100010
score_0_0_0_22111111

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.4223187982515182Allowed: p=0.15536240349696362Allowed: p=0.4223187982515182

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.2689414213699951Allowed: p=0.7310585786300049Forbidden: p=0
Query 2Allowed: p=0.15536240349696362Allowed: p=0.4223187982515182Allowed: p=0.4223187982515182

Saved row_0_0_0: allowed-key stable softmax

Mode 1: causal: key ≤ query. Common shift 0; allowed maximum 1; 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
0true110exp(0)=11 / 1 = 1
1false00Forbidden: no subtractionForbidden: 0, no exponential0 / 1 = 0
2false11Forbidden: 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
01
10.5
20.8446375965030364
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
01111
10001
20101

OHeads[0,0,0,0]=1. 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_00000011
concat_0_0_1_01013100

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
010
10.50.7310585786300049
20.84463759650303640.8446375965030364

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
011
11.2310585786300048-0.2310585786300049
21.68927519300607280
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 / 01111
11 / 00101

Y[0,0,0]=1. 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.

Inspect tensor shapes and full precision

All computed outputs

B
1
T
3
H
2
Dk
1
Dv
1
q0000
1
q0010
0
q0020
1
q0100
0
q0110
1
q0120
1
k0000
1
k0010
0
k0020
1
k0100
0
k0110
1
k0120
1
v0000
1
v0010
0
v0020
1
v0100
0
v0110
1
v0120
1
raw0000
1
score0000
1
raw0001
0
score0001
0
raw0002
1
score0002
1
raw0010
0
score0010
0
raw0011
0
score0011
0
raw0012
0
score0012
0
raw0020
1
score0020
1
raw0021
0
score0021
0
raw0022
1
score0022
1
raw0100
0
score0100
0
raw0101
0
score0101
0
raw0102
0
score0102
0
raw0110
0
score0110
0
raw0111
1
score0111
1
raw0112
1
score0112
1
raw0120
0
score0120
0
raw0121
1
score0121
1
raw0122
1
score0122
1
p0000
1
p0001
0
p0002
0
p0010
0.5
p0011
0.5
p0012
0
p0020
0.4223187982515182
p0021
0.15536240349696362
p0022
0.4223187982515182
p0100
1
p0101
0
p0102
0
p0110
0.2689414213699951
p0111
0.7310585786300049
p0112
0
p0120
0.15536240349696362
p0121
0.4223187982515182
p0122
0.4223187982515182
oh0000
1
oh0010
0.5
oh0020
0.8446375965030364
oh0100
0
oh0110
0.7310585786300049
oh0120
0.8446375965030364
c000
1
c001
0
c010
0.5
c011
0.7310585786300049
c020
0.8446375965030364
c021
0.8446375965030364
y000
1
y001
1
y010
1.2310585786300048
y011
-0.2310585786300049
y020
1.6892751930060728
y021
0
setup_B
1
setup_T
3
setup_D
2
setup_H
2
setup_Dk
1
setup_Dv
1
project_Q_0_0_0_0_product0
1
project_Q_0_0_0_0_product1
0
project_Q_0_0_0_0_value
1
project_Q_0_0_1_0_product0
0
project_Q_0_0_1_0_product1
0
project_Q_0_0_1_0_value
0
project_Q_0_1_0_0_product0
0
project_Q_0_1_0_0_product1
0
project_Q_0_1_0_0_value
0
project_Q_0_1_1_0_product0
0
project_Q_0_1_1_0_product1
1
project_Q_0_1_1_0_value
1
project_Q_0_2_0_0_product0
1
project_Q_0_2_0_0_product1
0
project_Q_0_2_0_0_value
1
project_Q_0_2_1_0_product0
0
project_Q_0_2_1_0_product1
1
project_Q_0_2_1_0_value
1
project_K_0_0_0_0_product0
1
project_K_0_0_0_0_product1
0
project_K_0_0_0_0_value
1
project_K_0_0_1_0_product0
0
project_K_0_0_1_0_product1
0
project_K_0_0_1_0_value
0
project_K_0_1_0_0_product0
0
project_K_0_1_0_0_product1
0
project_K_0_1_0_0_value
0
project_K_0_1_1_0_product0
0
project_K_0_1_1_0_product1
1
project_K_0_1_1_0_value
1
project_K_0_2_0_0_product0
1
project_K_0_2_0_0_product1
0
project_K_0_2_0_0_value
1
project_K_0_2_1_0_product0
0
project_K_0_2_1_0_product1
1
project_K_0_2_1_0_value
1
project_V_0_0_0_0_product0
1
project_V_0_0_0_0_product1
0
project_V_0_0_0_0_value
1
project_V_0_0_1_0_product0
0
project_V_0_0_1_0_product1
0
project_V_0_0_1_0_value
0
project_V_0_1_0_0_product0
0
project_V_0_1_0_0_product1
0
project_V_0_1_0_0_value
0
project_V_0_1_1_0_product0
0
project_V_0_1_1_0_product1
1
project_V_0_1_1_0_value
1
project_V_0_2_0_0_product0
1
project_V_0_2_0_0_product1
0
project_V_0_2_0_0_value
1
project_V_0_2_1_0_product0
0
project_V_0_2_1_0_product1
1
project_V_0_2_1_0_value
1
reshape_Q_elements
6
permute_Q_0_0_0_0_value
1
permute_Q_0_0_1_0_value
0
permute_Q_0_0_2_0_value
1
permute_Q_0_1_0_0_value
0
permute_Q_0_1_1_0_value
1
permute_Q_0_1_2_0_value
1
reshape_K_elements
6
permute_K_0_0_0_0_value
1
permute_K_0_0_1_0_value
0
permute_K_0_0_2_0_value
1
permute_K_0_1_0_0_value
0
permute_K_0_1_1_0_value
1
permute_K_0_1_2_0_value
1
reshape_V_elements
6
permute_V_0_0_0_0_value
1
permute_V_0_0_1_0_value
0
permute_V_0_0_2_0_value
1
permute_V_0_1_0_0_value
0
permute_V_0_1_1_0_value
1
permute_V_0_1_2_0_value
1
score_0_0_0_0_product0
1
score_0_0_0_0_raw
1
score_0_0_0_0_score
1
score_0_0_0_1_product0
0
score_0_0_0_1_raw
0
score_0_0_0_1_score
0
score_0_0_0_2_product0
1
score_0_0_0_2_raw
1
score_0_0_0_2_score
1
score_0_0_1_0_product0
0
score_0_0_1_0_raw
0
score_0_0_1_0_score
0
score_0_0_1_1_product0
0
score_0_0_1_1_raw
0
score_0_0_1_1_score
0
score_0_0_1_2_product0
0
score_0_0_1_2_raw
0
score_0_0_1_2_score
0
score_0_0_2_0_product0
1
score_0_0_2_0_raw
1
score_0_0_2_0_score
1
score_0_0_2_1_product0
0
score_0_0_2_1_raw
0
score_0_0_2_1_score
0
score_0_0_2_2_product0
1
score_0_0_2_2_raw
1
score_0_0_2_2_score
1
score_0_1_0_0_product0
0
score_0_1_0_0_raw
0
score_0_1_0_0_score
0
score_0_1_0_1_product0
0
score_0_1_0_1_raw
0
score_0_1_0_1_score
0
score_0_1_0_2_product0
0
score_0_1_0_2_raw
0
score_0_1_0_2_score
0
score_0_1_1_0_product0
0
score_0_1_1_0_raw
0
score_0_1_1_0_score
0
score_0_1_1_1_product0
1
score_0_1_1_1_raw
1
score_0_1_1_1_score
1
score_0_1_1_2_product0
1
score_0_1_1_2_raw
1
score_0_1_1_2_score
1
score_0_1_2_0_product0
0
score_0_1_2_0_raw
0
score_0_1_2_0_score
0
score_0_1_2_1_product0
1
score_0_1_2_1_raw
1
score_0_1_2_1_score
1
score_0_1_2_2_product0
1
score_0_1_2_2_raw
1
score_0_1_2_2_score
1
row_0_0_0_max
1
row_0_0_0_denominator
1
row_0_0_0_shifted0
0
row_0_0_0_term0
1
row_0_0_0_term1
0
row_0_0_0_term2
0
row_0_0_0_p0
1
row_0_0_0_p1
0
row_0_0_0_p2
0
row_0_0_1_max
0
row_0_0_1_denominator
2
row_0_0_1_shifted0
0
row_0_0_1_shifted1
0
row_0_0_1_term0
1
row_0_0_1_term1
1
row_0_0_1_term2
0
row_0_0_1_p0
0.5
row_0_0_1_p1
0.5
row_0_0_1_p2
0
row_0_0_2_max
1
row_0_0_2_denominator
2.3678794411714423
row_0_0_2_shifted0
0
row_0_0_2_shifted1
-1
row_0_0_2_shifted2
0
row_0_0_2_term0
1
row_0_0_2_term1
0.36787944117144233
row_0_0_2_term2
1
row_0_0_2_p0
0.4223187982515182
row_0_0_2_p1
0.15536240349696362
row_0_0_2_p2
0.4223187982515182
row_0_1_0_max
0
row_0_1_0_denominator
1
row_0_1_0_shifted0
0
row_0_1_0_term0
1
row_0_1_0_term1
0
row_0_1_0_term2
0
row_0_1_0_p0
1
row_0_1_0_p1
0
row_0_1_0_p2
0
row_0_1_1_max
1
row_0_1_1_denominator
1.3678794411714423
row_0_1_1_shifted0
-1
row_0_1_1_shifted1
0
row_0_1_1_term0
0.36787944117144233
row_0_1_1_term1
1
row_0_1_1_term2
0
row_0_1_1_p0
0.2689414213699951
row_0_1_1_p1
0.7310585786300049
row_0_1_1_p2
0
row_0_1_2_max
1
row_0_1_2_denominator
2.3678794411714423
row_0_1_2_shifted0
-1
row_0_1_2_shifted1
0
row_0_1_2_shifted2
0
row_0_1_2_term0
0.36787944117144233
row_0_1_2_term1
1
row_0_1_2_term2
1
row_0_1_2_p0
0.15536240349696362
row_0_1_2_p1
0.4223187982515182
row_0_1_2_p2
0.4223187982515182
head_mix_0_0_0_0_product0
1
head_mix_0_0_0_0_product1
0
head_mix_0_0_0_0_product2
0
head_mix_0_0_0_0_running0
1
head_mix_0_0_0_0_running1
1
head_mix_0_0_0_0_running2
1
head_mix_0_0_0_0_value
1
head_mix_0_0_1_0_product0
0.5
head_mix_0_0_1_0_product1
0
head_mix_0_0_1_0_product2
0
head_mix_0_0_1_0_running0
0.5
head_mix_0_0_1_0_running1
0.5
head_mix_0_0_1_0_running2
0.5
head_mix_0_0_1_0_value
0.5
head_mix_0_0_2_0_product0
0.4223187982515182
head_mix_0_0_2_0_product1
0
head_mix_0_0_2_0_product2
0.4223187982515182
head_mix_0_0_2_0_running0
0.4223187982515182
head_mix_0_0_2_0_running1
0.4223187982515182
head_mix_0_0_2_0_running2
0.8446375965030364
head_mix_0_0_2_0_value
0.8446375965030364
head_mix_0_1_0_0_product0
0
head_mix_0_1_0_0_product1
0
head_mix_0_1_0_0_product2
0
head_mix_0_1_0_0_running0
0
head_mix_0_1_0_0_running1
0
head_mix_0_1_0_0_running2
0
head_mix_0_1_0_0_value
0
head_mix_0_1_1_0_product0
0
head_mix_0_1_1_0_product1
0.7310585786300049
head_mix_0_1_1_0_product2
0
head_mix_0_1_1_0_running0
0
head_mix_0_1_1_0_running1
0.7310585786300049
head_mix_0_1_1_0_running2
0.7310585786300049
head_mix_0_1_1_0_value
0.7310585786300049
head_mix_0_1_2_0_product0
0
head_mix_0_1_2_0_product1
0.4223187982515182
head_mix_0_1_2_0_product2
0.4223187982515182
head_mix_0_1_2_0_running0
0
head_mix_0_1_2_0_running1
0.4223187982515182
head_mix_0_1_2_0_running2
0.8446375965030364
head_mix_0_1_2_0_value
0.8446375965030364
concat_0_0_0_0_value
1
concat_0_0_1_0_value
0
concat_0_1_0_0_value
0.5
concat_0_1_1_0_value
0.7310585786300049
concat_0_2_0_0_value
0.8446375965030364
concat_0_2_1_0_value
0.8446375965030364
output_0_0_0_product0
1
output_0_0_0_product1
0
output_0_0_0_running0
1
output_0_0_0_running1
1
output_0_0_0_value
1
output_0_0_1_product0
1
output_0_0_1_product1
0
output_0_0_1_running0
1
output_0_0_1_running1
1
output_0_0_1_value
1
output_0_1_0_product0
0.5
output_0_1_0_product1
0.7310585786300049
output_0_1_0_running0
0.5
output_0_1_0_running1
1.2310585786300048
output_0_1_0_value
1.2310585786300048
output_0_1_1_product0
0.5
output_0_1_1_product1
-0.7310585786300049
output_0_1_1_running0
0.5
output_0_1_1_running1
-0.2310585786300049
output_0_1_1_value
-0.2310585786300049
output_0_2_0_product0
0.8446375965030364
output_0_2_0_product1
0.8446375965030364
output_0_2_0_running0
0.8446375965030364
output_0_2_0_running1
1.6892751930060728
output_0_2_0_value
1.6892751930060728
output_0_2_1_product0
0.8446375965030364
output_0_2_1_product1
-0.8446375965030364
output_0_2_1_running0
0.8446375965030364
output_0_2_1_running1
0
output_0_2_1_value
0

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

X

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

Storage indexValue
01
10
20
31
41
51

WQ

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

WK

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

WV

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

QConcat

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

Storage indexValue
01
10
20
31
41
51

KConcat

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

Storage indexValue
01
10
20
31
41
51

VConcat

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

Storage indexValue
01
10
20
31
41
51

QSplit

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

Storage indexValue
01
10
20
31
41
51

QHeads

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
01
10
21
30
41
51

KSplit

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

Storage indexValue
01
10
20
31
41
51

KHeads

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
01
10
21
30
41
51

VSplit

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

Storage indexValue
01
10
20
31
41
51

VHeads

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
01
10
21
30
41
51

raw

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

Storage indexValue
01
10
21
30
40
50
61
70
81
90
100
110
120
131
141
150
161
171

scores

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
01
10
21
30
40
50
61
70
81
90
100
110
120
131
141
150
161
171

allowed

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

logits

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

Storage indexValue
01
10
21
30
40
50
61
70
81
90
100
110
120
131
141
150
161
171

probabilities

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.4223187982515182
70.15536240349696362
80.4223187982515182
91
100
110
120.2689414213699951
130.7310585786300049
140
150.15536240349696362
160.4223187982515182
170.4223187982515182

OHeads

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
01
10.5
20.8446375965030364
30
40.7310585786300049
50.8446375965030364

C

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
01
10
20.5
30.7310585786300049
40.8446375965030364
50.8446375965030364

WO

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

Y

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
01
11
21.2310585786300048
3-0.2310585786300049
41.6892751930060728
50

Open Output projection WO to edit the eight stored output weights; the four input/Q/K/V groups are also available. Dimensions and mask/shift remain visible. All 54 stored fields, including inactive head/feature weights, are validated. Select a batch, token/query, head, within-head value feature and final output coordinate to follow its actual saved products.

Reset uses e=exp(1). Its actual concatenated token rows are C=(1,0),(1/2,e/(1+e)),(2e/(1+2e),2e/(1+2e)). The active WO rows are (1,1),(1,−1), so the final rows are Y=(1,1),(1/2+e/(1+e),1/2−e/(1+e)),(4e/(1+2e),0). These are exact real expressions; tables and running sums show the actual approximate binary64 computation.

Change Dv from 1 to 2 to reveal the additional rows (head0,feature1)=(1/2,0) and (head1,feature1)=(0,1/2). WO packing follows named head/feature identity: the previous head1/feature0 row moves to packed row 2 without becoming a different parameter. Edit WO alone and inspect unchanged P/OHeads/C, then changed output products where the edited weight contributes. This is only attention plus an explicit linear output projection; no bias, dropout, residual, normalization or output softmax has been added.

Check your understanding

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

1. How is C[b,t,c] formed from actual OHeads?
2. At H=2,Dv=2 and fixed D=2, which shapes make Y=C WO legal?
3. Saved output_0_0_0 has current products [1, 0]. What is their final accumulated output?
4. Keep all other fields fixed and edit only a WO scalar. Which dependency claim is correct?
5. Counterexample: C=(1/2,3/4), with WO rows (1,1) and (1,−1). What is Y?

Reset uses B=1, T=3, H=2, Dk=Dv=1, causal attention, all validity flags one and shift zero. Inspect query one through its two head messages, joined row C and final row Y. The second output feature is negative although the attention probabilities are nonnegative. Output projection is a weighted sum with signed weights, not another probability normalization.

To edit a matrix, first open its initially closed disclosure: Input token rows X, Query projection WQ, Key projection WK, Value projection WV, or Output projection WO. Dimensions and mask controls remain visible outside these groups. Change only wo101 from −1 to zero, then inspect Y again. The joined row and every upstream head calculation stay fixed; only products that use that output weight can change. Reset before following the complete default derivation.

What enters and what leaves the join

A head is a separate query/key/value path; H counts heads, not an earlier hidden layer’s neuron width. “Independent heads” refers to separate parameters and calculations before WO. It implies neither statistical independence nor necessarily different probabilities; default Dk=2 swaps both query/key coordinates, so the head probability maps legitimately coincide. B counts sequences, T token positions, Dk query/key coordinates per head, Dv value coordinates per head, and D=2 the fixed input and final output width. Indices b,t,h,f,d,c mean batch, token/query, head, within-head value feature, final feature and joined feature. All start at zero.

OHeads has shape [B,H,T,Dv]. Its values already include score scaling, the selected mask and key-axis softmax, followed by weighted-value sums. C, the concatenation, has [B,T,H*Dv]: it places head features side by side for the same token. WO is the output projection matrix [H*Dv,2]. Y, the final output tensor, has [B,T,2].

The word “output” is local to this attention module. Y is not a vocabulary distribution, a predicted token, or a training loss. There is no bias, dropout, residual addition, normalization or output softmax in this chapter. Later block components must be introduced as additional operations with their own inputs and shapes.

Concatenation copies; it does not average

For fixed b,t, place all Dv features of head zero first, then all Dv features of head one. The rule is

c=hDv+f,C[b,t,c]=OHeads[b,h,t,f].c=hDv+f,\qquad C[b,t,c]=OHeads[b,h,t,f].

The right-hand side is one already-computed coordinate. There is no multiplication or addition here. Every token gets H·Dv joined features, and batches never exchange values.

This is the inverse head-layout operation from IV-27 — Separating Attention Heads and Dimensions: first change B,H,T,Dv to B,T,H,Dv, then combine the adjacent head and feature axes. Reshaping alone preserves a flat list, so it cannot substitute for the permutation. The source offset is ((b*H+h)*T+t)*Dv+f; the destination offset is (b*T+t)*(H*Dv)+h*Dv+f. These are actual positions in the two flattened layouts.

Let e=exp⁡(1)e=\exp(1), r=e/(1+e)r=e/(1+e) and a=2e/(1+2e)a=2e/(1+2e). These letters abbreviate exact real values from the preceding chapter. Default head zero messages are (1,1/2,a), and head one messages are (0,r,a). Here is the complete join:

b,h,t,fSource offsetValueJoined b,t,cDestination offset
0,0,0,0010,0,00
0,0,1,011/20,1,02
0,0,2,02a0,2,04
0,1,0,0300,0,11
0,1,1,04r0,1,13
0,1,2,05a0,2,15

The source list [1,1/2,a,0,r,a] becomes destination list [1,0,1/2,r,a,a]. C therefore has rows (1,0), (1/2,r), (a,a). All six values survive. For instance source offset four becomes destination offset three: head one’s message for query one becomes that token’s second joined feature.

Multiply the joined row by WO

WO has one row per joined input feature and two columns for the final features. Multiplication is legal because C’s last width H·Dv matches WO’s first width. For each output coordinate:

Y[b,t,d]=∑c=0HDv−1C[b,t,c]WO[c,d].Y[b,t,d]=\sum_{c=0}^{HDv-1} C[b,t,c]WO[c,d].

Keep b,t,d fixed, start a running sum at zero, and walk c in ascending order. Form one product and add it immediately before calculating the next product. Unlike the earlier attention value mixture, these coefficients need not be nonnegative or sum to one.

Parameter names preserve head identity. Field wo{h}{f}{d} belongs to head h, its value feature f and final feature d; the active matrix row is c=hDv+f. At reset Dv=1, the two active rows are:

Joined row cHead h, feature fWeight to d=0Weight to d=1
00,0wo000 = 1wo001 = 1
11,0wo100 = 1wo101 = −1

Thus (u,v)WO=(u⋅1+v⋅1,u⋅1+v⋅(−1))=(u+v,u−v)(u,v)WO=(u\cdot1+v\cdot1,u\cdot1+v\cdot(-1))=(u+v,u-v). This is a chosen linear transformation, not an implicit head-summing rule. With different WO it could select, scale or cancel other combinations.

All default products, running sums and outputs

We now apply that same matrix to each joined token row. Every final coordinate and all its products are visible here; r and a retain the definitions above.

Token t, output dProduct c=0Running after c=0Product c=1Running after c=1 = Y
0,01⋅1=11\cdot1=10+1=10+1=10⋅1=00\cdot1=01+0=11+0=1
0,11⋅1=11\cdot1=10+1=10+1=10⋅(−1)=00\cdot(-1)=01+0=11+0=1
1,0(1/2)⋅1=1/2(1/2)\cdot1=1/20+1/2=1/20+1/2=1/2r⋅1=rr\cdot1=r1/2+r1/2+r
1,1(1/2)⋅1=1/2(1/2)\cdot1=1/20+1/2=1/20+1/2=1/2r⋅(−1)=−rr\cdot(-1)=-r1/2−r1/2-r
2,0a⋅1=aa\cdot1=a0+a=a0+a=aa⋅1=aa\cdot1=aa+a=2a=4e/(1+2e)a+a=2a=4e/(1+2e)
2,1a⋅1=aa\cdot1=a0+a=a0+a=aa⋅(−1)=−aa\cdot(-1)=-aa−a=0a-a=0

The complete Y rows are (1,1)(1,1), (1/2+e/(1+e),1/2−e/(1+e))(1/2+e/(1+e),1/2-e/(1+e)), and (4e/(1+2e),0)(4e/(1+2e),0). Because e>1, e/(1+e)>1/2e/(1+e)>1/2, so query one’s second feature is negative. Query zero sums to two across its output features. Neither fact violates a probability rule: Y has no such rule. The earlier P rows are the quantities normalized over keys.

Head zero’s query-one message came from products (1/2)⋅1,(1/2)⋅0,0⋅1(1/2)\cdot1,(1/2)\cdot0,0\cdot1, giving running sums 1/2,1/2,1/2. Head one’s came from (1/(1+e))⋅0,r⋅1,0⋅1(1/(1+e))\cdot0,r\cdot1,0\cdot1, giving 0,r,r. Those are the actual two coordinates used above. WO consumes their computed results; it does not recompute attention or average their probability maps.

Widening values makes the feature order matter

Set Dv=2 after reset, leaving Dk=1. V’s head-zero token is (x0,x1), and head one’s is (x1,x0). The score paths and P do not change, because WV and Dv do not enter Q/K scoring. With causal query zero, both heads can read only token zero, so their messages are respectively (1,0) and (0,1).

The joined row is (1,0,0,1) in order (h0f0,h0f1,h1f0,h1f1). It is not the feature-interleaved order (h0f0,h1f0,h0f1,h1f1). Each newly active WO row has its own named weights; expanding Dv does not relabel head one’s old parameters:

cHead/featureDefault WO row
0h0f0(1,1)
1h0f1(1/2,0)
2h1f0(1,−1)
3h1f1(0,1/2)

For query zero, d=0 has products 1⋅1=11\cdot1=1, 0⋅(1/2)=00\cdot(1/2)=0, 0⋅1=00\cdot1=0, 1⋅0=01\cdot0=0, with running sums 1,1,1,1. Feature d=1 has products 1⋅1=11\cdot1=1, 0⋅0=00\cdot0=0, 0⋅(−1)=00\cdot(-1)=0, 1⋅(1/2)=1/21\cdot(1/2)=1/2, with running sums 1,1,1,3/2. Thus the widened-value output is (1,3/2), with unchanged input width and unchanged Dk. Both C and WO grew to four joined features; Y still has two.

Changing H similarly selects active head identities rather than reassigning their parameter names. H=1,Dk=Dv=2 reproduces IV-25’s single-head attention arrays after removing the head axis, under matched inputs/masks/weights/shift. Its additional WO transformation is a separate operation. To extend that equivalence from squeezed OHeads through final Y, set the active head-zero WO rows to identity explicitly: wo000=1, wo001=0, wo010=0, wo011=1. The default active matrix at H=1,Dv=2 is instead [[1,1],[1/2,0]], which is nonidentity. Thus reproducing IV-25 through OHeads does not by itself reproduce its O as Y.

Predict a WO-only edit and its limits

Return to the full reset and change only wo101 from −1 to zero. Joined C remains (1,0), (1/2,r), (a,a). The first output column is unchanged. The second now uses weights (1,0), so its products and sums are 1⋅1+0⋅0=11\cdot1+0\cdot0=1, (1/2)⋅1+r⋅0=1/2(1/2)\cdot1+r\cdot0=1/2, a⋅1+a⋅0=aa\cdot1+a\cdot0=a. No projection, score, mask, P or OHeads value changes. A zero joined coordinate also shows why editing an active output weight need not change every token’s output.

Concatenation by itself loses no head coordinate, but a projection to fewer output coordinates can lose information. For example, a WO of all zeros maps every possible joined row to Y=0, even if the heads strongly disagree. Output equality therefore cannot prove equality of upstream maps. Signed weights also let Y fall outside the interval spanned by head values; the convex-mixture bound for attention messages does not transfer to arbitrary WO.

The lab retains bounds B/H/Dk/Dv=1–2, T=1–3, X and all weights in [−4,4], shift in [−10000,10000] and exact Boolean key flags. All inactive entries remain validated. Default causal mode can be changed to all-keys, padding-only or their intersection. Flags mask keys across every batch/head, leaving queries present. Any fully masked row makes the entire result unavailable before a join can supply a valid Y. Large shifts and tiny softmax terms retain the floating-point caveats from IV-28; cancellation in a signed output is another reason to distinguish exact algebra from rounded display.

Read the complete actual implementation

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-29 — Head Concatenation and Output Projection.

Prerequisites: IV-28 and II.10. Copy actual OHeads into C[b,t,h*Dv+f],
pack WO by the same named head/feature identity, then explicitly compute Y=C WO.
Default active WO rows are (1,1),(1,-1). For e=exp(1), hand algebra gives Y
[(1,1),(1/2+e/(1+e),1/2-e/(1+e)),(4e/(1+2e),0)]. These expressions are
real-arithmetic identities, not executed floating-point values. A signed Y is
expected: concatenation is not averaging, and WO is not a probability map.
No bias, residual, dropout, normalization or output softmax is hidden here.
Keep head_reference.py beside this program.
"""
from types import MappingProxyType
from head_reference import OUTPUT_HEAD_DEFAULTS, attend_heads, guarded, head_state, head_trace, join_heads, project_heads, run

DEFAULT_IV29 = MappingProxyType(dict(OUTPUT_HEAD_DEFAULTS))


@guarded
def derive_iv29(state):
    """Trace real head values through concatenation and every WO contribution."""
    s = head_state(state, 29)
    trace = head_trace()
    projected = project_heads(s, trace)
    attended = attend_heads(s, projected, trace)
    joined = join_heads(s, attended, trace)
    summary = dict(B=s["B"], T=s["T"], H=s["H"], Dk=s["Dk"], Dv=s["Dv"])
    summary.update(projected["aliases"])
    summary.update(attended["aliases"])
    summary.update(joined["aliases"])
    return trace.result(summary, [*projected["tensors"], *attended["tensors"], *joined["tensors"]])


if __name__ == "__main__":
    run(derive_iv29, DEFAULT_IV29)
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 chapter wrapper composes project_heads, attend_heads and join_heads. In the helper, concat_0_1_1_0 copies head one’s query-one message to its joined address. output_0_1_1 records query one’s second output coordinate: each productc, each runningc, and final value. Alias c011 is C[0,1,1], while y011 is Y[0,1,1]. Follow the saved operands rather than treating a table’s rounded number as a new input. These imported files are the actual reference sources.

Five exercises matched to the lab

The lab grades five questions with corrective feedback. Each outline below follows its corresponding question. The live question fixes its own coordinates independently of inspector selectors.

  1. concatenation: What does joining do? Copy actual OHeads coordinates into C in order c=h·Dv+f: all head-zero features, then all head-one features. There is no averaging, extra normalization or substitution of another head map.
  2. output-shape: With H=2,Dv=2, what shapes make the output multiplication legal? C is [B,T,4], WO is [4,2], Y is [B,T,2]. The shared width four is contracted. Dk belongs to scoring and does not set the joined-value width.
  3. live-output: Sum every product saved in output_0_0_0. This is batch zero, token zero, output feature zero. Starting from zero, add in joined-feature order and read each runningc, then final value. Reset products are 1·1=1 and 0·1=0, giving running sums 1 and 1, so Y[0,0,0]=1. With wider values or edits, use all current products rather than only these two.
  4. wo-only-edit: Which quantities can change when only WO changes? Y may change; projection arrays, scores, probabilities, OHeads and C stay fixed. WO is downstream of them. A zero joined coordinate or inactive parameter can make even Y unchanged.
  5. signed-output: Project C=(1/2,3/4) with WO rows (1,1),(1,−1). Feature zero has products 1/2·1=1/2 and 3/4·1=3/4, with running sums 1/2 then 5/4. Feature one has products 1/2·1=1/2 and 3/4·(−1)=−3/4, with running sums 1/2 then −1/4. Thus Y=(5/4,−1/4) is valid; these signed output coordinates are not probabilities. The 3/4 is this question’s supplied value, not an approximation to the reset exponential ratio.

Recap and bridge

Concatenate in order c=hDv+f, preserving each message coordinate while explicitly changing axis placement. Apply WO with one product and immediate running-sum update per joined feature. The final width is two, and the output is a signed feature vector rather than a distribution. This completes the multi-head attention path; IV-30 — Residual Connections and Gradient Paths next introduces residual connections as an additional operation with an explicit shape requirement.