Electric Sheaves

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 V\mathcal{V} of size VV, which we will enumerate for convenience. An embedding is a map from tokens to vectors:

e:VRde: \mathcal{V} \rightarrow \mathbb{R}^d

The dimension dd is called the model width. The embedding matrix for the embedding ee is the matrix EMV×d(R)E \in M_{V \times d}(\mathbb{R}) such that the embedding of the tt-th token is the tt-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 xnx_n initially computed as a function of two things: (1) the embedding of the token in that position, and (2) the position itself. At the nn-th position, this is called the residual stream at position nn. 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:

final streamposition 1 final streamposition 2 final streamposition 3 final streamposition 4 final streamposition 5 transformer computations the streams interact and are repeatedly updated embedding+ position embedding+ position embedding+ position embedding+ position embedding+ position The cat sat on the unembedding softmax next-token probability distribution language modelling head
Each token position has its own residual stream, but the streams are not processed independently: transformer layers let later positions read from permitted earlier positions. For next-token prediction, the final stream at the last position is mapped to vocabulary logits by unembedding and then to probabilities by softmax.

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:

the same residual streams pass through a stack of learned blocks final streamposition 1 final streamposition 2 final streamposition 3 final streamposition 4 final streamposition 5 transformer block L layer norm → attention → layer norm → feedforward transformer block 2 layer norm → attention → layer norm → feedforward transformer block 1 layer norm → attention → layer norm → feedforward embedding+ position embedding+ position embedding+ position embedding+ position embedding+ position The cat sat on the unembedding softmax next-token probability distribution language modelling head each block updates the whole sequence
The cloud in the previous overview is a stack of transformer blocks, numbered 1 up to L starting from the input: block 1 acts first, block L last, and the vertical dots stand for the omitted blocks in between. A block acts on the collection of residual streams, letting earlier streams feed later ones (light arrows), returns one updated stream per position, and passes all of them to the next block. Different blocks have different learned parameters but share the same overall architecture.

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 xn\mathbf x_n in the nn-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 nn-th token and the integer nn (its position in the context). In this layer, the weights of the model dictate that the new value xn\mathbf{x}_n' of the nn-th stream xn\mathbf{x}_n should be a function of itself and all the streams preceding it (i.e. corresponding to the jj-th token, where j<nj < n). The form of this function is this:

xn=xn+jnαj,nxjTan,(αj,n)j=1n=softmax((xnGxj)j=1n),\mathbf{x}_n' = \mathbf{x}_n + \underbrace{\sum_{j \le n} \alpha_{j,n} \mathbf{x}_j T}_{\mathbf{a}_n},\quad (\alpha_{j,n})_{j=1}^{n} = \operatorname{softmax}\left( (\mathbf{x}_n G \mathbf{x}_j^\top)_{j=1}^n \right),

for some matrices TT and GG. The matrices TT and GG are part of the parameters θ\theta of the system, trained in some way. For now, observe that GG controls how much xj\mathbf{x}_j affects xn\mathbf{x}_n, and TT controls how we transform the resulting linear combination. The way that GG controls the interaction of one token with previous tokens is referred to as attention. When the pairing of two streams through GG 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 an\mathbf{a}_n the attention output at position nn. It is added to xn\mathbf{x}_n 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 nn, somehow coded into a vector in a high dimensional vector space. If GG is chosen well (trained well) then it may give a large scalar weight to “pencil”. At the same time, the transformation TT 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 V\mathcal{V} be a vocabulary of size VV, enumerated in some order. We have an embedding map

e:VRde: \mathcal{V} \rightarrow \mathbb{R}^d

We typically take the output of ee to be a column vector. The embedding matrix for the embedding ee is the matrix EMV×d(R)E \in M_{V \times d}(\mathbb{R}) such that the embedding of the tt-th token is the tt-th row transposed.

The map above allows us to embed information about which token we are considering as a vector in Rd\mathbb{R}^d. 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

p:{1,,T}Rd,tptp : \{1, \ldots, T \} \rightarrow \mathbb{R}^d, \quad t \mapsto p_t

We should think of ptp_t as carrying the information “we are at position tt”. We treat ptp_t 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 TT be the length of the context, as a sequence of tokens x1,,xTx_1, \ldots, x_T. For each position tt, we create a vector of Rd\mathbb{R}^d which contains information about the token xtx_t and its position tt. This is

r:VTRT×d,(xt)t=1T(X1XT),Xt:=e(xt)+pt.r : \mathcal{V}^T \rightarrow \mathbb{R}^{T\times d}, (x_t)_{t=1}^T \mapsto \begin{pmatrix} X_1^\top \\ \vdots \\ X_T^\top \end{pmatrix}, \quad X_t := e(x_t) + p_t.

This represents the context as a T×dT \times d matrix XX whose rows are XtX_t^\top, t=1,,Tt=1, \ldots, T.

We refer to an element of RT×d\mathbb{R}^{T \times d} as a residual stream, and the first step of the transformer is to initialize the residual stream to X:=r(x1,,xT)X := r(x_1, \ldots, x_T).


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 dkd_k and dvd_v (to be used as dimensions of vector spaces). Let

WQ,WKRd×dk,WVRd×dvW_Q,W_K\in\mathbb R^{d\times d_k}, \qquad W_V\in\mathbb R^{d\times d_v}

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 XX represent the stream, and suppose query, key and value projection matrices WQW_Q, WKW_K and WVW_V are given. Define the query matrix, key matrix and value matrix (as distinct from the corresponding “projection matrices”) by

