Chapter 4 · Section 4.6 · 50 min

Self-attention, cross-attention, and symmetry

"Dog bites man" is not news. "Man bites dog" is. The two sentences contain exactly the same words, and every reader knows they mean opposite things. Here is a surprising fact about the attention layer we have built. Without some extra ingredient, it cannot tell them apart. It would assign "dog" the same output vector in both sentences, and the same for "bites" and "man". We will prove this, because it is the cleanest example of a symmetry in deep learning and the reason every Transformer adds positional information to its inputs.

First, though, we generalize. Everything so far has been self-attention, where queries, keys, and values all come from the same sequence. Nothing forces that. The query side and the key-value side can be different sequences entirely, which is cross-attention, the original form of attention in translation and today the standard way to connect one modality to another. The section ends with two ideas that change how you see attention, as message passing on a graph, and as an operation on sets that the Perceiver turned into a general-purpose architecture.

Where the queries, keys, and values come from

Self-attention. One sequence X∈RT×d\mathbf{X} \in \R^{T\times d} supplies everything, Q=XWQ\mathbf{Q} = \mathbf{X}\mathbf{W}_Q, K=XWK\mathbf{K} = \mathbf{X}\mathbf{W}_K, V=XWV\mathbf{V} = \mathbf{X}\mathbf{W}_V. Each token gathers information from the other tokens of its own sequence. The score matrix is square, T×TT\times T.

Cross-attention. The queries come from one sequence X∈RTq×d\mathbf{X} \in \R^{T_q\times d}, and the keys and values from another, Z∈RTk×dz\mathbf{Z} \in \R^{T_k\times d_z}, often called the context or memory,

Q=XWQ,K=ZWK,V=ZWV,WQ∈Rd×dk, WK∈Rdz×dk, WV∈Rdz×dv,\mathbf{Q} = \mathbf{X}\mathbf{W}_Q, \quad \mathbf{K} = \mathbf{Z}\mathbf{W}_K, \quad \mathbf{V} = \mathbf{Z}\mathbf{W}_V, \qquad \mathbf{W}_Q \in \R^{d\times d_k},\ \mathbf{W}_K \in \R^{d_z\times d_k},\ \mathbf{W}_V \in \R^{d_z\times d_v}, O=softmax⁡ ⁣(QK⊤dk)V∈RTq×dv.\mathbf{O} = \operatorname{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V} \in \R^{T_q\times d_v}.

In plain words, each position of X\mathbf{X} asks a question, and the answers are looked up in Z\mathbf{Z}.

Three facts follow from the shapes. The score matrix is Tq×TkT_q\times T_k, generally not square. The output has one row per query, so cross-attention returns a sequence as long as X\mathbf{X}, enriched with information from Z\mathbf{Z}. And the two sequences can have different widths, dd and dzd_z, because WK\mathbf{W}_K and WV\mathbf{W}_V translate the context into the query's key space. An image encoder with 1,024-dimensional features can feed a language model of width 4,096 this way.

This is Bahdanau attention (§3.6) in modern notation, with a scaled dot product in place of the additive score. The decoder state is the query, and the encoder states are the keys and values. In the original Transformer, each decoder layer has three sublayers in order, a causal self-attention over the target tokens generated so far, then a cross-attention whose queries come from the decoder and whose keys and values come from the final encoder output, then a feed-forward network (Vaswani et al. 2017). The cross-attention needs no causal mask, because the whole source sentence is known before decoding starts. It does need the source's padding mask. And since the encoder output never changes during generation, each layer computes its cross-attention keys and values once per source and reuses them for every generated token.

The same block appears all over modern AI. Speech recognizers like Whisper cross-attend from text tokens to audio features. Text-to-image diffusion models cross-attend from image patches to the prompt's text embeddings, which is how the prompt steers the picture. Llama 3's vision adapter feeds image-encoder features into the language model through a series of cross-attention layers (Llama Team 2024), and vision-language models in the Flamingo family do the same with gated cross-attention layers inserted into a frozen language model.

