The neural notebook
← All chapters

IV-23 / Part V · Self-Attention

Dot-Product Attention Scores and Scaling

Expand all query–key dot products, derive their key-width scaling, and distinguish signed attention scores from probabilities.

Review the ideas this chapter uses

We have three representations of each position, but no rule yet for comparing positions. A query–key dot product supplies one number for each possible pair. Multiplying corresponding features and adding lets positive contributions reinforce one another and opposite-signed contributions cancel. We will inspect these contributions before dividing by a feature-width scale.

Learning objective: Compute each query-key dot product and its 1/sqrt(d_k) scaling.

The prerequisites are IV-22 — Queries, Keys and Values as Projections for the projected Q and K arrays and II.4 — Dot product, angle, and orthogonality for the dot product. Keep the distinction between a position and a feature close at hand: this lesson compares positions by summing over their features.

Follow one query across the keys

Compute it yourself

Inspect every dot product and its feature-width scaling

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

Outputs

B
1
T
3
D
2
Dk
2
Dv
2

Token rows → separate projections → query–key scores

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. Inspect the separate Q, K and V results below. 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
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
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

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

Reset gives raw rows [[1,0,1],[0,1,1],[1,1,2]] and every scaled entry is its raw value divided by sqrt(2). Select query 2 to inspect the two separate feature products behind each comparison. Choose another batch to inspect its own keys; batches never compare with one another.

Try Dk=1, load the nonsymmetric example, make two key rows identical by editing X, or set a query to zero with suitable inputs. Negative scores are valid. Changing Dv or WV does not change scores when X, WQ, WK and Dk stay fixed. Scaling controls magnitude; IV-24 adds masks and probability normalization.

Check your understanding

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

1. What does one query-key dot product compute?
2. With T=3, Dk=2 and Dv=1, what divides each raw score?
3. For current batch 0, query 0, key 0, raw=1 and divisor=1.4142135623730951. What is the scaled score?
4. Suppose two active key rows in the same batch are identical. For a fixed query, what must happen before masking?
5. Counterexample: one query row is all zeros but the keys are nonzero. What are its scores?

Reset uses the same three rows and identity projections as IV-22, with B=1, T=3 and Dk=Dv=2. Inspect a query row and its comparison with every active key. For each cell, read both feature products, their raw sum and the scaling divisor. Compare the raw and scaled tensors rather than treating either as an attention probability.

Try changing a query weight, then a key weight, then a value weight. The first two can change the comparisons; the third does not enter any score. Also try Dk=1. That edit changes both the number of dot-product terms and the divisor, so it is a different scoring calculation rather than a display zoom.

Which row compares with which column?

Write qb,i,f=Q[b,i,f]q_{b,i,f}=Q[b,i,f] and kb,j,f=K[b,j,f]k_{b,j,f}=K[b,j,f]. Lowercase q and k name individual coordinates of the projected tensors. b selects a batch, i a query position, j a key position, and f a query/key feature. Every index starts at zero. The widths Dk and Dv count query/key and value features respectively; D=2 remains the input width.

The raw score R[b,i,j]R[b,i,j] is

R[b,i,j]=∑f=0Dk−1qb,i,fkb,j,f.R[b,i,j]=\sum_{f=0}^{Dk-1}q_{b,i,f}k_{b,j,f}.

The summation sign means add the feature products for all active f. At Dk=2 the implementation first forms q0k0q_0k_0, then q1k1q_1k_1, then their sum. Subscripts 0 and 1 here abbreviate features of the currently chosen pair, not two different positions.

The scaled score is

S[b,i,j]=R[b,i,j]Dk.S[b,i,j]=\frac{R[b,i,j]}{\sqrt{Dk}}.

The square root Dk\sqrt{Dk} is the positive number whose square equals Dk. Since Dk is either one or two, the divisor is positive and never zero. Both R and S have shape [B,T,T], with axes B,Query,Key. Equal sizes of the last two axes do not make their meanings interchangeable.

