The neural notebook
← All chapters

IV-26 / Part V · Self-Attention

Causal, Bidirectional and Padding Attention

Hold projections fixed, change allowed keys, and recompute every probability and output coordinate for bidirectional, causal and padding attention.

Review the ideas this chapter uses

The same sequence can be used for different tasks. Reading a completed sequence may permit access to later positions; predicting while a sequence grows must exclude information from its future. Storage may also contain padding positions that should supply no information. We will change those access rules while keeping the input rows and projection weights fixed, then calculate the resulting messages again.

Learning objective: Contrast different allowed-key sets using the same real projected tensors.

Start with IV-25 — Self-Attention: Complete Numerical Trace for the complete weighted-value trace. Book II’s VII.7 — Numerical stability: log-sum-exp and stable softmax reviews stable softmax; Book III’s III-41 — Composition and Learned Representations separates computing representations from learning them. All weights here are hand-set, and the access rule alone cannot make a toy understand language.

Change the rule, inspect the whole result

Compute it yourself

Causal, bidirectional and padding attention

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
0
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
0
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 0: all keys. 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=0.4011120926797859Allowed: p=0.1977758146404282Allowed: p=0.4011120926797859
Query 1Allowed: p=0.1977758146404282Allowed: p=0.4011120926797859Allowed: p=0.4011120926797859
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.49306869139523984 + 1 = 2.49306869139524.

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 / 2.49306869139524 = 0.4011120926797859
1true00 + 0 = 00 − 0.7071067811865475 = -0.7071067811865475exp(-0.7071067811865475) = 0.493068691395239840.49306869139523984 / 2.49306869139524 = 0.1977758146404282
2true0.70710678118654750.7071067811865475 + 0 = 0.70710678118654750.7071067811865475 − 0.7071067811865475 = 0exp(0) = 11 / 2.49306869139524 = 0.4011120926797859

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] = 0.8022241853595719. 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)0.8022241853595719 (selected coordinate)0.5988879073202141
Query 10.59888790732021410.8022241853595719
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
0Allowed0.401112092679785910.40111209267978590 (start)0.4011120926797859
1Allowed0.1977758146404282000.40111209267978590.4011120926797859
2Allowed0.401112092679785910.40111209267978590.40111209267978590.8022241853595719

The final running sum is 0.8022241853595719. 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
0.4011120926797859
p001
0.1977758146404282
p002
0.4011120926797859
p010
0.1977758146404282
p011
0.4011120926797859
p012
0.4011120926797859
p020
0.2482550782577231
p021
0.2482550782577231
p022
0.5034898434845538
o000
0.8022241853595719
o001
0.5988879073202141
o010
0.5988879073202141
o011
0.8022241853595719
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
2.49306869139524
row_0_0_shifted0
0
row_0_0_shifted1
-0.7071067811865475
row_0_0_shifted2
0
row_0_0_term0
1
row_0_0_term1
0.49306869139523984
row_0_0_term2
1
row_0_0_p0
0.4011120926797859
row_0_0_p1
0.1977758146404282
row_0_0_p2
0.4011120926797859
row_0_1_max
0.7071067811865475
row_0_1_denominator
2.49306869139524
row_0_1_shifted0
-0.7071067811865475
row_0_1_shifted1
0
row_0_1_shifted2
0
row_0_1_term0
0.49306869139523984
row_0_1_term1
1
row_0_1_term2
1
row_0_1_p0
0.1977758146404282
row_0_1_p1
0.4011120926797859
row_0_1_p2
0.4011120926797859
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
0.4011120926797859
mix_0_0_0_product1
0
mix_0_0_0_product2
0.4011120926797859
mix_0_0_0_running0
0.4011120926797859
mix_0_0_0_running1
0.4011120926797859
mix_0_0_0_running2
0.8022241853595719
mix_0_0_0_value
0.8022241853595719
mix_0_0_1_product0
0
mix_0_0_1_product1
0.1977758146404282
mix_0_0_1_product2
0.4011120926797859
mix_0_0_1_running0
0
mix_0_0_1_running1
0.1977758146404282
mix_0_0_1_running2
0.5988879073202141
mix_0_0_1_value
0.5988879073202141
mix_0_1_0_product0
0.1977758146404282
mix_0_1_0_product1
0
mix_0_1_0_product2
0.4011120926797859
mix_0_1_0_running0
0.1977758146404282
mix_0_1_0_running1
0.1977758146404282
mix_0_1_0_running2
0.5988879073202141
mix_0_1_0_value
0.5988879073202141
mix_0_1_1_product0
0
mix_0_1_1_product1
0.4011120926797859
mix_0_1_1_product2
0.4011120926797859
mix_0_1_1_running0
0
mix_0_1_1_running1
0.4011120926797859
mix_0_1_1_running2
0.8022241853595719
mix_0_1_1_value
0.8022241853595719
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
1true
2true
3true
4true
5true
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
00.4011120926797859
10.1977758146404282
20.4011120926797859
30.1977758146404282
40.4011120926797859
50.4011120926797859
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
00.8022241853595719
10.5988879073202141
20.5988879073202141
30.8022241853595719
40.7517449217422769
50.7517449217422769

