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, and the target space is called the embedding space (or, especially outside the language-modelling literature, the latent space). 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 will strongly influence 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 directly to . Instead, we add . The role of is to interpret a stream vector in some way (by a linear transformation) before it is added in to .
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 the initial stream to be
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 row of the attention output 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.
Remark 2.6 (why divide by ). Suppose the coordinates of are independent across coordinates and between the two vectors, with mean zero and variance . Then is a sum of independent terms, each with mean and variance , so has expectation and variance . The scaling by in the definition of reduces the variance to , independent of the dimension. Without this scaling, the variance can become quite high, and as a result softmax saturates: the result of softmax tends to be near a corner of the simplex. Saturation makes training by gradient descent more difficult, since gradients are small (Proposition 6.1 below computes the Jacobian of softmax; it tends to zero as the softmax output approaches a corner). This is an idealized calculation about initialization, not an invariant of training: queries and keys in a trained model need not have independent, mean-zero coordinates.
3. Attention as averaging
Attention scores may be positive or negative and have no fixed scale. After softmax, however, every row belongs to the set
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 last display in the proof can be interpreted probabilistically. For each query position , let be a random variable taking values in , given by
Then
Attention is therefore literally an expectation of the value vector under a distribution selected by the geometry of the queries 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
4. Causal masking
There’s one important aspect we have so far ignored, which requires a modification. 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. To avoid this, we use a method called causal masking. 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.
Proposition 4.3 (autoregressive well-definedness). For causal attention, is a function only of . Wherever the map is differentiable,
Proof
Row of depends on , 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 of Proposition 3.1 can be strengthened to:
Remark 4.4 (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. Temperature
The entropy of is
with . The entropy is large when the distribution is spread-out and small when it is concentrated. The following proposition makes this precise.
Proposition 5.1 (entropy bounds). For every ,
The lower bound is attained exactly when is a vertex of the simplex (one coordinate equal to , the rest ), and the upper bound exactly when is the uniform distribution .
Proof
Each term is nonnegative, since , and it vanishes exactly when . Hence , with equality exactly when every coordinate is or ; as the coordinates sum to , that means is a vertex.
For the upper bound, let . Since is strictly concave, Jensen’s inequality gives
with equality in the first inequality exactly when the numbers , , are all equal, and in the second exactly when is all of . Both hold exactly when is uniform.
Let . The function , as a function of , is said to have temperature . The next proposition says that , acting on scores , produces a probability distribution which has mass on tokens with large scores, but is also spread-out. The amount of emphasis on being spread out is determined by the temperature. With temperature , we are using standard softmax; with a high temperature, we get more random variation in the final probability distribution.
Proposition 5.2 (Gibbs variational formula). For , is the unique probability distribution which maximizes the quantity
Proof
We will use the notion of KL divergence. For probability vectors and with , their Kullback—Leibler divergence is
Gibbs’ inequality (Lecture 1, Theorem 7.2) states that this quantity is nonnegative and is zero exactly when .
Put
Since , every satisfies
Gibbs’ inequality makes the last expression at most , with equality exactly when . Hence the displayed maximizer exists and is unique.
Example 5.3 (temperature in the running example). For
we have
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.
6. Log-sum-exp and computation remarks
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 6.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 6.1. This is the same softmax geometry developed in Lecture 2; here each attention row supplies its own logit vector.
7. Positional embeddings
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. In this section we discuss how we embed positional information into the input stream.
7.1 Permutation equivariance
Let be the group of permutations of . For , let be its permutation matrix, defined by the convention
i.e. acts from the left to permute the rows of by .
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 .
Theorem 7.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 ,
A position-wise map applies one function , with shared parameters, separately to every row. Such a map is equivariant as well, since . Sums and compositions of equivariant maps remain equivariant. Thus stacking unmasked attention with shared row-wise MLPs does not remove the symmetry.
Corollary 7.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.
Proof
Without positional information, the map from token sequences to stream matrices, defined below, is equivariant. Theorem 7.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.
To see exactly where positional information enters, compare the embedding maps with and without positions.
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.
Thus, supplying position-dependent information in the embedding or attention scores breaks this symmetry in the composite map from token sequences to outputs.
7.2 Types of positional embeddings: learned, sinusoidal, and rotary
Here are some of the standard ways to define positional vectors. Recall from Section 1 that a system of additive positional vectors is a map , defined for , where is the longest context the model supports. The column vector is called the -th positional embedding, and the stream is initialized with . In matrix form, has rows .
-
Learned positional embeddings. It is possible to consider the to be part of the parameters and learn these vectors, exactly as the token embeddings are learned. This is what the course project does.
-
Sinusoidal positional embeddings. Use fixed sinusoidal coordinates. At angular frequency , the two-coordinate feature vector defined by
satisfies
Observe that using such vectors as positional embeddings, , makes relative offsets accessible by taking inner products.
In higher dimensions, the standard fixed construction stacks such pairs at a range of frequencies. Indexing the coordinates of from , it sets, for ,
so that with : the frequencies range from down to nearly .
-
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.
These designs make relative position available to the model, but the model still has to learn how to use these features.
Remark 7.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.
Example 7.4 (a causal head is not equivariant). Take , set all query—key scores equal, and let denote the two output rows of causal attention as a function of the two distinct value rows . Causal attention gives
If the two input rows are swapped first, then
Swapping the original output instead, by the permutation matrix of the transposition, gives
which is generally different. The first row is special because the causal order permits it to read only itself.
8. Expressivity of attention
What weighting rules can an attention head express? To describe them uniformly, set
This quantity is strictly positive for finite query and key vectors.
Proposition 8.1 (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.
Remark 8.2 (Nadaraya—Watson estimation). The formula in Proposition 8.1 is reminiscent of, but more flexible than, a classical nonparametric regression 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 only a nonnegative weighting function and has nothing to do with Hilbert spaces. Attention is more flexible in that the locations and the targets are all learned projections of the current features, and the kernel can be asymmetric because and need not agree.
8.1 Three instructive special cases
Example 8.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 8.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,
Observe that
Since row-wise softmax ignores a row constant, this score is equivalent, for fixed , to the first two terms on the right. With , take
Then
which differs from the Gaussian score only by the row constant . The two score matrices therefore give identical attention weights.
Example 8.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.
8.2 Heatmaps
A heatmap displays with query position on one axis and source position on the other, with darker cells for larger weights. Here are the three examples above, drawn for .
Several visible features occur in every causal heatmap, even before any learning.
- The strict upper triangle is blank (grey above) 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.
9. Computational cost
How expensive is attention? To measure the complexity of an algorithm, we count the arithmetic operations it performs: each scalar addition, subtraction, multiplication, division, or exponential counts as one operation. For example, multiplying an matrix by an matrix by the usual formula takes multiplications and additions, so about operations. We are interested in how this count grows with , the length of the context, and , the dimension of the embedding space, along with the head widths and . Exact counts depend on implementation details, so we record only the growth rate, using big-O notation.
Definition 9.1 (big-O notation). Let and be nonnegative functions of the positive integers and (and of any other size parameters in play). We write
if there are constants and such that whenever .
Thus suppresses fixed multiplicative constants and lower-order terms: for instance . 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.
Storing either the score matrix or the attention matrix requires memory, in addition to the storage for projected queries, keys, and values. The quadratic dependence on , namely , 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.
9.1 Autoregressive generation and the key—value cache
Training evaluates all rows in parallel: the whole training sequence is known in advance, and one forward pass produces the loss at every position (Remark 4.4). Generation is sequential.
Definition 9.2 (autoregressive generation). Given a prompt , autoregressive generation produces tokens one at a time. At step , the model is run on the current sequence ; the output distribution at position is used to choose , by sampling or by taking the most probable token; and the new token is appended. The step is repeated until a stopping token or a length limit is reached.
Consider one attention head in one layer during this process, and suppose the sequence has grown to length . Its input rows are the same as they were at the previous step: by causality (Proposition 4.3, applied to every layer below; see Exercise 12), the stream at a position never depends on later tokens, so appending changes nothing at positions . Consequently the keys and values for are unchanged as well, and so are the earlier output rows. Only the new row , and hence , , and , must be computed, and the only output row needed is
Definition 9.3 (key—value cache). A key—value cache, or KV cache, for an attention head stores the keys and values computed at earlier generation steps. At step , the model computes from the new stream row, appends and to the cache, and evaluates the display above against the cached keys and values.
Proposition 9.4 (cost of generation). For one head, generating positions through costs
arithmetic operations with a KV cache, and operations if instead the full prefix is re-evaluated from scratch at every step. The cache occupies memory.
Proof
With the cache, step computes three projections of one row, operations; compares with keys, ; normalizes, ; and forms the weighted value sum, . Summing over and using gives the first count. Without the cache, step recomputes the full prefix, whose score and value products cost by the table above, and . The cache holds vectors of length and as many of length .
Summed over generated positions, dense cached attention still takes quadratic arithmetic, but it avoids recomputing the complete old prefix at every step. Note also that the cache is activation memory, which grows with the context length, rather than parameter memory, which does not: the cache for a long conversation can be far larger than the head’s parameters. Multi-head attention, which runs several heads side by side, is the subject of Lecture 5.
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 6.1 and Remark 2.6. 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 two procedures: mask the scores before softmax, as in Definition 4.1, 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 7.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 8.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.