The neural notebook
← All chapters

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.

Review the ideas this chapter uses

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

Compute it yourself

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
B1
T3
Dk2
Dv2

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.

X batch 0; stored values without display rounding
TokenInput feature D 0Input feature D 1
010
101
211

WQ shared weights

D=2 × Dk=2 · float64. Rows: Input feature D; columns: Query feature Dk.

WQ shared weights; stored values without display rounding
Input feature DQuery feature Dk 0Query feature Dk 1
010
101

WK shared weights

D=2 × Dk=2 · float64. Rows: Input feature D; columns: Key feature Dk.

WK shared weights; stored values without display rounding
Input feature DKey feature Dk 0Key feature Dk 1
010
101

WV shared weights

D=2 × Dv=2 · float64. Rows: Input feature D; columns: Value feature Dv.

WV shared weights; stored values without display rounding
Input feature DValue feature Dv 0Value feature Dv 1
010
101

Q batch 0

B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Query feature Dk.

Q batch 0; stored values without display rounding
TokenQuery feature Dk 0Query feature Dk 1
010
101
211

K batch 0

B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Key feature Dk.

K batch 0; stored values without display rounding
TokenKey feature Dk 0Key feature Dk 1
010
101
211

V batch 0

B=1 × T=3 × Dv=2 · float64. Rows: Token; columns: Value feature Dv.

V batch 0; stored values without display rounding
TokenValue feature Dv 0Value feature Dv 1
010
101
211

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.

Q, then K, then V; actual operands, products and sums in batch 0
Coordinatex0w0x0 × w0x1w1x1 × w1Sum
Q,0,0,01110001
Q,0,0,11000100
Q,0,1,00101000
Q,0,1,10001111
Q,0,2,01111001
Q,0,2,11001111
K,0,0,01110001
K,0,0,11000100
K,0,1,00101000
K,0,1,10001111
K,0,2,01111001
K,0,2,11001111
V,0,0,01110001
V,0,0,11000100
V,0,1,00101000
V,0,1,10001111
V,0,2,01111001
V,0,2,11001111

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.

raw batch 0; stored values without display rounding
QueryKey 0Key 1Key 2
0101
1011
2112

scores batch 0

B=1 × Query=3 × Key=3 · float64. Rows: Query; columns: Key.

scores batch 0; stored values without display rounding
QueryKey 0Key 1Key 2
00.707106781186547500.7071067811865475
100.70710678118654750.7071067811865475
20.70710678118654750.70710678118654751.414213562373095
Actual feature contributions for batch 0, query 0, across all keys
Key jq0k0q0 × k0q1k1q1 × k1Raw sumsqrt(Dk)Scaled score
011100011.41421356237309510.7071067811865475
110001001.41421356237309510
211101011.41421356237309510.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.

Probabilities by query and key, batch 0. Tint increases with actual p from 0 to 1; text supplies the same information. Forbidden keys have exact zero.
Query / keyKey 0Key 1Key 2
Query 0 (selected)Allowed: p=1Forbidden: p=0Forbidden: p=0
Query 1Allowed: p=0.3302384506733431Allowed: p=0.6697615493266569Forbidden: p=0
Query 2Allowed: p=0.2482550782577231Allowed: p=0.2482550782577231Allowed: p=0.5034898434845538

Softmax arithmetic for batch 0, query 0

Common shift = 0. Maximum over allowed logits = 0.7071067811865475. Denominator = 1 + 0 + 0 = 1.

Only allowed logits are subtracted from the maximum and exponentiated. Denominator sums terms in ascending key order.
Key jAllowed?ScoreLogit = score + shiftLogit − allowed maxExponential termTerm / denominator = p
0true0.70710678118654750.7071067811865475 + 0 = 0.70710678118654750.7071067811865475 − 0.7071067811865475 = 0exp(0) = 11 / 1 = 1
1false00 + 0 = 0Forbidden: no subtractionForbidden: term=0, no exponential0 / 1 = 0
2false0.70710678118654750.7071067811865475 + 0 = 0.7071067811865475Forbidden: no subtractionForbidden: term=0, no exponential0 / 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] = 1. These selectors change the view only.

Complete output O for batch 0; rows are queries, columns are value features. Stored values without display rounding.
Query iValue feature 0Value feature 1
Query 0 (selected)1 (selected coordinate)0
Query 10.33023845067334310.6697615493266569
Query 20.75174492174227690.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.

