How does attention work in a transformer?
Attention lets each token look up relevant information from every other token using query and key similarity, then return a weighted mix of value vectors. Here is the intuition, a worked numeric example, and what interviewers probe for.

TL;DR
- Attention lets each token look at other tokens using queries , keys , and values to compute a weighted sum of information.
- We score similarity with dot products , scale by , apply softmax, and multiply by to get outputs.
- Scaling by keeps the softmax from becoming too peaky as grows; this stabilizes gradients.
- Multi head attention runs several of these in parallel with different linear projections, letting the model focus on different relationships.
Key tradeoffs: simpler attention is flexible and parallelizable but costs memory/time in sequence length and can struggle with very long contexts.
In this question, we will learn how the attention mechanism in a transformer turns token embeddings into context-aware representations. We will walk from a simple intuition to the formal formula, then run a small worked example on the sentence "The cat sat on the mat".
We will cover the following:
- The intuition (an analogy)
- How it actually works
- Why we scale by
- Multi head attention
- Tradeoffs and failure modes
- Questions the interviewer might ask
- What the interviewer is really testing
Direct answer: Attention lets each token form a query that compares to keys of all tokens, producing softmax weights that mix the values into a context vector. The core computation is a scaled dot-product followed by softmax and a weighted sum. This is computed efficiently with matrix operations on , , and .
The intuition (an analogy)
Think of a classroom where each student holds a sticky note with facts. When one student wants to answer a question, they look at other students' notes. Their question is a query . Each other student presents a key that expresses what their note contains. The similarity between the question and a note determines how much the asking student reads that note. That reading is the weight, and the actual content copied is the value . The final answer is a weighted combination of those notes.
This lets every token selectively copy information from any other token, whether that information is nearby or far away in the sequence.
How it actually works
The formal, compact formula for scaled dot-product attention is:
Here , , and are matrices of queries, keys, and values; is the dimensionality of the keys. The inner product gives all pairwise scores.
Worked example on "The cat sat on the mat". For clarity we use and set embeddings so that (a common simplification in a single self-attention layer).
Token order: The | cat | sat | on | the | mat We will compute attention for the query of the token "sat", which we label .
Token vectors (rows are components):
| token | The | cat | sat | on | the2 | mat |
|---|---|---|---|---|---|---|
| component 1 | 1 | 1 | 0 | 0 | 1 | 1 |
| component 2 | 0 | 1 | 1 | 0 | 0 | 0.5 |
So . The dot-product scores are:
| token | The | cat | sat | on | the2 | mat |
|---|---|---|---|---|---|---|
| (unscaled) | 0 | 1 | 1 | 0 | 0 | 0.5 |
We scale by with , so . The scaled scores are:
| token | The | cat | sat | on | the2 | mat |
|---|---|---|---|---|---|---|
| 0 | 0.707 | 0.707 | 0 | 0 | 0.354 |
Apply softmax to the scaled scores to get weights :
Exp of scaled scores (approx):
| token | The | cat | sat | on | the2 | mat |
|---|---|---|---|---|---|---|
| 1.000 | 2.028 | 2.028 | 1.000 | 1.000 | 1.424 |
Softmax weights (normalized):
| token | The | cat | sat | on | the2 | mat |
|---|---|---|---|---|---|---|
| 0.118 | 0.239 | 0.239 | 0.118 | 0.118 | 0.168 |
Finally, the attention output for the query is the weighted sum of the values :
This output is a context-aware vector for "sat" that mixes nearby lexical items like "cat" and "mat" according to the learned similarities.
Why we scale by
When grows, typical dot products have variance proportional to . Without scaling, as increases the raw scores become larger in magnitude and softmax turns into a near one-hot distribution, which hurts gradient flow. Dividing by normalizes the scale so the softmax operates in a stable range.
A small table showing how grows and why large dominate softmax:
| 0 | 1.00 |
| 1 | 2.72 |
| 2 | 7.39 |
| 3 | 20.09 |
Because increases rapidly, a modest increase in raw dot-product magnitude can make one token dominate the weights. The factor keeps the values small enough that multiple tokens contribute.
Multi head attention
Multi head attention runs several parallel attention computations with different learned linear projections of , , and . Each head has its own subspace (often smaller, e.g., ). The separate heads can capture different kinds of relationships, such as syntactic connections in one head and semantic co-reference in another. The per-head outputs are concatenated and projected back to the model dimension.
Tradeoffs and failure modes
Attention is powerful but not perfect. It costs time and memory in sequence length , which becomes prohibitive for very long contexts. Attention can also focus on spurious tokens if training data is biased, and it does not by itself encode ordering unless positional information is added. Finally, if queries, keys, and values are poorly scaled or initialized, training can be unstable.
Questions the interviewer might ask
Some follow-up questions you might get:
- Why use dot product and not cosine similarity? Dot product is efficient to compute in matrix form and, with learned projections, the model can scale and shift vectors to represent useful comparisons; cosine would require extra normalization steps that complicate gradients.
- What is the role of positional encoding? Attention is permutation invariant, so positional encodings add order information so the model can distinguish "cat sat" from "sat cat".
- How does attention handle variable-length sequences? Attention naturally handles variable length because just computes pairwise scores over whatever tokens are present; padding and masks are used to ignore positions.
- Why have multiple heads instead of one wide head? Multiple heads let the model attend to different subspaces and relationships in parallel; splitting often helps learning more diverse patterns than a single head of equal total size.
- How do masks work in attention? A mask adds large negative values (e.g., ) to before softmax to zero out unwanted positions, used for padding or causal/auto-regressive attention.
- What happens if is omitted? Softmax can become extremely peaky for large , causing vanishing gradients and learning difficulties.
Some things to note:
- Attention parameters are learned via the linear projections that produce , , and .
- In practice we use residual connections and layer norm around attention for stable training.
What the interviewer is really testing
They want to see that you understand both the math and the intuition: how queries, keys, and values interact, why scaling matters, and what practical consequences attention has for computation and model behavior. Showing that you can walk through a small numeric example and mention implementation details like masking and complexity signals depth of understanding.
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.