IV-25 / Part V · Self-Attention
Self-Attention: Complete Numerical Trace
Follow every projection, score, mask, softmax term and weighted-value sum to compute all coordinates of a complete one-head attention output.
Suppose each position in a sequence holds a small numerical message. We have already calculated how strongly each position weights the available messages. Now we use those weights to combine the messages themselves. This final step completes one self-attention head: one set of query, key and value projections followed by one weighted combination per query.
Learning objective: Derive X→Q,K,V→QKᵀ→scale→mask→softmax→AV without gaps.
Review IV-22 — Queries, Keys and Values as Projections, IV-23 — Dot-Product Attention Scores and Scaling and IV-24 — Masking and Numerically Stable Softmax for the three earlier stages. Book II’s II.9 — Matrix × vector explains multiplying a row by a weight column; II.4 — Dot product, angle, and orthogonality explains the dot products below. This is an authored arithmetic example with hand-set weights. No training or understanding of text is implied.
Begin with the complete editable calculation
Self-attention: complete numerical trace
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
- Dk
- 2
- Dv
- 2
- x000
- 1
- x001
- 0
- x010
- 0
- x011
- 1
- x020
- 1
- x021
- 1
- x100
- 1
- x101
- 1
- x110
- -1
- x111
- 0
- x120
- 0
- x121
- 2
- wq00
- 1
- wq01
- 0
- wq10
- 0
- wq11
- 1
- wk00
- 1
- wk01
- 0
- wk10
- 0
- wk11
- 1
- wv00
- 1
- wv01
- 0
- wv10
- 0
- wv11
- 1
- mode
- 1
- valid0
- 1
- valid1
- 1
- valid2
- 1
- shift
- 0
B 1. T 3. Dk 2. Dv 2. Validate all scalar inputs and select active dimensions. All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.. B 1. T 3. D 2. Dk 2. Dv 2
Validate all scalar inputs and select active dimensions
D=2; X[B,T,D]; WQ,WK[D,Dk]; WV[D,Dv]
All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.
Inputs
- B
- 1
- T
- 3
- Dk
- 2
- Dv
- 2
- x000
- 1
- x001
- 0
- x010
- 0
- x011
- 1
- x020
- 1
- x021
- 1
- x100
- 1
- x101
- 1
- x110
- -1
- x111
- 0
- x120
- 0
- x121
- 2
- wq00
- 1
- wq01
- 0
- wq10
- 0
- wq11
- 1
- wk00
- 1
- wk01
- 0
- wk10
- 0
- wk11
- 1
- wv00
- 1
- wv01
- 0
- wv10
- 0
- wv11
- 1
- mode
- 1
- valid0
- 1
- valid1
- 1
- valid2
- 1
- shift
- 0
Outputs
- B
- 1
- T
- 3
- D
- 2
- Dk
- 2
- Dv
- 2
Token rows → separate projections → query–key scores → allowed-key probabilities → weighted value outputs
These are hand-set weights, not a trained model. D=2 always counts input features. Dk=2 counts query/key features; Dv=2 counts value features. All indices start at zero. Inactive stored slots remain validated but do not appear in active tensors.
The example button restores B=1, T=3, Dk=Dv=2 and X=[[1,0],[0,1],[1,1]], then sets three different matrices. Mask mode, validity and shift keep their current values. Reset example above restores every lesson default.
Showing batch 0, query 0 against all 3 active keys. These selectors change the view only. Trace navigation above selects a saved operation independently; highlighted rows mark that operation when it is in this view.
X batch 0
B=1 × T=3 × D=2 · float64. Rows: Token; columns: Input feature D.
| Token | Input feature D 0 | Input feature D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
WQ shared weights
D=2 × Dk=2 · float64. Rows: Input feature D; columns: Query feature Dk.
| Input feature D | Query feature Dk 0 | Query feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
WK shared weights
D=2 × Dk=2 · float64. Rows: Input feature D; columns: Key feature Dk.
| Input feature D | Key feature Dk 0 | Key feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
WV shared weights
D=2 × Dv=2 · float64. Rows: Input feature D; columns: Value feature Dv.
| Input feature D | Value feature Dv 0 | Value feature Dv 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
Q batch 0
B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Query feature Dk.
| Token | Query feature Dk 0 | Query feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
K batch 0
B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Key feature Dk.
| Token | Key feature Dk 0 | Key feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
V batch 0
B=1 × T=3 × Dv=2 · float64. Rows: Token; columns: Value feature Dv.
| Token | Value feature Dv 0 | Value feature Dv 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
Every projection coordinate in batch 0
For row-feature inputs, output feature f is x0·W[0,f]+x1·W[1,f]. A column-vector version uses the transposed weights: q_column=WQᵀ·x_column.
| Coordinate | x0 | w0 | x0 × w0 | x1 | w1 | x1 × w1 | Sum |
|---|---|---|---|---|---|---|---|
| Q,0,0,0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| Q,0,0,1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| Q,0,1,0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| Q,0,1,1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| Q,0,2,0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| Q,0,2,1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 |
| K,0,0,0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| K,0,0,1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| K,0,1,0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| K,0,1,1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| K,0,2,0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| K,0,2,1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 |
| V,0,0,0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| V,0,0,1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| V,0,1,0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| V,0,1,1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| V,0,2,0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| V,0,2,1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 |
Batch 0, query 0: one dot product per key
Each comparison stays inside batch 0. Multiply matching features, add those products, then divide by sqrt(Dk). There is no softmax in IV-23: scores can be negative and need not sum to one.
raw batch 0
B=1 × Query=3 × Key=3 · float64. Rows: Query; columns: Key.
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 2 | 1 | 1 | 2 |
scores batch 0
B=1 × Query=3 × Key=3 · float64. Rows: Query; columns: Key.
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 0.7071067811865475 | 0 | 0.7071067811865475 |
| 1 | 0 | 0.7071067811865475 | 0.7071067811865475 |
| 2 | 0.7071067811865475 | 0.7071067811865475 | 1.414213562373095 |
| Key j | q0 | k0 | q0 × k0 | q1 | k1 | q1 × k1 | Raw sum | sqrt(Dk) | Scaled score |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 |
| 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 1.4142135623730951 | 0 |
| 2 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 |
Effective allowed keys and probabilities in batch 0
Mode 1: causal keys j≤i. Padding removes keys only; even a position marked as a padding key retains its query row. Every row must have at least one allowed key, or the entire result is unavailable.
| Query / key | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| Query 0 (selected) | Allowed: p=1 | Forbidden: p=0 | Forbidden: p=0 |
| Query 1 | Allowed: p=0.3302384506733431 | Allowed: p=0.6697615493266569 | Forbidden: p=0 |
| Query 2 | Allowed: p=0.2482550782577231 | Allowed: p=0.2482550782577231 | Allowed: p=0.5034898434845538 |
Softmax arithmetic for batch 0, query 0
Common shift = 0. Maximum over allowed logits = 0.7071067811865475. Denominator = 1 + 0 + 0 = 1.
| Key j | Allowed? | Score | Logit = score + shift | Logit − allowed max | Exponential term | Term / denominator = p |
|---|---|---|---|---|---|---|
| 0 | true | 0.7071067811865475 | 0.7071067811865475 + 0 = 0.7071067811865475 | 0.7071067811865475 − 0.7071067811865475 = 0 | exp(0) = 1 | 1 / 1 = 1 |
| 1 | false | 0 | 0 + 0 = 0 | Forbidden: no subtraction | Forbidden: term=0, no exponential | 0 / 1 = 0 |
| 2 | false | 0.7071067811865475 | 0.7071067811865475 + 0 = 0.7071067811865475 | Forbidden: no subtraction | Forbidden: term=0, no exponential | 0 / 1 = 0 |
exp(z) means the positive exponential function e raised to z. An allowed maximum has shifted value 0 and exp(0)=1, so the denominator is at least 1. Other allowed terms may underflow to 0 for very negative shifted values. The boolean mask distinguishes that rounded zero from a forbidden key.
Adding a common shift cancels exactly in real arithmetic; adding and subtracting ±10000 can lose low bits in binary64. This complete result also contains weighted value products and output vectors. Inspect those saved products and running sums in the output section below.
Weighted values → O
O has shape [1,3,2] and axes B,Query,Dv. For one batch b, query i and value feature f, start the running sum at zero. For each key j in ascending order, multiply P[b,i,j] by V[b,j,f] and immediately add that product to the running sum before moving to the next key. The key axis j is consumed; the value-feature axis f remains. Dk does not set the output width.
This inspector and the probability inspector above have independent view selectors. Both show numbers calculated from the same starting inputs. The saved operation selected in the trace above is also independent: setup. Navigating it highlights matching operations; it does not replace these complete results with a partially computed state.
Output inspector: batch 0, query 0, value feature 0. Saved weighted sum mix_0_0_0 gives O[0,0,0] = . These selectors change the view only.
| Query i | Value feature 0 | Value feature 1 |
|---|---|---|
| Query 0 (selected) | 1 (selected coordinate) | 0 |
| Query 1 | 0.3302384506733431 | 0.6697615493266569 |
| Query 2 | 0.7517449217422769 | 0.7517449217422769 |
Every contribution to O[0,0,0]
The operands, products and running sums below are read from saved step mix_0_0_0; the view does not calculate a second weighted sum. Running sum before key 0 is 0. Every key is shown, including forbidden keys whose exact zero probability still multiplies its actual signed V coordinate.
| Key j | Allowed? | P[b,i,j] | V[b,j,f] | Product P × V | Running before | Running after |
|---|---|---|---|---|---|---|
| 0 | Allowed | 1 | 1 | 1 | 0 (start) | 1 |
| 1 | Forbidden | 0 | 0 | 0 | 1 | 1 |
| 2 | Forbidden | 0 | 1 | 0 | 1 | 1 |
The final running sum is 1. There is no additional division by T or Dv. Probabilities are nonnegative and normalized over allowed keys in real arithmetic; V and O coordinates may be negative. Each real output coordinate lies between the smallest and largest allowed V coordinates, with floating-point rounding in the stored calculation. An allowed probability can underflow to zero; its allowed flag distinguishes that from an exact masked zero.
Inspect tensor shapes and full precision
All computed outputs
- B
- 1
- T
- 3
- Dk
- 2
- Dv
- 2
- q000
- 1
- q001
- 0
- q010
- 0
- q011
- 1
- q020
- 1
- q021
- 1
- k000
- 1
- k001
- 0
- k010
- 0
- k011
- 1
- k020
- 1
- k021
- 1
- v000
- 1
- v001
- 0
- v010
- 0
- v011
- 1
- v020
- 1
- v021
- 1
- raw000
- 1
- score000
- 0.7071067811865475
- raw001
- 0
- score001
- 0
- raw002
- 1
- score002
- 0.7071067811865475
- raw010
- 0
- score010
- 0
- raw011
- 1
- score011
- 0.7071067811865475
- raw012
- 1
- score012
- 0.7071067811865475
- raw020
- 1
- score020
- 0.7071067811865475
- raw021
- 1
- score021
- 0.7071067811865475
- raw022
- 2
- score022
- 1.414213562373095
- p000
- 1
- p001
- 0
- p002
- 0
- p010
- 0.3302384506733431
- p011
- 0.6697615493266569
- p012
- 0
- p020
- 0.2482550782577231
- p021
- 0.2482550782577231
- p022
- 0.5034898434845538
- o000
- 1
- o001
- 0
- o010
- 0.3302384506733431
- o011
- 0.6697615493266569
- o020
- 0.7517449217422769
- o021
- 0.7517449217422769
- setup_B
- 1
- setup_T
- 3
- setup_D
- 2
- setup_Dk
- 2
- setup_Dv
- 2
- project_Q_0_0_0_product0
- 1
- project_Q_0_0_0_product1
- 0
- project_Q_0_0_0_value
- 1
- project_Q_0_0_1_product0
- 0
- project_Q_0_0_1_product1
- 0
- project_Q_0_0_1_value
- 0
- project_Q_0_1_0_product0
- 0
- project_Q_0_1_0_product1
- 0
- project_Q_0_1_0_value
- 0
- project_Q_0_1_1_product0
- 0
- project_Q_0_1_1_product1
- 1
- project_Q_0_1_1_value
- 1
- project_Q_0_2_0_product0
- 1
- project_Q_0_2_0_product1
- 0
- project_Q_0_2_0_value
- 1
- project_Q_0_2_1_product0
- 0
- project_Q_0_2_1_product1
- 1
- project_Q_0_2_1_value
- 1
- project_K_0_0_0_product0
- 1
- project_K_0_0_0_product1
- 0
- project_K_0_0_0_value
- 1
- project_K_0_0_1_product0
- 0
- project_K_0_0_1_product1
- 0
- project_K_0_0_1_value
- 0
- project_K_0_1_0_product0
- 0
- project_K_0_1_0_product1
- 0
- project_K_0_1_0_value
- 0
- project_K_0_1_1_product0
- 0
- project_K_0_1_1_product1
- 1
- project_K_0_1_1_value
- 1
- project_K_0_2_0_product0
- 1
- project_K_0_2_0_product1
- 0
- project_K_0_2_0_value
- 1
- project_K_0_2_1_product0
- 0
- project_K_0_2_1_product1
- 1
- project_K_0_2_1_value
- 1
- project_V_0_0_0_product0
- 1
- project_V_0_0_0_product1
- 0
- project_V_0_0_0_value
- 1
- project_V_0_0_1_product0
- 0
- project_V_0_0_1_product1
- 0
- project_V_0_0_1_value
- 0
- project_V_0_1_0_product0
- 0
- project_V_0_1_0_product1
- 0
- project_V_0_1_0_value
- 0
- project_V_0_1_1_product0
- 0
- project_V_0_1_1_product1
- 1
- project_V_0_1_1_value
- 1
- project_V_0_2_0_product0
- 1
- project_V_0_2_0_product1
- 0
- project_V_0_2_0_value
- 1
- project_V_0_2_1_product0
- 0
- project_V_0_2_1_product1
- 1
- project_V_0_2_1_value
- 1
- score_0_0_0_product0
- 1
- score_0_0_0_product1
- 0
- score_0_0_0_raw
- 1
- score_0_0_0_score
- 0.7071067811865475
- score_0_0_1_product0
- 0
- score_0_0_1_product1
- 0
- score_0_0_1_raw
- 0
- score_0_0_1_score
- 0
- score_0_0_2_product0
- 1
- score_0_0_2_product1
- 0
- score_0_0_2_raw
- 1
- score_0_0_2_score
- 0.7071067811865475
- score_0_1_0_product0
- 0
- score_0_1_0_product1
- 0
- score_0_1_0_raw
- 0
- score_0_1_0_score
- 0
- score_0_1_1_product0
- 0
- score_0_1_1_product1
- 1
- score_0_1_1_raw
- 1
- score_0_1_1_score
- 0.7071067811865475
- score_0_1_2_product0
- 0
- score_0_1_2_product1
- 1
- score_0_1_2_raw
- 1
- score_0_1_2_score
- 0.7071067811865475
- score_0_2_0_product0
- 1
- score_0_2_0_product1
- 0
- score_0_2_0_raw
- 1
- score_0_2_0_score
- 0.7071067811865475
- score_0_2_1_product0
- 0
- score_0_2_1_product1
- 1
- score_0_2_1_raw
- 1
- score_0_2_1_score
- 0.7071067811865475
- score_0_2_2_product0
- 1
- score_0_2_2_product1
- 1
- score_0_2_2_raw
- 2
- score_0_2_2_score
- 1.414213562373095
- row_0_0_max
- 0.7071067811865475
- row_0_0_denominator
- 1
- row_0_0_shifted0
- 0
- row_0_0_term0
- 1
- row_0_0_term1
- 0
- row_0_0_term2
- 0
- row_0_0_p0
- 1
- row_0_0_p1
- 0
- row_0_0_p2
- 0
- row_0_1_max
- 0.7071067811865475
- row_0_1_denominator
- 1.4930686913952398
- row_0_1_shifted0
- -0.7071067811865475
- row_0_1_shifted1
- 0
- row_0_1_term0
- 0.49306869139523984
- row_0_1_term1
- 1
- row_0_1_term2
- 0
- row_0_1_p0
- 0.3302384506733431
- row_0_1_p1
- 0.6697615493266569
- row_0_1_p2
- 0
- row_0_2_max
- 1.414213562373095
- row_0_2_denominator
- 1.9861373827904796
- row_0_2_shifted0
- -0.7071067811865475
- row_0_2_shifted1
- -0.7071067811865475
- row_0_2_shifted2
- 0
- row_0_2_term0
- 0.49306869139523984
- row_0_2_term1
- 0.49306869139523984
- row_0_2_term2
- 1
- row_0_2_p0
- 0.2482550782577231
- row_0_2_p1
- 0.2482550782577231
- row_0_2_p2
- 0.5034898434845538
- mix_0_0_0_product0
- 1
- mix_0_0_0_product1
- 0
- mix_0_0_0_product2
- 0
- mix_0_0_0_running0
- 1
- mix_0_0_0_running1
- 1
- mix_0_0_0_running2
- 1
- mix_0_0_0_value
- 1
- mix_0_0_1_product0
- 0
- mix_0_0_1_product1
- 0
- mix_0_0_1_product2
- 0
- mix_0_0_1_running0
- 0
- mix_0_0_1_running1
- 0
- mix_0_0_1_running2
- 0
- mix_0_0_1_value
- 0
- mix_0_1_0_product0
- 0.3302384506733431
- mix_0_1_0_product1
- 0
- mix_0_1_0_product2
- 0
- mix_0_1_0_running0
- 0.3302384506733431
- mix_0_1_0_running1
- 0.3302384506733431
- mix_0_1_0_running2
- 0.3302384506733431
- mix_0_1_0_value
- 0.3302384506733431
- mix_0_1_1_product0
- 0
- mix_0_1_1_product1
- 0.6697615493266569
- mix_0_1_1_product2
- 0
- mix_0_1_1_running0
- 0
- mix_0_1_1_running1
- 0.6697615493266569
- mix_0_1_1_running2
- 0.6697615493266569
- mix_0_1_1_value
- 0.6697615493266569
- mix_0_2_0_product0
- 0.2482550782577231
- mix_0_2_0_product1
- 0
- mix_0_2_0_product2
- 0.5034898434845538
- mix_0_2_0_running0
- 0.2482550782577231
- mix_0_2_0_running1
- 0.2482550782577231
- mix_0_2_0_running2
- 0.7517449217422769
- mix_0_2_0_value
- 0.7517449217422769
- mix_0_2_1_product0
- 0
- mix_0_2_1_product1
- 0.2482550782577231
- mix_0_2_1_product2
- 0.5034898434845538
- mix_0_2_1_running0
- 0
- mix_0_2_1_running1
- 0.2482550782577231
- mix_0_2_1_running2
- 0.7517449217422769
- mix_0_2_1_value
- 0.7517449217422769
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 input token rows, selected without padding or broadcasting.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
WQ
D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk query columns of the editable WQ.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
WK
D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk key columns of the editable WK.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
WV
D=2 × Dv=2 · float64 · display precision 8 · Both input rows; leading Dv value columns of the editable WV.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
Q
B=1 × T=3 × Dk=2 · float64 · display precision 8 · Q=XWQ, with each coordinate traced as two products and one sum.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
K
B=1 × T=3 × Dk=2 · float64 · display precision 8 · K=XWK, with each coordinate traced as two products and one sum.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
V
B=1 × T=3 × Dv=2 · float64 · display precision 8 · V=XWV, available for later value mixing; not mixed in IV-22–24.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
raw
B=1 × Query=3 × Key=3 · float64 · display precision 8 · QK transpose: explicit feature products followed by their sum, within each batch.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 2 |
scores
B=1 × Query=3 × Key=3 · float64 · display precision 8 · Raw query-key agreement divided by sqrt(Dk); not softmax probabilities.
| Storage index | Value |
|---|---|
| 0 | 0.7071067811865475 |
| 1 | 0 |
| 2 | 0.7071067811865475 |
| 3 | 0 |
| 4 | 0.7071067811865475 |
| 5 | 0.7071067811865475 |
| 6 | 0.7071067811865475 |
| 7 | 0.7071067811865475 |
| 8 | 1.414213562373095 |
allowed
B=1 × Query=3 × Key=3 · bool · display precision 8 · True means this key may contribute to this query; key validity is shared across batches.
| Storage index | Value |
|---|---|
| 0 | true |
| 1 | false |
| 2 | false |
| 3 | true |
| 4 | true |
| 5 | false |
| 6 | true |
| 7 | true |
| 8 | true |
logits
B=1 × Query=3 × Key=3 · float64 · display precision 8 · Finite score+common shift for every active key, including forbidden keys; no mask sentinel.
| Storage index | Value |
|---|---|
| 0 | 0.7071067811865475 |
| 1 | 0 |
| 2 | 0.7071067811865475 |
| 3 | 0 |
| 4 | 0.7071067811865475 |
| 5 | 0.7071067811865475 |
| 6 | 0.7071067811865475 |
| 7 | 0.7071067811865475 |
| 8 | 1.414213562373095 |
probabilities
B=1 × Query=3 × Key=3 · float64 · display precision 8 · Allowed-key stable softmax along the key axis only. Forbidden keys have exactly zero; allowed exponential underflow is separately possible.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0.3302384506733431 |
| 4 | 0.6697615493266569 |
| 5 | 0 |
| 6 | 0.2482550782577231 |
| 7 | 0.2482550782577231 |
| 8 | 0.5034898434845538 |
O
B=1 × Query=3 × Dv=2 · float64 · display precision 8 · O=PV: one weighted sum over keys per query and value feature, with every product and sequential running sum recorded.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0.3302384506733431 |
| 3 | 0.6697615493266569 |
| 4 | 0.7517449217422769 |
| 5 | 0.7517449217422769 |
Reset is the complete causal reference: identity Q/K/V projections, X=[[1,0],[0,1],[1,1]], B=1, T=3 and Dk=Dv=2. Write a=1/sqrt(2), r=exp(a). The output rows are (1,0), (1/(1+r),r/(1+r)), and ((1+r)/(2+r),(1+r)/(2+r)). These are exact real expressions; the tables expose the stored binary64 calculation.
Select any output batch, query and value feature. Read its p and V operands, product for every key, and running sum from zero. Follow the separate saved trace from projections through scores, mask, maximum subtraction, exponentials, denominator, probabilities and the weighted output. All 33 controls recompute the whole dependency chain and reset the graded answers and trace selection after a valid edit.
Load the nonsymmetric example to expose orientation errors and negative value coordinates. With the causal default mask, its query 1 output is ((r+2)/(r+1),−r/(r+1)); query 2 is ((r²+2+3r³)/(1+r²+r³),−(r²+r³)/(1+r²+r³)). The example button keeps the current mask and shift, so restore them for these particular expressions.
Try B=2, Dk=1 with Dv=2, Dv=1 with Dk=2, and T=1. At T=1 the only allowed probability is 1, so O equals V at position 0; a mask forbidding that sole key instead makes the result unavailable. Repeated token rows can produce equal projections; zeros can produce uniform allowed weights; neither implies a learned semantic relationship. Change WV alone to inspect unchanged Q/K/P with potentially changed signed O. Large common shifts preserve real ratios but may change 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 selects a causal mask, identity weights and three rows. Inspect output O, then select an output batch, query and feature to reveal its probability–value products and running sums. The probability inspector has its own batch/query selection; match the labels when comparing them. Both views read the same complete numerical result. Trace navigation independently selects a saved operation, rather than changing which input produced the full results.
Try changing only WV first. The probabilities stay fixed, while values and their mixture can change. Reset before following the hand trace. An input edit recomputes the chain and clears previous exercise answers; a view selection merely changes what you inspect.
What is being combined?
A token is an item at a sequence position; this lesson starts with its supplied numerical representation, an embedding. A tensor is an array with named axes. B counts independent sequences, T positions, D=2 input features, Dk query/key features and Dv value features. Zero-based indices b, i, j and f select a batch, query position, key position and value feature respectively.
| Quantity | Shape | Meaning of axes |
|---|---|---|
| X | [B,T,2] | batch, position, input feature |
| WQ, WK | [2,Dk] | input feature, query/key feature |
| WV | [2,Dv] | input feature, value feature |
| Q, K | [B,T,Dk] | batch, position, comparison feature |
| V | [B,T,Dv] | batch, key position, value feature |
| raw, scores, allowed, logits, P | [B,T,T] | batch, query, key |
| O | [B,T,Dv] | batch, query, value feature |
A query Q is the asking side of a comparison; a key K is its candidate side. V supplies the coordinates to mix. These are computational roles, not English questions or semantic labels. P holds normalized nonnegative weights over keys; O holds weighted value coordinates, which may be negative and need not sum to one. Some texts name the probability matrix A: their AV is our PV.
For each batch, matrix multiplication has matching inner dimensions: P is [T,T], V is [T,Dv], so O is [T,Dv]. The repeated dimension is Key. There is no sum over batches or value features:
The summation sign means add one contribution for each key j. Start each coordinate’s running sum at zero. For each key, compute its product, add it immediately to the running sum, then move to the next key. A forbidden key still has an actual product . Do not divide by T or Dv afterward: P already supplies normalized weights.
Stage 1: project every input row
At reset B=1, T=3, Dk=Dv=2 and
Here is the two-feature identity matrix. A projection here is a linear map, with no bias or activation. For each of Q, K and V, both feature products and their sum are:
| Position | Feature 0 | Feature 1 |
|---|---|---|
| 0 | 1·1+0·0=1+0=1 | 1·0+0·1=0+0=0 |
| 1 | 0·1+1·0=0+0=0 | 0·0+1·1=0+1=1 |
| 2 | 1·1+1·0=1+0=1 | 1·0+1·1=0+1=1 |
Thus Q=K=V=X. In general they differ. For example, : the input row multiplies a weight column. The equivalent column-vector equation uses transposed weights. Identity matrices hide that orientation distinction.
Stage 2: compare, then scale
A dot product multiplies matching features and adds. The superscript in means transpose, exchanging K’s position and feature axes within each batch. Every reset raw score is:
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 1·1+0·0=1 | 1·0+0·1=0 | 1·1+0·1=1 |
| 1 | 0·1+1·0=0 | 0·0+1·1=1 | 0·1+1·1=1 |
| 2 | 1·1+1·0=1 | 1·0+1·1=1 | 1·1+1·1=2 |
Divide each raw score by , the positive square root of the comparison width. Write . The score rows become , and . Scaling uses Dk, not T or Dv. It moderates dot-product magnitude; these signed scores are still not probabilities.
Stage 3: mask and normalize every row
A causal mask permits key j only when , so allowed rows are 100, 110 and 111. A one means permitted. A logit is an input to softmax; here it equals score plus the common shift, which is zero at reset.
Write for key j’s logit. For each row choose the maximum m over allowed logits. For an allowed key form , where ; for a forbidden key set . Sum the terms in key order to get d, then divide: . Let , so .
| Query | Allowed subtractions | All terms | Denominator | All divisions, simplified |
|---|---|---|---|---|
| 0 | a−a=0 | |||
| 1 | ||||
| 2 |
Subtracting m cancels a common exponential factor from numerator and denominator without changing real ratios. All allowed differences are nonpositive; at least one term is , so d is positive. Forbidden keys have no shifted-logit operation. Their exact zero probabilities come from the mask rule.
Stage 4: calculate all six output coordinates
Keep b=0 implicit. Each row below lists products for keys 0, 1 and 2, alongside all three running sums starting from zero. The code interleaves each product with its immediate addition before moving to the next key. Values are , and .
| Output | Products in key order | Running sums after keys 0, 1, 2 |
|---|---|---|
Therefore the output rows are
These are exact real expressions, not measured decimals or a promise of identical floating-point rounding. Query two’s output coordinates happen to match; its probability row has three entries and is a different object. Each output coordinate combines the corresponding feature from every key, rather than combining different features from one value.
Recompute after removing a key
Keep reset inputs, choose causal + padding and set valid2=0. Query two now allows only keys zero and one. Their scores are both a: maximum a, subtractions , terms and denominator . Thus P becomes .
Feature zero forms , then ; next , then ; finally , then . Feature one forms , then ; next , then ; finally , then . O becomes . The last query survives; only its key permission changed.
Signed values expose a second misconception
Load the nonsymmetric example after reset. It uses
The projections are Q rows , K rows and V rows . For example V’s last row is . Raw scores are rows .
Under the causal mask, query zero returns . Query one’s probabilities are . Its first coordinate adds ; its second adds .
For query two, let . Probabilities are . The two sums are and . They give . A negative output is legitimate: nonnegative probabilities multiply signed values.
In real arithmetic each coordinate lies between the smallest and largest allowed value coordinate, because its nonnegative weights sum to one. This convex combination property does not make O a probability vector. No extra softmax or absolute value belongs on O.
Read the exact programs and their records
The chapter program composes the stages:
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.
"""IV25: the complete single-head causal self-attention numerical trace.
X -> Q,K,V -> QK transpose -> scale -> mask -> stable softmax -> O=PV.
All 33 stored scalar inputs are validated, including inactive slots.
With a=1/sqrt(2), r=exp(a), the default causal output rows are
(1,0), (1/(1+r),r/(1+r)), ((1+r)/(2+r),(1+r)/(2+r)).
These are real-arithmetic identities, not exact binary64 serializations.
Keep attention_reference.py and value_reference.py beside this program.
"""
from types import MappingProxyType
from attention_reference import ATTENTION_DEFAULTS, attention_trace, guarded, normalize, project, run, score, validated_state
from value_reference import mix_values
DEFAULT_IV25 = MappingProxyType(dict(ATTENTION_DEFAULTS))
@guarded
def derive_iv25(state):
"""Recompute the full chain; return no partial record for an invalid row."""
s = validated_state(state, attention=True)
trace = attention_trace()
# Each stage consumes the real arrays produced by its predecessor.
projection = project(s, trace)
scored = score(s, projection, trace)
normalized = normalize(s, scored, trace)
mixed = mix_values(s, projection, normalized, trace)
# Aliases precede ALL flattened trace outputs, including the new mix steps.
summary = dict(B=s["B"], T=s["T"], Dk=s["Dk"], Dv=s["Dv"])
summary.update(projection["aliases"])
summary.update(scored["aliases"])
summary.update(normalized["aliases"])
summary.update(mixed["aliases"])
return trace.result(summary, [*projection["tensors"], *scored["tensors"],
*normalized["tensors"], *mixed["tensors"]])
if __name__ == "__main__":
run(derive_iv25, DEFAULT_IV25)
The original helper supplies validation, projections, scores and normalization:
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Shared IV22–24 source: strict states, explicit scalar loops, NumPy storage.
X uses row features: Q[b,t,f] = X[b,t,0]*WQ[0,f] + X[b,t,1]*WQ[1,f].
This is the transpose convention of a single column-vector map. No matmul,
BLAS reduction, broadcasting, learned parameters or value mixing is hidden here.
Keep this helper beside the lesson programs. Authored, never executed under hold.
"""
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 actual numeric scalars, never booleans or numeric strings.
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
PROJECTION_DEFAULTS = MappingProxyType(dict(
B=1, T=3, Dk=2, Dv=2,
x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
wq00=1, wq01=0, wq10=0, wq11=1,
wk00=1, wk01=0, wk10=0, wk11=1,
wv00=1, wv01=0, wv10=0, wv11=1,
))
ATTENTION_DEFAULTS = MappingProxyType(dict(
**PROJECTION_DEFAULTS, mode=1, valid0=1, valid1=1, valid2=1, shift=0,
))
def validated_state(state, attention=False):
defaults = ATTENTION_DEFAULTS if attention else PROJECTION_DEFAULTS
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
if set(state) != set(defaults):
raise NumericalFault("INVALID_INPUT", "Provide every named scalar field and no extra fields, including inactive slots.")
integer_bounds = dict(B=(1, 2), T=(1, 3), Dk=(1, 2), Dv=(1, 2),
mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
result = {}
# Defaults determine record order, regardless of the incoming object's order.
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 AttentionTrace:
def __init__(self):
self.outputs = {}
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, values):
inputs, values = numbers(inputs), numbers(values)
self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
self.steps.append({"id": identifier, "label": label, "equation": equation,
"explanation": explanation, "inputs": inputs, "outputs": values})
def result(self, summary, tensors):
return {"status": "defined", "outputs": numbers({**summary, **self.outputs}),
"steps": self.steps, "tensors": tensors}
def attention_trace():
return AttentionTrace()
def tensor(identifier, shape, axes, values, provenance):
array = np.asarray(values, dtype=np.float64)
if array.size != math.prod(shape) or len(shape) != len(axes) or len(set(axes)) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
# Flatten into detached Python scalars; no record retains a view of an array.
flat = [finite(value, identifier) for value in array.reshape(-1)]
return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
"values": flat, "provenance": provenance, "precision": 8}
def project(s, trace):
"""Build real arrays, then trace Q, K, V in that order, each b,t,f."""
B, T, Dk, Dv = s["B"], s["T"], s["Dk"], s["Dv"]
# D stays 2; smaller Dk/Dv select leading weight COLUMNS, never input rows.
X = np.empty((B, T, 2), dtype=np.float64)
WQ = np.empty((2, Dk), dtype=np.float64)
WK = np.empty((2, Dk), dtype=np.float64)
WV = np.empty((2, Dv), 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}"]
for weights, prefix, width in ((WQ, "wq", Dk), (WK, "wk", Dk), (WV, "wv", Dv)):
for d in range(2):
for f in range(width):
weights[d, f] = s[f"{prefix}{d}{f}"]
Q = np.empty((B, T, Dk), dtype=np.float64)
K = np.empty((B, T, Dk), dtype=np.float64)
V = np.empty((B, T, Dv), dtype=np.float64)
trace.add("setup", "Validate all scalar inputs and select active dimensions", "D=2; X[B,T,D]; WQ,WK[D,Dk]; WV[D,Dv]",
"All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.",
s, dict(B=B, T=T, D=2, Dk=Dk, Dv=Dv))
aliases = {}
for name, weights, output, width in (("Q", WQ, Q, Dk), ("K", WK, K, Dk), ("V", WV, V, Dv)):
for b in range(B):
for t in range(T):
for f in range(width):
x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
w0, w1 = float(weights[0, f]), float(weights[1, f])
product0 = finite(x0 * w0, "projection product0")
product1 = finite(x1 * w1, "projection product1")
value = finite(product0 + product1, "projection value")
output[b, t, f] = value
aliases[f"{name.lower()}{b}{t}{f}"] = value
trace.add(f"project_{name}_{b}_{t}_{f}", f"{name}[{b},{t},{f}]: two input-feature contributions",
"product0=x0*w0; product1=x1*w1; value=product0+product1",
"One token row times one weight column. Both products are computed separately, then added; no bias, activation or training is hidden.",
dict(b=b, t=t, f=f, x0=x0, x1=x1, w0=w0, w1=w1),
dict(product0=product0, product1=product1, value=value))
tensors = [
tensor("X", [B, T, 2], ["B", "T", "D"], X, "Active input token rows, selected without padding or broadcasting."),
tensor("WQ", [2, Dk], ["D", "Dk"], WQ, "Both input rows; leading Dk query columns of the editable WQ."),
tensor("WK", [2, Dk], ["D", "Dk"], WK, "Both input rows; leading Dk key columns of the editable WK."),
tensor("WV", [2, Dv], ["D", "Dv"], WV, "Both input rows; leading Dv value columns of the editable WV."),
tensor("Q", [B, T, Dk], ["B", "T", "Dk"], Q, "Q=XWQ, with each coordinate traced as two products and one sum."),
tensor("K", [B, T, Dk], ["B", "T", "Dk"], K, "K=XWK, with each coordinate traced as two products and one sum."),
tensor("V", [B, T, Dv], ["B", "T", "Dv"], V, "V=XWV, available for later value mixing; not mixed in IV-22–24."),
]
return dict(X=X, WQ=WQ, WK=WK, WV=WV, Q=Q, K=K, V=V, aliases=aliases, tensors=tensors)
def score(s, projection, trace):
"""Compute one feature product at a time; scaling is not normalization."""
B, T, Dk = s["B"], s["T"], s["Dk"]
Q, K = projection["Q"], projection["K"]
raw = np.empty((B, T, T), dtype=np.float64)
scores = np.empty((B, T, T), dtype=np.float64)
divisor = finite(math.sqrt(Dk), "score divisor")
aliases = {}
for b in range(B):
for i in range(T):
for j in range(T):
q0, k0 = float(Q[b, i, 0]), float(K[b, j, 0])
inputs = dict(b=b, i=i, j=j, Dk=Dk, divisor=divisor, q0=q0, k0=k0)
product0 = finite(q0 * k0, "score product0")
values = dict(product0=product0)
dot = product0
if Dk == 2:
q1, k1 = float(Q[b, i, 1]), float(K[b, 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, i, j], scores[b, i, j] = dot, scaled
values.update(raw=dot, score=scaled)
aliases[f"raw{b}{i}{j}"] = dot
aliases[f"score{b}{i}{j}"] = scaled
trace.add(f"score_{b}_{i}_{j}", f"Batch {b}: 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)",
"Compare matching query/key features in the same batch. The divisor uses key-feature width Dk, not time length T or value width Dv. A signed score is not a probability.",
inputs, values)
tensors = [tensor("raw", [B, T, T], ["B", "Query", "Key"], raw, "QK transpose: explicit feature products followed by their sum, within each batch."),
tensor("scores", [B, T, T], ["B", "Query", "Key"], scores, "Raw query-key agreement divided by sqrt(Dk); not softmax probabilities.")]
return dict(raw=raw, scores=scores, aliases=aliases, tensors=tensors)
def stable_softmax(logits, allowed):
"""Scalar counterpart of platform stableSoftmax; reject an empty support."""
if len(logits) != len(allowed) or not 1 <= len(logits) <= 64:
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 = []
denominator = 0.0
for j in range(len(logits)):
# An allowed exp can underflow to 0; the boolean mask still says allowed.
term = math.exp(finite(logits[j] - maximum, "shifted logit")) if allowed[j] else 0.0
terms.append(finite(term, "softmax term"))
denominator = finite(denominator + term, "softmax denominator")
probabilities = []
for term in terms:
probabilities.append(finite(term / denominator, "softmax probability"))
return dict(max=maximum, terms=terms, denominator=denominator, probabilities=probabilities)
def normalize(s, scored, trace):
"""Retain every query; mask keys, then normalize along each row's key axis."""
B, T = s["B"], s["T"]
# Keep real finite logits for forbidden keys too; never invent -infinity.
allowed = np.empty((B, T, T), dtype=np.bool_)
logits = np.empty((B, T, T), dtype=np.float64)
probabilities = np.empty((B, T, T), dtype=np.float64)
aliases = {}
causal = s["mode"] in (1, 3)
padding = s["mode"] in (2, 3)
for b in range(B):
for i in range(T):
row_logits, row_allowed = [], []
inputs = dict(b=b, i=i, mode=s["mode"], shift=s["shift"])
for j in range(T):
value = float(scored["scores"][b, i, j])
inputs[f"score{j}"] = value
permit = (not causal or j <= i) and (not padding or s[f"valid{j}"] == 1)
allowed[b, i, j] = permit
logit = finite(value + s["shift"], "shifted score")
logits[b, 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}, query {i} has no allowed keys; no probability distribution exists.")
row = stable_softmax(row_logits, row_allowed)
values = dict(max=row["max"], denominator=row["denominator"])
# These are the actual shifted operands passed to exp; forbidden keys
# have no shifted operand and therefore no fabricated shifted field.
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):
probability = row["probabilities"][j]
values[f"p{j}"] = probability
probabilities[b, i, j] = probability
aliases[f"p{b}{i}{j}"] = probability
trace.add(f"row_{b}_{i}", f"Batch {b}: masked key-axis 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",
"Keys alone are masked; every query remains. Terms sum in increasing key order. Forbidden keys have exact zero probability; allowed terms can also underflow to zero in binary64. The common shift preserves real softmax but can change rounded results.",
inputs, values)
allowed_record = tensor("allowed", [B, T, T], ["B", "Query", "Key"], allowed.astype(np.float64),
"True means this key may contribute to this query; key validity is shared across batches.")
# Validate 0/1 storage through tensor first, then expose actual JSON booleans.
allowed_record["values"] = [bool(value) for value in allowed_record["values"]]
allowed_record["dtype"] = "bool"
tensors = [allowed_record,
tensor("logits", [B, T, T], ["B", "Query", "Key"], logits, "Finite score+common shift for every active key, including forbidden keys; no mask sentinel."),
tensor("probabilities", [B, T, T], ["B", "Query", "Key"], probabilities,
"Allowed-key stable softmax along the key axis only. Forbidden keys have exactly zero; allowed exponential underflow is separately possible.")]
return dict(allowed=allowed, logits=logits, probabilities=probabilities, aliases=aliases, tensors=tensors)
_JSON_INT = int
def run(derive, defaults):
"""No argument: defaults. A JSON object fully replaces them; '-' 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 = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
The value helper performs the final products and sequential sums:
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.
"""IV25–26 weighted values: real NumPy storage, Python-float scalar loops.
The shared attention helper owns validation, projections, scores and softmax.
This continuation contracts only the key axis: O[b,i,f]=sum_j P[b,i,j]*V[b,j,f].
The signed value coordinates are not probabilities. No extra average is taken.
"""
import numpy as np
from attention_reference import finite, tensor
def mix_values(s, projection, normalized, trace):
"""Append every actual product, running sum and output in b,i,f order."""
B, T, Dv = s["B"], s["T"], s["Dv"]
probabilities, V = normalized["probabilities"], projection["V"]
O = np.empty((B, T, Dv), dtype=np.float64)
aliases = {}
for b in range(B):
for i in range(T):
for f in range(Dv):
inputs = dict(b=b, i=i, f=f)
products, running = {}, {}
value = 0.0
for j in range(T):
p = float(probabilities[b, i, j])
v = float(V[b, j, f])
inputs[f"p{j}"] = p
inputs[f"v{j}"] = v
# Masked probabilities still take the actual 0*V path.
product = finite(p * v, f"O[{b},{i},{f}] key {j} product")
products[f"product{j}"] = product
value = finite(value + product, f"O[{b},{i},{f}] running sum through key {j}")
running[f"running{j}"] = value
O[b, i, f] = value
aliases[f"o{b}{i}{f}"] = value
trace.add(f"mix_{b}_{i}_{f}", f"O[{b},{i},{f}]: weighted value coordinate",
"product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
"Use the saved probability row and the same value feature across all keys in this batch. Each product is computed before its running sum in ascending key order, including actual 0 times V for forbidden keys. There is no extra division by T or Dv. Value coordinates and the output may be signed.",
inputs, {**products, **running, "value": value})
tensors = [tensor("O", [B, T, Dv], ["B", "Query", "Dv"], O,
"O=PV: one weighted sum over keys per query and value feature, with every product and sequential running sum recorded.")]
return dict(O=O, aliases=aliases, tensors=tensors)
Follow project_Q_b_t_f, score_b_i_j and row_b_i into mix_b_i_f. In the mix step, p0,v0 through the last key are operands; product0 onward are products, running0 onward are sums, and value is the final coordinate. Alias o000 means O[0,0,0]. O is the last tensor, with axes B,Query,Dv. The loops preserve separate batches and explicit arithmetic order; displayed source is the actual implementation, not a second formula engine.
Boundaries worth exploring
Set Dk=1 and Dv=2: comparison uses one feature and divisor one, but outputs still have two coordinates. Dv=1 keeps the first WV output column and both input features. B=2 adds an independent sequence; T=1 with its key allowed gives P=1 and O=V at that position. Repeated keys can share probabilities, while repeated value coordinates can make different distributions produce the same output. Zero values can hide a genuine probability change.
Padding flags declare key validity; zero input vectors do not declare padding. A fully masked query makes the entire result unavailable with FULLY_MASKED_ROW. Stable softmax avoids large positive exponentials but cannot preserve arbitrarily tiny positive tails in binary64, the stored double-precision number format. Read allowed flags to distinguish forbidden zero from underflow zero. A common shift cancels in real ratios; large stored additions can round away differences. Inputs and weights are finite and bounded, including inactive slots. Nothing here establishes that a heatmap explains a trained model’s reasoning.
Five exercises matched to the lab
- What does one output coordinate O[b,i,f] combine? The same value feature f across keys, weighted by this query’s probabilities. Keep b, i and f fixed; form P[b,i,j] times V[b,j,f] for each key j and immediately add to the running sum. The query/key feature sum happened earlier in scoring. There is no extra division by T or Dv.
- With B=1, T=3, Dk=2 and Dv=1, what is the complete output shape?
[1,3,1]. P has shape[1,3,3]and V[1,3,1]; their matching key axis is summed, leaving batch, query and value feature.[1,3,2]confuses Dk with Dv;[1,3,3]describes the probability tensor. Both input-feature rows still participate when projecting to one value feature. - For the current starting inputs, batch 0, query 0, value feature 0 has saved products shown in the lab. Starting at 0, what is its final weighted sum? Read
mix_0_0_0: eachproductjis added to the preceding running sum in ascending j, and its finalvalueis O[0,0,0], aliaso000. Reset gives((0+1·1)+0·0)+0·1=1. After edits use the current products andrunningjfields, not the reset answer. The question fixes these coordinates independently of view selectors. - Keep X, WQ, WK, dimensions, mask and shift fixed, and edit only WV. Which dependency claim is correct? V and O may change; Q, K, scores and P stay unchanged. WV supplies only V, which the unchanged P then mixes. An inactive-feature edit, zero operand or cancellation can leave an output unchanged, so “every output must change” is incorrect.
- Counterexample: two allowed V coordinates are −2 and 4, with probabilities 3/4 and 1/4. What is the output coordinate? It is , a valid signed weighted sum. First product , first running sum ; second product , final sum . This lies between −2 and 4. The weights are probabilities; output values need not be. Dividing again would incorrectly give −1/4.
Recap and bridge
Projections produce three roles; dot products and scaling produce scores; allowed-key softmax produces P; explicit weighted sums produce O. Follow each product and its immediate running-sum update. Probabilities are normalized over keys, while value outputs may be signed. Next, IV-26 — Causal, Bidirectional and Padding Attention holds projections fixed and changes which keys may contribute, then recomputes the complete outputs.