Reset uses bidirectional mode with the same projections and input rows as IV-25. With a=1/sqrt(2), r=exp(a), query 0 has P=(r,1,r)/(1+2r) and O=(2r/(1+2r),(1+r)/(1+2r)). Switch only the mask to causal: its probability becomes (1,0,0) and output becomes (1,0), while Q, K, V and unmasked scores stay fixed.

For a full changed-mask recomputation, restore reset inputs, choose padding-only and set valid2=0. Query 0 retains scores (a,0), maximum a, shifted terms (1,exp(−a),0), denominator 1+exp(−a), and P=(r/(1+r),1/(1+r),0). Its feature-0 products are (r/(1+r),0,0), so running sums stay r/(1+r). Its feature-1 products are (0,1/(1+r),0), so running sums go 0,1/(1+r),1/(1+r). The output is (r/(1+r),1/(1+r)).

The same padding-only experiment gives query 1 output (1/(1+r),r/(1+r)) and query 2 output (1/2,1/2). Query 2 still exists even though key 2 is forbidden. Switch to causal + padding without changing the flags: only query 0 changes to (1,0). With that combined mode, turning valid0 off instead makes query 0 fully masked and the complete result unavailable.

To inspect future exclusion, hold the earlier rows and weights fixed and edit X at position 2. Earlier causal outputs stay fixed even if their displayed forbidden scores change; earlier bidirectional outputs may change. Batches remain separate, while key-validity flags are intentionally shared. Compare a valid zero vector with an invalid padding key: the zero vector can receive probability and changes normalization despite contributing zero through V. All four modes call the same complete numerical chain.

Check your understanding

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

1. What does the causal allowed-key rule j≤i mean?
2. Reset to bidirectional attention. Put a=1/sqrt(2), r=exp(a). What is the first output row?
3. For the current starting inputs, batch 0, query 0 uses mask mode 0 and active T=3. How many keys are allowed by its saved Boolean mask?
4. Keep earlier X rows, all projection weights, dimensions and mask policy fixed. Change only a later token row. Which statement holds for an earlier causal output?
5. Choose T=3, causal + padding mode, valid0=0 and valid1=valid2=1. What happens to the complete attention result?

Reset is bidirectional: every active key may contribute to every query. Change only the mask to causal, then compare the first output. Next restore reset, choose padding-only and set valid2=0. Inspect the retained last query and its new probabilities and value contributions. The worked calculations below use exactly these edits.

The probability inspector and output inspector have independent labelled batch/query selectors; the output inspector also selects a value feature. Match their labels to compare one coordinate’s operands. Both read the same complete result. The saved trace selection is independent of these views, and does not replace the full result with a partially computed tensor. Editing inputs recomputes all stages, resets trace selection and clears graded answers.