In matrix notation, within one batch, R=QKTR=QK^{\mathsf T}. Q has shape [T,Dk], and transposing K changes [T,Dk] to [Dk,T]. Their matching Dk dimensions are summed out, leaving query rows and key columns. The transpose symbol T\mathsf T exchanges axes; the unsuperscripted T still counts positions. Multiplying KQTKQ^{\mathsf T} would reverse the pair roles.

Expand all nine reset comparisons

At reset, both Q and K have rows (1,0)(1,0), (0,1)(0,1) and (1,1)(1,1). The first query compares with all three keys:

R[0,0,0]=1(1)+0(0)=1+0=1,R[0,0,1]=1(0)+0(1)=0+0=0,R[0,0,2]=1(1)+0(1)=1+0=1.\begin{aligned} R[0,0,0]&=1(1)+0(0)=1+0=1,\\ R[0,0,1]&=1(0)+0(1)=0+0=0,\\ R[0,0,2]&=1(1)+0(1)=1+0=1. \end{aligned}

The second query gives

R[0,1,0]=0(1)+1(0)=0+0=0,R[0,1,1]=0(0)+1(1)=0+1=1,R[0,1,2]=0(1)+1(1)=0+1=1.\begin{aligned} R[0,1,0]&=0(1)+1(0)=0+0=0,\\ R[0,1,1]&=0(0)+1(1)=0+1=1,\\ R[0,1,2]&=0(1)+1(1)=0+1=1. \end{aligned}

The third query gives

R[0,2,0]=1(1)+1(0)=1+0=1,R[0,2,1]=1(0)+1(1)=0+1=1,R[0,2,2]=1(1)+1(1)=1+1=2.\begin{aligned} R[0,2,0]&=1(1)+1(0)=1+0=1,\\ R[0,2,1]&=1(0)+1(1)=0+1=1,\\ R[0,2,2]&=1(1)+1(1)=1+1=2. \end{aligned}

Therefore the complete raw and scaled matrices are

R=[101011112],S=[1/20/21/20/21/21/21/21/22/2].R=\begin{bmatrix}1&0&1\\0&1&1\\1&1&2\end{bmatrix},\qquad S=\begin{bmatrix} 1/\sqrt2&0/\sqrt2&1/\sqrt2\\ 0/\sqrt2&1/\sqrt2&1/\sqrt2\\ 1/\sqrt2&1/\sqrt2&2/\sqrt2 \end{bmatrix}.

Let a=1/2a=1/\sqrt2. Then the score rows are (a,0,a)(a,0,a), (0,a,a)(0,a,a) and (a,a,2a)(a,a,2a). These are exact real expressions; the inspector stores finite binary64 approximations to the square-root divisions. Binary64, also called double precision, represents real values with a limited number of binary digits. The third raw self-comparison is two because two feature products contribute one each. There are three keys, but three is not the divisor.

Why this dot product, and what it does not measure

For a fixed query, the score is a weighted sum of key coordinates, with query coordinates supplying the weights. A query feature equal to zero removes that feature’s contribution. A negative query feature reverses the sign of its corresponding key contribution. This is one precise sense in which a dot product measures feature agreement.

It is not a universal semantic similarity measure. Larger vector lengths can increase a dot product even when the directions match equally well. At reset, the third row’s dot product with itself is two, whereas the first row’s self-dot product is one. That difference does not prove the third position is more meaningful. A cosine comparison would additionally divide by vector lengths; this lab does not do that.

Opposite-signed features provide a counterexample to “all scores must be positive.” For q=(1,−1)q=(1,-1) and k=(1,2)k=(1,2), the products are 1(1)=11(1)=1 and (−1)(2)=−2(-1)(2)=-2, giving R=−1R=-1 and S=−1/2S=-1/\sqrt2. Negative results are valid comparisons, not invalid probabilities needing clipping. A zero query gives zero against every key, however large those keys are.

