To translate “How are you doing” into Chinese, a model has to do two things at once: understand the English sentence, and write the Chinese sentence one token at a time. While writing each Chinese token, it must keep looking back at the English to decide what to say next.
A Transformer encoder is good at the first job, and a Transformer decoder is good at the second. Cross-attention is the bridge that connects them: it lets every position of the decoder look at every word of the source sentence. This reading explains how cross-attention works, where it sits in the full Transformer, and why this encoder–decoder design was such a success for machine translation.
1Sequence-to-sequence with Transformers
Many tasks map one sequence to another: translation, summarization, question answering with a written answer. The standard design has two parts:
- an encoder that reads the source sentence $x_1,\dots,x_n$ (e.g., How are you doing) and produces one context-aware vector per source word. It uses full self-attention: every source word can see every other source word.
- a decoder that generates the target sentence $y_1,\dots,y_m$ (e.g., 你 好 嗎) one token at a time, starting from
<bos>. It uses masked self-attention: each target position sees only itself and earlier target positions.
Something is missing. With only masked self-attention, the decoder sees nothing but the target tokens produced so far; it has no idea what the source sentence says. It needs a way to read the encoder's output. That is exactly what cross-attention provides.
2How cross-attention works
Cross-attention is ordinary attention in which the three roles are split between the two sequences:
- Queries come from the decoder: each target position asks “what in the source do I need right now?”
- Keys and values come from the encoder: each source word offers a key (to be matched) and a value (the information it passes on).
Let $H_{\text{dec}}\in\mathbb{R}^{m\times d}$ hold the decoder's vectors for the $m$ target positions (the output of its masked self-attention sublayer), and $H_{\text{enc}}\in\mathbb{R}^{n\times d}$ hold the encoder's final output vectors for the $n$ source words. Then
$$Q = H_{\text{dec}}W^Q,\qquad K = H_{\text{enc}}W^K,\qquad V = H_{\text{enc}}W^V,$$ $$\text{CrossAttention} = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.$$A few things to notice:
- The attention matrix $QK^\top$ has shape $m\times n$ (target length × source length). It is generally not square: row $t$ holds how much target position $t$ attends to each source word.
- The output has one vector per target position ($m\times d_v$): each target position receives a weighted summary of the source.
- No causal mask is needed. The whole source sentence is available from the start, so every target position may look at every source word.
- The encoder runs once. Every decoder layer uses the same final encoder output $H_{\text{enc}}$, projected with that layer's own $W^K$ and $W^V$. Like self-attention, cross-attention is multi-headed.
<bos> 你 好 嗎, and each position predicts the next token. Pick a query to see how much it attends to each source word (line thickness and the highlighted row of the $4\times 4$ matrix). The weights are illustrative, chosen to resemble what a trained model might learn.3Three kinds of attention
An encoder–decoder Transformer uses attention in three different places. They differ only in where the queries, keys, and values come from, and whether a mask is applied:
| Attention | Queries from | Keys & values from | Mask | Matrix shape |
|---|---|---|---|---|
| Encoder self-attention | encoder | encoder | none | $n\times n$ |
| Decoder masked self-attention | decoder | decoder | causal | $m\times m$ |
| Cross-attention | decoder | encoder output | none | $m\times n$ |
<bos> 你 好 嗎 (red).4The full Transformer
Putting everything together gives the original Transformer architecture. The encoder is a stack of $N$ identical layers, each with two sublayers. The decoder is a stack of $N$ layers, each with three sublayers; cross-attention is the one in the middle.
Training and generation
- Training: the encoder reads the source; the decoder receives the whole true target shifted right (
<bos>你 好 嗎) and predicts the next token at every position (你 好 嗎<eos>) in parallel. The causal mask in the decoder's self-attention prevents cheating; cross-attention needs no mask. The loss is the cross-entropy summed over target positions. - Generation: run the encoder once on the source. Then generate target tokens one at a time, as in any decoder; at every step, cross-attention reads the same encoder output, so its keys and values can be computed once and reused.
5Results and cost
The Transformer was introduced for machine translation, evaluated with BLEU: a score from 0 to 100 measuring how many $n$-grams of the system's translation also appear in human reference translations (higher is better). On the WMT 2014 English–German and English–French benchmarks it beat the previous best systems, including ensembles, at a fraction of the training cost:
| Model | BLEU EN–DE | BLEU EN–FR | Training cost EN–DE (FLOPs) |
|---|---|---|---|
| GNMT + RL (recurrent) | 24.6 | 39.92 | $2.3\cdot 10^{19}$ |
| ConvS2S (convolutional) | 25.16 | 40.46 | $9.6\cdot 10^{18}$ |
| ConvS2S ensemble | 26.36 | 41.29 | $7.7\cdot 10^{19}$ |
| Transformer (base) | 27.3 | 38.1 | $3.3\cdot 10^{18}$ |
| Transformer (big) | 28.4 | 41.8 | $2.3\cdot 10^{19}$ |
Numbers from Vaswani et al. (2017), Table 2.
Why is it cheaper to train?
The paper compares three kinds of layers for a sequence of length $n$ with dimension $d$ (and kernel size $k$ for convolutions):
| Layer | Computation per layer | Sequential steps | Max path length between two words |
|---|---|---|---|
| Self-attention | $O(n^2\cdot d)$ | $O(1)$ | $O(1)$ |
| Recurrent | $O(n\cdot d^2)$ | $O(n)$ | $O(n)$ |
| Convolutional | $O(k\cdot n\cdot d^2)$ | $O(1)$ | $O(\log_k n)$ (stacked dilated convolutions) |
- Sequential steps: a recurrent layer must process the words one after another; self-attention handles all positions at once, which suits GPUs.
- Path length: in self-attention any two words are directly connected, so long-range dependencies are easier to learn.
- Computation: self-attention costs $n^2 d$ versus $n d^2$ for a recurrent layer. It is cheaper when $n \lt d$, which is typical for sentences (e.g., $n\approx 30$, $d=512$), but becomes expensive for very long sequences.
6Summary
- An encoder–decoder Transformer reads the source with an encoder and generates the target with a decoder.
- Cross-attention connects them: queries from the decoder, keys and values from the encoder's final output.
- The cross-attention matrix is $m\times n$ (target × source) and needs no mask.
- Each decoder layer has three sublayers: masked self-attention, cross-attention, feed-forward, each followed by Add & Norm.
- The Transformer reached state-of-the-art translation quality with much lower training cost, thanks to parallel computation and short paths between words.
7Practice
Exercise 1: shapes
A source sentence has $n=12$ tokens and the target has $m=9$ tokens, with $d=512$ and $d_k=d_v=64$ for one head. Give the shapes of $Q$, $K$, $V$, $QK^\top$, and the cross-attention output.
Exercise 2: which attention?
For each statement, name the kind of attention: (a) the query is 好 and the keys are <bos>, 你, 好; (b) the query is you and the keys are all four English words; (c) the query is 好 and the keys are all four English words.
Exercise 3: cost
With $d=512$, for which sequence lengths is a self-attention layer cheaper than a recurrent layer (ignoring constants)?
Quick quiz
8Further reading
- Voita. Sequence to Sequence (seq2seq) and Attention. NLP Course For You. (From recurrent attention to the Transformer, with clear figures.)
- Alammar. The Illustrated Transformer. (See “The Decoder Side” for encoder–decoder attention.)
- Harvard NLP. The Annotated Transformer. (The full model in PyTorch, including where cross-attention gets its keys and values.)
- Vaswani et al. (2017). Attention Is All You Need. NeurIPS. (Sections 3.2.3 and 4; Tables 1 and 2.)