# What Is Cross-Attention?

> How cross-attention lets one text look at another, in translation and image generators, explained simply for your AI interview.

**In short:** Cross-attention is an attention layer where one sequence's queries look at another sequence's keys and values. A translation model uses it to read the source text while it writes.

AI and LLM interview question Q051, Transformer architecture. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-cross-attention

## Say it in 30 seconds

Cross-attention is attention between two pieces of text. One side asks questions with its queries, and the other side answers with its keys and values. In a translation model, the English writer looks across at the German source as it writes each word. Self-attention is the same idea inside one text. Cross-attention is also how a text prompt can steer an image generator.

## Say it in 2 minutes

Attention lets a model weigh which other words matter for the word it is working on. Self-attention does this inside one text. Cross-attention does it between two. The words on one side make queries, the words on the other side offer keys and values, and the model blends the values that match best.

Take an encoder-decoder model that translates. The encoder reads the German contract clause once and turns it into a set of vectors, one per word. The decoder writes English one word at a time. For each English word it makes a query and looks across at the German vectors. So the word deadline leans on the German words for delivery period and days.

Cross-attention is a layer inside the decoder, after self-attention and before the feed-forward step. Not every model has it. A decoder-only model has no encoder, so the prompt and any retrieved text sit in one stream and use self-attention. Image generators use cross-attention to let a text prompt guide the picture.

In a real project I would also flag the practical catch. When you join a pretrained encoder and decoder, the cross-attention layers may start with random numbers, so they must be trained. And every writing step compares with every source word, so long documents cost more time and memory.

## What is cross-attention, in plain words?

A model uses attention to decide which other words matter for the word it is working on. Self-attention does this inside one text, so every word looks at the other words of its own sentence. Cross-attention does it between two texts: the words of one sequence look at the words of another.

Picture a claims handler at an insurer writing a reply letter with the policy wording open beside her. For each sentence she writes, she checks the right clause. The letter is one text and the policy is another, and she keeps looking across from one to the other. A translation model does the same. It writes English while it looks back at the German contract it is translating.

- **Query:** The question a word asks: what do I need from the other text?
- **Key and value:** Each word of the other text offers a key (what it is about) and a value (what it carries).
- **Encoder:** The part that reads the source text and turns it into vectors (lists of numbers), one per word.
- **Decoder:** The part that writes the output one word at a time, looking at the words it has already written.
- **Encoder-decoder model:** A model with two parts: an encoder that reads one text, and a decoder that writes another.

## How does cross-attention work?

The decoder makes a query for the word it is writing. The encoder has already read the source, so each source word has a key and a value. The query is compared with every key. Those scores become weights that add up to one, and the output is the weighted mix of the values.

*Diagram, Who asks, who answers: The English word being written sends a query. The German encoder output offers keys and values. The blend that comes back is the context the next English word is built from.*
1. The English word being written sends its question.
2. The German encoder output offers keys and values.
3. The blend that comes back is the context for the next word.

The 2017 Transformer paper, Attention Is All You Need, calls this layer "encoder-decoder attention". It says the queries come from the previous decoder layer, while the memory keys and values come from the encoder.

> "the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder" (Vaswani et al., Attention Is All You Need (2017))

1. **Build the query:** The decoder turns the word it is writing into a query, a list of numbers that says what it needs.
2. **Read the keys:** Each German word already has a key, a list of numbers that says what it is about. The query is compared with every key.
3. **Turn scores into weights:** A softmax step, a standard way to turn scores into weights that add up to one, gives the best matches the most say.
4. **Blend the values:** The output is the weighted mix of the matching values, and the next word is built from it.

## Where does it sit in a decoder layer?

Inside a decoder layer the steps run in order. Self-attention reads the English written so far, which keeps the sentence consistent. Cross-attention then reads the encoder output. A feed-forward step last works on each word alone.

The 2017 paper gives every decoder layer this extra look-across step. The decoder must also be blocked from looking at later words. The paper says this preserves the auto-regressive property, meaning each new word is predicted from the words before it.

*Diagram, One decoder layer, in order: One decoder layer, in order: self-attention on the English so far, cross-attention on the German encoder output, then a feed-forward step. The decoder stacks several of these layers, so this pass repeats.*
1. The English written so far goes into the layer.
2. Self-attention checks it against itself first.
3. The German encoder output meets the layer here.
4. The German context passes on to the feed-forward step.
5. The result picks the next English word.

## What does it look like with real numbers?

A legal team at a logistics firm translates supplier contracts from German into English. The English writer has reached the word deadline. The German clause says Die Lieferfrist betraegt 30 Tage, which means the delivery period is 30 days. Here is one step with made-up numbers, so you can follow the arithmetic.