Q=XWQRT×dk,K=XWKRT×dk,V=XWVRT×dv.Q=XW_Q\in\mathbb R^{T\times d_k}, \qquad K=XW_K\in\mathbb R^{T\times d_k}, \qquad V=XW_V\in\mathbb R^{T\times d_v}.

Define also the rows of these matrices, as column vectors:

qi=WQXi,kj=WKXj,vj=WVXj.q_i=W_Q^\top X_i, \qquad k_j=W_K^\top X_j, \qquad v_j=W_V^\top X_j.

Here the matrix VV of values is distinguished by context from the scalar V=VV=|\mathcal V|.

When Q,K,VQ,K,V are all obtained from the same stream XX, 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 SRT×TS\in\mathbb R^{T\times T}, row-wise softmax is defined by

(softmaxrowS)ij=eSij=1TeSi.(\operatorname{softmax}_{\mathrm{row}}S)_{ij} = \frac{e^{S_{ij}}}{\sum_{\ell=1}^Te^{S_{i\ell}}}.

Definition 2.2 (scaled dot-product attention). Define the score matrix, attention matrix, and attention output by

S=QKdk,A=softmaxrow(S),Attn(X)=AV.S=\frac{QK^\top}{\sqrt{d_k}}, \qquad A=\operatorname{softmax}_{\mathrm{row}}(S), \qquad \operatorname{Attn}(X)=AV.

Entrywise,

Sij=qi,kjdk,Aij=eSij=1TeSi,Attn(X)i=j=1TAijvj.S_{ij}=\frac{\langle q_i,k_j\rangle}{\sqrt{d_k}}, \qquad A_{ij}=\frac{e^{S_{ij}}}{\sum_{\ell=1}^Te^{S_{i\ell}}}, \qquad \operatorname{Attn}(X)_i=\sum_{j=1}^TA_{ij}v_j.

Here Attn(X)i\operatorname{Attn}(X)_i denotes the column-vector form of output row ii. The index order matters:

Aij=weight assigned by query position i to key position j.A_{ij} = \text{weight assigned by query position }i \text{ to key position }j.

Now the attention head can be described by the following diagram, illustrating the algorithm taking as input the stream XX, computing intermediate matrices Q,K,V,S,AQ, K, V, S, A and producing attention output AVAV.

stream X ∈ Rᵀˣᵈ queries Q = XWQ keys K = XWK values V = XWV scores S = QKᵀ/√dk row softmax A ∈ Rᵀˣᵀ attention output Attn(X) = AV
One self-attention head.

With reference to our introduction, the key and query matrices determine GG, and TT is determined from the value matrix and a final operation that comes later.

The intuition is as follows. The product QKQK^\top is comparing every pair (query (row),key (column))=(qi,kj)(\text{query (row)}, \text{key (column)}) = (q_i, k_j). 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 AA, the attention matrix, is multiplied by the value matrix VV. 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 VV. The role of VV 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:

  • qiq_i is what position ii is looking for.
  • kjk_j is how position jj advertises itself.
  • vjv_j is the information position jj offers if selected.

Example 2.3 (one attention head, completely by hand). Let T=3T=3, d=4d=4, dk=1d_k=1, and dv=2d_v=2. Take

X=(10201log2031log311),X = \begin{pmatrix} 1&0&2&0\\ 1&\log2&0&3\\ 1&\log3&1&1 \end{pmatrix},

and let the three projections select coordinates as follows:

WQ=(1000),WK=(0100),WV=(00001001).W_Q = \begin{pmatrix}1\\0\\0\\0\end{pmatrix}, \qquad W_K = \begin{pmatrix}0\\1\\0\\0\end{pmatrix}, \qquad W_V = \begin{pmatrix} 0&0\\ 0&0\\ 1&0\\ 0&1 \end{pmatrix}.

Then

Q=(111),K=(0log2log3),V=(200311).Q = \begin{pmatrix}1\\1\\1\end{pmatrix}, \qquad K = \begin{pmatrix}0\\\log2\\\log3\end{pmatrix}, \qquad V = \begin{pmatrix} 2&0\\ 0&3\\ 1&1 \end{pmatrix}.

Because dk=1d_k=1, the scaling factor is 11. Every query is the same, so every score row is the same:

S=QK=(0log2log30log2log30log2log3).S=QK^\top = \begin{pmatrix} 0&\log2&\log3\\ 0&\log2&\log3\\ 0&\log2&\log3 \end{pmatrix}.

Exponentiating a row gives (1,2,3)(1,2,3), and therefore

A=(1/61/31/21/61/31/21/61/31/2).A = \begin{pmatrix} 1/6&1/3&1/2\\ 1/6&1/3&1/2\\ 1/6&1/3&1/2 \end{pmatrix}.

Writing the value rows as

v1=(2,0),v2=(0,3),v3=(1,1),v_1=(2,0)^\top, \qquad v_2=(0,3)^\top, \qquad v_3=(1,1)^\top,

each output row is

16v1+13v2+12v3=(5/63/2).\frac16v_1+\frac13v_2+\frac12v_3 = \begin{pmatrix}5/6\\3/2\end{pmatrix}.

The score matrix has a useful rank restriction.

Proposition 2.4 (low-rank score factorization). The score matrix satisfies

S=XWQWKXdk,rank(S)dk.S = \frac{XW_QW_K^\top X^\top}{\sqrt{d_k}}, \qquad \operatorname{rank}(S)\leq d_k.
Proof