Python · cell 1
Interview

Multi-head cross-attention with a source padding mask

Implement cross_attention(X, Z, W_Q, W_K, W_V, W_O, h, z_mask=None). X has shape (B, T_q, d) and supplies the queries. Z has shape (B, T_k, d_z) and supplies the keys and values. W_Q is (d, d), W_K and W_V are (d_z, d), W_O is (d, d), there are h heads of width dk=d/hd_k = d/h, and z_mask is an optional boolean array of shape (B, T_k) that is True for real source tokens. No causal mask. Return the output of shape (B, T_q, d). No loops over heads.

Hidden tests, hints, and AI help, from $1.99 a month.

Attention does not know the order of its inputs

Now the symmetry. Reorder the tokens of a sequence, and ask what happens to the outputs of self-attention. Let's first check numerically on "dog bites man" with random embeddings and random weights, and no position information.

Python · cell 2

Each word gets exactly the same output in both sentences, just in a different row. The outputs are permuted along with the inputs. Any summary that ignores row order, such as the mean, is therefore identical for the two sentences, so a classifier built on it would give "dog bites man" and "man bites dog" the same label. This property has a name.

Definition. A function ff from T×dT\times d matrices to T×d′T\times d' matrices is permutation equivariant if f(PX)=Pf(X)f(\mathbf{P}\mathbf{X}) = \mathbf{P}f(\mathbf{X}) for every T×TT\times T permutation matrix P\mathbf{P}. It is permutation invariant if f(PX)=f(X)f(\mathbf{P}\mathbf{X}) = f(\mathbf{X}).

Here a permutation matrix has exactly one 1 in every row and every column. If π\pi is a permutation of {1,…,T}\{1, \dots, T\} and P\mathbf{P} has Pi,π(i)=1P_{i,\pi(i)} = 1, then row ii of PX\mathbf{P}\mathbf{X} is row π(i)\pi(i) of X\mathbf{X}, so PX\mathbf{P}\mathbf{X} is the same tokens in a new order. Permutation matrices are orthogonal, P⊤P=I\mathbf{P}^\top\mathbf{P} = \mathbf{I}, because undoing a reordering is another reordering.

The proof

Theorem. Self-attention without a mask, f(X)=softmax⁡ ⁣(XWQ(XWK)⊤/dk) XWVf(\mathbf{X}) = \operatorname{softmax}\!\big(\mathbf{X}\mathbf{W}_Q(\mathbf{X}\mathbf{W}_K)^\top/\sqrt{d_k}\big)\,\mathbf{X}\mathbf{W}_V with a row-wise softmax, is permutation equivariant.

We need one lemma about the softmax first.

Lemma. For any matrix S∈RT×T\mathbf{S} \in \R^{T\times T} and permutation matrix P\mathbf{P}, the row-wise softmax satisfies softmax⁡(PSP⊤)=Psoftmax⁡(S)P⊤\operatorname{softmax}(\mathbf{P}\mathbf{S}\mathbf{P}^\top) = \mathbf{P}\operatorname{softmax}(\mathbf{S})\mathbf{P}^\top.

Proof of the lemma. Entry (i,j)(i, j) of PSP⊤\mathbf{P}\mathbf{S}\mathbf{P}^\top is ∑a,bPiaSabPjb=Sπ(i)π(j)\sum_{a,b}P_{ia}S_{ab}P_{jb} = S_{\pi(i)\pi(j)}, so permuting this way reorders both the rows and the columns of S\mathbf{S} by π\pi. Apply the softmax to row ii,

