TL;DR
Attention is a way for a network to build each output as a weighted average of many inputs, where the weights are computed from the data at that moment. Instead of squeezing a whole sentence into one fixed vector, the model asks, at each step, which parts of the input matter right now, and reads those parts more closely.
The weights come from a score that compares a question (the query) with a label for each input (the key). A Softmax turns those scores into probabilities. Each input also carries content (the value), and that content is what gets mixed together.
Where you'll see it: in the translation models that replaced earlier recurrent designs, in every layer of a Transformer, and in captioning models that look at different parts of an image while they write each word.
Intuition
A lookup that returns a blend
Think of a library card catalogue. You have a question, you compare it with the card for each book, and you read each book in proportion to how well its card matches. A hard lookup returns exactly one book. Attention is the soft version: it returns a blend of all the books, with most of the weight on the best matches and a little on the rest.
Why does this matter? Early neural translation models read a whole source sentence into one fixed-size vector through an encoder, usually built from a Recurrent Neural Network, and then wrote the translation from that vector alone. For a long sentence the vector was a bottleneck: details from the start were squeezed out before the decoder needed them. Bahdanau, Cho and Bengio fixed this by keeping every encoder state and letting the decoder pick from them at each output step. That is attention.
flowchart LR Q[Query: what I need now] --> S[Score against each key] K[Keys: a label for each input] --> S S --> W[Softmax: weights that sum to 1] W --> M[Weighted sum] V[Values: the content of each input] --> M M --> O[Output for this step]
Three roles: query, key, value
Each input is described twice. The key says what the input is about, and the value says what the input contains. The query says what the reader is looking for. Keeping keys and values separate lets the model match on one property and return a different one, so the same item can be findable by one feature and useful for another.
Why it exists
Attention solves three problems together. It removes the fixed-size bottleneck. It lets the model reach information far back in a sequence without that signal passing through many steps and fading. And the weights form a readable record of what the model used, which is why attention maps became a popular way to inspect models. Those maps are a partial guide, not a full explanation, as discussed below.
The math
Setup
Let the query be . There are inputs, each with a key and a value . Here is the length of the query and key vectors, is the length of the value vectors, and runs from 1 to .
Given a query , keys and values , the output is
where each is a single real number. The weights are positive and sum to 1.
In words: score each input against the query, turn the scores into weights with softmax, and take the weighted average of the values. The are the attention weights. Because the output is a weighted average, it always lies inside the convex hull of the values (the region between them, such as a segment for two values or a triangle for three).
Scoring with a dot product
The most common score is
A dot product measures alignment. Vectors that point the same way give a large positive score. The division by matters. If the entries of and are independent with mean 0 and variance 1, each product has variance 1, so the sum has variance and typically grows like . Large scores push softmax towards a one-hot output, where its gradients are nearly zero and learning stalls. Dividing by brings the variance back to 1. This is the scaled dot-product attention of Vaswani and colleagues.
Scoring with a small network
Bahdanau and colleagues used an additive score:
Here and are learned matrices that project the query and key into a shared hidden space, is the bend applied there, and is a learned vector that reduces the result to one number. This form costs more than a dot product, but it does not need the query and key to have the same length, and it showed that the alignment itself could be learned. (In the paper the query is the decoder state and the keys are encoder states. We use the same letters here for clarity.)
Matrix form
Stack queries into a matrix , the keys into , and the values into . Then all outputs are computed at once:
The softmax is applied to each row separately. The score matrix has size , so the work is and the memory for scores is . That quadratic growth in sequence length is the main practical cost of attention.
Why it can be trained
Every step is differentiable: dot products, exponentials, division and sums. The scores, and through them the projections that produced the queries and keys, learn by Backpropagation from the final loss. Nobody tells the network which input is relevant. It learns to score the relevant inputs highly because that lowers the loss. Attention is called "soft" for this reason. A hard choice of a single input cannot be differentiated.
Self-attention
When queries, keys and values all come from the same sequence, the layer is self-attention. Each position builds its query from its own vector, and the keys and values come from every position. The projections are linear maps with learned matrices:
Each position ends up with a new vector that mixes in context from the rest of the sequence. There is no recurrence, so every position can be computed in parallel. This is the core of the Transformer.
Worked examples
Use and three inputs:
- with
- with
- with
The query is . Use the scaled dot product, so the divisor is .
- Raw dot products: , , .
- Scores after dividing by : .
- Exponentials: , , . Their sum is .
- Weights: . They sum to 1.
- Output: .
The query matches and equally and gives little weight. The output leans towards and , and contributes only through its small weight of 0.1978.
A decoder is about to write the French word for "cat" and has a state vector. Its scores against the encoder states for "the", "cat" and "sat" are, after scaling, . These numbers are illustrative; a trained model learns its own.
- Exponentials: , , . Their sum is .
- Weights: .
- Context vector: .
- Interpretation: about 82% of the context comes from "cat". The decoder is mostly reading the source word that matches what it is writing, which is what a human translator would look at.
Tradeoffs and failure modes
| Situation | What goes wrong | Better choice |
|---|---|---|
| Very long sequences, such as whole books | The score matrix grows with the square of length, so memory and time explode | Sparse, windowed or linear-attention variants |
| Streaming input with a tight memory budget | Attention keeps every past key and value in a cache | A recurrent model with a fixed-size state |
| Small data with strong local structure | Attention has no built-in sense of order or locality and needs learned positions | A Convolutional Neural Network |
| You need a hard, discrete choice | Soft weights blur the choice across inputs | Top-k selection, or hard attention trained with a score-function estimator |
| Thousands of similar candidates | Weights spread thin and the output averages out the signal | Sharper scores, retrieval first, then attention over the short list |
Two failure modes need extra care. First, high attention weight is not proof that the model used that input. Attention maps are suggestive, but a model can route information in ways the weights do not show. Second, unscaled dot products saturate softmax, which is why the factor is there. Without it, large models train slowly or get stuck.
History
Attention entered neural networks through machine translation around 2014. Sutskever, Vinyals and Le showed that a pair of recurrent networks, one reading and one writing, could translate, but the whole source sentence still went through one vector. Bahdanau, Cho and Bengio, working on that bottleneck, introduced the additive attention model in 2014, which let the decoder search over all the encoder states at each step. Their paper was presented at ICLR in 2015.
In 2015 Luong, Pham and Manning simplified the scoring and compared dot-product and multiplicative forms with a local variant. The same year Xu and colleagues used soft attention for image captioning, where the decoder looked at different regions of the picture for different words.
In 2017 Vaswani and colleagues dropped recurrence entirely and built the Transformer on self-attention, under the title "Attention Is All You Need". It caught on because it was simple, parallel, and worked well across tasks. Most large language models now use it at their core.
Check yourself
QuestionIn an attention layer, what are the three inputs, and what does the softmax produce?Show answer
The three inputs are the query, the keys and the values. The softmax turns the scores, one per key, into positive weights that sum to 1. Those weights are then used to take a weighted average of the values.
QuestionThree inputs have scores . Their values are , and . What are the weights and the output?Show answer
Each exponential is , so the weights are each. The output is . Equal scores give a plain average of the values.
QuestionWhy do we divide the dot product by ?Show answer
If the entries of the query and key are independent with mean 0 and variance 1, their dot product has variance . Large dot products push softmax into a near one-hot output, where gradients are nearly zero. Dividing by brings the variance back to 1, so the softmax stays in a range where it can learn.
QuestionA model summarises a 50,000-token document with full self-attention and runs out of memory on one attention layer. Why, and what is one fix?Show answer
The score matrix has entries per head. In 32-bit floats that is about 10 GB for one head in one layer, before any other memory. The cost is quadratic in length. One fix is windowed or sparse attention, so each position only scores a neighbourhood. Another is to split the document into chunks and summarise hierarchically.
Sources
- Bahdanau, Cho, Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2014): https://arxiv.org/abs/1409.0473
- Vaswani et al., Attention Is All You Need (2017): https://arxiv.org/abs/1706.03762
- Luong, Pham, Manning, Effective Approaches to Attention-based Neural Machine Translation (2015): https://arxiv.org/abs/1508.04025
- Attention (machine learning), Wikipedia: https://en.wikipedia.org/wiki/Attention_(machine_learning)