Vocabulary, symbols and axes

A mask is a Boolean permission rule: true permits a query–key pair; false forbids it. Causal permits earlier and current positions. Bidirectional permits both earlier and later positions within this sequence. Padding is an explicit declaration that a stored position is invalid as a key. It is not inferred from its numerical contents.

B counts independent sequences, T active positions, D=2 input features, Dk query/key features and Dv value features. Queries Q compare with keys K; values V carry the coordinates combined using probabilities P. A tensor is an array with named axes. Input embeddings X have shape [B,T,2]; WQ/WK have [2,Dk], WV [2,Dv]; Q/K have [B,T,Dk] and V [B,T,Dv]. Scores, allowed flags, logits and probabilities P each have [B,T,T], axes B,Query,Key. Output O has [B,T,Dv], axes B,Query,Dv.

Indices b, i, j and f mean batch, query, key and value feature, starting at zero. For a row, AiA_i denotes the set of allowed keys; it is not an extra tensor. The weighted sum keeps b, i and f fixed:

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

Start at zero; for each key compute its product, add it immediately to the running sum, then move to the next key. A forbidden probability is exactly zero, but its 0⋅V0\cdot V product is still recorded. There is no extra average over positions or features.

Four modes, one permission predicate

CodeModeKey j belongs to query i’s allowed set when…
0Bidirectionalj is any active key
1Causalj≤ij\leq i
2Padding onlyvalidj=1
3Causal + paddingj≤ij\leq i and validj=1

The symbol ≤\leq includes equality: causal query zero may use key zero. Mode 3 is an intersection, requiring both conditions. Flags valid0, valid1, valid2 are deliberately shared across batches, and mask keys only. No mode deletes a query row or changes T. Modes 0 and 1 ignore flags for permissions, although all stored flags remain validated, including inactive ones.

Keep the projections and raw scores fixed

At reset X rows are (1,0),(0,1),(1,1)(1,0),(0,1),(1,1) and every weight matrix is identity. For each of Q, K and V, feature pairs are calculated as

(1⋅1+0⋅0,1⋅0+0⋅1)=(1,0),(0⋅1+1⋅0,0⋅0+1⋅1)=(0,1),(1⋅1+1⋅0,1⋅0+1⋅1)=(1,1).(1\cdot1+0\cdot0,1\cdot0+0\cdot1)=(1,0),\quad (0\cdot1+1\cdot0,0\cdot0+1\cdot1)=(0,1),\quad (1\cdot1+1\cdot0,1\cdot0+1\cdot1)=(1,1).

Thus Q=K=V=X. Dot products multiply matching query/key features, then sum. Their rows are (1⋅1+0⋅0,1⋅0+0⋅1,1⋅1+0⋅1)=(1,0,1)(1\cdot1+0\cdot0,1\cdot0+0\cdot1,1\cdot1+0\cdot1)=(1,0,1); (0⋅1+1⋅0,0⋅0+1⋅1,0⋅1+1⋅1)=(0,1,1)(0\cdot1+1\cdot0,0\cdot0+1\cdot1,0\cdot1+1\cdot1)=(0,1,1); and (1⋅1+1⋅0,1⋅0+1⋅1,1⋅1+1⋅1)=(1,1,2)(1\cdot1+1\cdot0,1\cdot0+1\cdot1,1\cdot1+1\cdot1)=(1,1,2).

Divide each by Dk=2\sqrt{Dk}=\sqrt2. Put a=1/2a=1/\sqrt2, r=exp⁡(a)r=\exp(a), where exp⁡(z)=ez\exp(z)=e^z and exp⁡(0)=1\exp(0)=1. Scores are (a,0,a),(0,a,a),(a,a,2a)(a,0,a),(0,a,a),(a,a,2a). A logit is the softmax input score plus the common shift, zero at reset. Changing only the mask changes none of these projections or scores.

