IV-24 / Part V · Self-Attention
Masking and Numerically Stable Softmax
Derive causal and padding key masks, compute every stable-softmax intermediate, and separate exact mask zeros from roundoff and allowed-key underflow.
Review the ideas this chapter uses
A score answers how one query compares with one key. It does not say whether that key may be used. A prediction made at the start of a sequence should not consult a future position, and a padding position should not receive weight merely because storage reserved a slot for it. We will first declare allowed keys, then turn each valid row’s allowed scores into probabilities.
Learning objective: Apply causal/padding masks then rowwise stable softmax.
Review IV-23 — Dot-Product Attention Scores and Scaling for the signed scaled scores and VII.7 — Numerical stability: log-sum-exp and stable softmax for stable softmax. This lesson repeats the normalization derivation locally, including the empty-row failure case. A probability here is a nonnegative relative weight over allowed key positions for one query, not a measured probability that a word is true or meaningful.
Inspect the allowed row before its weights
Mask keys and compute stable rowwise probabilities
These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.
Complete results from this trace’s starting inputs
Starting inputs for these results
- B
- 1
- T
- 3
- Dk
- 2
- Dv
- 2
- x000
- 1
- x001
- 0
- x010
- 0
- x011
- 1
- x020
- 1
- x021
- 1
- x100
- 1
- x101
- 1
- x110
- -1
- x111
- 0
- x120
- 0
- x121
- 2
- wq00
- 1
- wq01
- 0
- wq10
- 0
- wq11
- 1
- wk00
- 1
- wk01
- 0
- wk10
- 0
- wk11
- 1
- wv00
- 1
- wv01
- 0
- wv10
- 0
- wv11
- 1
- mode
- 1
- valid0
- 1
- valid1
- 1
- valid2
- 1
- shift
- 0
B 1. T 3. Dk 2. Dv 2. Validate all scalar inputs and select active dimensions. All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.. B 1. T 3. D 2. Dk 2. Dv 2
Validate all scalar inputs and select active dimensions
D=2; X[B,T,D]; WQ,WK[D,Dk]; WV[D,Dv]
All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.
Inputs
- B
- 1
- T
- 3
- Dk
- 2
- Dv
- 2
- x000
- 1
- x001
- 0
- x010
- 0
- x011
- 1
- x020
- 1
- x021
- 1
- x100
- 1
- x101
- 1
- x110
- -1
- x111
- 0
- x120
- 0
- x121
- 2
- wq00
- 1
- wq01
- 0
- wq10
- 0
- wq11
- 1
- wk00
- 1
- wk01
- 0
- wk10
- 0
- wk11
- 1
- wv00
- 1
- wv01
- 0
- wv10
- 0
- wv11
- 1
- mode
- 1
- valid0
- 1
- valid1
- 1
- valid2
- 1
- shift
- 0
Outputs
- B
- 1
- T
- 3
- D
- 2
- Dk
- 2
- Dv
- 2
Token rows → separate projections → query–key scores → allowed-key probabilities
These are hand-set weights, not a trained model. D=2 always counts input features. Dk=2 counts query/key features; Dv=2 counts value features. All indices start at zero. Inactive stored slots remain validated but do not appear in active tensors.
The example button restores B=1, T=3, Dk=Dv=2 and X=[[1,0],[0,1],[1,1]], then sets three different matrices. Mask mode, validity and shift keep their current values. Reset example above restores every lesson default.
Showing batch 0, query 0 against all 3 active keys. These selectors change the view only. Trace navigation above selects a saved operation independently; highlighted rows mark that operation when it is in this view.
X batch 0
B=1 × T=3 × D=2 · float64. Rows: Token; columns: Input feature D.
| Token | Input feature D 0 | Input feature D 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
WQ shared weights
D=2 × Dk=2 · float64. Rows: Input feature D; columns: Query feature Dk.
| Input feature D | Query feature Dk 0 | Query feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
WK shared weights
D=2 × Dk=2 · float64. Rows: Input feature D; columns: Key feature Dk.
| Input feature D | Key feature Dk 0 | Key feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
WV shared weights
D=2 × Dv=2 · float64. Rows: Input feature D; columns: Value feature Dv.
| Input feature D | Value feature Dv 0 | Value feature Dv 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
Q batch 0
B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Query feature Dk.
| Token | Query feature Dk 0 | Query feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
K batch 0
B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Key feature Dk.
| Token | Key feature Dk 0 | Key feature Dk 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
V batch 0
B=1 × T=3 × Dv=2 · float64. Rows: Token; columns: Value feature Dv.
| Token | Value feature Dv 0 | Value feature Dv 1 |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 1 |
Every projection coordinate in batch 0
For row-feature inputs, output feature f is x0·W[0,f]+x1·W[1,f]. A column-vector version uses the transposed weights: q_column=WQᵀ·x_column.
| Coordinate | x0 | w0 | x0 × w0 | x1 | w1 | x1 × w1 | Sum |
|---|---|---|---|---|---|---|---|
| Q,0,0,0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| Q,0,0,1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| Q,0,1,0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| Q,0,1,1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| Q,0,2,0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| Q,0,2,1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 |
| K,0,0,0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| K,0,0,1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| K,0,1,0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| K,0,1,1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| K,0,2,0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| K,0,2,1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 |
| V,0,0,0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| V,0,0,1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| V,0,1,0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| V,0,1,1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| V,0,2,0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 |
| V,0,2,1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 |
Batch 0, query 0: one dot product per key
Each comparison stays inside batch 0. Multiply matching features, add those products, then divide by sqrt(Dk). There is no softmax in IV-23: scores can be negative and need not sum to one.
raw batch 0
B=1 × Query=3 × Key=3 · float64. Rows: Query; columns: Key.
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 2 | 1 | 1 | 2 |
scores batch 0
B=1 × Query=3 × Key=3 · float64. Rows: Query; columns: Key.
| Query | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| 0 | 0.7071067811865475 | 0 | 0.7071067811865475 |
| 1 | 0 | 0.7071067811865475 | 0.7071067811865475 |
| 2 | 0.7071067811865475 | 0.7071067811865475 | 1.414213562373095 |
| Key j | q0 | k0 | q0 × k0 | q1 | k1 | q1 × k1 | Raw sum | sqrt(Dk) | Scaled score |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 |
| 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 1.4142135623730951 | 0 |
| 2 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1.4142135623730951 | 0.7071067811865475 |
Effective allowed keys and probabilities in batch 0
Mode 1: causal keys j≤i. Padding removes keys only; even a position marked as a padding key retains its query row. Every row must have at least one allowed key, or the entire result is unavailable.
| Query / key | Key 0 | Key 1 | Key 2 |
|---|---|---|---|
| Query 0 (selected) | Allowed: p=1 | Forbidden: p=0 | Forbidden: p=0 |
| Query 1 | Allowed: p=0.3302384506733431 | Allowed: p=0.6697615493266569 | Forbidden: p=0 |
| Query 2 | Allowed: p=0.2482550782577231 | Allowed: p=0.2482550782577231 | Allowed: p=0.5034898434845538 |
Softmax arithmetic for batch 0, query 0
Common shift = 0. Maximum over allowed logits = 0.7071067811865475. Denominator = 1 + 0 + 0 = 1.
| Key j | Allowed? | Score | Logit = score + shift | Logit − allowed max | Exponential term | Term / denominator = p |
|---|---|---|---|---|---|---|
| 0 | true | 0.7071067811865475 | 0.7071067811865475 + 0 = 0.7071067811865475 | 0.7071067811865475 − 0.7071067811865475 = 0 | exp(0) = 1 | 1 / 1 = 1 |
| 1 | false | 0 | 0 + 0 = 0 | Forbidden: no subtraction | Forbidden: term=0, no exponential | 0 / 1 = 0 |
| 2 | false | 0.7071067811865475 | 0.7071067811865475 + 0 = 0.7071067811865475 | Forbidden: no subtraction | Forbidden: term=0, no exponential | 0 / 1 = 0 |
exp(z) means the positive exponential function e raised to z. An allowed maximum has shifted value 0 and exp(0)=1, so the denominator is at least 1. Other allowed terms may underflow to 0 for very negative shifted values. The boolean mask distinguishes that rounded zero from a forbidden key.
Adding a common shift cancels exactly in real arithmetic; adding and subtracting ±10000 can lose low bits in binary64. This lab stops at probabilities. IV-25 adds weighted value sums; no value mixing is performed here.
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
- 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
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
X
B=1 × T=3 × D=2 · float64 · display precision 8 · Active input token rows, selected without padding or broadcasting.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
WQ
D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk query columns of the editable WQ.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
WK
D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk key columns of the editable WK.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
WV
D=2 × Dv=2 · float64 · display precision 8 · Both input rows; leading Dv value columns of the editable WV.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
Q
B=1 × T=3 × Dk=2 · float64 · display precision 8 · Q=XWQ, with each coordinate traced as two products and one sum.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
K
B=1 × T=3 × Dk=2 · float64 · display precision 8 · K=XWK, with each coordinate traced as two products and one sum.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
V
B=1 × T=3 × Dv=2 · float64 · display precision 8 · V=XWV, available for later value mixing; not mixed in IV-22–24.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
raw
B=1 × Query=3 × Key=3 · float64 · display precision 8 · QK transpose: explicit feature products followed by their sum, within each batch.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 2 |
scores
B=1 × Query=3 × Key=3 · float64 · display precision 8 · Raw query-key agreement divided by sqrt(Dk); not softmax probabilities.
| Storage index | Value |
|---|---|
| 0 | 0.7071067811865475 |
| 1 | 0 |
| 2 | 0.7071067811865475 |
| 3 | 0 |
| 4 | 0.7071067811865475 |
| 5 | 0.7071067811865475 |
| 6 | 0.7071067811865475 |
| 7 | 0.7071067811865475 |
| 8 | 1.414213562373095 |
allowed
B=1 × Query=3 × Key=3 · bool · display precision 8 · True means this key may contribute to this query; key validity is shared across batches.
| Storage index | Value |
|---|---|
| 0 | true |
| 1 | false |
| 2 | false |
| 3 | true |
| 4 | true |
| 5 | false |
| 6 | true |
| 7 | true |
| 8 | true |
logits
B=1 × Query=3 × Key=3 · float64 · display precision 8 · Finite score+common shift for every active key, including forbidden keys; no mask sentinel.
| Storage index | Value |
|---|---|
| 0 | 0.7071067811865475 |
| 1 | 0 |
| 2 | 0.7071067811865475 |
| 3 | 0 |
| 4 | 0.7071067811865475 |
| 5 | 0.7071067811865475 |
| 6 | 0.7071067811865475 |
| 7 | 0.7071067811865475 |
| 8 | 1.414213562373095 |
probabilities
B=1 × Query=3 × Key=3 · float64 · display precision 8 · Allowed-key stable softmax along the key axis only. Forbidden keys have exactly zero; allowed exponential underflow is separately possible.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0.3302384506733431 |
| 4 | 0.6697615493266569 |
| 5 | 0 |
| 6 | 0.2482550782577231 |
| 7 | 0.2482550782577231 |
| 8 | 0.5034898434845538 |
At the causal default the allowed rows are [true,false,false], [true,true,false], [true,true,true]. With a=1/sqrt(2) and r=exp(a), probability rows are [1,0,0], [1/(1+r),r/(1+r),0], [1/(2+r),1/(2+r),r/(2+r)]. Select each query to inspect every subtraction, exponential, denominator and division.
Compare all four mask modes, toggle key validity and try shifts ±10000. Validity is checked even when the chosen mode ignores it. Only active keys are normalized. No value vectors are mixed yet. Causal probabilities exclude future keys when earlier input embeddings and projection weights are fixed; they cannot undo future information already mixed into those earlier inputs by another operation.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Reset uses the same identity projections and three input rows, a causal mask, all three key-validity flags set to one, and common score shift zero. Inspect the Boolean allowed table alongside the probability table. A forbidden key has probability exactly zero and remains identifiable as forbidden independently of its color or number.
Change the mask mode before editing the matrices. Then try turning one key-validity flag off in a padding mode. Finally add a common shift of +10000 or −10000. Compare the row maximum, subtracted logits, exponent terms and denominator. Restore reset before doing the worked example below. The arithmetic comes from the current result; this chapter still stops before combining the value vectors.
Axes and four allowed-key rules
B counts batches, T active positions, Dk query/key features and Dv value features. The input width is two. A score cell belongs to batch b, query position i and key position j, with zero-based indices. Scores, allowed flags, logits and probabilities each have shape [B,T,T] and axes B,Query,Key. Softmax will run along Key, separately for every batch/query row.
A mask is a rule for permitting or forbidding individual pairs. Here a true Boolean allowed flag permits a key; false forbids it. The four mode codes are:
| Code | Mode | Key j is allowed for query i when… |
|---|---|---|
| 0 | Bidirectional / all keys | every active key is allowed |
| 1 | Causal | j is at most i |
| 2 | Padding only | key-validity flag j equals one |
| 3 | Causal and padding | j is at most i, and flag j equals one |
Causal means a query can use its own position and earlier positions, including equality in . Padding means a position is present in storage but declared invalid as a key for this computation. Mode 3 takes the intersection of the two conditions; passing either condition alone is insufficient.
The three flags valid0, valid1 and valid2 are shared across batches deliberately. They mask keys only. Turning valid1 off does not delete query row one, shorten T, or remove the input from projection. Modes 0 and 1 ignore those flags when constructing allowed pairs, although every flag is still validated as exactly zero or one. There is no inferred padding rule based on a zero embedding.
At reset, allowed rows are [true,false,false], [true,true,false] and [true,true,true]. In compact form these are 100, 110 and 111. A causal mask is about positions, not score size: a forbidden future key stays forbidden even if it has the row’s highest score.
Softmax turns differences into ratios
For a particular row, write for key j’s score. A logit is an input number to softmax; it may be signed and need not be bounded by one. Here the logits are , where c is the common shift control. Logits are calculated for every active key, including forbidden ones, but forbidden keys do not enter normalization.
The exponential function raises the constant e to a real power. It maps every finite real number to a positive real number, with and . The ideal probability of an allowed key is
The index k runs over allowed keys in this row. Forbidden keys have by the mask rule. Every allowed numerator appears in the denominator, so the allowed probabilities sum to one in real arithmetic. For two allowed keys j and k,
Thus equal allowed logits receive equal probabilities; a larger logit receives a larger probability. The denominator makes these weights relative to the other allowed choices. Removing an allowed competitor can change surviving probabilities even when their scores are unchanged.
Computing the exponentials of large positive logits directly can overflow a machine number. Large negative logits can all exponentiate to machine zero. Either failure can spoil the division, despite perfectly well-defined real ratios. We can cancel a shared exponential factor before asking the machine to form it.
Derive the maximum subtraction
Let , the maximum over this row’s allowed logits. Multiply numerator and denominator by :
For each allowed j, define its shifted logit and exponential term . Every such is at most zero, and at least one is zero. Consequently each real term is at most one, at least one term is one, and the denominator is at least one and at most the number of allowed keys. The lab sums terms in ascending key order and divides each term by d.
A forbidden key contributes term zero and probability zero. It has no shifted-logit entry in the trace: a fabricated shifted zero would imply an exponential of one and misdescribe the mask. The allowed flags, finite logits, row maximum, actual shifted entries, terms and probabilities are separately inspectable. No numeric infinity is needed as a mask sentinel.
Work through the reset rows completely
Let and . IV-23 gives score rows , and . With shift c=0, the logits equal those scores.
For query zero, only key zero is allowed. Its maximum is , subtraction is , and allowed term is . The complete term row is , denominator , and divisions give . The two forbidden scores cannot affect that denominator.
For query one, keys zero and one are allowed. Their maximum is a. The allowed subtractions are and . Because , the term row is and
The three divisions give
The simplified fractions describe the same real ratios; the implementation forms the exponent terms, adds them, then divides in its declared floating-point order.
For query two, every key is allowed. Write out every step:
The complete default probability matrix is therefore
The third row’s first two weights are equal because their scores are equal. Their shared denominator includes all three allowed terms. No averaging across query rows occurs.
A missing choice is not a uniform choice
With causal-and-padding mode, turn valid0 off. Query zero has no allowed key, regardless of the other flags: the future keys remain forbidden. The maximum over allowed keys is undefined and there is no positive denominator to normalize. The entire result becomes unavailable with reason FULLY_MASKED_ROW, identifying the offending batch/query. It does not return a mixture of apparently valid rows and a fabricated empty row.
Returning zeros would give a row sum of zero. Returning a uniform distribution would assign mass to forbidden keys. Both would misrepresent the requested operation. All flags zero in padding-only mode is another invalid example. By contrast, all flags zero in causal mode still leaves the causal allowed rows intact because that mode ignores padding flags.
An all-zero query vector is a different case. It gives equal zero scores to all keys. If n keys are allowed, maximum subtraction gives n terms of one and each allowed probability . Under default causal mode, a zero query at position one has two allowed keys and probabilities . Valid uniformity follows equal allowed scores; it is not a repair for an empty allowed set.
Common shifts, rounding and two meanings of zero
In real arithmetic, adding any common finite c cancels:
This explains the shift control. It adds the same scalar to scores before the allowed maximum is taken; it is not a learned bias, a position-specific preference, or a mask sentinel. At c=+10000 or −10000, stable subtraction avoids directly exponentiating those enormous-magnitude logits.
Binary64 stores a finite set of numbers. Adding a large common shift can round small score differences before subtraction. Subtracting the maximum cannot recover information already rounded away. Thus shifted and unshifted probabilities may differ slightly in stored arithmetic even though real softmax is shift invariant. A row sum may likewise differ slightly from one. Comparisons should account for the shifted logits’ magnitude; bit-for-bit equality with an unshifted real expression is not promised.
There is another boundary: an allowed shifted logit can be so negative that its exponential underflows, rounding to zero. Score differences of roughly 745 or more in magnitude can reach this region, and the permitted inputs can create such differences. The real exponential is still positive. Stable softmax protects the denominator through a maximum term of one, but cannot represent every tiny real tail.
Therefore a numeric zero alone does not prove masking. A forbidden flag with probability zero is an exact structural exclusion. A true allowed flag with stored probability zero can instead be numerical underflow. Read the Boolean table, trace and annotations together. The heatmap uses actual probabilities; its table provides the same numbers without requiring color perception.
What causal isolation actually guarantees
With earlier input embeddings and projection weights fixed, changing a future position cannot affect an earlier query’s allowed projections, allowed scores or probabilities in this mechanism. The future score may change in the full score table, but its forbidden key still contributes zero to that earlier normalization. Merely inspecting a future score is different from using it in the probability denominator.
This statement assumes no preceding operation has already mixed future information into the earlier embeddings. It also keeps the weights fixed. Causal masking at this layer cannot undo leakage introduced upstream, and changing shared projection weights can change earlier results. A causal attention map alone is not proof that an entire model or data pipeline is causal.
Read the actual reference files
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.
"""IV24: causal/padding key masks and stable rowwise softmax.
Mode 0 permits all keys, 1 is causal, 2 masks invalid keys, 3 combines both.
The validity bits are shared across batches and never delete queries.
With a=1/sqrt(2), r=exp(a), default causal probabilities have rows
[1,0,0], [1/(1+r),r/(1+r),0], [1/(2+r),1/(2+r),r/(2+r)].
These are real-arithmetic identities, not binary64 exactness promises.
IV25 will add weighted value mixing; no output O is computed here.
"""
from types import MappingProxyType
from attention_reference import ATTENTION_DEFAULTS, attention_trace, guarded, normalize, project, run, score, validated_state
DEFAULT_IV24 = MappingProxyType(dict(ATTENTION_DEFAULTS))
@guarded
def derive_iv24(state):
"""Trace masks and probabilities; any fully masked row makes all unavailable."""
s = validated_state(state, attention=True)
trace = attention_trace()
projection = project(s, trace)
scored = score(s, projection, trace)
normalized = normalize(s, scored, 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"])
return trace.result(summary, [*projection["tensors"], *scored["tensors"], *normalized["tensors"]])
if __name__ == "__main__":
run(derive_iv24, DEFAULT_IV24)
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 chapter source composes projections, scores and normalization. In the helper, follow the allowed predicate before the row maximum, then the allowed shifted entries, all key terms, denominator and probabilities. The row trace’s allowed inputs use numeric zero/one for finite scalar records; the allowed tensor exposes Boolean values. Both encode the same predicate.
The full state adds mode, three flags and shift to IV-22’s twenty-eight fields. Shift must be finite in , and inactive flags remain validated. The V projection is present for continuity, but IV-24 does not multiply P by V.
Five exercises matched to the lab
- What does a true entry in the allowed mask mean? That key may contribute to that query. Padding removes key columns from the allowed set but retains query rows, and its validity flags are shared across batches. Causal mode additionally requires . True does not mean probability one: the score and all other allowed keys determine the eventual weight.
- Reset to the causal default. With a=1/sqrt(2) and r=exp(a), what is query row 1 over keys [0,1,2]? It is . The scores are , but key two is forbidden. Subtract the allowed maximum a to obtain for keys zero and one, giving terms and denominator . Dividing yields the stated ratios. Equal halves would ignore the unequal allowed scores; would discard a positive allowed term.
- Read the current batch 0, query 0 row. What is the denominator of its displayed terms? Start at zero and add
term0throughterm(T-1)in ascending key order from tracerow_0_0. The result is that step’sdenominator, also exposed asrow_0_0_denominator. At reset the arithmetic is . After mask or score edits, use the actual current terms, including exact zeros for forbidden keys. At least one allowed maximum contributes , so the denominator is at least one. An allowed term can also underflow to zero; its Boolean flag distinguishes that cause from masking. - Keep scores and mask fixed, then add a common shift of +10000. Which statement is correct? Real probabilities are unchanged, while binary64 results can differ slightly. In real arithmetic , with both maxima over allowed keys, so exponential ratios agree. Stored additions and subtractions round and may lose low bits. Probabilities do not increase by 10000, and a shared translation is neither a learned per-key bias nor a mask sentinel.
- Transfer: choose causal + padding mode, T=3, valid0=0 and valid1=valid2=1. What happens? The entire result is unavailable with
FULLY_MASKED_ROW, identifying batch zero, query zero. Causality permits query zero only key zero, and padding forbids that key, leaving no maximum or denominator. Later queries having valid keys cannot repair this row. Zeros would not sum to one, and uniform weights would use forbidden keys. Restore valid0, use causal mode to ignore padding flags, or choose padding-only mode with another active valid key to define a different, valid calculation.
Recap and bridge
A mask specifies allowed query–key pairs. Stable softmax subtracts each row’s allowed maximum, exponentiates allowed differences, sums along Key and divides. Forbidden probabilities are exactly zero; a fully forbidden row is unavailable. Real shift invariance, floating-point roundoff and allowed exponential underflow are distinct facts.
Next, IV-25 — Self-Attention: Complete Numerical Trace uses these probabilities to weight the value rows and completes the self-attention calculation.