softmax⁡(PSP⊤)ij=eSπ(i)π(j)∑leSπ(i)π(l)=eSπ(i)π(j)∑leSπ(i)l=softmax⁡(S)π(i)π(j)=(Psoftmax⁡(S)P⊤)ij.\operatorname{softmax}(\mathbf{P}\mathbf{S}\mathbf{P}^\top)_{ij} = \frac{e^{S_{\pi(i)\pi(j)}}}{\sum_{l} e^{S_{\pi(i)\pi(l)}}} = \frac{e^{S_{\pi(i)\pi(j)}}}{\sum_{l} e^{S_{\pi(i)l}}} = \operatorname{softmax}(\mathbf{S})_{\pi(i)\pi(j)} = \big(\mathbf{P}\operatorname{softmax}(\mathbf{S})\mathbf{P}^\top\big)_{ij}.

The middle step holds because as ll runs over all positions, so does π(l)\pi(l), and a sum does not depend on the order of its terms. ∎

Proof of the theorem. Replace X\mathbf{X} by PX\mathbf{P}\mathbf{X}. The projections act row by row, so Q′=PXWQ=PQ\mathbf{Q}' = \mathbf{P}\mathbf{X}\mathbf{W}_Q = \mathbf{P}\mathbf{Q}, and likewise K′=PK\mathbf{K}' = \mathbf{P}\mathbf{K} and V′=PV\mathbf{V}' = \mathbf{P}\mathbf{V}. The scores become

S′=PQ(PK)⊤dk=P QK⊤dk P⊤=PSP⊤.\mathbf{S}' = \frac{\mathbf{P}\mathbf{Q}(\mathbf{P}\mathbf{K})^\top}{\sqrt{d_k}} = \mathbf{P}\,\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\,\mathbf{P}^\top = \mathbf{P}\mathbf{S}\mathbf{P}^\top .

By the lemma, A′=PAP⊤\mathbf{A}' = \mathbf{P}\mathbf{A}\mathbf{P}^\top. Finally,

f(PX)=A′V′=PAP⊤PV=PAV=Pf(X),f(\mathbf{P}\mathbf{X}) = \mathbf{A}'\mathbf{V}' = \mathbf{P}\mathbf{A}\mathbf{P}^\top\mathbf{P}\mathbf{V} = \mathbf{P}\mathbf{A}\mathbf{V} = \mathbf{P}f(\mathbf{X}),

using P⊤P=I\mathbf{P}^\top\mathbf{P} = \mathbf{I}. ∎

In plain words, reordering the tokens reorders the queries, keys, and values in the same way, the attention matrix gets its rows and columns shuffled consistently, and every token ends up with exactly the output it had before, sitting in its new slot.

The result extends to a whole Transformer. Multi-head attention is a sum of equivariant heads followed by a row-wise WO\mathbf{W}_O, so it is equivariant. The MLP, LayerNorm, and residual connection each act on every row separately, and any row-wise map gg satisfies g(PX)=Pg(X)g(\mathbf{P}\mathbf{X}) = \mathbf{P}g(\mathbf{X}). A composition of equivariant maps is equivariant, since f2(f1(PX))=f2(Pf1(X))=Pf2(f1(X))f_2(f_1(\mathbf{P}\mathbf{X})) = f_2(\mathbf{P}f_1(\mathbf{X})) = \mathbf{P}f_2(f_1(\mathbf{X})). So an encoder with no positional information is permutation equivariant from end to end, and anything it outputs after mean pooling is permutation invariant. It treats its input as a set of tokens (strictly, a multiset, since repeated tokens are allowed).

Cross-attention has a slightly different symmetry. Permuting the context with Pz\mathbf{P}_z gives scores SPz⊤\mathbf{S}\mathbf{P}_z^\top (the columns are reordered), the row-wise softmax commutes with that reordering, and the output is softmax⁡(S)Pz⊤PzV=O\operatorname{softmax}(\mathbf{S})\mathbf{P}_z^\top\mathbf{P}_z\mathbf{V} = \mathbf{O}. Cross-attention is invariant to the order of its context and equivariant in its queries. Exercise 4.6a tested exactly this.

Why position must be added, and what breaks the symmetry

