Self-Attention in Matrix Form
Matrix notation computes all query positions together, with query rows and readable key-value columns kept explicit. Apply the causal mask before stable row-wise softmax, then distinguish scores, weights, values, and vector contributions.
Matrix notation computes every query position at once. It is compact, but only if we keep the two position axes distinct: rows are queries, and columns are keys whose values may be read.
For one sequence,
The score matrix is
Entry compares query with key . The transpose is what turns from into , so the inner axes contract.
Mask Before Normalizing
For causal self-attention, define
Then normalize across the final, key-position axis:
Every row of sums to 1 over its allowed columns. Future columns receive exactly zero weight. Masking after softmax and simply setting entries to zero would reduce the row sum; the remaining entries would no longer be the same normalized distribution.
In code, a finite minimum value is often used instead of literal . The required behavior is the same: forbidden entries must contribute zero after softmax, and every allowed row must remain finite and normalized.
Extend the Four-Token Trace
The Language Modeling trace used
and
For the final position, the scaled scores were approximately
the weights were
and the weighted value reading was
This chapter treats that calculation as verified prior work. The matrix form performs the same steps for all four rows and produces .
Keep Four Quantities Separate
For one pair of positions :
- is an unnormalized compatibility score.
- is the row-normalized attention weight.
- is the value vector at source position .
- is that source position's vector contribution to .
A large score need not imply a weight near 1 if other scores are similar. A large weight need not imply a large contribution if the value is small. A large contribution in may later be changed or cancelled by the output projection and other parts of the network.
Q1. Identify the softmax axis
A score tensor for one batch has shape . Row 3 belongs to one query, and its five columns refer to key positions. Along which axis must softmax operate?
Select one choice, then check.
Hint
Solution
Audit the Equations in Dependency Order
Check shapes and values in the same order as the computation: projections, scores, mask, softmax row sums, forbidden zeroes, then weighted values. Looking only at the final matrix makes an earlier axis or mask error much harder to locate.