Write ℓj\ell_j for key j’s logit. For each row, maximum m is taken over allowed logits only. Allowed terms are exp⁡(ℓj−m)\exp(\ell_j-m); forbidden terms are zero. Add terms from zero in key order for denominator d, then divide each term by d. This softmax normalizes over keys. Maximum subtraction cancels a common exponential factor, so it preserves real ratios while avoiding huge positive exponentials.

Complete bidirectional reset

All keys are allowed. Define h=1+2rh=1+2r and g=2+rg=2+r solely to shorten the following exact expressions.

QueryMaximum and all subtractionsTermsDenominator and probabilities
0m=a; a−a=0, 0−a=−a, a−a=0m=a;\ a-a=0,\ 0-a=-a,\ a-a=0(1,1/r,1)(1,1/r,1)((0+1)+1/r)+1=h/r; P=(r,1,r)/h((0+1)+1/r)+1=h/r;\ P=(r,1,r)/h
1m=a; 0−a=−a, a−a=0, a−a=0m=a;\ 0-a=-a,\ a-a=0,\ a-a=0(1/r,1,1)(1/r,1,1)((0+1/r)+1)+1=h/r; P=(1,r,r)/h((0+1/r)+1)+1=h/r;\ P=(1,r,r)/h
2m=2a; a−2a=−a, a−2a=−a, 2a−2a=0m=2a;\ a-2a=-a,\ a-2a=-a,\ 2a-2a=0(1/r,1/r,1)(1/r,1/r,1)((0+1/r)+1/r)+1=g/r; P=(1,1,r)/g((0+1/r)+1/r)+1=g/r;\ P=(1,1,r)/g

For example query zero divides terms by h/r: 1/(h/r)=r/h1/(h/r)=r/h, (1/r)/(h/r)=1/h(1/r)/(h/r)=1/h, and 1/(h/r)=r/h1/(h/r)=r/h. The same divisions give the remaining rows. Every output coordinate is then:

Output, batch 0Key products 0, 1, 2Running sum after each key
Query 0, feature 0(r/h)⋅1=r/h, (1/h)⋅0=0, (r/h)⋅1=r/h(r/h)\cdot1=r/h,\ (1/h)\cdot0=0,\ (r/h)\cdot1=r/h0+r/h=r/h; r/h+0=r/h; r/h+r/h=2r/h0+r/h=r/h;\ r/h+0=r/h;\ r/h+r/h=2r/h
Query 0, feature 1(r/h)⋅0=0, (1/h)⋅1=1/h, (r/h)⋅1=r/h(r/h)\cdot0=0,\ (1/h)\cdot1=1/h,\ (r/h)\cdot1=r/h0+0=0; 0+1/h=1/h; 1/h+r/h=(1+r)/h0+0=0;\ 0+1/h=1/h;\ 1/h+r/h=(1+r)/h
Query 1, feature 0(1/h)⋅1=1/h, (r/h)⋅0=0, (r/h)⋅1=r/h(1/h)\cdot1=1/h,\ (r/h)\cdot0=0,\ (r/h)\cdot1=r/h0+1/h=1/h; 1/h+0=1/h; 1/h+r/h=(1+r)/h0+1/h=1/h;\ 1/h+0=1/h;\ 1/h+r/h=(1+r)/h
Query 1, feature 1(1/h)⋅0=0, (r/h)⋅1=r/h, (r/h)⋅1=r/h(1/h)\cdot0=0,\ (r/h)\cdot1=r/h,\ (r/h)\cdot1=r/h0+0=0; 0+r/h=r/h; r/h+r/h=2r/h0+0=0;\ 0+r/h=r/h;\ r/h+r/h=2r/h
Query 2, feature 0(1/g)⋅1=1/g, (1/g)⋅0=0, (r/g)⋅1=r/g(1/g)\cdot1=1/g,\ (1/g)\cdot0=0,\ (r/g)\cdot1=r/g0+1/g=1/g; 1/g+0=1/g; 1/g+r/g=(1+r)/g0+1/g=1/g;\ 1/g+0=1/g;\ 1/g+r/g=(1+r)/g
Query 2, feature 1(1/g)⋅0=0, (1/g)⋅1=1/g, (r/g)⋅1=r/g(1/g)\cdot0=0,\ (1/g)\cdot1=1/g,\ (r/g)\cdot1=r/g0+0=0; 0+1/g=1/g; 1/g+r/g=(1+r)/g0+0=0;\ 0+1/g=1/g;\ 1/g+r/g=(1+r)/g

