16 / 28 · Transformers
Self-Attention
Derive content-dependent attention, follow every Q/K/V gradient, and test masking, scaling and permutation claims on explicit reproducible arrays.
On this page 15
A return message mentions a lamp, its battery and a charging station. A useful representation of battery should depend on which object owns it and what happened to that object. Static lookup returns the same row every time. The attention mechanism already used in sequence-to-sequence models provides a way to retrieve other states. We can apply that retrieval at every position of the same sequence.
A token needs information from its neighbours#
Suppose the input is a sequence of token vectors. Each vector initially contains whatever the embedding and input preparation supply. A contextual layer must transmit information between positions before a token-level decision is made. Giving the classifier more parameters does not create that communication if it receives only one isolated lookup row.
The desired connection can depend on content. A fixed local window always covers the same offsets, while the relevant object may be farther away. An attention layer calculates a different distribution of source positions for each receiving position. It therefore needs both a rule for deciding where to read and representations containing what can be read.
From a recurrent state to direct connections#
A recurrent model moves information through successive state updates. Attention over those states adds direct retrieval, but the states themselves still require the recurrence. Self-attention instead obtains its queries, keys and values from one sequence of input states. Every output can be calculated from the previous layer’s complete input, so the positions of that layer need not be updated sequentially.
This changes the dependency graph within a layer. It does not make autoregressive generation parallel: an unknown next token still depends on tokens not yet generated. It also creates many pairwise comparisons. The shorter path between two positions comes with a different memory and computation cost.
Queries select what values contribute#
Think of a query as the representation used to select information, a key as the representation used to offer a match, and a value as the representation transmitted after selection. These are learned numerical roles. A query need not contain a literal question, and a key is not a database identifier.
For receiving position , the nonnegative weights sum to one across its allowed source positions. The output is
Thus one head’s output lies in the convex hull of its allowed value vectors. This statement concerns the vectors after the value projection. It does not restrict a later output projection or residual sum to the convex hull of the original token embeddings. If all values are identical, changing the attention weights cannot change this output.
Project the input into three roles#
Let have rows and columns: one width- state per position. With row-vector conventions, define
The projection matrices have shapes , and . They are shared across positions. Biases can be added; we omit them in the following example so every number can be traced directly. Query and key widths must agree for their dot product. Value width can differ because it determines the transmitted payload.
A batched implementation adds a leading batch axis. It must keep that axis separate: tokens from one example must not become available keys for another. Padding to a shared length changes storage, not which positions belong to a real message.
Matching and transmission can learn different coordinates#
Separate query and key projections permit an asymmetric relation. Position can strongly request information from without making the same request in return. Before normalization, a score is a bilinear function of the two input vectors:
The middle matrix need not be symmetric. Even with tied query and key projections, row-wise normalization can produce asymmetric weights because different rows have different normalizers. A symmetric score matrix therefore does not imply a symmetric attention matrix.
The value projection serves another purpose. Features useful for recognizing a relevant position need not be the features its recipient should receive. Keeping these roles separate supplies flexibility, while the training objective must still provide evidence that makes this flexibility useful.
A score becomes a distribution#
A dot product combines coordinate agreement into one scalar and permits all scores to be computed by matrix multiplication. Its magnitude depends on both vector lengths and directions. It is generally different from cosine similarity; no division by the query and key norms is implied.
Softmax turns a row of scores into positive weights. Adding the same finite constant to every allowed score leaves the row unchanged because the common exponential factor cancels. Subtracting the largest allowed score before exponentiation uses this identity to avoid overflow. This numerical adjustment does not alter the intended probabilities.
The matrix calculation and its derivatives#
For an unmasked head, scaled dot-product attention is
The score and weight matrices are ; the output is . The scale and row normalization follow the mechanism of Vaswani et al.. The values and calculations below are independently specified.
We can follow the training signal through the same chain. Let . Differentiating the weighted sum gives
The last line follows from differentiating the softmax numerator and denominator. A row’s gradient subtracts the attention-weighted average of its upstream values. Increasing every score equally cannot change the output, so its score-gradient row sums to zero.
Writing that last derivative as , matrix multiplication gives
The three contributions to must be added. A token participates as a query, as a key and as a value. Retaining only the value path would train a different computation. Each projection gradient is obtained by multiplying the corresponding projected-state derivative by on the left.
A complete small forward pass#
Choose three two-coordinate input states and three projection matrices:
These coordinates are chosen inputs, not pretrained word vectors. The first query is (0.5, 0.75). Its dot products with the three keys, before scaling, are 0.375, −0.5625 and 1. Divide each by the square root of two and apply softmax. All rows are shown to make the calculation reproducible:
| Row | Attention weights | Output coordinates |
|---|---|---|
| 1 | 0.325619; 0.167807; 0.506574 | 0.790241; −0.409523 |
| 2 | 0.463363; 0.238793; 0.297844 | 0.701508; −0.582760 |
| 3 | 0.200964; 0.312645; 0.486390 | 0.609193; −0.357287 |
For the first output, the first coordinate is the weighted sum of 1, −0.25 and 1; its second coordinate combines −1, −0.5 and 0. The largest weight is not by itself the entire explanation of the output. Both the values and their signs matter.
To check backward propagation, prescribe target rows (0.2, −0.1), (0.4, 0.3) and (−0.2, 0.5) and use half the summed squared output error. Its value is 1.3520477800. Analytic derivatives for all six input coordinates and twelve projection weights agree with centered finite differences within 2.11e−10. Updating all eighteen numbers simultaneously with step size 0.02 reduces this constructed loss to 1.1096148900. This checks the local computation; it supplies no linguistic evaluation.
The scaling argument has assumptions#
Suppose corresponding query and key coordinates are independent, centered and have variance one, and products from different coordinates are uncorrelated. Each product then has variance one. Summing such products gives variance , so division by its square root produces variance one. Keeping score variation controlled can keep softmax away from extremely concentrated rows at initialization.
The assumptions matter. For width four, independently enumerating all sign-vector queries and keys gives dot-product variance four. If every query coordinate shares one sign and every key coordinate shares another, the dot product is always either four or minus four; its variance is sixteen. After the standard scaling, these variances become one and four. Learned vectors need not obey the independent-coordinate model. The scaling is a useful design choice, not a guarantee about every trained score distribution.
Masks define available information#
Let a Boolean mask specify which keys each query may use. Our convention is True for allowed. Excluded scores receive zero weight, and the remaining scores are renormalized. Filtering before exponentiation avoids giving a huge forbidden score any contribution. An entirely excluded row has no probability distribution; the reference calculation rejects it explicitly.
A causal mask allows position to read positions up to . With the chosen values above, the first output becomes exactly (1, −1), because only its own value is available. Replacing the third input by (−3, 4) leaves that first causal output unchanged while changing the first unmasked output. This direct perturbation tests the information boundary rather than merely checking that a mask array exists.
A padding-key mask prevents real queries from reading padding. It does not automatically remove outputs at padded query positions. Exclude those positions separately from pooling and the loss. For autoregressive prediction, a causal mask must be combined with a correctly shifted target input; otherwise the current target can already be present in its own allowed row.
Content-only attention is permutation-equivariant#
Without positions or an order-dependent mask, permuting the input rows permutes the output rows in the same way. Let be a permutation matrix. Projections commute with row permutation; scores become . Row-wise softmax permutes its rows and columns accordingly, so
The chosen permutation [2, 0, 1] reproduces the corresponding output permutation to floating-point precision. Averaging these outputs would erase that permutation completely. A fixed causal mask supplies an order-dependent relation and falls outside this unmasked claim. Positional representations add another source of order information; neither restriction should be omitted when stating equivariance.
Several heads can read different mixtures#
Each head has its own query, key and value projections. Concatenate their outputs and apply a shared output projection:
This retains several independently selected mixtures before combining them. Heads are not guaranteed to specialize into human-readable roles, and two heads can learn redundant behavior. Splitting a fixed total width across heads also reduces each head’s matching and value width. Increasing head count is therefore a structural change, not an automatic increase in all representational resources.
For the usual choice where the total projected width remains , four dense projections contain weights, independent of how that width is split. At width six with three width-two heads, that is 144 weights, plus 24 biases if all four projections use biases. This count excludes normalization, feed-forward layers and the rest of the model.
Count the operations and stored scores#
Projection work scales as under the usual width convention. Computing pairwise scores and applying them to values costs on the order of . Materializing all attention weights for batch size and heads requires scalar entries. With two examples, three heads and length five, this is 150 entries before gradients or other intermediate arrays.
An implementation may reorganize exact attention to avoid storing the full score matrix. That changes its memory traffic and intermediate storage; it does not make a fully connected dense computation require only a linear number of pair interactions. Sparse or local masks change which interactions are computed. Hardware, dtype and kernels determine measured runtime, so an operation count is not a latency measurement.
A weight map has a limited interpretation#
Our weight matrix comes from supplied projections. It visualizes the mechanism, not a discovered linguistic pattern. In a trained model, a large weight identifies an influential route for that head’s weighted sum, but the route also depends on its value vector and subsequent processing. Equal values can produce the same output under different weight distributions.
To investigate a proposed functional role, change the relevant inputs or connections and measure the effect on a specified output or task. Such interventions need their own controls: replacing a token can also alter its query, key and value paths. A visually appealing row of weights alone does not establish a causal explanation of the model’s final decision.
What changed#
The layer now lets every position retrieve from the same previous-layer sequence through a learned content-dependent relation. Information no longer has to traverse one recurrent update per intervening position inside this layer. A mask states the allowed relation, and a later architecture must combine the resulting mixtures with preserved input information and nonlinear transformations.
Limitations#
Soft averaging can merge distinct configurations. Finite widths and the objective determine which distinctions survive. Without appropriate positional or mask information, the layer has the permutation symmetry proved above. Dense pair interactions become expensive as length grows, and a poorly formed mask can expose a target that should be unavailable. None of these issues is resolved merely by naming the mechanism attention.
What to remember#
Queries and keys choose weights; values carry the information. Softmax normalizes each allowed row. Backpropagation reaches inputs through all three roles. Scaling relies on a variance argument with stated assumptions. Content-only unmasked attention is permutation-equivariant. Mask correctness is an information-flow property.
Notebook#
- The standalone constructed-case script records projections, scores, weights, outputs, all eighteen derivatives and a simultaneous update.
- It separately checks causal future-token invariance, invalid mask rejection, permutation behavior, two-head composition and the independent-versus-shared-coordinate variance example. Only Python’s standard library is required; no corpus or model is downloaded.
Next#
Attention supplies a mechanism for mixing positions. A stack also needs nonlinear transformations, a preserved residual route and a controlled activation scale. Transformer architecture combines these parts and distinguishes what each part contributes.
References#
- Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin. Attention Is All You Need. NeurIPS, 2017; version 7, 2023. Sections 3.2 and 4: scaled dot-product attention, multiple heads and dependency/complexity analysis. Scientific mechanism only; no source diagram, attention visualization, benchmark table or example is reproduced.