Identical key rows produce identical scores for a fixed query. The scoring operation cannot distinguish those keys by their positions alone. This lesson has no added positional representation. If you change the order of key rows, the corresponding score columns move with them; the dot-product rule does not secretly assign a position preference.

Why divide by the key-feature width’s square root?

Adding many feature contributions can increase the spread of raw scores. In the next lesson, exponentiation will turn score differences into ratios. Very large differences can concentrate nearly all probability on one allowed key and reduce sensitivity to other candidates. The scaling factor moderates this width effect before that nonlinear operation.

A useful derivation needs explicit assumptions. Suppose the products uf=qfkfu_f=q_fk_f each have mean zero and variance one, and different feature products have zero covariance. Mean is the average across an assumed distribution; variance measures average squared deviation from that mean; zero covariance means the paired deviations do not systematically reinforce each other. Then the variance of their sum is

Var⁡ ⁣(∑fuf)=∑fVar⁡(uf)=Dk.\operatorname{Var}\!\left(\sum_f u_f\right)=\sum_f\operatorname{Var}(u_f)=Dk.

Dividing the sum by Dk\sqrt{Dk} divides its variance by Dk, producing variance one under those assumptions. One sufficient idealization is independent, zero-mean, unit-variance query and key coordinates across features and between the two vectors. Actual self-attention projections can be correlated and have different scales. The displayed hand-set inputs are not a random sample promised to satisfy these assumptions.

Thus scaling is a design choice motivated by a conditional statistical argument, not a theorem that every raw attention row has variance Dk. It does not force vector lengths to one, bound scores to [−1,1][-1,1], or make a row sum to one. It divides every score by the same positive width-based divisor and therefore preserves their ordering in real arithmetic.

Test the axes with a nonsymmetric case

Enter IV-22’s nonsymmetric matrices, keeping both feature widths two. They produce Q rows (1,2),(0,1),(1,3)(1,2),(0,1),(1,3) and K rows (0,1),(1,0),(1,1)(0,1),(1,0),(1,1). For example,

R[0,0,1]=1(1)+2(0)=1,R[0,1,0]=0(0)+1(1)=1,R[0,0,1]=1(1)+2(0)=1,\qquad R[0,1,0]=0(0)+1(1)=1,

Other comparisons give

R[0,0,2]=1(1)+2(1)=3,R[0,2,0]=1(0)+3(1)=3.R[0,0,2]=1(1)+2(1)=3,\qquad R[0,2,0]=1(0)+3(1)=3.

Those pairs happen to agree; inspect the whole matrix before assuming symmetry:

R=[213101314].R=\begin{bmatrix}2&1&3\\1&0&1\\3&1&4\end{bmatrix}.

Even this particular nonsymmetric-projection example yields a symmetric raw matrix. It is therefore not, by itself, a counterexample to score symmetry. To expose the general failure, reset WK to identity while retaining this WQ. Now the raw first-row/second-column entry is 1(0)+2(1)=21(0)+2(1)=2, while the second-row/first-column entry is 0(1)+1(0)=00(1)+1(0)=0. Distinct query and key maps permit asymmetric scores even when the number of query and key positions matches.

Width, batching and valid inputs

With reset projections and Dk=1, Q and K retain their first output feature: the position coordinates are 1,0,11,0,1. The raw matrix becomes [[1,0,1],[0,0,0],[1,0,1]][[1,0,1],[0,0,0],[1,0,1]], and division by 1=1\sqrt1=1 changes nothing. Dropping a query/key feature can remove a contribution; it does not merely alter the divisor.

Changing Dv affects V’s shape, but neither the feature products nor their divisor uses Dv. Changing T changes how many pairs are calculated, not how many features contribute to each pair. B=2 calculates two separate [T,T] matrices with no cross-batch comparisons. These distinctions are why the tensor inspector names axes as well as listing sizes.