Query zero’s output is (2r/(1+2r),(1+r)/(1+2r))(2r/(1+2r),(1+r)/(1+2r)). Switch only to causal mode: allowed keys become 100, 110, 111. Query zero has sole term one and P=(1,0,0); its two sums are ((0+1⋅1)+0⋅0)+0⋅1=1((0+1\cdot1)+0\cdot0)+0\cdot1=1 and ((0+1⋅0)+0⋅1)+0⋅1=0((0+1\cdot0)+0\cdot1)+0\cdot1=0. The first output becomes (1,0) with identical X and weights. Query one becomes (1/(1+r),r/(1+r))(1/(1+r),r/(1+r)); query two is unchanged because it already permits every active key.

Remove key two and recompute all outputs

Restore reset, select padding-only and set valid2=0, leaving the other flags one. Every allowed row is now 110. With k=1+rk=1+r, stable normalization gives:

QueryMaximum; allowed subtractionsAll terms; denominatorDivisions give P
0a; a−a=0, 0−a=−aa;\ a-a=0,\ 0-a=-a(1,1/r,0); ((0+1)+1/r)+0=k/r(1,1/r,0);\ ((0+1)+1/r)+0=k/r(r/k,1/k,0)(r/k,1/k,0)
1a; 0−a=−a, a−a=0a;\ 0-a=-a,\ a-a=0(1/r,1,0); ((0+1/r)+1)+0=k/r(1/r,1,0);\ ((0+1/r)+1)+0=k/r(1/k,r/k,0)(1/k,r/k,0)
2a; a−a=0, a−a=0a;\ a-a=0,\ a-a=0(1,1,0); ((0+1)+1)+0=2(1,1,0);\ ((0+1)+1)+0=2(1/2,1/2,0)(1/2,1/2,0)

The last query’s maximum is now a, even though its forbidden key-two score is 2a. Forbidden logits do not enter the maximum or denominator. V is unchanged. Here is the complete downstream recomputation:

Output, batch 0Key products 0, 1, 2Running sum after each key
Query 0, feature 0(r/k)⋅1=r/k, (1/k)⋅0=0, 0⋅1=0(r/k)\cdot1=r/k,\ (1/k)\cdot0=0,\ 0\cdot1=00+r/k=r/k; r/k+0=r/k; r/k+0=r/k0+r/k=r/k;\ r/k+0=r/k;\ r/k+0=r/k
Query 0, feature 1(r/k)⋅0=0, (1/k)⋅1=1/k, 0⋅1=0(r/k)\cdot0=0,\ (1/k)\cdot1=1/k,\ 0\cdot1=00+0=0; 0+1/k=1/k; 1/k+0=1/k0+0=0;\ 0+1/k=1/k;\ 1/k+0=1/k
Query 1, feature 0(1/k)⋅1=1/k, (r/k)⋅0=0, 0⋅1=0(1/k)\cdot1=1/k,\ (r/k)\cdot0=0,\ 0\cdot1=00+1/k=1/k; 1/k+0=1/k; 1/k+0=1/k0+1/k=1/k;\ 1/k+0=1/k;\ 1/k+0=1/k
Query 1, feature 1(1/k)⋅0=0, (r/k)⋅1=r/k, 0⋅1=0(1/k)\cdot0=0,\ (r/k)\cdot1=r/k,\ 0\cdot1=00+0=0; 0+r/k=r/k; r/k+0=r/k0+0=0;\ 0+r/k=r/k;\ r/k+0=r/k
Query 2, feature 0(1/2)⋅1=1/2, (1/2)⋅0=0, 0⋅1=0(1/2)\cdot1=1/2,\ (1/2)\cdot0=0,\ 0\cdot1=00+1/2=1/2; 1/2+0=1/2; 1/2+0=1/20+1/2=1/2;\ 1/2+0=1/2;\ 1/2+0=1/2
Query 2, feature 1(1/2)⋅0=0, (1/2)⋅1=1/2, 0⋅1=0(1/2)\cdot0=0,\ (1/2)\cdot1=1/2,\ 0\cdot1=00+0=0; 0+1/2=1/2; 1/2+0=1/20+0=0;\ 0+1/2=1/2;\ 1/2+0=1/2

