Cross-attention is an attention mechanism in which the queries come from one sequence and the keys and values come from a different sequence, so that each position in the first stream can retrieve relevant information from the second. In neural networks, and above all in the transformer, it is the component that connects two sources of information: a decoder to an encoder, an image generator to a text prompt or a language model to visual features.
In the original transformer for machine translation it was called encoder-decoder attention, because every decoder layer used it to look at the encoded source sentence. The same operation now underpins text-to-image diffusion, speech recognition and many multimodal systems.
How cross-attention computes its output
Cross-attention uses the same scaled dot-product attention as self-attention; only the origin of its inputs differs. The target sequence X, for example decoder states, is projected into queries Q = XW_Q, while the source sequence C, for example encoder outputs, is projected into keys K = CW_K and values V = CW_V.
The output is softmax(QK^T / sqrt(d_k)) V. Each query produces a probability distribution over source positions, and the output vector is the weighted sum of the source values. The result therefore has the length of the target sequence but carries content drawn from the source. The scaling by the square root of the key dimension keeps the softmax from saturating when vectors are large.
The table lists the tensors involved and their shapes for a single attention head.
| Tensor | Comes from | Shape |
|---|---|---|
| Queries Q | Target sequence of length n | n × d_k |
| Keys K | Source sequence of length m | m × d_k |
| Values V | Source sequence of length m | m × d_v |
| Attention weights | softmax of QK^T scaled | n × m |
| Output | Weights multiplied by V | n × d_v |
In practice cross-attention is multi-head: several heads with separate projections run in parallel, their outputs are concatenated and projected again, and the block is wrapped with a residual connection and layer normalization like any other transformer sublayer.
Cross-attention compared with self-attention
The essential difference is that self-attention mixes information within one sequence, while cross-attention imports information from another. The comparison below summarizes the practical consequences.
| Property | Self-attention | Cross-attention |
|---|---|---|
| Source of Q, K, V | All from the same sequence | Q from target, K and V from source |
| Weight matrix size | n × n | n × m |
| Causal masking | Needed in decoders | Usually not needed |
| Typical role | Builds context within a sequence | Conditions output on external input |
| Caching at inference | Key-value cache grows per token | Source keys and values computed once |
Because the source is fully known before decoding begins, its keys and values can be computed once and reused for every generated token. This makes cross-attention comparatively cheap during autoregressive generation, with cost that grows linearly with source length for each new target token.
Where cross-attention appears in modern architectures
Cross-attention is the standard conditioning mechanism whenever a model must generate or process one modality under the guidance of another. Its placement differs between architectures, as the table shows.
| Architecture | Queries from | Keys and values from |
|---|---|---|
| Encoder-decoder transformer | Decoder token states | Encoded source sentence |
| Speech recognition model | Text decoder states | Encoded audio frames |
| Latent diffusion U-Net | Image latent features | Text encoder embeddings |
| Perceiver-style model | Small learned latent array | Large raw input array |
| Vision-language model | Language model states | Image encoder features |
In text-to-image diffusion, cross-attention layers inside the U-Net let each spatial region of the image attend to the prompt tokens, which is why editing techniques can manipulate the attention maps to move or reweight objects. Perceiver-style models use cross-attention in the opposite direction to compress a very long input into a fixed number of latent vectors, avoiding the quadratic cost of full self-attention over the raw input.
Design choices and computational cost
The cost of cross-attention is proportional to n × m, the product of target and source lengths, in both computation and attention-matrix memory. Designers control this cost and the quality of conditioning through a few decisions.
- Placement: inserting cross-attention in every layer gives fine-grained conditioning; inserting it every few layers saves compute.
- Source length: pooling or compressing the source, for example with learned latents, reduces m and therefore cost.
- Gating: some multimodal models add a learnable gate initialized near zero, so a pretrained language model is not disrupted when new cross-attention layers are added.
- Head sharing: grouped-query or multi-query variants reduce the size of cached source keys and values.
An alternative to cross-attention is to concatenate both sequences and use self-attention only, as decoder-only models often do with image tokens. Concatenation is simpler and lets the source attend to the target, but it lengthens the sequence and gives up the clean separation that cross-attention provides.
Common pitfalls and misreadings
Cross-attention is easy to implement but also easy to misuse or overinterpret. The following table lists frequent problems.
| Symptom | Likely cause | Remedy |
|---|---|---|
| Output ignores the condition | Weak or untrained cross-attention | Add classifier-free guidance or more conditioned data |
| Padding tokens receive attention | Missing source padding mask | Mask padded key positions |
| Memory spikes on long inputs | Large n × m attention matrix | Use memory-efficient attention kernels |
| Misleading alignment plots | Treating weights as explanations | Validate with ablation tests |
Attention maps are useful diagnostics, but attention weights are not proof of causal influence. A high weight shows where information was read, not that it determined the output, so interpretability claims should be checked with interventions.
In everyday language
Cross-attention lets one part of a model look things up in another. Imagine a translator writing a sentence in French. For each word, the translator glances back at the English original. The glance picks the most relevant words to use next.
Cross-attention does the same with numbers. One stream asks questions. The other stream holds the answers. The model mixes in the information that matters most at each step.
Seen in the real world
A product designer types the prompt “a red ceramic mug on a wooden desk, morning light” into a text-to-image diffusion model. The text encoder turns the prompt into a sequence of token embeddings. At every denoising step, cross-attention layers in the image network let each patch of the developing picture query those embeddings, so regions that become the mug draw strongly on the words “red” and “ceramic”.
When the first image shows a pale mug, the designer uses an editing tool that increases the attention weight on the token “red”. The regenerated image keeps the same layout but shows a deeper color, because only the conditioning strength changed. The example illustrates why cross-attention is the main point of control between language and image in such systems.