```python
# One English word is being written. Its query asks the four German words for help.
# Keys say what each German word is about; values carry what it adds. Made-up numbers.
import math

german = ["Lieferfrist", "betraegt", "30", "Tage"]
keys = [[1.0, 0.2], [0.1, 0.9], [0.0, 0.1], [0.8, 0.3]]
values = [[2.0, 0.0], [0.0, 1.0], [0.5, 0.5], [1.5, 0.5]]
query = [1.2, 0.4]  # the decoder's question while it writes "deadline"

scores = [sum(q * k for q, k in zip(query, key)) / math.sqrt(2) for key in keys]
exps = [math.exp(s) for s in scores]
weights = [e / sum(exps) for e in exps]
mix = [sum(w * v[i] for w, v in zip(weights, values)) for i in range(2)]

for word, w in zip(german, weights):
    print(f"{word:12} weight {w:.2f}")
print("mixed context:", [round(x, 2) for x in mix])
```

Output:

```text
Lieferfrist  weight 0.35
betraegt     weight 0.20
30           weight 0.15
Tage         weight 0.30
mixed context: [1.23, 0.42]
```

The English word leans most on Lieferfrist (delivery period) and Tage (days), with weights of 0.35 and 0.30. So the context for deadline is mostly about the time limit. A real model uses much longer vectors and many heads at once (parallel copies of the same look-across), but each step is the same kind of arithmetic.

## Is every AI model built with it?

No. Cross-attention needs two sides, a reader and a writer. Encoder-decoder models have both. Hugging Face's library guide describes one as a pretrained autoencoder (its word for the encoder) joined to a pretrained autoregressive model. The Transformer paper notes that most competitive neural sequence transduction models (models that turn one sequence into another) have this structure.

A decoder-only model (one with only the writing part) has no separate encoder, so it has no cross-attention layer. Your prompt and any retrieved text sit in one stream, and the model reads all of it with self-attention.

Image generators use it in a different way. The latent diffusion research (a way of making images by gradually removing noise) added cross-attention layers so that a text prompt, or a bounding box, can steer the picture. When you join a pretrained encoder and decoder, the cross-attention layers may start with random numbers and need training. The two official lines below back these points.

> "By introducing cross-attention layers into the model architecture, we turn diffusion models into powerful and flexible generators for general conditioning inputs such as text or bounding boxes" (Latent diffusion researchers)
>
> "But depending on the decoder architecture, the cross-attention layers may be randomly initialized" (Hugging Face Transformers docs)

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: attention where one text looks at another.
- [ ] Who supplies what: queries from one side, keys and values from the other.
- [ ] Where it lives: encoder-decoder models and image generators.
- [ ] Why a decoder-only model has no cross-attention layer, since it has no encoder.
- [ ] The practical catch: joined cross-attention layers may need training.
- [ ] A real case with stakes, like a contract translation.

**Common traps**

- Trap: "Cross-attention is just self-attention with a different name." Better: No. Self-attention reads one text. Cross-attention reads a second text, with queries from one side.
- Trap: "Chat models use cross-attention to read the prompt." Better: A decoder-only model reads the prompt through self-attention, in one stream, with no separate encoder.
- Trap: "The keys and values come from the same side as the query." Better: That is self-attention. In cross-attention the keys and values come from the other sequence.

## Can you spot the mix-up?

**Spot the wrong design note:** A bank's support bot answers from policy documents. Which design note is wrong?

A. A translation model's decoder reads the German encoder output through cross-attention.
B. Our chat model reads the retrieved policy text through cross-attention, so it needs a separate encoder.
C. Cross-attention takes its queries from the decoder and its keys and values from the encoder.
D. An image model's cross-attention lets a text prompt steer the picture.

**Answer:** B. Cross-attention needs a separate encoder to read from. The retrieved policy text sits in the same stream as the prompt, so self-attention handles it and no encoder is needed.

**Quick check:** A contract translator's decoder is writing the English word deadline. Which setup is right?

A. Queries from the German side, keys and values from the English side
B. Queries from the English side, keys and values from the German side
C. Queries, keys and values all from the English sentence
D. A bigger decoder, with no separate look at the German text

**Answer:** B. The decoder makes the queries, and the encoder output supplies the keys and values. All three from one sentence is self-attention, and the last option skips the look across entirely.

## Can you answer these from memory?

**Flash cards**

- **What is cross-attention?** Attention where one sequence's queries look at another sequence's keys and values.
- **Where do the queries come from?** The decoder side: the words being written.
- **Where do keys and values come from?** The other side, usually the encoder output.
- **Which models use it?** Encoder-decoder models, and image generators guided by a text prompt.
- **Does a decoder-only model use it?** A decoder-only model has no encoder, so it uses self-attention only, in one stream.
- **What is the practical catch?** Joined cross-attention layers may start random and need training.

## Likely follow-up questions

- Q049 Encoder-only vs decoder-only vs encoder-decoder? https://designervenkat.online/interview/ai/encoder-only-vs-decoder-only-vs-encoder-decoder
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q053 What do residual connections do? https://designervenkat.online/interview/ai/what-do-residual-connections-do
- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache
- Q056 Why is attention quadratic in sequence length? https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length

## Learn it in depth

- [Attention Mechanisms](https://designervenkat.online/learn/machine-learning/attention-mechanisms)