O rows are (r/k,1/k),(1/k,r/k),(1/2,1/2)(r/k,1/k),(1/k,r/k),(1/2,1/2). Query two remains present, reads the first two keys and produces a full output. This is key masking, not deletion of a position. Switch to causal + padding with the same flags: allowed rows are 100, 110, 110, so only query zero changes to (1,0).

Empty intersections and blank-looking vectors

Keep combined mode and turn valid0=0, with valid1=valid2=1. Query zero is causally permitted only key zero, which padding forbids. Its allowed set is empty. There is no maximum or normalized distribution; the whole result becomes unavailable with FULLY_MASKED_ROW, identifying batch and query. Neither a fabricated zero output nor deleting that query implements the requested computation. All flags zero in padding-only mode is another empty-set example; causal mode ignores the flags instead.

A valid all-zero embedding is different. With the identity maps it produces K=V=(0,0), and its score is zero. If allowed, its exponential is positive in real arithmetic and enters normalization even though its weighted V contribution is zero. For instance, make reset position two zero while keeping it valid and bidirectional: query zero scores become (a,0,0)(a,0,0) and P becomes (r,1,1)/(r+2)(r,1,1)/(r+2). O is (r/(r+2),1/(r+2))(r/(r+2),1/(r+2)). Masking that key instead gives (r/(r+1),1/(r+1))(r/(r+1),1/(r+1)). Blank-looking numerical content and declared padding have different effects.

Why future exclusion is conditional

Fix earlier X rows, weights, dimensions, shift and mask policy. For an earlier causal query i, Q_i and all permitted K_j/V_j with j≤ij\leq i use unchanged inputs. Changing a later row cannot affect that earlier output: future probabilities are exactly zero, and normalization ignores forbidden scores. A displayed future score may change without being used. Bidirectional outputs may change because future keys remain permitted.

This assumes no earlier operation already copied future information into earlier embeddings. Changing shared weights or earlier position representations also breaks the conditions. Masking here cannot undo upstream leakage or establish causality for an entire training pipeline.

Further counterexamples and the actual Python

Reset, choose causal mode, then load the nonsymmetric example from IV-25. Query two originally has probabilities (r2,1,r3)/(1+r2+r3)(r^2,1,r^3)/(1+r^2+r^3) and V rows (1,−1),(2,0),(3,−1)(1,-1),(2,0),(3,-1). Enable combined mode with valid2=0: ratios become (r2,1,0)/(1+r2)(r^2,1,0)/(1+r^2), so O becomes ((r2+2)/(1+r2),−r2/(1+r2))((r^2+2)/(1+r^2),-r^2/(1+r^2)). Masking recomputes signed mixtures too; it does not replace V with probabilities.

B=2 keeps batches independent while deliberately sharing validity flags. Dk and Dv may differ: score scaling uses Dk, output width uses Dv. T=1 gives O=V if its sole key is allowed, otherwise unavailable. Repeated keys can have equal weights; zero or identical values can hide changes in P. A common shift of ±10000 preserves real ratios but can round score differences in binary64. An allowed tiny probability may underflow to zero; count Boolean permissions rather than nonzero printed probabilities. The expressions above are manual real identities, not measured decimal results.