For sets, equivariance is exactly right. A point cloud, the atoms of a molecule, the objects in a scene, or a bag of retrieved documents has no natural order, and a model that depended on the order you happened to list them in would be wrong. For language it is a disaster, since order carries meaning. The fix is to break the symmetry on purpose by making each token's vector depend on its position, for instance by adding a position vector pt\mathbf{p}_t to the embedding at position tt. Then permuting the tokens does not permute the position vectors, which stay attached to slots, and the proof above no longer applies. How to choose those vectors (sinusoidal, learned, or relative, as in rotary embeddings) is the subject of §5.4 and §5.5.

There is a subtlety that catches people out in interviews. A causal mask also breaks the symmetry. The proof used S′=PSP⊤\mathbf{S}' = \mathbf{P}\mathbf{S}\mathbf{P}^\top. With a fixed mask M\mathbf{M} the masked scores become PSP⊤+M\mathbf{P}\mathbf{S}\mathbf{P}^\top + \mathbf{M}, which equals P(S+M)P⊤\mathbf{P}(\mathbf{S}+\mathbf{M})\mathbf{P}^\top only if PMP⊤=M\mathbf{P}\mathbf{M}\mathbf{P}^\top = \mathbf{M}, and for the causal mask only the identity permutation does that. A decoder therefore knows something about position even with no position encoding at all. The cleanest way to see it is that the first token can attend only to itself, the second to two tokens, and so on. A head whose scores are all equal attends uniformly to the tt tokens it can see, and if the first token's value is distinctive, the output at position tt is exactly 1/t1/t times that value. Position is written into the output.

Python · cell 3

This is not just a curiosity. Haviv et al. (2022) trained causal language models with no positional encoding at all and found them competitive with models that had one, and probes showed the models had learned absolute position internally. Kazemnejad et al. (2023) found that, on a suite of small-scale reasoning and arithmetic tasks, such "NoPE" decoders generalized to sequences longer than those seen in training better than decoders with absolute, rotary, or ALiBi encodings. Whether that holds for large language models is not settled. Encoders like BERT have no such escape, since without a causal mask they are fully equivariant and need explicit positions.

Does self-attention care about the order of its inputs?
Five tokens go through one self-attention head. Reorder them and compare each word's output with its output in the original order. Then add positions or a causal mask.
Loading interactive figure…

Attention as message passing on a graph

Here is another way to read oi=∑jaijvj\mathbf{o}_i = \sum_j a_{ij}\mathbf{v}_j. Draw each token as a node. Draw an edge from jj to ii whenever ii may attend to jj. A layer of attention then performs one round of message passing. Every node jj prepares a message vj\mathbf{v}_j, every node ii assigns its incoming edges the weights aija_{ij} (a softmax over its neighbors only), and every node replaces its state with the weighted sum of its incoming messages. Self-attention without a mask runs on the complete graph. Each mask from §4.4 is just a different edge set.

maskgrapheach node hears from
none (encoder)complete graph with self-loopsevery token
causala directed acyclic graph, edges from earlier to lateritself and every earlier token
block-diagonal (packed)disjoint cliques, one per documentits own document (causally)
sliding window wwa bandthe last ww tokens, so LL layers reach L(w−1)L(w-1) back
cross-attentionbipartite, from context nodes to query nodesevery context token

This view connects Transformers to graph neural networks. A Graph Attention Network (Veličković et al. 2018) is attention restricted to the edges of a given graph, with its own (additive) score function and multiple heads. Joshi (2020) put the connection plainly, that a Transformer is a graph neural network on the complete graph of its tokens. The complete graph has no structure of its own, so whatever the model knows about order has to arrive as node features, which is the job of positional encodings. It also explains the cost. Message passing costs one message per edge, and the complete graph on TT nodes has T2T^2 edges, which is where the quadratic cost of §4.7 comes from. Sparse attention patterns (§12.6) are cheaper graphs, chosen so that information still reaches everywhere within a few layers.

