IV-28 / Part VI · Multi-Head Attention
Independent Attention Heads
Follow each head's own dot products, allowed-key softmax and weighted values, including complete causal hand calculations and changed-mask counterexamples.
Review the ideas this chapter uses
Two people can summarize the same list using different scoring rules. That is a useful analogy for multiple attention heads, with one important boundary: our heads are numerical paths, not people interpreting meaning. Each path compares its own queries and keys, normalizes its own scores, and uses the resulting probabilities to combine its own values. We will calculate both paths completely so that different-looking maps cannot hide an unchanged or fabricated output.
Learning objective: Execute separate head-specific score, mask, softmax and value paths.
Begin with IV-27 — Separating Attention Heads and Dimensions for head addresses and IV-26 — Causal, Bidirectional and Padding Attention for mask semantics. Book II’s II.4 — Dot product, angle, and orthogonality reviews the dot product; VII.7 — Numerical stability: log-sum-exp and stable softmax explains stable softmax. Book III’s III-41 — Composition and Learned Representations distinguishes computing representations from learning them. All parameters below are hand-set, with no training claim.
Compare the real paths
Independent Attention Heads
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
Input token rows X
Query projection WQ
Key projection WK
Value projection WV
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
Outputs
- B
- 1
- T
- 3
- D
- 2
- H
- 2
- Dk
- 1
- Dv
- 1
Projected coordinates, declared layout, real head probabilities and outputs
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. 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.
| Token | Input D 0 | Input D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
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}.
| Input D | Packed h*F+f 0 | Packed h*F+f 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
QConcat: batch 0
B=1 × T=3 × QueryFeature=2 · float64. XWQ; each packed coordinate has two products and one sum.
| Token | Packed h*F+f 0 | Packed h*F+f 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
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.
| Saved step | Token | Feature | x0 | w0 | product0 | x1 | w1 | product1 | Sum |
|---|---|---|---|---|---|---|---|---|---|
| project_Q_0_0_0_0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| project_Q_0_1_0_0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| project_Q_0_2_0_0 | 2 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| Saved step | [b,t,h,f] → [b,h,t,f] | Packed feature | Source flat offset | Destination flat offset | Split source value | Heads copied value |
|---|---|---|---|---|---|---|
| permute_Q_0_0_0_0 | [0,0,0,0] → [0,0,0,0] | 0 | 0 | 0 | 1 | 1 |
| permute_Q_0_0_1_0 | [0,1,0,0] → [0,0,1,0] | 0 | 2 | 1 | 0 | 0 |
| permute_Q_0_0_2_0 | [0,2,0,0] → [0,0,2,0] | 0 | 4 | 2 | 1 | 1 |
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.
| Token | Within-head feature 0 |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
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}.
| Input D | Packed h*F+f 0 | Packed h*F+f 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
KConcat: batch 0
B=1 × T=3 × KeyFeature=2 · float64. XWK; each packed coordinate has two products and one sum.
| Token | Packed h*F+f 0 | Packed h*F+f 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
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.
| Saved step | Token | Feature | x0 | w0 | product0 | x1 | w1 | product1 | Sum |
|---|---|---|---|---|---|---|---|---|---|
| project_K_0_0_0_0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| project_K_0_1_0_0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| project_K_0_2_0_0 | 2 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| Saved step | [b,t,h,f] → [b,h,t,f] | Packed feature | Source flat offset | Destination flat offset | Split source value | Heads copied value |
|---|---|---|---|---|---|---|
| permute_K_0_0_0_0 | [0,0,0,0] → [0,0,0,0] | 0 | 0 | 0 | 1 | 1 |
| permute_K_0_0_1_0 | [0,1,0,0] → [0,0,1,0] | 0 | 2 | 1 | 0 | 0 |
| permute_K_0_0_2_0 | [0,2,0,0] → [0,0,2,0] | 0 | 4 | 2 | 1 | 1 |
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.
| Token | Within-head feature 0 |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
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}.
| Input D | Packed h*F+f 0 | Packed h*F+f 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
VConcat: batch 0
B=1 × T=3 × ValueFeature=2 · float64. XWV; values are projected separately from queries and keys.
| Token | Packed h*F+f 0 | Packed h*F+f 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
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.
| Saved step | Token | Feature | x0 | w0 | product0 | x1 | w1 | product1 | Sum |
|---|---|---|---|---|---|---|---|---|---|
| project_V_0_0_0_0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| project_V_0_1_0_0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| project_V_0_2_0_0 | 2 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| Saved step | [b,t,h,f] → [b,h,t,f] | Packed feature | Source flat offset | Destination flat offset | Split source value | Heads copied value |
|---|---|---|---|---|---|---|
| permute_V_0_0_0_0 | [0,0,0,0] → [0,0,0,0] | 0 | 0 | 0 | 1 | 1 |
| permute_V_0_0_1_0 | [0,1,0,0] → [0,0,1,0] | 0 | 2 | 1 | 0 | 0 |
| permute_V_0_0_2_0 | [0,2,0,0] → [0,0,2,0] | 0 | 4 | 2 | 1 | 1 |
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.
| Token | Within-head feature 0 |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
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.
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 0 |
| 2 | 1 | 0 | 1 |
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.
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 0 |
| 2 | 1 | 0 | 1 |
| Saved step | Key | q0 | k0 | product0 | Raw | sqrt(Dk) | Score |
|---|---|---|---|---|---|---|---|
| score_0_0_0_0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
| score_0_0_0_1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 |
| score_0_0_0_2 | 2 | 1 | 1 | 1 | 1 | 1 | 1 |
Real probability map for head 0, batch 0
| Query / key | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| Query 0 | Allowed: p=1 | Forbidden: p=0 | Forbidden: p=0 |
| Query 1 | Allowed: p=0.5 | Allowed: p=0.5 | Forbidden: p=0 |
| Query 2 | Allowed: p=0.4223187982515182 | Allowed: p=0.15536240349696362 | Allowed: p=0.4223187982515182 |
Real probability map for head 1, batch 0
| Query / key | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| Query 0 | Allowed: p=1 | Forbidden: p=0 | Forbidden: p=0 |
| Query 1 | Allowed: p=0.2689414213699951 | Allowed: p=0.7310585786300049 | Forbidden: p=0 |
| Query 2 | Allowed: p=0.15536240349696362 | Allowed: p=0.4223187982515182 | Allowed: 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.
| Key | Allowed? | Score | Logit=score+shift | Allowed logit−max | Exponential term | p=term/denominator |
|---|---|---|---|---|---|---|
| 0 | true | 1 | 1 | 0 | exp(0)=1 | 1 / 1 = 1 |
| 1 | false | 0 | 0 | Forbidden: no subtraction | Forbidden: 0, no exponential | 0 / 1 = 0 |
| 2 | false | 1 | 1 | Forbidden: no subtraction | Forbidden: 0, no exponential | 0 / 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.
| Query | Value feature 0 |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | 0.8446375965030364 |
| Key | This head’s p | This head’s V | p × V | Running sum from 0 |
|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 |
| 1 | 0 | 0 | 0 | 1 |
| 2 | 0 | 1 | 0 | 1 |
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.
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
- 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
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
WQ
D=2 × QueryFeature=2 · float64 · display precision 8 · Query columns packed by h*Dk+f from wq{d}{h}{f}.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
WK
D=2 × KeyFeature=2 · float64 · display precision 8 · Key columns packed by h*Dk+f from wk{d}{h}{f}.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
WV
D=2 × ValueFeature=2 · float64 · display precision 8 · Value columns packed by h*Dv+f from wv{d}{h}{f}.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
QConcat
B=1 × T=3 × QueryFeature=2 · float64 · display precision 8 · XWQ; each packed coordinate has two products and one sum.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
KConcat
B=1 × T=3 × KeyFeature=2 · float64 · display precision 8 · XWK; each packed coordinate has two products and one sum.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
VConcat
B=1 × T=3 × ValueFeature=2 · float64 · display precision 8 · XWV; values are projected separately from queries and keys.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
QSplit
B=1 × T=3 × H=2 × Dk=1 · float64 · display precision 8 · QConcat reshaped without changing flat order; feature=h*F+f.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
KSplit
B=1 × T=3 × H=2 × Dk=1 · float64 · display precision 8 · KConcat reshaped without changing flat order; feature=h*F+f.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
VSplit
B=1 × T=3 × H=2 × Dv=1 · float64 · display precision 8 · VConcat reshaped without changing flat order; feature=h*F+f.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
raw
B=1 × H=2 × Query=3 × Key=3 · float64 · display precision 8 · Separate QHeads KHeads transpose products within every batch and head.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 1 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 1 |
| 14 | 1 |
| 15 | 0 |
| 16 | 1 |
| 17 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 1 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 1 |
| 14 | 1 |
| 15 | 0 |
| 16 | 1 |
| 17 | 1 |
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 index | Value |
|---|---|
| 0 | true |
| 1 | false |
| 2 | false |
| 3 | true |
| 4 | true |
| 5 | false |
| 6 | true |
| 7 | true |
| 8 | true |
| 9 | true |
| 10 | false |
| 11 | false |
| 12 | true |
| 13 | true |
| 14 | false |
| 15 | true |
| 16 | true |
| 17 | true |
logits
B=1 × H=2 × Query=3 × Key=3 · float64 · display precision 8 · Finite score+shift, including forbidden cells; mask applied separately.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 1 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 1 |
| 14 | 1 |
| 15 | 0 |
| 16 | 1 |
| 17 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0.5 |
| 4 | 0.5 |
| 5 | 0 |
| 6 | 0.4223187982515182 |
| 7 | 0.15536240349696362 |
| 8 | 0.4223187982515182 |
| 9 | 1 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0.2689414213699951 |
| 13 | 0.7310585786300049 |
| 14 | 0 |
| 15 | 0.15536240349696362 |
| 16 | 0.4223187982515182 |
| 17 | 0.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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | 0.8446375965030364 |
| 3 | 0 |
| 4 | 0.7310585786300049 |
| 5 | 0.8446375965030364 |
Open a matrix group before editing its values. B,T,H,Dk,Dv, mask mode, three shared key-validity flags and common shift remain visible. All 46 stored fields are checked before active dimensions are selected. Changing an input recomputes every head; batch/head/query/value-feature selectors only choose which saved operands to inspect.
Reset is causal with e=exp(1). Head 0 reads (1,0,1) and produces O=(1,1/2,2e/(1+2e)). Head 1 reads (0,1,1) and produces O=(0,e/(1+e),2e/(1+2e)). At query 1, head 0 has allowed scores (0,0) and probabilities (1/2,1/2); head 1 has (0,1) and probabilities (1/(1+e),e/(1+e)). Those different actual probabilities multiply the actual V values in each head. At query 2 the output coordinates happen to agree.
Try Dk=2: the default head projections swap the two coordinates, which preserves dot products, so the probability maps agree. Try WV-only edits to leave P unchanged while changing a head’s O. With H=1,Dk=Dv=2 the attention arrays match IV25’s scalar operation order after removing H. With T=1 each allowed row has p=1; marking its sole key invalid in a padding mode instead rejects the result. Large common shifts preserve real ratios but can alter rounded stored values.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Reset uses causal attention, B=1, T=3, H=2, Dk=Dv=1, all validity flags one and shift zero. Compare head zero and head one at query one: their probability rows and weighted outputs differ. At query two, the probability rows still differ but the outputs happen to agree. That agreement is a useful counterexample, not a display error.
Open Input token rows X, Query projection WQ, Key projection WK or Value projection WV before editing a matrix. These native disclosures start closed. Dimensions, mask mode, validity flags and shift remain outside the matrix groups. The selected head/batch/query/feature changes what you inspect; an input edit recomputes the underlying complete numerical result.
Name every axis before multiplying
B counts independent sequences, T positions, H attention heads, Dk query/key coordinates per head and Dv value coordinates per head. D=2 is the fixed input feature width. H is a number of paths, not the neuron width of an earlier hidden layer. Indices b, h, i, j and f mean batch, head, query position, key position and within-head feature, beginning at zero.
QHeads and KHeads have shape [B,H,T,Dk]; VHeads has [B,H,T,Dv]. The previous chapter computed them by projecting X [B,T,2], reshaping packed columns hF+f without changing flat values, then explicitly permuting B,T,H,F to B,H,T,F. Different heads have separate weight entries; the same head’s weights are reused across tokens and batches. “Independent” means separate per-head parameters and calculations before WO, not statistical independence or a promise of different P. The heads share input X and mask policy, so equal results are entirely legitimate.
Raw dot products, scaled scores, allowed flags, logits and probabilities P each have shape [B,H,T,T], with axes B,H,Query,Key. “Row” below means one fixed b,h,i and all key positions j. OHeads has [B,H,T,Dv]: one Dv-coordinate message per query per head. Normalization removes no axis; the later value sum removes the key axis.
Build scores from each head’s own projections
At reset, Q=K=V within each head. Their sequences follow from the full projection arithmetic:
| Head | Token 0 projection | Token 1 projection | Token 2 projection | Sequence for each role |
|---|---|---|---|---|
| 0 | (1,0,1) | |||
| 1 | (0,1,1) |
The role-specific maps need not stay equal after edits. For a fixed head, multiply matching query/key features and sum:
R denotes the raw score and S the scaled score. The square-root divisor uses Dk, not H or Dv. Width one gives divisor one and one product per score; width two gives two products summed in feature order, then division by . A larger width can increase a dot product’s scale, motivating this scaling; it does not guarantee well-behaved scores for arbitrary parameters.
Here are every reset score’s products. The rows inside each cell are key order 0,1,2; nothing is shared between heads’ score calculations.
| Head, query | All three dot products | Raw and scaled row, since Dk=1 |
|---|---|---|
| 0, 0 | (1,0,1) | |
| 0, 1 | (0,0,0) | |
| 0, 2 | (1,0,1) | |
| 1, 0 | (0,0,0) | |
| 1, 1 | (0,1,1) | |
| 1, 2 | (0,1,1) |
Normalize only the permitted keys of this head
A mask is a Boolean permission rule. Mode 0 permits all active keys; mode 1 permits j≤i; mode 2 permits keys with validj=1; mode 3 requires both causal and validity conditions. Validity flags are intentionally shared across B and H, and apply to keys only. Every query remains present. A zero vector is not automatically padding.
A logit here is the finite score plus the common shift. For this row’s allowed set A, compute the maximum m over allowed logits only. For an allowed key form ; for a forbidden key set exactly. Add terms from zero in ascending key order for denominator d, then divide . There is a separate maximum, denominator and probability row for every b,h,i; there is no normalization across heads.
For the complete causal default put and . These are exact real expressions, not measured or rounded decimals. In the following table, a dash means no subtraction is performed for that forbidden key, not that its shifted logit is zero.
| Head, query | Allowed flags | m; allowed subtractions in key order | All terms; denominator | Probability row |
|---|---|---|---|---|
| 0, 0 | 100 | (1,0,0) | ||
| 0, 1 | 110 | (1/2,1/2,0) | ||
| 0, 2 | 111 | |||
| 1, 0 | 100 | (1,0,0) | ||
| 1, 1 | 110 | |||
| 1, 2 | 111 |
For example, head one’s middle key probability is . Subtracting the maximum cancels the same exponential factor from numerator and denominator, so this equals the direct real softmax ratio. Forbidden keys enter neither maximum nor normalization, even when their displayed scores are large.
These probabilities actually drive the messages
For fixed b,h,i,f, calculate
Multiply by the value from the same head and key. Starting at zero, add each product immediately before advancing j. The probability row is reused for all Dv features of this head; it is not reused for another head. Here is every default message coordinate, including masked-zero products:
| Head, query, feature 0 | Products for keys 0,1,2 | Running sums after keys 0,1,2 |
|---|---|---|
| 0,0 | ||
| 0,1 | ||
| 0,2 | ||
| 1,0 | ||
| 1,1 | ||
| 1,2 |
Head zero’s sequence is and head one’s is . Query two has different P rows but equal scalar messages: head zero weights its two value-one positions by e/g each; head one does the same at two different positions. A different probability map need not produce a different output. Identical values would provide an even simpler counterexample.
Change one head or one access rule
Reset, then open WQ and change wq110 from one to two. Only head one’s query coordinate becomes at token one and at token two. Its keys and values stay (0,1,1). Its middle score row is now (0,2,2), so the causal row is and the message is . Its last message becomes . Head zero keeps its entire previous calculation. Independence means these separate dependencies; it does not promise that heads learn different linguistic jobs.
Restore reset and use causal + padding with valid2=0. Query two now permits only keys zero and one. Head zero has terms (1,1/e,0), denominator , P= and message . Head one has terms (1/e,1,0), P= and message . Query two still exists, even though key two is forbidden.
With combined mode, valid0=0 makes query zero fully masked. There is no maximum or denominator for that row. The whole result becomes unavailable with FULLY_MASKED_ROW and batch/head/query identity; it does not invent zero messages or skip a head. In causal mode alone, flags do not affect permission, although their stored values remain validated.
Equality, numerical limits and actual source
Set Dk=2 with default weights: queries and keys become (x0,x1) in head zero and (x1,x0) in head one. Swapping both vectors’ coordinates preserves their dot product, so the two heads now have equal score and probability matrices under the shared mask. Different projection labels do not guarantee different attention.
With H=1 and Dk=Dv=2, head zero has identity Q/K/V projections at default weights. For matched X, projection weights, mask and shift, removing the singleton head axis reproduces IV-25 arrays through OHeads: Q, K, V, raw scores, scaled scores, allowed flags, logits, probabilities and value outputs. This equivalence stops before the extra output projection in IV-29. Its final Y matches the old O under this correspondence when the active WO is explicitly identity: wo000=1, wo001=0, wo010=0, wo011=1. Default WO is nonidentity. Dv controls the messages separately; it never replaces Dk in the divisor.
B=2 supplies independent input sequences with shared weights and validity flags; no score or message crosses batches. T=1 yields the sole value if allowed. Signed values can yield signed messages; probabilities normalize over keys, not output features. Bounds are B/H/Dk/Dv=1–2, T=1–3, X and weights in [−4,4], shift in [−10000,10000], flags exactly zero or one. All stored fields, including inactive ones, are validated.
A common shift preserves real softmax ratios but can round score differences in binary64. Very small allowed terms may underflow; count permissions from Boolean flags rather than printed nonzero probabilities. Finite storage, finite intermediates and display rounding are distinct concerns. These manual identities do not establish numerical or browser validation.
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-28 — Independent Attention Heads.
Prerequisite: IV-27. Each batch/head/query gets its own scaled score row,
allowed-key stable softmax and actual weighted value output. Mode 1 is causal;
0 permits all keys, 2 uses key-validity flags, 3 intersects causal and validity.
Queries remain present. Any fully masked row makes the whole result unavailable.
With default widths 1 and e=exp(1), hand algebra gives head0 outputs
[1,1/2,2e/(1+2e)] and head1 [0,e/(1+e),2e/(1+2e)]. Heads can agree too:
at default Dk=2 their swapped-coordinate dot products coincide. These are
real-arithmetic identities, not binary64 run output. Keep head_reference.py here.
"""
from types import MappingProxyType
from head_reference import ATTENTION_HEAD_DEFAULTS, attend_heads, guarded, head_state, head_trace, project_heads, run
DEFAULT_IV28 = MappingProxyType(dict(ATTENTION_HEAD_DEFAULTS))
@guarded
def derive_iv28(state):
"""Project, split, attend independently, then expose each real head output."""
s = head_state(state, 28)
trace = head_trace()
projected = project_heads(s, trace)
attended = attend_heads(s, projected, 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"])
# Stage results are local: combine their tensors explicitly, exactly once.
return trace.result(summary, [*projected["tensors"], *attended["tensors"]])
if __name__ == "__main__":
run(derive_iv28, DEFAULT_IV28)
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=(",", ":")))
project_heads supplies Q/K/V; attend_heads scores, masks, normalizes and mixes them. In score_0_1_1_0, read head one’s middle query against key zero. row_0_1_1 saves that row’s own denominator and probabilities. head_mix_0_1_1_0 consumes those probabilities and VHeads values, recording every product and running sum. Alias p0111 is P[0,1,1,1]; oh0110 is OHeads[0,1,1,0]. The wrapper composes the stages; the helper is the actual local implementation, not a parallel illustrative algorithm.
Five exercises matched to the lab
Attempt the five graded questions above before reading these corrective outlines. The live question fixes its own coordinates independently of selectors.
independent-path: Which probabilities drive one head message? Each batch/head/query has its own probability row over keys, and that exact row multiplies the values from the same head and batch. Probabilities are not normalized across heads or borrowed from another head.head-output-shape: What is OHeads for B=1,H=2,T=3,Dv=2?[1,2,3,2], in B,H,Query,Dv order. Dk was summed in each score; the later key sum removes the key axis while leaving two value coordinates. H counts paths, not message features.live-head-mix: Sum the saved products inhead_mix_0_0_0_0. Start at zero and add eachproductjin key order; compare the correspondingrunningjand finalvalue. Reset head zero, query zero, feature zero gives products (1,0,0), running sums (1,1,1) and output 1. After edits use the actual saved operands; this question does not follow the head selector.value-head-edit: Change onlywv010. This is head one, value feature zero, input feature zero. Active head-one V and its OHeads messages may change; every Q, K and P, and head-zero OHeads, remain fixed. WV never enters score calculation. If head one is inactive or a relevant operand is zero, the output may stay unchanged.equal-or-masked: Must independent heads disagree, and can an empty row become uniform? Neither claim holds. Default Dk=2 swaps both query/key coordinates, preserving dot products and allowing equal maps. Conversely, fully masking even one batch/head/query leaves no denominator and makes the whole result unavailable. Uniform or zero output would invent a result.
Recap and bridge
Each b,h,i gets an independent key-normalized probability row. Those actual probabilities multiply that head’s actual values, including recorded zero products for forbidden keys. Heads can disagree, agree, or produce equal messages from different maps; none of these proves a linguistic interpretation. IV-29 — Head Concatenation and Output Projection keeps every head message, joins features in a declared order and applies an explicit output matrix.