The chapter composes the same stages as IV-25, with a different default mode:

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.

"""IV26: compare masks using the same complete attention computation.

Mode 0 (the default) permits all keys; 1 is causal; 2 applies key validity;
3 intersects causal and validity rules. Queries remain in every mode.
For identity defaults, put a=1/sqrt(2), r=exp(a). Bidirectional query 0
has P=(r,1,r)/(1+2r), hence O=(2r,1+r)/(1+2r); causal O is (1,0).
Padding-only valid2=0 gives O rows (r,1)/(1+r), (1,r)/(1+r), (1/2,1/2).
A fully masked query makes the entire result unavailable, never a zero row.
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_IV26 = MappingProxyType(dict(ATTENTION_DEFAULTS, mode=0))


@guarded
def derive_iv26(state):
    """Recompute projections through weighted values for the selected mask."""
    s = validated_state(state, attention=True)
    trace = attention_trace()
    projection = project(s, trace)
    scored = score(s, projection, trace)
    # Shared validity masks keys in every batch; it does not remove queries.
    normalized = normalize(s, scored, trace)
    mixed = mix_values(s, projection, normalized, trace)
    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_iv26, DEFAULT_IV26)

The shared attention helper implements the allowed predicate, maximum, exponentials and divisions:

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 consumes those exact probabilities and projected values:

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)

Read row_b_i for allowedj, termj, denominator and pj; then read mix_b_i_f for each product and immediately updated running sum. Both helpers use real arrays and scalar operations. The trace stores products before running fields for inspection; that record layout does not mean all products execute before all additions. Every stored scalar is validated, including ignored flags and inactive slots.

Five exercises matched to the lab

  1. What does the causal allowed-key rule j≤i mean? Query i can use its own position and earlier positions. Padding is a separate condition; combined mode requires both. No query is deleted.
  2. Reset to bidirectional attention. Put a=1/sqrt(2), r=exp(a). What is the first output row? It is (2r/(1+2r),(1+r)/(1+2r))(2r/(1+2r),(1+r)/(1+2r)): probabilities (r,1,r)/(1+2r)(r,1,r)/(1+2r) weight values (1,0),(0,1),(1,1)(1,0),(0,1),(1,1). The answer (1,0) belongs to causal mode, while (r/(1+r),1/(1+r))(r/(1+r),1/(1+r)) belongs to padding-only with key two forbidden.
  3. For the current starting inputs, batch 0, query 0 uses the displayed mask mode and active T. How many keys are allowed by its saved Boolean mask? Count the true flags saved in row_0_0, considering only active T keys and the current mode. Reset gives three; causal gives one; padding-only with valid2=0 gives two. An allowed probability rounded to zero still counts. This question fixes batch/query zero independently of view selections.
  4. Keep earlier X rows, all projection weights, dimensions and mask policy fixed. Change only a later token row. Which statement holds for an earlier causal output? It cannot change here, provided earlier representations contain no future information already mixed into them. Future displayed scores are forbidden; a prior layer’s leak cannot be repaired by this mask.
  5. Choose T=3, causal + padding mode, valid0=0 and valid1=valid2=1. What happens to the complete attention result? The whole result is unavailable: query zero’s causal and valid-key sets have empty intersection. There is no denominator or weighted output for that row. Deleting it or inventing zeros would change the operation.

Recap and bridge

Permissions change P and therefore O while projections and unmasked scores stay fixed. Causal means earlier-or-self; padding removes keys and retains queries; combined mode intersects the conditions. Empty allowed rows reject the whole calculation. Future exclusion requires unchanged earlier representations without upstream leakage. Part VI begins with IV-27 — Separating Attention Heads and Dimensions, separating several heads while preserving the axes and mask rules established here.