The first identity follows from K=(XWK)=WKXK^\top=(XW_K)^\top=W_K^\top X^\top. Since S=QK/dkS=QK^\top/\sqrt{d_k} factors through Rdk\mathbb R^{d_k}, the rank of the product is at most dkd_k. \square

Remark 2.5 (nonlinearity). The map XAttn(X)X\mapsto\operatorname{Attn}(X) 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 AA 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

ΔT1={aRT:aj0, j=1Taj=1}.\Delta^{T-1} = \left\{ a\in\mathbb R^T: a_j\geq0,\ \sum_{j=1}^Ta_j=1 \right\}.

This is the standard (T1)(T-1)-dimensional probability simplex. Its relative interior consists of the vectors with every coordinate strictly positive.

For a finite collection of vectors v1,,vTv_1,\ldots,v_T, their convex hull is

conv{v1,,vT}={j=1Tajvj:aj0, j=1Taj=1}.\operatorname{conv}\{v_1,\ldots,v_T\} = \left\{ \sum_{j=1}^Ta_jv_j: a_j\geq0,\ \sum_{j=1}^Ta_j=1 \right\}.

Proposition 3.1 (simplex and convex-hull property). For every sRTs\in\mathbb R^T,

softmax(s)relintΔT1.\operatorname{softmax}(s) \in \operatorname{relint}\Delta^{T-1}.

Consequently, every row Ai,:A_{i,:} lies in the simplex and

Attn(X)iconv{v1,,vT}.\operatorname{Attn}(X)_i \in \operatorname{conv}\{v_1,\ldots,v_T\}.
Proof

Every exponential esje^{s_j} is positive. Dividing by their positive sum gives

softmax(s)j>0,j=1Tsoftmax(s)j=1.\operatorname{softmax}(s)_j>0, \qquad \sum_{j=1}^T\operatorname{softmax}(s)_j=1.

Thus the softmax vector lies in the relative interior of the simplex. By Definition 2.2,

Attn(X)i=j=1TAijvj,\operatorname{Attn}(X)_i = \sum_{j=1}^TA_{ij}v_j,

and the coefficients are nonnegative and sum to one. This is a convex combination by definition. \square

The same statement has a probabilistic form. For each query position ii, let JiJ_i be a random source index with

P(Ji=j)=Aij.\mathbb P(J_i=j)=A_{ij}.

Then

Attn(X)i=E[vJi].\operatorname{Attn}(X)_i = \mathbb E[v_{J_i}].

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

v1=(2,0),v2=(0,3),v3=(1,1).v_1=(2,0)^\top, \qquad v_2=(0,3)^\top, \qquad v_3=(1,1)^\top.

The attention row (1/6,1/3,1/2)(1/6,1/3,1/2) gives

y=16v1+13v2+12v3=(56,32).y = \frac16v_1+\frac13v_2+\frac12v_3 = \left(\frac56,\frac32\right)^\top.

Because the three values are affinely independent in R2\mathbb R^2 and all three weights are positive, yy lies in the interior of their triangle.

v₁ = (2, 0) v₂ = (0, 3) v₃ = (1, 1) y = (5/6, 3/2) weight 1/6 weight 1/3 weight 1/2 first value coordinate second value coordinate
The attention output is specified by barycentric coordinates in the value triangle. Changing the score row moves the output within this convex hull; changing the value projection moves the vertices themselves.

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 uRdvu\in\mathbb R^{d_v}, then

minju,vju,Attn(X)imaxju,vj.\min_j\langle u,v_j\rangle \leq \left\langle u,\operatorname{Attn}(X)_i\right\rangle \leq \max_j\langle u,v_j\rangle.

Taking the Euclidean norm and using the triangle inequality gives

Attn(X)i2jAijvj2maxjvj2.\left\|\operatorname{Attn}(X)_i\right\|_2 \leq \sum_jA_{ij}\|v_j\|_2 \leq \max_j\|v_j\|_2.

More generally, Jensen’s inequality says that every convex ϕ:RdvR\phi:\mathbb R^{d_v}\to\mathbb R satisfies

ϕ ⁣(Attn(X)i)jAijϕ(vj).\phi\!\left(\operatorname{Attn}(X)_i\right) \leq \sum_jA_{ij}\phi(v_j).

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 AVAV 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, Aij>0A_{ij}>0 for all i,ji,j. 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 ΔT1\Delta^{T-1}. 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 QQ and KK, from the information being averaged, encoded by VV.


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 ii is used to predict the next token, it should depend on the tokens up through position ii but not on the later positions i+1,,Ti+1,\ldots,T.

Right now, our score matrix SS can have non-zero entries in position (i,j)(i,j) where j>ij > i. 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 SS, define extended-real masked scores by

