IV-27 / Part VI · Multi-Head Attention
Separating Attention Heads and Dimensions
Calculate packed query, key and value projections, preserve their values through a reshape, then follow the explicit permutation into named attention-head axes.
Review the ideas this chapter uses
One token can supply several different sets of query, key and value coordinates. Before calculating attention separately with them, we need to say exactly which coordinate belongs to which set. Otherwise an innocent-looking rearrangement can pair a query from one head with a key from another. This chapter builds the projections and follows their addresses; the next chapter uses them to calculate attention.
Learning objective: Reshape concatenated projections into named head-specific axes.
Review IV-25 — Self-Attention: Complete Numerical Trace for the complete single-head calculation. Book II’s II.10 — Matrix × matrix as composition explains matrix composition, and II.11 — Transpose and orthogonality explains changing axis order. Book III’s III-41 — Composition and Learned Representations connects compositions to representations. Here the weights are hand-set; editing a weight is an experiment, not a training update.
Open a matrix, then edit one coordinate
Separating Attention Heads and Dimensions
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
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
Outputs
- B
- 1
- T
- 3
- D
- 2
- H
- 2
- Dk
- 1
- Dv
- 1
Projected coordinates, declared layout
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 |
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
- 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
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 |
Open Input token rows X, Query projection WQ, Key projection WK or Value projection WV before editing a matrix. The five dimension selectors remain visible. All 41 stored scalars are validated, including inactive batches, heads and features. A valid edit recomputes the actual projections and resets trace navigation and graded answers.
Reset uses B=1,T=3,H=2,Dk=Dv=1. Q/K/V packed token rows are (1,0),(0,1),(1,1). Reshaping to [1,3,2,1] preserves flat [1,0,0,1,1,1]. The separate [0,2,1,3] permutation produces [1,2,3,1] with flat [1,0,1,0,1,1]: head 0 receives (1,0,1), head 1 receives (0,1,1). Every source and destination offset is shown, rather than inferred from a diagram.
Select H=1,Dk=Dv=2 to inspect head 0’s two-feature identity projection, matching the protected IV25 projection after removing the singleton head axis. At H=2,Dk=Dv=2, head 1 reads the two input features in reverse order. Changing a width keeps parameter names tied to the same head and within-head feature. This chapter stops at projections and layout; IV28 adds each head’s actual attention path.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Start with reset. Dimensions remain visible; the matrix controls are inside initially closed disclosures. Open Input token rows X, Query projection WQ, Key projection WK or Value projection WV before editing that matrix. Closing a group hides controls, not their validation or their effect on the calculation.
Keep B=1, T=3, H=2 and both head widths one. The projected query rows are (1,0), (0,1), (1,1). Inspect their split and head layouts. Then open WQ and change wq010 from zero to two: this is input feature zero, head one, within-head feature zero. Head one’s query sequence becomes (2,1,3). K and V keep their previous numbers. Reset before following the default arithmetic below.
A head is a calculation path, not a neuron width
A head is one query/key/value projection path with its own attention calculation. Separate per-head parameters and calculations are what “independent heads” means here, before any output projection mixes them. It does not mean statistical independence or guarantee different probabilities: heads receive the same X and may compute equal results. H counts those paths. It does not denote the hidden-layer neuron width used in earlier neural-network chapters. Within one head, Dk counts query and key coordinates, while Dv counts value coordinates. These are separate choices: increasing H does not mean increasing Dk.
A tensor is an array with named axes. B counts independent sequences in a batch; T counts active token positions in each sequence; D=2 is this lab’s fixed input feature count. Each token is represented by two real numbers, not by a word string. Lowercase b, t, h, d and f name a batch, token, head, input feature and within-head feature. Indices start at zero.
A shape lists the number of entries along each axis. [B,T,2] means B sequences, T token rows per sequence, two input coordinates per row. Multiplication here uses row-feature weights: X is multiplied on the right. Earlier column-vector formulas such as Wx describe the same linear transformation only after the weight orientation is translated explicitly.
| Tensor | Shape | Axes and purpose |
|---|---|---|
| X | [B,T,2] | Batch, token, input feature |
| WQ, WK | [2,H*Dk] | Input feature, packed query/key feature |
| WV | [2,H*Dv] | Input feature, packed value feature |
| QConcat, KConcat | [B,T,H*Dk] | Batch, token, packed query/key feature |
| VConcat | [B,T,H*Dv] | Batch, token, packed value feature |
| QSplit, KSplit | [B,T,H,Dk] | Batch, token, head, query/key feature |
| VSplit | [B,T,H,Dv] | Batch, token, head, value feature |
| QHeads, KHeads | [B,H,T,Dk] | Batch, head, token, query/key feature |
| VHeads | [B,H,T,Dv] | Batch, head, token, value feature |
Q means query, K key and V value. The word packed means several heads’ features occupy consecutive columns in one matrix. For a generic within-head width F, column c is h*F+f: all features of head zero come first, followed by all features of head one. Use F=Dk for Q/K and F=Dv for V. The two input rows always remain present, even when F=1.
Calculate the projections before rearranging anything
For any role R, its packed coordinate is the same two-product sum:
J is a name for the packed projection, not an additional model input. Each output column has two weights because each input token has two features. The matching input-feature axis is summed away. Batch and token stay fixed; no other token participates in a projection.
At reset each role has active weights [[1,0],[0,1]]. Head zero reads input feature zero; head one reads input feature one. For Q, K and V, every active projection product is:
| Token t | Head h, feature f | Input-feature-zero product | Input-feature-one product | Sum |
|---|---|---|---|---|
| 0 | 0, 0 | |||
| 0 | 1, 0 | |||
| 1 | 0, 0 | |||
| 1 | 1, 0 | |||
| 2 | 0, 0 | |||
| 2 | 1, 0 |
Each role therefore has packed rows (1,0), (0,1), (1,1). Their equality is a consequence of the initial weights, not a rule that Q, K and V must agree. The WQ edit above changes head one’s sums to , , . The other head and the other roles have no changed weight.
Reshape preserves the flat sequence
Flattening lists entries by walking the last axis fastest. For the reset packed Q tensor, [1,3,2], that list is [1,0,0,1,1,1]. Reshaping it to [1,3,2,1] replaces the packed-feature address c with the pair (h,f), where c=hF+f. It does not change the list or compute new numbers:
This works because the packed width is exactly H times F. The entry count remains BTHF. Equality of total entry counts alone is insufficient if a proposed split gives the wrong named head width: a projection width of three cannot be split into two heads of width two. The lab rejects a mismatched layout rather than discarding a column or guessing another head count.
Permuting the axes changes placement
The attention calculation wants to keep a head’s token sequence together. We therefore explicitly permute axes from B,T,H,F to B,H,T,F, in the order 0,2,1,3:
The value at the corresponding address is copied unchanged, but its position in a flattened list generally moves. Here is the complete reset mapping, including every entry. Offsets are zero-based positions in their respective flat lists.
| b,t,h,f | Packed feature hF+f | Source offset | Destination b,h,t,f | Destination offset | Value |
|---|---|---|---|---|---|
| 0,0,0,0 | 0 | 0 | 0,0,0,0 | 0 | 1 |
| 0,0,1,0 | 1 | 1 | 0,1,0,0 | 3 | 0 |
| 0,1,0,0 | 0 | 2 | 0,0,1,0 | 1 | 0 |
| 0,1,1,0 | 1 | 3 | 0,1,1,0 | 4 | 1 |
| 0,2,0,0 | 0 | 4 | 0,0,2,0 | 2 | 1 |
| 0,2,1,0 | 1 | 5 | 0,1,2,0 | 5 | 1 |
For example, token one, head one is source offset . Its head-first destination is . Thus the head-first flat sequence becomes [1,0,1,0,1,1]: head zero’s (1,0,1), then head one’s (0,1,1). Calling both operations “just a reshape” would conceal this change of placement.
For arbitrary active dimensions, source offset is ((b*T+t)*(H*F)+h*F+f); destination offset is ((b*H+h)*T+t)*F+f. The trace’s permute_Q_b_h_t_f records those addresses and the copied value. K and V use the identical rule with their own widths. reshape_Q records the shape boundary separately from these copies.
More features preserve parameter identity
Set Dk=2. The packed Q/K weight rows become (1,0,0,1) and (0,1,1,0). For token (a,b), its packed projection is . Head zero gets (a,b), head one gets (b,a). H stays two: wider heads are not extra heads. Dv changes V’s width separately.
With H=1 and Dk=Dv=2, head zero uses both input coordinates and its default matrices are identity. Removing the singleton head axis recovers IV-25’s projected arrays for matched inputs. Conversely, H=2 with width one has the same packed width two but a different partition and, in the next chapter, different score calculations. Equal storage size does not imply equal attention.
Actual Python and the record to follow
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-27 — Separating Attention Heads and Dimensions.
Prerequisite: IV-25. Reshape concatenated projections into named head axes,
then separately permute axes (0,2,1,3). H counts heads; Dk/Dv count features
within one head. Both original input features remain in every projection.
Default Q/K/V concatenated flat storage [1,0,0,1,1,1] is unchanged by reshape;
the head-major permutation has flat storage [1,0,1,0,1,1]. These are hand
index identities, not recorded execution results. Keep head_reference.py here.
"""
from types import MappingProxyType
from head_reference import HEAD_DEFAULTS, guarded, head_state, head_trace, project_heads, run
DEFAULT_IV27 = MappingProxyType(dict(HEAD_DEFAULTS))
@guarded
def derive_iv27(state):
"""Trace real projections, storage-preserving splits and head permutations."""
s = head_state(state, 27)
trace = head_trace()
projected = project_heads(s, trace)
summary = dict(B=s["B"], T=s["T"], H=s["H"], Dk=s["Dk"], Dv=s["Dv"])
summary.update(projected["aliases"])
# All flattened trace outputs follow the dimension and projection aliases.
return trace.result(summary, projected["tensors"])
if __name__ == "__main__":
run(derive_iv27, DEFAULT_IV27)
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=(",", ":")))
head_state validates the complete stored parameter set; project_heads packs weights and computes the products. split_heads performs the checked reshape and declared permutation used by those projections. Read project_Q_0_0_1_0 for the edited coordinate’s two products, then permute_Q_0_1_0_0 for its destination. q0100 names QHeads[0,1,0,0]; the digits follow the tensor axes, not the packed column order.
The lab allows B=1–2, T=1–3, H=1–2 and Dk/Dv=1–2, with inputs and projection weights in [−4,4]. Inactive entries remain stored and validated; hiding a second batch or feature does not erase it. No mask, softmax or head output is computed in this chapter. All displayed tensors and trace records come from the projection result. Display rounding does not change model storage; nonfinite or invalid inputs make the result unavailable rather than being silently clipped.
Five exercises matched to the lab
The graded questions appear in the lab above. Each outline follows the same question and explains how to correct a mistaken answer. The live question uses its named coordinates independently of the view selectors.
head-axis: What does H count? Independent attention heads, each with its own projected coordinates and attention path. T counts positions; Dk and Dv count within-head features. H is not an earlier hidden-layer neuron width.split-shape: Split a query projection[1,3,4]with H=2 and Dk=2. The reshape is[1,3,2,2]with axes B,T,H,Dk. The separate permutation produces[1,2,3,2]with axes B,H,T,Dk. Four packed features become two heads times two features; reshaping does not move values.live-projection: Add the two actual products inproject_Q_0_0_0_0. This fixes batch zero, token zero, head zero, feature zero. Itsvalueisproduct0+product1; at reset this is 1·1+0·0=1. After edits read the saved products and use their sum, rather than assuming the reset answer. Even Dk=1 still uses both input features.head-edit: Change onlywq010. This names input feature zero, head one, query feature zero. It may change active head-one Q, while head-zero Q, every K and every V stay fixed. With H=1, head one is inactive and the edit changes no active projection, although its field is still validated. A zero input may also hide an otherwise active edit.layout-counterexample: Does moving T and H preserve the flat list? A reshape preserves it; the explicit axis permutation generally changes placement. Reset packed[1,0,0,1,1,1]becomes head-first[1,0,1,0,1,1]. A packed feature count unequal to H·Dk is rejected, never truncated or repaired by relabeling a head.
Recap and bridge
A head has its own named projection coordinates. Packed column hF+f keeps head features together; reshape preserves flat values, and the following permutation changes their placement. Projection still uses both input features and does not mix tokens or batches. In IV-28 — Independent Attention Heads, these actual QHeads, KHeads and VHeads will produce a separate probability matrix and weighted output for each head.