The base state’s twenty-eight fields and bounds remain those of IV-22. Every input and weight slot is validated even when its batch, position or output column is inactive. Invalid widths, missing fields and nonfinite values make the result unavailable. Valid scores remain signed and unnormalized. No mask or softmax is applied in IV-23.

Read the canonical program

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.

"""IV23: explicit feature products, query-key sums and sqrt(Dk) scaling.

With the default identity projections, raw rows are [1,0,1], [0,1,1],
[1,1,2]. Scores divide those values by sqrt(2). Scores may be negative
and need not sum to one; this lesson deliberately performs no softmax.
"""
from types import MappingProxyType
from attention_reference import PROJECTION_DEFAULTS, attention_trace, guarded, project, run, score, validated_state

DEFAULT_IV23 = MappingProxyType(dict(PROJECTION_DEFAULTS))


@guarded
def derive_iv23(state):
    """Trace the active projections and every scaled query-key dot product."""
    s = validated_state(state, attention=False)
    trace = attention_trace()
    projection = project(s, trace)
    scored = score(s, projection, trace)
    summary = dict(B=s["B"], T=s["T"], Dk=s["Dk"], Dv=s["Dv"])
    summary.update(projection["aliases"])
    summary.update(scored["aliases"])
    return trace.result(summary, [*projection["tensors"], *scored["tensors"]])


if __name__ == "__main__":
    run(derive_iv23, DEFAULT_IV23)
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 composes projection and scoring. In the helper, follow the feature products to raw, then the division by divisor to score. Each score trace identifies b, i and j; a Dk=1 trace has one actual feature product rather than an invented second term. Raw and scaled tensors preserve the same batch/query/key orientation. The shown source is the actual implementation text.

Five exercises matched to the lab

  1. What does one query-key dot product compute? A sum of products of matching query/key features, before scaling. For two features, multiply q0k0q_0k_0 and q1k1q_1k_1, then add. Equal signs give nonnegative contributions and opposite signs give nonpositive ones; a zero factor gives zero. The result is neither a probability restricted to [0,1][0,1] nor a sum of value-vector coordinates. No softmax is applied here.
  2. With T=3, Dk=2 and Dv=1, what divides each raw score? 2\sqrt2, because Dk counts the two features contributing to the dot product. Three counts positions, so 3\sqrt3 would use the wrong axis; one counts value features, so using one would confuse the value path with scoring. The conditional variance argument motivates this width scale without claiming all dot-product variances must equal Dk.
  3. For current batch 0, query 0, key 0, what is the scaled score? Read raw and divisor from score_0_0_0, then divide: score000 = raw000/sqrt(Dk). At Dk=2, the raw sum is q000*k000 + q001*k001; at Dk=1, it is just q000*k000. Reset therefore gives (1(1)+0(0))/2=(1+0)/2=1/2(1(1)+0(0))/\sqrt2=(1+0)/\sqrt2=1/\sqrt2. Use the current stored products after editing; neither the reset answer nor a row-normalization sum replaces that division.
  4. Two active key rows in the same batch are identical. For a fixed query, what must happen before masking? They receive equal raw and scaled scores, even if their value rows differ. Every corresponding feature product is the same, as are the sum and divisor. Token indices add no extra score here, and values do not enter scoring. Equal scores need not be 1/21/2; later masking can also permit one of these positions and forbid the other.
  5. Counterexample: a query row is all zeros but the keys are nonzero. What are its scores? Every raw and scaled score is zero: each product is 0kf=00k_f=0, their sum is zero, and the positive divisor leaves it zero. This is not automatically a uniform probability distribution. IV-24 will normalize over whichever keys are allowed; IV-23 stops at the zero score row.

Recap and bridge

Each cell compares one query row with one key row by summing feature products. The scale uses Dk, not sequence length or value width. Signed scores describe comparisons and remain distinct from probabilities. Symmetry at reset follows the chosen projections and is not a general attention requirement.

Next, IV-24 — Masking and Numerically Stable Softmax declares which keys are allowed for each query and converts only those scores into stable, rowwise probabilities.