mix_0_0_0: ascending keys, each stored product followed by its sequential running sum
Key jAllowed?P[b,i,j]V[b,j,f]Product P × VRunning beforeRunning after
0Allowed1110 (start)1
1Forbidden00011
2Forbidden01011

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 indexValue
01
10
20
31
41
51

WQ

D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk query columns of the editable WQ.

Storage indexValue
01
10
20
31

WK

D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk key columns of the editable WK.

Storage indexValue
01
10
20
31

WV

D=2 × Dv=2 · float64 · display precision 8 · Both input rows; leading Dv value columns of the editable WV.

Storage indexValue
01
10
20
31

Q

B=1 × T=3 × Dk=2 · float64 · display precision 8 · Q=XWQ, with each coordinate traced as two products and one sum.

Storage indexValue
01
10
20
31
41
51

K

B=1 × T=3 × Dk=2 · float64 · display precision 8 · K=XWK, with each coordinate traced as two products and one sum.

Storage indexValue
01
10
20
31
41
51

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 indexValue
01
10
20
31
41
51

raw

B=1 × Query=3 × Key=3 · float64 · display precision 8 · QK transpose: explicit feature products followed by their sum, within each batch.

Storage indexValue
01
10
21
30
41
51
61
71
82

scores

B=1 × Query=3 × Key=3 · float64 · display precision 8 · Raw query-key agreement divided by sqrt(Dk); not softmax probabilities.

Storage indexValue
00.7071067811865475
10
20.7071067811865475
30
40.7071067811865475
50.7071067811865475
60.7071067811865475
70.7071067811865475
81.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 indexValue
0true
1false
2false
3true
4true
5false
6true
7true
8true

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 indexValue
00.7071067811865475
10
20.7071067811865475
30
40.7071067811865475
50.7071067811865475
60.7071067811865475
70.7071067811865475
81.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 indexValue
01
10
20
30.3302384506733431
40.6697615493266569
50
60.2482550782577231
70.2482550782577231
80.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 indexValue
01
10
20.3302384506733431
30.6697615493266569
40.7517449217422769
50.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.

1. What does one output coordinate O[b,i,f] combine?
2. With B=1, T=3, Dk=2 and Dv=1, what is the complete output shape?
3. For the current starting inputs, batch 0, query 0, value feature 0 has saved products [1, 0, 0]. Starting at 0, what is its final weighted sum?
4. Keep X, WQ, WK, dimensions, mask and shift fixed, and edit only WV. Which dependency claim is correct?
5. Counterexample: two allowed V coordinates are −2 and 4, with probabilities 3/4 and 1/4. What is the output coordinate?

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.

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

O[b,i,f]=∑j=0T−1P[b,i,j]V[b,j,f].O[b,i,f]=\sum_{j=0}^{T-1}P[b,i,j]V[b,j,f].

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 0⋅V[b,j,f]=00\cdot V[b,j,f]=0. 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

X=[100111],WQ=WK=WV=I2.X=\begin{bmatrix}1&0\\0&1\\1&1\end{bmatrix},\qquad W_Q=W_K=W_V=I_2.

Here I2I_2 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:

PositionFeature 0Feature 1
01·1+0·0=1+0=11·0+0·1=0+0=0
10·1+1·0=0+0=00·0+1·1=0+1=1
21·1+1·0=1+0=11·0+1·1=0+1=1

Thus Q=K=V=X. In general they differ. For example, Q[b,i,f]=X[b,i,0]WQ[0,f]+X[b,i,1]WQ[1,f]Q[b,i,f]=X[b,i,0]W_Q[0,f]+X[b,i,1]W_Q[1,f]: 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 QKTQK^{\mathsf T} means transpose, exchanging K’s position and feature axes within each batch. Every reset raw score is:

QueryKey 0Key 1Key 2
01·1+0·0=11·0+0·1=01·1+0·1=1
10·1+1·0=00·0+1·1=10·1+1·1=1
21·1+1·0=11·0+1·1=11·1+1·1=2

Divide each raw score by Dk=2\sqrt{Dk}=\sqrt2, the positive square root of the comparison width. Write a=1/2a=1/\sqrt2. The score rows become (a,0,a)(a,0,a), (0,a,a)(0,a,a) and (a,a,2a)(a,a,2a). 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 j≤ij\leq i, 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 ℓj\ell_j for key j’s logit. For each row choose the maximum m over allowed logits. For an allowed key form uj=exp⁡(ℓj−m)u_j=\exp(\ell_j-m), where exp⁡(z)=ez\exp(z)=e^z; for a forbidden key set uj=0u_j=0. Sum the terms in key order to get d, then divide: pj=uj/dp_j=u_j/d. Let r=exp⁡(a)r=\exp(a), so exp⁡(−a)=1/r\exp(-a)=1/r.