What graph does each mask define, and how far can information travel?
Tokens are nodes. Click a node to make it the query. Arrows show the messages it receives, with thickness equal to the attention weight. Faint lines are the other edges of the graph.
Loading interactive figure…
Core

Attention restricted to a graph

Implement graph_attention(X, adj, W_Q, W_K, W_V) for node features X of shape (n, d) and a boolean adjacency matrix adj of shape (n, n), where adj[i, j] is True when node ii may receive a message from node jj. Every node always receives from itself (add self-loops whether or not adj has them). Return the (n, d_v) outputs of single-head scaled dot-product attention over each node's neighbors.

Hidden tests, hints, and AI help, from $1.99 a month.

Sets, learned queries, and the Perceiver

If attention is naturally an operation on sets, we can design for that instead of fighting it. Three ideas build on each other.

Pooling a set with a learned query. To summarize a set into one vector, cross-attend to it with a single learned query vector q\mathbf{q} that is a parameter of the model, o=∑jsoftmax⁡j(q⊤kj/dk) vj\mathbf{o} = \sum_j \operatorname{softmax}_j(\mathbf{q}^\top\mathbf{k}_j/\sqrt{d_k})\,\mathbf{v}_j. By the cross-attention result above, the output is invariant to the order of the set. Zaheer et al. (2017) proved that for sets drawn from a countable universe every permutation-invariant function can be written as ρ(∑jϕ(xj))\rho\big(\sum_j\phi(\mathbf{x}_j)\big) (the Deep Sets form), and attention pooling is a learned, input-dependent weighting of that sum. Lee et al. (2019) built the Set Transformer from such blocks, using a few learned "seed" queries to pool, and a few learned "inducing points" to cut the cost of self-attention over large sets.

Learned queries as slots. Use several learned queries, and cross-attention returns several summaries, one per query, each free to specialize. DETR (Carion et al. 2020) detects objects with 100 learned "object queries" that cross-attend to image features, and each query learns to claim one object. The Q-Former and similar resamplers in vision-language models compress hundreds of image patches into a fixed, small number of tokens the same way.

The Perceiver. Self-attention over MM inputs costs O(M2)O(M^2) per layer, hopeless for raw inputs like the 50,176 pixels of a 224×224224\times224 image. Jaegle et al. (2021) proposed a small array of N≪MN \ll M learned latent vectors that cross-attend to the input, at cost O(MN)O(MN), followed by a deep stack of self-attention among the latents, at O(N2)O(N^2) per layer, independent of MM. The input is touched only through cross-attention, so the depth of the network is decoupled from the size of its input, and one architecture handles images, audio, point clouds, and video given suitable position features. Perceiver IO (Jaegle et al. 2021b) adds a cross-attention at the output, with one query per desired output element, so the outputs can be structured however a task needs.

Python · cell 4
Core

Attention pooling with a learned query

Implement attention_pool(X, q, W_K, W_V, mask=None) that summarizes a set X of shape (B, n, d) into one vector per example, shape (B, d_v), using a single learned query q of shape (d_k,) shared by all examples, keys X @ W_K, values X @ W_V, scaled dot-product scores, and an optional boolean mask of shape (B, n) (True for real elements, at least one per row). The result must not depend on the order of the set, and padded elements must be ignored.

Hidden tests, hints, and AI help, from $1.99 a month.

In PyTorch

PyTorch's attention functions take the query and the key-value sequences separately, so cross-attention needs nothing new. Here is an encoder-decoder layer's cross-attention with a source padding mask, followed by a numerical check of permutation equivariance for a whole encoder layer.

🔥 In PyTorchfor a machine with PyTorch

Read more

Watch next

🎬 Let's build GPT: from scratch, in code, spelled out. · Andrej Karpathy · starts at 71:38Karpathy's notes on attention as communication, on attention operating over sets, and on self- versus cross-attention.
🎬 Attention Is All You Need · Yannic KilcherA paper reading of the original Transformer, including how the decoder cross-attends to the encoder.