Lecture 4 — Attention
Project connection. Project Step 4 implements one causal self-attention head, turns the simplex, scaling, and causality results below into numerical tests, and visualizes attention matrices on real text and controlled positional kernels.
Chapter overview. The Step 3 MLP reads a fixed number of preceding tokens by concatenating their embeddings. Attention instead gives every position content-dependent access to all permitted positions. Queries and keys decide where to read, values determine what is returned, and softmax makes the result a convex average. We will calculate one head completely before studying its geometry. Causal masking restricts every average to the past, while positional information breaks an otherwise exact permutation symmetry. The final sections reinterpret the same operation as kernel smoothing and account for its quadratic cost.
0. Embeddings and Transformers
Recall that we work with a vocabulary of size , which we will enumerate for convenience. An embedding is a map from tokens to vectors:
The dimension is called the model width. The embedding matrix for the embedding is the matrix such that the embedding of the -th token is the -th row.
In a neural network, as we saw, we concatenated the embeddings of the tokens in the context. Then this longer vector was modified as it passed through each layer of the network, and finally results in an output that is interpreted as a probability distribution on the next token.
In a transformer architecture (the model we will study next, namely a decoder-only causal single-head transformer, to be defined formally shortly), the token positions in the context each have a residual stream, which is a vector initially computed as a function of two things: (1) the embedding of the token in that position, and (2) the position itself. At the -th position, this is called the residual stream at position . Each stream is modified at each layer of the network, until at the end, each stream is unembedded (we’ll define this later) and fed through softmax. These two operations form the language modelling head (although sometimes this terminology only refers to the first operation). The output of the language modelling head on the last stream is interpreted as the probability distribution on the next token. The picture is like this:
We need to examine what is happening in the puffy cloud. Inside the cloud there are several layers, or steps, to this process. These layers are grouped into transformer blocks that have a standardized layer structure, and are stacked up, each with its own parameters. So now our picture looks like this:
Inside one common transformer block style, we have, in order of execution: a layer norm, an attention layer, another layer norm and then a feedforward layer. The layer norms are layers that normalize vectors. The feedforward layer is a small feedforward neural network.
The most important layer is the attention layer. An attention layer can be multi-headed, but for now we will assume we have just one attention head (which we will describe formally in the next section). In the single-headed case, the attention layer looks like the following. A row vector in the -th stream is holding some type of “meaning” for the LLM. As mentioned above, the initial meaning of that vector is just a function of the embedding of the -th token and the integer (its position in the context). In this layer, the weights of the model dictate that the new value of the -th stream should be a function of itself and all the streams preceding it (i.e. corresponding to the -th token, where ). The form of this function is this:
for some matrices and . The matrices and are part of the parameters of the system, trained in some way. For now, observe that controls how much affects , and controls how we transform the resulting linear combination. The way that controls the interaction of one token with previous tokens is referred to as attention. When the pairing of two streams through is large, the earlier token has a large relative effect on the later one, and we say that the later token is attending strongly to the earlier one.
We call the attention output at position . It is added to to update the stream. This style of update (computing a vector to add to the existing stream) is called residual connection, and the stream is sometimes called the residual stream for this reason. The feedforward network’s output is also added into the stream; we will discuss this later.
For example, suppose we have a sentence “I picked up the pencil and ate it” tokenized in terms of words. An English speaker would say the word “it” refers to the pencil. At the beginning of the model’s process, the last stream holds the token “it”, and the integer , somehow coded into a vector in a high dimensional vector space. If is chosen well (trained well) then it may give a large scalar weight to “pencil”. At the same time, the transformation may transform vectors in some way so the meaning of the stream becomes something nuanced like “it, referring to pencil”. This is just an intuition for what’s going on, not a literal example, but it gives some flavour to how LLMs are working. Loosely, they are doing linear algebra on meaning (“representation”) vectors.
1. Presenting the context to the transformer
We now describe how a context, as a raw sequence of tokens, is formatted for the use of a transformer block.
As in the last section, let be a vocabulary of size , enumerated in some order. We have an embedding map
We typically take the output of to be a column vector. The embedding matrix for the embedding is the matrix such that the embedding of the -th token is the -th row transposed.
The map above allows us to embed information about which token we are considering as a vector in . We also wish to carry positional information: which position is the token occupying in the context. A system of additive positional vectors is a map
We should think of as carrying the information “we are at position ”. We treat as a column vector.
These two maps allow us to feed our context into a transformer block as a sequence of streams, as follows. Let be the length of the context, as a sequence of tokens . For each position , we create a vector of which contains information about the token and its position . This is
This represents the context as a matrix whose rows are , .
We refer to an element of as a residual stream, and the first step of the transformer is to initialize the residual stream to .
2. The transformer head
In the introductory material, we conflated the transformer layer with the attention head, in a single-head model. We will now define an attention head more precisely. In general, an attention head and transformer layer are not exactly the same, even in a single-head model.
Fix positive integers and (to be used as dimensions of vector spaces). Let
be matrices called the query, key, and value projections or projection matrices. These matrices are part of the parameters of the system, to be adjusted during training.
Definition 2.1 (query, key, and value matrices). Let represent the stream, and suppose query, key and value projection matrices , and are given. Define the query matrix, key matrix and value matrix (as distinct from the corresponding “projection matrices”) by
Define also the rows of these matrices, as column vectors:
Here the matrix of values is distinguished by context from the scalar .
When are all obtained from the same stream , the operation is called self-attention. In cross-attention, queries come from one stream and keys and values from another. This lecture studies self-attention.
For a matrix , row-wise softmax is defined by
Definition 2.2 (scaled dot-product attention). Define the score matrix, attention matrix, and attention output by
Entrywise,
Here denotes the column-vector form of output row . The index order matters:
Now the attention head can be described by the following diagram, illustrating the algorithm taking as input the stream , computing intermediate matrices and producing attention output .
With reference to our introduction, the key and query matrices determine , and is determined from the value matrix and a final operation that comes later.
The intuition is as follows. The product is comparing every pair . When the resulting row-column product (normalized, and called the score) is large, the residual vector at the query position will attend strongly to the residual vector at the key position, meaning the vector in the key position will strongly influence the vector in the query position during the transformer block algorithm. In other words, the score matrix tells the query vectors which key vectors to attend to.
The score matrix is row-wise softmaxed, as a type of normalization. Then the result , the attention matrix, is multiplied by the value matrix . Now we need to actually exert the influence the scores are indicating we should. You might think we simply add a multiple of the stream vector in a well-attended-to key position directly to the stream vector in the query position. Instead, we multiply by . The role of is to interpret a stream vector in some way (by a linear transformation) before it is added in to the stream vector in the query position.
In summary:
- is what position is looking for.
- is how position advertises itself.
- is the information position offers if selected.
Example 2.3 (one attention head, completely by hand). Let , , , and . Take
and let the three projections select coordinates as follows:
Then
Because , the scaling factor is . Every query is the same, so every score row is the same:
Exponentiating a row gives , and therefore
Writing the value rows as
each output row is
The score matrix has a useful rank restriction.
Proposition 2.4 (low-rank score factorization). The score matrix satisfies
Proof
The first identity follows from . Since factors through , the rank of the product is at most .
Remark 2.5 (nonlinearity). The map is generally nonlinear, thanks to the softmax. Applying a nonlinear function row by row can increase matrix rank. Low-dimensional query and key spaces therefore do not imply that is a low-rank matrix.
3. Attention as averaging
Attention scores may be positive or negative and have no fixed scale. After softmax, however, every row belongs to a familiar geometric object. Let
This is the standard -dimensional probability simplex. Its relative interior consists of the vectors with every coordinate strictly positive.
For a finite collection of vectors , their convex hull is
Proposition 3.1 (simplex and convex-hull property). For every ,
Consequently, every row lies in the simplex and
Proof
Every exponential is positive. Dividing by their positive sum gives
Thus the softmax vector lies in the relative interior of the simplex. By Definition 2.2,
and the coefficients are nonnegative and sum to one. This is a convex combination by definition.
The same statement has a probabilistic form. For each query position , let be a random source index with
Then
Attention is therefore literally an expectation of the value vector under a distribution selected by the query and keys.
Example 3.2 (the convex geometry of Example 2.3). The three values in our running example are
The attention row gives
Because the three values are affinely independent in and all three weights are positive, lies in the interior of their triangle.
Corollary 3.3 (no extrapolation from the values). For fixed value vectors, a single attention head cannot output a point outside their convex hull.
There are several useful scalar consequences. If , then
Taking the Euclidean norm and using the triangle inequality gives
More generally, Jensen’s inequality says that every convex satisfies
Remark 3.4 (scope of the corollary). The value projection can create new feature directions before averaging, and an output projection and residual addition can transform the result afterward. The corollary is the precise statement that the averaging step itself does not extrapolate beyond its current values. It is not a claim that a complete transformer remains inside the convex hull of its input token embeddings.
Corollary 3.5 (soft attention has full support). With finite, unmasked scores, for all . A one-hot attention row is approached only as score gaps tend to infinity.
The qualification “unmasked” matters. Causal masking will set forbidden coordinates exactly to zero, so a causal row lies in a lower-dimensional face of . Among its permitted coordinates, finite scores still give strictly positive weights.
Geometric aside 3.6. The attention row gives barycentric coordinates in the convex hull of the values. When the values are affinely independent, those coordinates are unique. When they are affinely dependent, different attention rows can produce the same output. Thus an attention pattern need not be recoverable from the output vector alone. The simplex picture separates the selection rule, encoded by and , from the information being averaged, encoded by .
4. Causal masking
There’s one important aspect we have so far ignored. For token prediction, we wish to train the model to predict later tokens from earlier ones. When the representation at position is used to predict the next token, it should depend on the tokens up through position but not on the later positions .
Right now, our score matrix can have non-zero entries in position where . In other words, stream vectors associated to later tokens in the context can contribute to earlier ones. The solution is causal masking, which happens inside the attention operator. Everything preceding this section described an unmasked transformer.
Definition 4.1 (causal mask). Given the unmasked score matrix , define extended-real masked scores by
The causal attention matrix is
using . Equivalently,
Thus is lower triangular, meaning whenever , and row-stochastic, meaning its entries are nonnegative and every row sums to one. Row lies in the face of the simplex supported on its first coordinates.
Example 4.2 (causally masking the running head). In Example 2.3, every unmasked score row was
Causal masking gives
Softmax now normalizes over a different prefix in each row:
Multiplying by the same value matrix gives
Position has no choice but to return . Position averages only and . Position has access to all three values and therefore reproduces the unmasked output. The mask changes neither the permitted scores nor the values; it changes the set over which softmax normalizes.
Proposition 4.3 (autoregressive well-definedness). For causal attention, is a function only of . Wherever the map is differentiated,
Proof
Row uses , the keys with , the values with , and a normalizing sum over . These quantities depend only on . None depends on for , so the output itself does not depend on . Its derivative with respect to that variable is therefore zero.
The convex-hull result also acquires a prefix form:
Implementation aside 4.4 (mask before softmax). Setting forbidden weights to zero after an unmasked softmax, without renormalizing, leaves the row sums below one and changes the derivatives; masking the scores to before softmax normalizes over exactly the allowed positions. Numerical implementations use negative infinity or, when required by a numerical format, a sufficiently large negative number.
Remark 4.5 (parallel training). In teacher-forced training, the full token sequence is available to the computer, and losses for all positions can be computed in one forward pass. Inputs and targets are shifted: the representation after token predicts . Allowing position to attend to itself therefore reveals , not the target . The causal mask proves that no position uses a future target, so parallel training is consistent with left-to-right generation.
5. Log-sum-exp, temperature, and score scaling
Every row of attention applies softmax to a vector of scores. We now study that map as a mathematical object. Define the log-sum-exp function by
For a probability vector , let denote the diagonal matrix with diagonal , and let . A symmetric matrix is positive semidefinite if
for every vector . The Hessian of a twice differentiable scalar function is the matrix of its second partial derivatives.
Proposition 5.1 (differential geometry of log-sum-exp). If , then
The Hessian is positive semidefinite, with nullspace . Hence log-sum-exp is convex on and strictly convex on .
Proof
Direct differentiation gives
Differentiating once more,
which is the entry of . For any ,
Because for every , this variance is zero exactly when all are equal. The nullspace is therefore . Positive semidefiniteness of the Hessian gives convexity, and its positive definiteness on gives strict convexity there.
The calculation simultaneously gives the Jacobian of softmax:
In coordinates, a perturbation changes probability to first order by
Only the centered part of matters. Indeed,
The common-shift direction is exactly the null direction found in Proposition 5.1. This is the same softmax geometry developed in Lecture 2; here each attention row supplies its own logit vector.
5.1 Temperature as entropy regularization
For , the vector has temperature . The entropy of is
with . For probability vectors and with , their Kullback—Leibler divergence is
Gibbs’ inequality states that this quantity is nonnegative and is zero exactly when .
Proposition 5.2 (Gibbs variational formula). For ,
Proof
Put
Since , every satisfies
Gibbs’ inequality makes the last expression at most , with equality exactly when . Hence the displayed maximizer exists and is unique.
The formula says that softmax balances two desires. The linear term rewards mass on large scores. The entropy term rewards a spread-out distribution. Temperature is the relative strength of that entropy reward.
Example 5.3 (temperature in the running score row). For
two temperatures give
and
Lowering the temperature from to preserves the score ordering but moves more mass to the largest score. Raising the temperature moves the row toward .
Remark 5.4 (temperature limits). Let . Dividing numerator and denominator by shows that, as , tends to the uniform distribution on . As , every tends to , so the distribution tends to the uniform distribution on all positions. The same variational principle governs sampling temperature in Lecture 7.
5.2 Why the score is divided by
The score normalization follows from a variance calculation.
Lemma 5.5 (variance of a dot product). Suppose the coordinates of are independent across coordinates and between the two vectors, with mean zero and variance . Then
Proof
Write
Each product has mean
and variance
Independence makes the products independent, and in particular uncorrelated, across . The mean of their sum is zero and its variance is the sum .
Consequently,
With unit coordinate variance, the expected scales are therefore:
| standard deviation of | standard deviation of | |
|---|---|---|
Remark 5.6 (why divide by ). Without normalization, score gaps typically grow with the head dimension. Large gaps move a softmax row toward a simplex vertex, a regime called softmax saturation. If tends to a one-hot vector, then tends entrywise to zero. Gradients passing from the attention weights back to the scores can therefore become very small. Dividing by keeps the initial score scale approximately independent of .
The word “initial” is important. The lemma is an idealized calculation, not an invariant of training. Queries and keys in a trained model need not have independent coordinates, equal variances, or mean zero. Even at initialization, a self-score compares two projections of the same stream row, so exact independence depends on the initialization model. The calculation motivates the architectural scale; it does not assert that every trained score matrix has variance one.
Probabilistic aside 5.7. Under suitable moment hypotheses, the central limit theorem makes the normalized sum approximately Gaussian for large . The variance calculation, rather than the normal approximation, is the essential justification. Project Step 4 measures the scale directly instead of assuming that a finite random sample exactly matches the asymptotic model.
6. Permutation equivariance and positional information
Attention compares content at different rows. Does the operator itself know which row is “first” or “third”? The answer for unmasked attention is no: if its input rows are reordered, its output rows undergo exactly the same reordering.
Let be the group of permutations of . For , let be its permutation matrix, with the convention
Define the corresponding token action by
Thus left multiplication by and the action use the same reordering.
A map is permutation-equivariant if
for every and . Equivariance is not invariance. An invariant map would satisfy ; an equivariant map changes its output, but in a completely prescribed way.
Theorem 6.1 (permutation equivariance of unmasked self-attention). For unmasked attention,
Proof
Row-wise linear projection commutes with row permutation:
The same identity holds for and . Therefore
The matrix on the right simultaneously permutes the rows and columns of . Row-wise softmax commutes with this simultaneous permutation, so
Finally, using ,
The simultaneous row—column action on has a concrete meaning. If source position and query position are both renamed by the same permutation, the weight coupling those two renamed positions is unchanged. The attention pattern follows the objects being permuted rather than remaining attached to absolute row numbers.
Position-wise maps are equivariant for the same reason. If is applied separately with shared parameters to every row, then
Sums and compositions of equivariant maps remain equivariant. Thus stacking unmasked attention with shared row-wise MLPs does not remove the symmetry.
6.1 Where positional embeddings break the symmetry
Let have row and let have row . Define the token-sequence embedding maps
and
Without positions, embedding commutes with token permutation:
With fixed, nonconstant position vectors, in general
These are unequal because permuting the tokens leaves the positional matrix fixed in the first expression but permutes it in the second.
Corollary 6.2 (positional information is required for order awareness). An unmasked transformer assembled from permutation-equivariant attention and position-wise maps cannot distinguish token orders except by correspondingly permuting its outputs. Supplying position-dependent information in the embedding or attention scores breaks this symmetry in the composite map from token sequences to outputs.
Proof
Without positional information, the embedding map is equivariant. Theorem 6.1 and the observation above show that each subsequent attention or position-wise map is equivariant. Equivariance is preserved under composition, so the entire composite is equivariant. With fixed position-dependent information, the embedding identity already fails in general, as the two displayed formulas show.
Precision remark 6.3. Adding positional vectors to a particular numerical matrix does not make the function cease to be equivariant. Theorem 6.1 holds for every input matrix, including one whose rows happen to contain positional information. Symmetry is broken by the preceding map from token sequences to matrices, because positions stay fixed while tokens are permuted. Step 4 tests both statements separately.
This distinction is easiest to remember as a comparison of two experiments.
- Permute completed stream rows. Starting from a numerical matrix , compare with . They are equal.
- Permute tokens before fixed-position embedding. Compare with . They are generally unequal.
The first experiment tests the attention map. The second tests the composite from discrete tokens through positional embedding and attention.
6.2 Additive, sinusoidal, and rotary position information
Two common positional constructions illustrate absolute and relative geometry.
-
Additive positional embeddings. Use learned vectors , as in the course project, or fixed sinusoidal coordinates. At angular frequency , the two-coordinate feature
satisfies
Thus absolute vectors also make relative offsets accessible through inner products. The standard fixed construction uses a range of frequencies, for example
-
Rotary positional embeddings (RoPE). In one two-dimensional query/key coordinate plane, let
Rotate the query at position by and the key at position by . Then
The positional contribution to the query—key comparison depends on the relative offset . RoPE uses several such planes with different frequencies.
The model still has to learn how to use these features. A position encoding makes order available; it does not prescribe a particular linguistic algorithm.
6.3 What the causal mask contributes
Remark 6.3 (the causal mask). A causal mask is not invariant under arbitrary permutations and therefore already breaks the full symmetry. In fact, the finite total order has no nontrivial permutation preserving every relation . The mask supplies ordered prefix structure, while explicit positional information supplies richer access to absolute positions, offsets, and distances.
A two-position example shows the failure of equivariance. Set all query—key scores equal and use distinct values . Causal attention gives
If the two input rows are swapped first, then
Swapping the original output instead gives
which is generally different. The first row is special because the causal order permits it to read only itself.
7. Attention as kernel smoothing
The formula for an attention row is not unique to neural networks. It has the same normalized-weight form as a classical nonparametric regression estimator.
Definition 7.1 (Nadaraya—Watson estimator). Given input—value pairs and a nonnegative weighting function , the Nadaraya—Watson regression estimate at is
provided the denominator is positive.
The word kernel is often used for . Here it means a nonnegative similarity or weighting function. It need not be a symmetric positive-definite kernel in the sense of reproducing-kernel Hilbert spaces.
For attention, set
This quantity is strictly positive for finite query and key vectors.
Proposition 7.2 (attention is learned kernel smoothing). Unmasked attention satisfies
Causal attention satisfies the same formula with the sum restricted to .
Proof
By the definition of row-wise softmax,
in the unmasked case. Substituting this expression into gives the first formula. Under a causal mask, removes the terms with from numerator and denominator.
This is more flexible than a classical smoother in three ways.
- The query locations and key locations are learned projections of the current features.
- The kernel can be asymmetric because and need not agree.
- The targets are themselves learned projections rather than fixed observed responses.
The normalization still performs the same mathematical job: it turns nonnegative similarities into barycentric weights.
7.1 Three instructive special cases
Example 7.3 (uniform attention and the running mean). If , then every finite score equals zero. Unmasked attention gives
All output positions receive the same global mean. Under a causal mask,
and hence
This is the running mean of the value sequence. The operation depends on position only through the mask.
Example 7.4 (Gaussian positional smoothing). Prescribe scores
Then causal attention has weights
The positive number is the bandwidth. Small concentrates near the query position; large spreads weight across the prefix. More precisely,
This score rule can itself be represented by dot products of positional features. Since row-wise softmax ignores a row constant,
is equivalent, for fixed , to the first two terms. With , take
Then
which differs from the Gaussian score only by the row constant . The two score matrices therefore give identical attention weights.
Example 7.5 (the retrieval limit). Introduce temperature and use
As , the row becomes uniform on the permitted keys with maximal score. If the maximum is unique, the output tends to the value at that single selected position. Thus smooth averaging and nearly discrete retrieval are two temperature regimes of the same operation.
The kernel view turns attention into a continuum.
- Equal similarities give averaging.
- Position-based similarities give ordinary smoothing along the sequence.
- Content-based similarities let the neighborhood change with the input.
- Large score gaps approximate a database lookup.
Attention does not add content dependence to a particular fixed Gaussian kernel; it learns the feature spaces in which similarity is measured.
Interpretability remark 7.3. A trained attention head may be studied through its learned weighting rule. A row may emphasize the previous token, a recent delimiter, or a position whose token matches the current token. This suggests hypotheses about the head’s algorithm.
8. Computational cost and multi-head attention
Attention replaces the fixed context width of an -gram MLP by access to a length- sequence. That flexibility has a computational price.
The notation suppresses fixed multiplicative constants and lower-order terms in an operation count. For one head, the main forward operations are:
| operation | output shape | arithmetic cost |
|---|---|---|
| and | two matrices | |
| row-wise softmax | ||
For fixed widths, the two products involving the attention matrix are quadratic in sequence length. A causal mask removes roughly half the query—key pairs but does not change the asymptotic order.
Materializing either the score matrix or the attention matrix requires memory, in addition to the storage for projected queries, keys, and values. The quadratic matrix is often the main activation-memory bottleneck for long sequences.
The three projection matrices of one bias-free head contain
parameters. This count does not depend on . Attention therefore has a useful separation: its learned parameter count can remain fixed as the context grows, even though the arithmetic and temporary memory grow with the number of position pairs.
Aside 8.1 (streaming softmax). A softmax-weighted value sum can be evaluated without storing a complete row of weights. For scores , choose and write
When keys and values arrive in blocks, maintain a running maximum, a rescaled denominator, and a rescaled weighted-value numerator. If a new block has a larger maximum, multiply the old accumulators by the appropriate exponential factor before adding the new block. This is an exact algebraic reorganization, apart from floating-point rounding. FlashAttention combines this streaming identity with hardware-aware blocking so that the full matrix need not be stored. It reduces memory traffic and activation storage without changing the general quadratic arithmetic count of dense attention.
8.1 Autoregressive inference and the key—value cache
Training evaluates all rows in parallel. Generation is sequential: after producing a new token, the model appends one new stream row and predicts again. At step , the keys and values of positions have already been computed and do not change within a fixed layer. A key—value cache, or KV cache, stores them.
For one new query, comparison with cached keys costs and the weighted value sum costs . The cache for one head through length uses
memory. Summed over generated positions, dense cached attention still takes quadratic arithmetic, but it avoids recomputing the complete old prefix at every step. A naive full-prefix evaluation at every generation step would repeatedly pay a quadratic prefix cost and therefore accumulate a cubic attention cost.
8.2 Preview of multi-head attention
A single head produces one attention distribution per query position. It must use the same distribution for every coordinate of its value output. In Lecture 5, multi-head attention runs heads with independent query, key, and value projections, concatenates their outputs, and applies an output projection.
When each head has width , all heads together have query, key, and value weights, and the output projection contributes another weights, ignoring biases. Different heads can therefore implement different weighting rules at the same position while the total projection parameter count remains . Position-wise MLPs, residual connections, and LayerNorm then complete the transformer block.
9. Connection to Project Step 4
Project Step 4 isolates one causal head so that its structural properties can be tested before training a full transformer. This is a useful scientific order: first establish what the implementation must satisfy for every parameter value, then examine the patterns produced by particular parameters.
9.1 From proofs to executable assertions
A minibatch of size adds a leading coordinate to every shape:
| object | batched shape |
|---|---|
| input | |
| scores and weights | |
| output |
Matrix multiplication acts on the final two coordinates and preserves the batch coordinate. Before running the implementation, writing these shapes beside every line catches most transposition mistakes.
Each main test in Step 4 is a theorem specialized to finite arrays.
| assertion | mathematical source |
|---|---|
| all weights are nonnegative and rows sum to one | Proposition 3.1 |
| the strict upper triangle is zero | Definition 4.1 |
| earlier outputs survive a future perturbation | Proposition 4.3 |
| future input-gradient blocks are zero | Proposition 4.3 |
| raw score scale grows like | Lemma 5.5 |
| row-permuted unmasked inputs give row-permuted outputs | Theorem 6.1 |
Some equalities are structural and some are numerical. A stored causal mask can make the upper triangle exactly zero. Floating-point row sums are usually only close to one. A perturbation test should compare outputs that execute the same deterministic arithmetic on the same earlier data; gradient tests should allow for the numerical tolerance appropriate to the chosen data type.
A good unit test is a small proof with numbers substituted. Proposition 5.1 says that a future variable is absent from an earlier output formula. The perturbation test checks the resulting function equality; the gradient test checks its differential consequence. Agreement between the two makes an indexing accident much less likely.
9.2 Reading an attention heatmap
A heatmap displays with query position on one axis and source position on the other. Several visible features occur before any learning.
- The strict upper triangle is blank because it is masked.
- The first row is forced to be ; it has only one permitted source.
- Row distributes unit mass across permitted columns. Even exchangeable random scores therefore look different near the top and bottom of the triangle.
- Different random seeds produce different columns and diagonals by chance. An untrained pattern is not evidence of a learned linguistic algorithm.
The Gaussian positional experiment supplies a controlled comparison. Its bandwidth is known, so a narrow diagonal or a broad running average has a mathematical explanation. Trained heatmaps can later be compared with these baselines.
9.3 What this head changes from Step 3
The Step 3 neural -gram compresses a fixed concatenated context with one MLP. Its first-layer parameter count grows with the chosen context length. The Step 4 head uses shared projections at every position, and its parameter count is independent of the current . Its attention matrix then selects a different convex combination for every input and query position.
This does not make one head a language model. It has no multi-head output projection, residual connection, normalization, position-wise MLP, or unembedding to vocabulary logits. Lecture 5 assembles those pieces. Step 4’s goal is narrower and foundational: make the data-dependent communication operator correct before multiplying and stacking it.
Summary
-
Scaled dot-product self-attention projects each stream row into a query, key, and value. Query—key inner products determine a probability distribution; the output is the corresponding value average.
-
The unmasked score matrix factors through and has rank at most . The attention matrix after row-wise softmax need not have low rank.
-
Every attention row lies in a simplex, so each output lies in the convex hull of the available values and can be written as an expectation. The value projection chooses the points being averaged; the query and key projections choose their barycentric weights.
-
Causal masking normalizes each row over its prefix. The result is lower triangular and row-stochastic, and output row depends only on input rows . This makes parallel teacher-forced training consistent with left-to-right generation.
-
Softmax is the gradient of log-sum-exp. Its Jacobian is the categorical covariance matrix . Temperature trades score maximization against entropy, and the common-shift direction is invisible.
-
Under an idealized independent-coordinate model, an unscaled dot product has variance . Dividing by keeps its variance independent of head dimension and reduces initial softmax saturation.
-
Unmasked self-attention is permutation-equivariant as a function of its stream rows. Fixed positional information breaks symmetry in the map from token sequences to stream matrices; the attention formula itself remains equivariant. A causal mask separately supplies ordered prefix structure.
-
Attention is a learned Nadaraya—Watson smoother. Uniform scores give a mean, Gaussian positional scores give ordinary sequence smoothing, and low temperature approaches retrieval from the highest-scoring key.
-
Dense attention has quadratic arithmetic and, naively, quadratic memory in sequence length. Streaming softmax reduces stored intermediates, and a KV cache avoids recomputing old keys and values during generation.
Exercises (paired with Step 4)
A star marks a Project Step 4 task.
-
★ Reproduce Examples 2.3 and 4.2 without looking at the displayed answers. Label every matrix dimension, compute all three causal output rows, and locate each one in the convex hull of its permitted values.
-
★ Implement one causal head. Test simplex membership, a zero upper triangle, invariance of earlier outputs under a future perturbation, and zero future derivatives. Match each assertion to a precise result above. Explain why permitted gradients are not guaranteed to be nonzero.
-
★ Measure raw and scaled score variance for . Record a typical largest weight in each row and relate the observed saturation to Proposition 5.1 and Lemma 5.5. State why the empirical standard deviations need not equal their theoretical values exactly.
-
Prove Proposition 5.2, including existence and uniqueness of the maximizer. Prove both temperature limits in Remark 5.4, treating multiple score maximizers explicitly.
-
Starting from the zero score matrix, compare the two procedures in Implementation aside 4.4: mask the scores before softmax, and zero the forbidden weight after an unmasked softmax. Compute the resulting attention matrices and every derivative under each procedure. What changes if post-softmax masking is followed by exact renormalization?
-
Prove Theorem 6.1. Then verify that attention remains equivariant as a function of stream rows even when those rows already contain positional vectors. Locate exactly where equivariance of the composite from tokens fails.
-
★ Implement the masked Gaussian positional kernel for several bandwidths. Verify both limits in Example 7.4 numerically. Then use the displayed two-dimensional queries and keys to reproduce the same weights by scaled dot-product attention.
-
Prove . Construct a example in which the row-wise softmax of has rank larger than , showing that the rank bound does not pass through softmax.
-
Show that is Lipschitz on every bounded subset of . Explain why the bilinear score map prevents this argument from giving one global Lipschitz constant on the whole space.
-
Fix keys and values and regard one unmasked output as a function of its query. Prove that for a query perturbation ,
Interpret the centered value and determine when this differential is zero for every .
-
Apply Jensen’s inequality to prove the norm bound in Section 3. Give conditions for equality when the Euclidean norm is strictly convex along the relevant value segments.
-
Prove directly, without Jacobians, that a composition of two causal sequence maps is causal. Then derive the corresponding block lower-triangular Jacobian statement by the chain rule.
-
For one head, compare the arithmetic required to generate tokens (a) by reevaluating the full prefix at every step and (b) with a KV cache. State the cache memory, and distinguish parameter memory from activation memory.
-
Prove the rotary identity
What information about and is absent from this expression? Compare that relative encoding with a learned additive positional matrix.
Pointers
Bahdanau, Cho, and Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2015); Vaswani et al., Attention Is All You Need (2017); Nadaraya (1964) and Watson (1964) on kernel regression; Phuong and Hutter, Formal Algorithms for Transformers (2022); Elhage et al., A Mathematical Framework for Transformer Circuits (2021); Su et al., RoFormer (2021); and Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (2022). See the resources page, Project Step 4, and Lecture 5.