QueryAllowed subtractionsAll termsDenominatorAll divisions, simplified
0a−a=0(1,0,0)(1,0,0)((0+1)+0)+0=1((0+1)+0)+0=1(1/1,0/1,0/1)=(1,0,0)(1/1,0/1,0/1)=(1,0,0)
10−a=−a, a−a=00-a=-a,\ a-a=0(1/r,1,0)(1/r,1,0)((0+1/r)+1)+0=(1+r)/r((0+1/r)+1)+0=(1+r)/r(1/(1+r),r/(1+r),0)(1/(1+r),r/(1+r),0)
2a−2a=−a, a−2a=−a, 2a−2a=0a-2a=-a,\ a-2a=-a,\ 2a-2a=0(1/r,1/r,1)(1/r,1/r,1)((0+1/r)+1/r)+1=(2+r)/r((0+1/r)+1/r)+1=(2+r)/r(1/(2+r),1/(2+r),r/(2+r))(1/(2+r),1/(2+r),r/(2+r))

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 exp⁡(0)=1\exp(0)=1, 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 V0=(1,0)V_0=(1,0), V1=(0,1)V_1=(0,1) and V2=(1,1)V_2=(1,1).

OutputProducts in key orderRunning sums after keys 0, 1, 2
O[0,0,0]O[0,0,0]1⋅1=1, 0⋅0=0, 0⋅1=01\cdot1=1,\ 0\cdot0=0,\ 0\cdot1=00+1=1; 1+0=1; 1+0=10+1=1;\ 1+0=1;\ 1+0=1
O[0,0,1]O[0,0,1]1⋅0=0, 0⋅1=0, 0⋅1=01\cdot0=0,\ 0\cdot1=0,\ 0\cdot1=00+0=0; 0+0=0; 0+0=00+0=0;\ 0+0=0;\ 0+0=0
O[0,1,0]O[0,1,0]1/(1+r)⋅1=1/(1+r), r/(1+r)⋅0=0, 0⋅1=01/(1+r)\cdot1=1/(1+r),\ r/(1+r)\cdot0=0,\ 0\cdot1=00+1/(1+r)=1/(1+r); 1/(1+r)+0=1/(1+r); 1/(1+r)+0=1/(1+r)0+1/(1+r)=1/(1+r);\ 1/(1+r)+0=1/(1+r);\ 1/(1+r)+0=1/(1+r)
O[0,1,1]O[0,1,1]1/(1+r)⋅0=0, r/(1+r)⋅1=r/(1+r), 0⋅1=01/(1+r)\cdot0=0,\ r/(1+r)\cdot1=r/(1+r),\ 0\cdot1=00+0=0; 0+r/(1+r)=r/(1+r); r/(1+r)+0=r/(1+r)0+0=0;\ 0+r/(1+r)=r/(1+r);\ r/(1+r)+0=r/(1+r)
O[0,2,0]O[0,2,0]1/(2+r)⋅1=1/(2+r), 1/(2+r)⋅0=0, r/(2+r)⋅1=r/(2+r)1/(2+r)\cdot1=1/(2+r),\ 1/(2+r)\cdot0=0,\ r/(2+r)\cdot1=r/(2+r)0+1/(2+r)=1/(2+r); 1/(2+r)+0=1/(2+r); 1/(2+r)+r/(2+r)=(1+r)/(2+r)0+1/(2+r)=1/(2+r);\ 1/(2+r)+0=1/(2+r);\ 1/(2+r)+r/(2+r)=(1+r)/(2+r)
O[0,2,1]O[0,2,1]1/(2+r)⋅0=0, 1/(2+r)⋅1=1/(2+r), r/(2+r)⋅1=r/(2+r)1/(2+r)\cdot0=0,\ 1/(2+r)\cdot1=1/(2+r),\ r/(2+r)\cdot1=r/(2+r)0+0=0; 0+1/(2+r)=1/(2+r); 1/(2+r)+r/(2+r)=(1+r)/(2+r)0+0=0;\ 0+1/(2+r)=1/(2+r);\ 1/(2+r)+r/(2+r)=(1+r)/(2+r)