S~ij={Sij,ji,,j>i.\widetilde S_{ij} = \begin{cases} S_{ij},&j\leq i,\\ -\infty,&j>i. \end{cases}

The causal attention matrix is

A=softmaxrow(S~),A = \operatorname{softmax}_{\mathrm{row}}(\widetilde S),

using e=0e^{-\infty}=0. Equivalently,

Aij={eSijieSi,ji,0,j>i.A_{ij} = \begin{cases} \displaystyle \frac{e^{S_{ij}}}{\sum_{\ell\leq i}e^{S_{i\ell}}}, &j\leq i,\\[9pt] 0,&j>i. \end{cases}

Thus AA is lower triangular, meaning Aij=0A_{ij}=0 whenever j>ij>i, and row-stochastic, meaning its entries are nonnegative and every row sums to one. Row ii lies in the face of the simplex supported on its first ii coordinates.

Example 4.2 (causally masking the running head). In Example 2.3, every unmasked score row was

(0,log2,log3).(0,\log2,\log3).

Causal masking gives

S~=(00log20log2log3).\widetilde S = \begin{pmatrix} 0&-\infty&-\infty\\ 0&\log2&-\infty\\ 0&\log2&\log3 \end{pmatrix}.

Softmax now normalizes over a different prefix in each row:

A=(1001/32/301/61/31/2).A = \begin{pmatrix} 1&0&0\\ 1/3&2/3&0\\ 1/6&1/3&1/2 \end{pmatrix}.

Multiplying by the same value matrix gives

AV=(202/325/63/2).AV = \begin{pmatrix} 2&0\\ 2/3&2\\ 5/6&3/2 \end{pmatrix}.

Position 11 has no choice but to return v1v_1. Position 22 averages only v1v_1 and v2v_2. Position 33 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, Attn(X)i\operatorname{Attn}(X)_i is a function only of X1,,XiX_1,\ldots,X_i. Wherever the map is differentiated,

Attn(X)iXj=0(j>i).\frac{\partial\operatorname{Attn}(X)_i}{\partial X_j} = 0 \qquad (j>i).
Proof

Row ii uses qiq_i, the keys kk_\ell with i\ell\leq i, the values vv_\ell with i\ell\leq i, and a normalizing sum over i\ell\leq i. These quantities depend only on X1,,XiX_1,\ldots,X_i. None depends on XjX_j for j>ij>i, so the output itself does not depend on XjX_j. Its derivative with respect to that variable is therefore zero. \square

The convex-hull result also acquires a prefix form:

Attn(X)iconv{v1,,vi}.\operatorname{Attn}(X)_i \in \operatorname{conv}\{v_1,\ldots,v_i\}.

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 -\infty 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 TT positions can be computed in one forward pass. Inputs and targets are shifted: the representation after token xix_i predicts xi+1x_{i+1}. Allowing position ii to attend to itself therefore reveals xix_i, not the target xi+1x_{i+1}. 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

lse(s)=logj=1Tesj,sRT.\operatorname{lse}(s) = \log\sum_{j=1}^Te^{s_j}, \qquad s\in\mathbb R^T.

For a probability vector pΔT1p\in\Delta^{T-1}, let diag(p)\operatorname{diag}(p) denote the diagonal matrix with diagonal pp, and let 1=(1,,1)\mathbf1=(1,\ldots,1)^\top. A symmetric matrix MM is positive semidefinite if

uMu0u^\top Mu\geq0

for every vector uu. 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 p=softmax(s)p=\operatorname{softmax}(s), then

lse(s)=p,2lse(s)=diag(p)pp.\nabla\operatorname{lse}(s)=p, \qquad \nabla^2\operatorname{lse}(s) = \operatorname{diag}(p)-pp^\top.

The Hessian is positive semidefinite, with nullspace R1\mathbb R\mathbf1. Hence log-sum-exp is convex on RT\mathbb R^T and strictly convex on 1\mathbf1^\perp.

Proof

Direct differentiation gives

silse(s)=esijesj=pi.\frac{\partial}{\partial s_i}\operatorname{lse}(s) = \frac{e^{s_i}}{\sum_je^{s_j}} = p_i.

Differentiating once more,

pisj=pi(1{i=j}pj),\frac{\partial p_i}{\partial s_j} = p_i\bigl(\mathbf1_{\{i=j\}}-p_j\bigr),

which is the (i,j)(i,j) entry of diag(p)pp\operatorname{diag}(p)-pp^\top. For any uRTu\in\mathbb R^T,

u(diag(p)pp)u=ipiui2(ipiui)2=VarIp(uI)0.\begin{aligned} u^\top(\operatorname{diag}(p)-pp^\top)u &= \sum_ip_iu_i^2-\left(\sum_ip_iu_i\right)^2\\ &= \operatorname{Var}_{I\sim p}(u_I) \geq0. \end{aligned}

Because pi>0p_i>0 for every ii, this variance is zero exactly when all uiu_i are equal. The nullspace is therefore R1\mathbb R\mathbf1. Positive semidefiniteness of the Hessian gives convexity, and its positive definiteness on 1\mathbf1^\perp gives strict convexity there. \square

The calculation simultaneously gives the Jacobian of softmax:

Dsoftmax(s)=diag(p)pp.D\operatorname{softmax}(s) = \operatorname{diag}(p)-pp^\top.

In coordinates, a perturbation hRTh\in\mathbb R^T changes probability pip_i to first order by

(Dsoftmax(s)h)i=pi(hijpjhj).\bigl(D\operatorname{softmax}(s)h\bigr)_i = p_i\left(h_i-\sum_jp_jh_j\right).

Only the centered part of hh matters. Indeed,

lse(s+c1)=c+lse(s),softmax(s+c1)=softmax(s).\operatorname{lse}(s+c\mathbf1) = c+\operatorname{lse}(s), \qquad \operatorname{softmax}(s+c\mathbf1) = \operatorname{softmax}(s).

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 τ>0\tau>0, the vector softmax(s/τ)\operatorname{softmax}(s/\tau) has temperature τ\tau. The entropy of aΔT1a\in\Delta^{T-1} is

H(a)=jajlogaj,H(a) = -\sum_ja_j\log a_j,

with 0log0=00\log0=0. For probability vectors aa and pp with pj>0p_j>0, their Kullback—Leibler divergence is

DKL(ap)=j:aj>0ajlogajpj.D_{\mathrm{KL}}(a\|p) = \sum_{j:a_j>0}a_j\log\frac{a_j}{p_j}.

Gibbs’ inequality states that this quantity is nonnegative and is zero exactly when a=pa=p.

Proposition 5.2 (Gibbs variational formula). For τ>0\tau>0,

softmax(s/τ)=arg maxaΔT1{a,s+τH(a)}.\operatorname{softmax}(s/\tau) = \operatorname*{arg\,max}_{a\in\Delta^{T-1}} \left\{ \langle a,s\rangle+\tau H(a) \right\}.
Proof

Put

Z=jesj/τ,p=softmax(s/τ).Z=\sum_je^{s_j/\tau}, \qquad p=\operatorname{softmax}(s/\tau).

Since logpj=sj/τlogZ\log p_j=s_j/\tau-\log Z, every aΔT1a\in\Delta^{T-1} satisfies

a,s+τH(a)=τjajlogpj+τlogZτjajlogaj=τlogZτDKL(ap).\begin{aligned} \langle a,s\rangle+\tau H(a) &= \tau\sum_ja_j\log p_j +\tau\log Z -\tau\sum_ja_j\log a_j\\ &= \tau\log Z-\tau D_{\mathrm{KL}}(a\|p). \end{aligned}

Gibbs’ inequality makes the last expression at most τlogZ\tau\log Z, with equality exactly when a=pa=p. Hence the displayed maximizer exists and is unique. \square

The formula says that softmax balances two desires. The linear term a,s\langle a,s\rangle rewards mass on large scores. The entropy term τH(a)\tau H(a) rewards a spread-out distribution. Temperature is the relative strength of that entropy reward.

Example 5.3 (temperature in the running score row). For

s=(0,log2,log3),s=(0,\log2,\log3),

two temperatures give

softmax(s)=(16,13,12),\operatorname{softmax}(s) = \left(\frac16,\frac13,\frac12\right),

and

softmax(2s)=softmax(s/(1/2))=(114,414,914).\operatorname{softmax}(2s) = \operatorname{softmax}(s/(1/2)) = \left(\frac1{14},\frac4{14},\frac9{14}\right).

Lowering the temperature from 11 to 1/21/2 preserves the score ordering but moves more mass to the largest score. Raising the temperature moves the row toward (1/3,1/3,1/3)(1/3,1/3,1/3).

Remark 5.4 (temperature limits). Let M={j:sj=maxs}M=\{j:s_j=\max_\ell s_\ell\}. Dividing numerator and denominator by exp(maxs/τ)\exp(\max_\ell s_\ell/\tau) shows that, as τ0+\tau\to0^+, softmax(s/τ)\operatorname{softmax}(s/\tau) tends to the uniform distribution on MM. As τ\tau\to\infty, every esj/τe^{s_j/\tau} tends to 11, so the distribution tends to the uniform distribution on all TT positions. The same variational principle governs sampling temperature in Lecture 7.

5.2 Why the score is divided by dk\sqrt{d_k}

The score normalization follows from a variance calculation.

Lemma 5.5 (variance of a dot product). Suppose the coordinates of q,kRdkq,k\in\mathbb R^{d_k} are independent across coordinates and between the two vectors, with mean zero and variance σ2\sigma^2. Then

Eq,k=0,Var(q,k)=dkσ4.\mathbb E\langle q,k\rangle=0, \qquad \operatorname{Var}(\langle q,k\rangle)=d_k\sigma^4.
Proof

Write

q,k=m=1dkqmkm.\langle q,k\rangle = \sum_{m=1}^{d_k}q_mk_m.

Each product has mean

E[qmkm]=E[qm]E[km]=0\mathbb E[q_mk_m] = \mathbb E[q_m]\mathbb E[k_m] = 0

and variance

E[qm2km2]=E[qm2]E[km2]=σ4.\mathbb E[q_m^2k_m^2] = \mathbb E[q_m^2]\mathbb E[k_m^2] = \sigma^4.

Independence makes the products qmkmq_mk_m independent, and in particular uncorrelated, across mm. The mean of their sum is zero and its variance is the sum dkσ4d_k\sigma^4. \square

Consequently,

Var(q,kdk)=σ4.\operatorname{Var} \left( \frac{\langle q,k\rangle}{\sqrt{d_k}} \right) = \sigma^4.

With unit coordinate variance, the expected scales are therefore:

dkd_kstandard deviation of qkq^\top kstandard deviation of qk/dkq^\top k/\sqrt{d_k}
16164411
64648811
256256161611

Remark 5.6 (why divide by dk\sqrt{d_k}). 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 pp tends to a one-hot vector, then diag(p)pp\operatorname{diag}(p)-pp^\top tends entrywise to zero. Gradients passing from the attention weights back to the scores can therefore become very small. Dividing by dk\sqrt{d_k} keeps the initial score scale approximately independent of dkd_k.

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 q,k/dk\langle q,k\rangle/\sqrt{d_k} approximately Gaussian for large dkd_k. 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 STS_T be the group of permutations of {1,,T}\{1,\ldots,T\}. For πST\pi\in S_T, let Pπ{0,1}T×TP_\pi\in\{0,1\}^{T\times T} be its permutation matrix, with the convention

(PπX)t=Xπ1(t).(P_\pi X)_t = X_{\pi^{-1}(t)}.

Define the corresponding token action by

(πx)t=xπ1(t).(\pi\mathbin{\cdot}x)_t = x_{\pi^{-1}(t)}.

Thus left multiplication by PπP_\pi and the action πx\pi\mathbin{\cdot}x use the same reordering.

A map F:RT×dRT×dF:\mathbb R^{T\times d}\to\mathbb R^{T\times d'} is permutation-equivariant if

F(PπX)=PπF(X)F(P_\pi X) = P_\pi F(X)

for every π\pi and XX. Equivariance is not invariance. An invariant map would satisfy F(PπX)=F(X)F(P_\pi X)=F(X); an equivariant map changes its output, but in a completely prescribed way.

Theorem 6.1 (permutation equivariance of unmasked self-attention). For unmasked attention,

Attn(PπX)=PπAttn(X)(πST).\operatorname{Attn}(P_\pi X) = P_\pi\operatorname{Attn}(X) \qquad (\pi\in S_T).
Proof

Row-wise linear projection commutes with row permutation:

Q(PπX)=(PπX)WQ=PπQ(X).Q(P_\pi X) = (P_\pi X)W_Q = P_\pi Q(X).

The same identity holds for KK and VV. Therefore

S(PπX)=(PπQ)(PπK)dk=PπS(X)Pπ.\begin{aligned} S(P_\pi X) &= \frac{(P_\pi Q)(P_\pi K)^\top}{\sqrt{d_k}}\\ &= P_\pi S(X)P_\pi^\top. \end{aligned}

The matrix on the right simultaneously permutes the rows and columns of SS. Row-wise softmax commutes with this simultaneous permutation, so

A(PπX)=PπA(X)Pπ.A(P_\pi X) = P_\pi A(X)P_\pi^\top.

Finally, using PπPπ=IP_\pi^\top P_\pi=I,

Attn(PπX)=(PπAPπ)(PπV)=PπAV=PπAttn(X).\begin{aligned} \operatorname{Attn}(P_\pi X) &= \bigl(P_\pi AP_\pi^\top\bigr)(P_\pi V)\\ &= P_\pi AV\\ &= P_\pi\operatorname{Attn}(X). \end{aligned}

\square

The simultaneous row—column action on AA has a concrete meaning. If source position jj and query position ii 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 ϕ:RdRd\phi:\mathbb R^d\to\mathbb R^{d'} is applied separately with shared parameters to every row, then

ϕrow(PπX)=Pπϕrow(X).\phi_{\mathrm{row}}(P_\pi X) = P_\pi\phi_{\mathrm{row}}(X).

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 ExRT×dE_x\in\mathbb R^{T\times d} have row Ext,:E_{x_t,:} and let pRT×dp\in\mathbb R^{T\times d} have row ptp_t^\top. Define the token-sequence embedding maps

ι0(x)t=Ext\iota_0(x)_t = E_{x_t}^\top

and

ιp(x)t=Ext+pt.\iota_p(x)_t = E_{x_t}^\top+p_t.

Without positions, embedding commutes with token permutation:

ι0(πx)=Pπι0(x).\iota_0(\pi\mathbin{\cdot}x) = P_\pi\iota_0(x).

With fixed, nonconstant position vectors, in general

ιp(πx)=PπEx+p,Pπιp(x)=PπEx+Pπp.\begin{aligned} \iota_p(\pi\mathbin{\cdot}x) &= P_\pi E_x+p,\\ P_\pi\iota_p(x) &= P_\pi E_x+P_\pi p. \end{aligned}

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. \square

Precision remark 6.3. Adding positional vectors to a particular numerical matrix XX does not make the function XAttn(X)X\mapsto\operatorname{Attn}(X) 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.

  1. Permute completed stream rows. Starting from a numerical matrix XX, compare Attn(PπX)\operatorname{Attn}(P_\pi X) with PπAttn(X)P_\pi\operatorname{Attn}(X). They are equal.
  2. Permute tokens before fixed-position embedding. Compare Attn(ιp(πx))\operatorname{Attn}(\iota_p(\pi\cdot x)) with PπAttn(ιp(x))P_\pi\operatorname{Attn}(\iota_p(x)). 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.

  1. Additive positional embeddings. Use learned vectors p1,,pTmaxp_1,\ldots,p_{T_{\max}}, as in the course project, or fixed sinusoidal coordinates. At angular frequency ω\omega, the two-coordinate feature

    rt(ω)=(sin(ωt),cos(ωt))r_t(\omega) = \bigl(\sin(\omega t),\cos(\omega t)\bigr)

    satisfies

    ri(ω),rj(ω)=cos(ω(ij)).\langle r_i(\omega),r_j(\omega)\rangle = \cos\bigl(\omega(i-j)\bigr).

    Thus absolute vectors also make relative offsets accessible through inner products. The standard fixed construction uses a range of frequencies, for example

    pt,2m=sin ⁣(t/100002m/d),pt,2m+1=cos ⁣(t/100002m/d).p_{t,2m} = \sin\!\left(t/10000^{2m/d}\right), \qquad p_{t,2m+1} = \cos\!\left(t/10000^{2m/d}\right).
  2. Rotary positional embeddings (RoPE). In one two-dimensional query/key coordinate plane, let

    Rθ=(cosθsinθsinθcosθ)SO(2).R_\theta = \begin{pmatrix} \cos\theta&-\sin\theta\\ \sin\theta&\cos\theta \end{pmatrix} \in SO(2).

    Rotate the query at position ii by RiωR_{i\omega} and the key at position jj by RjωR_{j\omega}. Then

    Riωqi,Rjωkj=qiRiωRjωkj=qiR(ji)ωkj.\begin{aligned} \langle R_{i\omega}q_i,R_{j\omega}k_j\rangle &= q_i^\top R_{i\omega}^\top R_{j\omega}k_j\\ &= q_i^\top R_{(j-i)\omega}k_j. \end{aligned}

    The positional contribution to the query—key comparison depends on the relative offset jij-i. 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 STS_T symmetry. In fact, the finite total order has no nontrivial permutation preserving every relation jij\leq i. 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 v1,v2v_1,v_2. Causal attention gives

F(v1,v2)=(v1,v1+v22).F(v_1,v_2) = \left( v_1,\frac{v_1+v_2}{2} \right).

If the two input rows are swapped first, then

F(v2,v1)=(v2,v1+v22).F(v_2,v_1) = \left( v_2,\frac{v_1+v_2}{2} \right).

Swapping the original output instead gives

PF(v1,v2)=(v1+v22,v1),P F(v_1,v_2) = \left( \frac{v_1+v_2}{2},v_1 \right),

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 (zj,vj)(z_j,v_j) and a nonnegative weighting function κ(z,zj)\kappa(z,z_j), the Nadaraya—Watson regression estimate at zz is

f^(z)=jκ(z,zj)vjjκ(z,zj),\widehat f(z) = \frac{\sum_j\kappa(z,z_j)v_j} {\sum_j\kappa(z,z_j)},

provided the denominator is positive.

The word kernel is often used for κ\kappa. 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

κ(qi,kj)=exp ⁣(qi,kjdk).\kappa(q_i,k_j) = \exp\!\left( \frac{\langle q_i,k_j\rangle}{\sqrt{d_k}} \right).

This quantity is strictly positive for finite query and key vectors.

Proposition 7.2 (attention is learned kernel smoothing). Unmasked attention satisfies

Attn(X)i=jκ(qi,kj)vjjκ(qi,kj).\operatorname{Attn}(X)_i = \frac{\sum_j\kappa(q_i,k_j)v_j} {\sum_j\kappa(q_i,k_j)}.

Causal attention satisfies the same formula with the sum restricted to jij\leq i.

Proof

By the definition of row-wise softmax,

Aij=κ(qi,kj)κ(qi,k)A_{ij} = \frac{\kappa(q_i,k_j)} {\sum_\ell\kappa(q_i,k_\ell)}

in the unmasked case. Substituting this expression into jAijvj\sum_jA_{ij}v_j gives the first formula. Under a causal mask, e=0e^{-\infty}=0 removes the terms with j>ij>i from numerator and denominator. \square

This is more flexible than a classical smoother in three ways.

  1. The query locations qiq_i and key locations kjk_j are learned projections of the current features.
  2. The kernel can be asymmetric because WQW_Q and WKW_K need not agree.
  3. The targets vjv_j 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 WQ=WK=0W_Q=W_K=0, then every finite score equals zero. Unmasked attention gives

Aij=1T,Attn(X)i=1Tj=1Tvj.A_{ij}=\frac1T, \qquad \operatorname{Attn}(X)_i = \frac1T\sum_{j=1}^Tv_j.

All output positions receive the same global mean. Under a causal mask,

Aij={1/i,ji,0,j>i,A_{ij} = \begin{cases} 1/i,&j\leq i,\\ 0,&j>i, \end{cases}

and hence

Attn(X)i=1ij=1ivj.\operatorname{Attn}(X)_i = \frac1i\sum_{j=1}^iv_j.

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

Sij=(ij)22s2,s>0.S_{ij} = -\frac{(i-j)^2}{2s^2}, \qquad s>0.

Then causal attention has weights

Aij=exp ⁣((ij)2/(2s2))iexp ⁣((i)2/(2s2))1{ji}.A_{ij} = \frac{ \exp\!\left(-(i-j)^2/(2s^2)\right) }{ \sum_{\ell\leq i} \exp\!\left(-(i-\ell)^2/(2s^2)\right) } \mathbf1_{\{j\leq i\}}.

The positive number ss is the bandwidth. Small ss concentrates near the query position; large ss spreads weight across the prefix. More precisely,

lims0+Attn(X)i=vi,limsAttn(X)i=1ij=1ivj.\lim_{s\to0^+}\operatorname{Attn}(X)_i=v_i, \qquad \lim_{s\to\infty}\operatorname{Attn}(X)_i = \frac1i\sum_{j=1}^iv_j.

This score rule can itself be represented by dot products of positional features. Since row-wise softmax ignores a row constant,

(ij)22s2=ijs2j22s2i22s2-\frac{(i-j)^2}{2s^2} = \frac{ij}{s^2}-\frac{j^2}{2s^2} -\frac{i^2}{2s^2}

is equivalent, for fixed ii, to the first two terms. With dk=2d_k=2, take

qi=(i,1),kj=2(js2,j22s2).q_i=(i,1)^\top, \qquad k_j = \sqrt2 \left( \frac{j}{s^2}, -\frac{j^2}{2s^2} \right)^\top.

Then

qi,kj2=ijs2j22s2,\frac{\langle q_i,k_j\rangle}{\sqrt2} = \frac{ij}{s^2}-\frac{j^2}{2s^2},

which differs from the Gaussian score only by the row constant i2/(2s2)i^2/(2s^2). The two score matrices therefore give identical attention weights.

Example 7.5 (the retrieval limit). Introduce temperature and use

Aij(τ)exp ⁣(qi,kjτdk).A_{ij}^{(\tau)} \propto \exp\!\left( \frac{\langle q_i,k_j\rangle} {\tau\sqrt{d_k}} \right).

As τ0+\tau\to0^+, 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 nn-gram MLP by access to a length-TT sequence. That flexibility has a computational price.

The notation O(g(T,d))O(g(T,d)) suppresses fixed multiplicative constants and lower-order terms in an operation count. For one head, the main forward operations are:

operationoutput shapearithmetic cost
XWQXW_Q and XWKXW_Ktwo T×dkT\times d_k matricesO(Tddk)O(Tdd_k)
XWVXW_VT×dvT\times d_vO(Tddv)O(Tdd_v)
QKQK^\topT×TT\times TO(T2dk)O(T^2d_k)
row-wise softmaxT×TT\times TO(T2)O(T^2)
AVAVT×dvT\times d_vO(T2dv)O(T^2d_v)

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 O(T2)O(T^2) asymptotic order.

Materializing either the score matrix or the attention matrix requires O(T2)O(T^2) memory, in addition to the O(T(dk+dv))O(T(d_k+d_v)) 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

d(2dk+dv)d(2d_k+d_v)

parameters. This count does not depend on TT. 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 sjs_j, choose m=maxjsjm=\max_js_j and write

jesjvjjesj=jesjmvjjesjm.\frac{\sum_je^{s_j}v_j}{\sum_je^{s_j}} = \frac{\sum_je^{s_j-m}v_j}{\sum_je^{s_j-m}}.

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 T×TT\times T 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 tt, the keys and values of positions 1,,t11,\ldots,t-1 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 tt cached keys costs O(tdk)O(td_k) and the weighted value sum costs O(tdv)O(td_v). The cache for one head through length TT uses

O(T(dk+dv))O\bigl(T(d_k+d_v)\bigr)

memory. Summed over TT 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 HH heads with independent query, key, and value projections, concatenates their outputs, and applies an output projection.

When each head has width d/Hd/H, all heads together have 3d23d^2 query, key, and value weights, and the output projection contributes another d2d^2 weights, ignoring biases. Different heads can therefore implement different weighting rules at the same position while the total projection parameter count remains O(d2)O(d^2). 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 BB adds a leading coordinate to every shape:

objectbatched shape
input XXB×T×dB\times T\times d
Q,KQ,KB×T×dkB\times T\times d_k
VVB×T×dvB\times T\times d_v
scores and weightsB×T×TB\times T\times T
outputB×T×dvB\times T\times d_v

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.

assertionmathematical source
all weights are nonnegative and rows sum to oneProposition 3.1
the strict upper triangle is zeroDefinition 4.1
earlier outputs survive a future perturbationProposition 4.3
future input-gradient blocks are zeroProposition 4.3
raw score scale grows like dk\sqrt{d_k}Lemma 5.5
row-permuted unmasked inputs give row-permuted outputsTheorem 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 AijA_{ij} with query position ii on one axis and source position jj 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 (1,0,,0)(1,0,\ldots,0); it has only one permitted source.
  • Row ii distributes unit mass across ii 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 nn-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 TT. 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 Rdk\mathbb R^{d_k} and has rank at most dkd_k. 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 ii depends only on input rows 1,,i1,\ldots,i. 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 diag(p)pp\operatorname{diag}(p)-pp^\top. 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 dkσ4d_k\sigma^4. Dividing by dk\sqrt{d_k} 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.

  1. ★ 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.

  2. ★ 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.

  3. ★ Measure raw and scaled score variance for dk{16,64,256}d_k\in\{16,64,256\}. 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.

  4. Prove Proposition 5.2, including existence and uniqueness of the maximizer. Prove both temperature limits in Remark 5.4, treating multiple score maximizers explicitly.

  5. Starting from the 2×22\times2 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 A1j/S1\partial A_{1j}/\partial S_{1\ell} under each procedure. What changes if post-softmax masking is followed by exact renormalization?

  6. 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.

  7. ★ 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.

  8. Prove rank(QK)dk\operatorname{rank}(QK^\top)\leq d_k. Construct a T>dkT>d_k example in which the row-wise softmax of QKQK^\top has rank larger than dkd_k, showing that the rank bound does not pass through softmax.

  9. Show that XAttn(X)X\mapsto\operatorname{Attn}(X) is Lipschitz on every bounded subset of RT×d\mathbb R^{T\times d}. Explain why the bilinear score map prevents this argument from giving one global Lipschitz constant on the whole space.

  10. Fix keys and values and regard one unmasked output as a function y(q)y(q) of its query. Prove that for a query perturbation hh,

    Dy(q)[h]=1dkjAjh,kj(vjy).Dy(q)[h] = \frac1{\sqrt{d_k}} \sum_jA_j\langle h,k_j\rangle(v_j-y).

    Interpret the centered value vjyv_j-y and determine when this differential is zero for every hh.

  11. 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.

  12. 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.

  13. For one head, compare the arithmetic required to generate TT 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.

  14. Prove the rotary identity

    (Riωq)(Rjωk)=qR(ji)ωk.(R_{i\omega}q)^\top(R_{j\omega}k) = q^\top R_{(j-i)\omega}k.

    What information about ii and jj 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.