What is Cross Attention in Transformers?
Cross Attention in Transformers explains how a query sequence attends to a different context sequence, such as decoder queries attending to encoder keys and values. Learn the key formula, a small numeric example, and when cross attention matters for encoder-decoder and multimodal models.

TL;DR
- Cross attention is the attention mechanism where one sequence provides queries and another sequence provides keys and values.
- It appears in encoder-decoder transformers and multimodal models when you need to inject external context into a decoder.
- Compute attention weights as softmax of query-key scaled dot products and multiply by values to produce the aggregated context.
- Practical issues include computational cost and alignment between query and context representations. Key tradeoffs: accuracy of contextual retrieval versus compute and memory cost.
In this question, we will learn what cross attention is, how it differs from self attention, and how it computes context using queries, keys, and values from different sequences.
We will cover the following:
- The intuition
- How it actually works
- When to use cross attention
- Computational cost and optimization
- Tradeoffs and failure modes
Direct answer: Cross attention is the attention mechanism where queries come from one sequence and keys and values come from a different sequence, commonly used in encoder-decoder architectures to let the decoder read encoded context. The operation computes weights by comparing queries to keys with the softmax of scaled dot products and then aggregates values to produce context-aware outputs. It differs from self attention only by the origin of keys and values, and it is central to tasks that combine two streams of information.
The intuition (an analogy that makes it click)
Imagine you are answering a question in a classroom while holding a stack of reference cards. Your current question and partial answer are the queries. The reference cards are the keys and values. You scan the cards with the question in mind, rank which cards are most relevant, and then read the content from the top-ranked cards to form your final answer.
Queries ask, keys say how relevant each reference is, and values supply the content you borrow. Cross attention is simply this process when the questions and the reference stack come from two different places.
How it actually works (the real mechanics, with a concrete worked example)
Mechanically, if queries are , keys are , and values are , the basic attention output is
Here is the dimensionality of keys used for scaling. In an encoder-decoder model the decoder supplies and the encoder supplies and .
Worked numeric example. Suppose you have a single decoder query vector of dimension and three encoder key/value pairs. Let
,
,
and corresponding values
.
Compute raw scores by dot product and scale with .
The raw dot products are:
| key | dot product | scaled score |
|---|---|---|
| 1 | ||
| 0 | ||
| 1 |
Applying softmax to the scaled scores produces attention weights. Numerically softmax of is roughly .
Multiply weights by values and sum:
which yields roughly . That vector is the context the decoder reads from the encoder for that query.
Comparison to self attention. Here is a compact table showing the origin of Q K V and the main purpose.
| mechanism | Q source | K source | V source | typical use |
|---|---|---|---|---|
| self attention | same sequence | same sequence | same sequence | model internal interactions |
| cross attention | decoder | encoder or other modality | encoder or other modality | inject external context into decoder |
When to use cross attention
Use cross attention whenever you must condition one sequence on another. Typical cases include:
- Machine translation with an encoder for the source and a decoder for the target. The decoder queries the encoder for relevant source tokens.
- Multimodal models where text queries image features or vice versa.
- Retrieval-augmented generation where the decoder queries a set of retrieved documents represented as keys and values.
Cross attention provides an explicit, learnable way to read from external information while producing sequence outputs.
Computational cost and optimization
Cross attention costs similar compute to self attention between sequences of size and . The dominant cost is the matrix multiply that yields which is where is the head dimension. Memory for the full attention matrix is . Practical optimizations include:
- Reducing by retrieving a small number of relevant context chunks instead of attending to a huge document.
- Using approximate attention or locality-sensitive hashing when is large.
- Caching projected and when the context is static across decoding steps.
Tradeoffs and failure modes
Cross attention is powerful, but it can fail or become expensive. Common failure modes include attention focusing on irrelevant keys, poor alignment between modalities, and out of memory errors when is large. Regularization, better tokenization of context, and retrieval filtering help mitigate these problems.
Questions the interviewer might ask
Some follow-up questions you might get:
How does cross attention differ from self attention? Self attention uses Q K and V from the same sequence so tokens attend over each other. Cross attention separates the query source from the context source so one sequence reads another.
Why divide by the square root of ? Scaling by keeps the dot products from growing with dimension and keeps the softmax in a numerically stable, non-saturated regime.
Can cross attention be multiheaded? Yes. You split , , and into heads, compute attention per head, then concatenate and project. Multihead attention allows the model to attend to different aspects of the context in parallel.
What happens when context length is huge? Compute and memory grow as which can be prohibitive. Use retrieval to shrink , approximate attention, or sparse patterns to control cost.
How do you handle alignment between modalities? Use modality-specific encoders to produce compatible representations, and train cross-modal objectives or alignment losses so keys and queries are comparable.
When might you prefer concatenating sequences and using self attention instead? Concatenation can work when both sequences should interact symmetrically, but it forces compute and mixes positional encodings. Cross attention keeps a structured read mechanism that can be more efficient and clearer to control.
Some things to note:
- Caching and is cheap when context is fixed and saves repeated projection work.
- Cross attention typically sits in the decoder block after self attention over previously generated tokens.
What the interviewer is really testing
They want to see that you understand the data flow: where queries come from, where keys and values come from, and how the softmax of scaled dot products yields weights. They also want practical awareness of compute and memory implications and strategies to mitigate OOM or misalignment when using large or noisy contexts.
Further reading in the curriculum
Go deeper on the fundamentals behind this question.
- How LLMs Actually Work A ground-up tour of tokens, embeddings, attention, and why transformers scale.
Related questions
How would you rate the quality of this article?
Prepare for your AI engineering interview
This is one of many detailed questions and explainers on StudyAIDesign. Browse the full set, work through the curriculum, and walk into your interview ready.