Therefore the output rows are

O0=(1,0),O1=(11+r,r1+r),O2=(1+r2+r,1+r2+r).O_0=(1,0),\quad O_1=\left(\frac1{1+r},\frac r{1+r}\right),\quad O_2=\left(\frac{1+r}{2+r},\frac{1+r}{2+r}\right).

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 a−a=0,a−a=0a-a=0,a-a=0, terms (1,1,0)(1,1,0) and denominator ((0+1)+1)+0=2((0+1)+1)+0=2. Thus P becomes (1/2,1/2,0)(1/2,1/2,0).

Feature zero forms 1/2⋅1=1/21/2\cdot1=1/2, then 0+1/2=1/20+1/2=1/2; next 1/2⋅0=01/2\cdot0=0, then 1/2+0=1/21/2+0=1/2; finally 0⋅1=00\cdot1=0, then 1/2+0=1/21/2+0=1/2. Feature one forms 1/2⋅0=01/2\cdot0=0, then 0+0=00+0=0; next 1/2⋅1=1/21/2\cdot1=1/2, then 0+1/2=1/20+1/2=1/2; finally 0⋅1=00\cdot1=0, then 1/2+0=1/21/2+0=1/2. O becomes (1/2,1/2)(1/2,1/2). The last query survives; only its key permission changed.

Signed values expose a second misconception

Load the nonsymmetric example after reset. It uses

WQ=[1201],WK=[0110],WV=[1−120].W_Q=\begin{bmatrix}1&2\\0&1\end{bmatrix},\quad W_K=\begin{bmatrix}0&1\\1&0\end{bmatrix},\quad W_V=\begin{bmatrix}1&-1\\2&0\end{bmatrix}.

The projections are Q rows (1,2),(0,1),(1,3)(1,2),(0,1),(1,3), K rows (0,1),(1,0),(1,1)(0,1),(1,0),(1,1) and V rows (1,−1),(2,0),(3,−1)(1,-1),(2,0),(3,-1). For example V’s last row is (1⋅1+1⋅2,1⋅(−1)+1⋅0)=(3,−1)(1\cdot1+1\cdot2,1\cdot(-1)+1\cdot0)=(3,-1). Raw scores are rows (2,1,3),(1,0,1),(3,1,4)(2,1,3),(1,0,1),(3,1,4).

Under the causal mask, query zero returns (1,−1)(1,-1). Query one’s probabilities are (r,1,0)/(r+1)(r,1,0)/(r+1). Its first coordinate adds r/(r+1)⋅1+1/(r+1)⋅2+0⋅3=(r+2)/(r+1)r/(r+1)\cdot1+1/(r+1)\cdot2+0\cdot3=(r+2)/(r+1); its second adds r/(r+1)⋅(−1)+1/(r+1)⋅0+0⋅(−1)=−r/(r+1)r/(r+1)\cdot(-1)+1/(r+1)\cdot0+0\cdot(-1)=-r/(r+1).

For query two, let h=1+r2+r3h=1+r^2+r^3. Probabilities are (r2,1,r3)/h(r^2,1,r^3)/h. The two sums are (r2⋅1+1⋅2+r3⋅3)/h(r^2\cdot1+1\cdot2+r^3\cdot3)/h and (r2⋅(−1)+1⋅0+r3⋅(−1))/h(r^2\cdot(-1)+1\cdot0+r^3\cdot(-1))/h. They give ((r2+2+3r3)/h,−(r2+r3)/h)((r^2+2+3r^3)/h,-(r^2+r^3)/h). 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

  1. 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.
  2. 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.
  3. 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: each productj is added to the preceding running sum in ascending j, and its final value is O[0,0,0], alias o000. Reset gives ((0+1·1)+0·0)+0·1=1. After edits use the current products and runningj fields, not the reset answer. The question fixes these coordinates independently of view selectors.
  4. 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.
  5. Counterexample: two allowed V coordinates are −2 and 4, with probabilities 3/4 and 1/4. What is the output coordinate? It is −1/2-1/2, a valid signed weighted sum. First product (3/4)(−2)=−3/2(3/4)(-2)=-3/2, first running sum 0+(−3/2)=−3/20+(-3/2)=-3/2; second product (1/4)4=1(1/4)4=1, final sum −3/2+1=−1/2-3/2+1=-1/2. 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.