Audit a Single-Head Self-Attention Layer
Audit self-attention in dependency order instead of trusting a plausible final tensor. An executable trace checks projections, scores, masks, softmax rows, forbidden weights, weighted values, output width, finite values, and common axis failures.
An implementation is easiest to trust when it reports the same intermediate objects as the equations. A final output with the expected shape is not enough: the wrong softmax axis or a late mask can still produce a finite tensor.
The audit order is
At each arrow, check both shape and meaning.
State the Contract Before the Code
This implementation uses one sequence rather than a batch so every matrix can be printed. It accepts
It must return . Its causal weight matrix must be finite, have row sums near 1, and contain exact zeroes above the diagonal.
Audit one causal self-attention layer
Run the verified trace, then change one parameter. The checks expose incompatible shapes, non-finite values, invalid row sums, and forbidden future weights.
Ready to run.
The expected final rows are approximately
Small rounding differences are normal. A different shape, a nonzero future weight, or a large numerical difference is not.
Five Failures and Their First Checks
| Symptom | Likely error | First local check |
|---|---|---|
| score shape is | position and feature axes were swapped | inspect Q and the transpose of K |
| columns sum to 1 instead of rows | softmax used the query axis | print row sums and column sums |
| future entries remain positive | mask was omitted or applied late | inspect masked scores before softmax |
| output width is | output projection is missing or reversed | check |
| NaN or infinity appears | unsafe softmax, invalid inputs, or empty allowed row | find the first non-finite intermediate |
The first non-finite or semantically wrong intermediate is usually more useful than the final exception. Debugging backward from can hide the earliest failure behind several valid matrix operations.
Repair a Wrong Softmax Axis
Suppose a program has a score matrix but normalizes each column. Every key column then distributes weight across different queries. That is not the intended operation: queries do not compete with one another for a key. Each query needs its own distribution over readable key-value positions, so the final axis must be normalized.
Q1. Diagnose a misleading success
An implementation returns a finite tensor with shape , but each column of its attention matrix sums to 1 and most rows do not. What is the most direct repair?
Select one choice, then check.
Hint
Solution
Preserve an Evidence Record
A useful attention audit records shapes, masks, row sums, forbidden weights, and selected numerical rows. It also separates observations from interpretations. “Weight 0.54 was assigned to position 4” is an observation; “position 4 caused the prediction” requires an intervention and evidence from the rest of the model.