Search

Search papers and lessons

Attention Mechanism

Level 4 · 10 min read

Attention lets a network build each output as a weighted mix of many inputs, with the weights computed from the data itself, so it can look up whatever is relevant.

On this page

  • Colour = topic mix
  • Linear algebra
  • Neural network basics
  • Discrete math
  • Architectures
  • Probability
  • Sign in to see your progress

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 q∈Rd\mathbf{q} \in \mathbb{R}^{d}. There are nn inputs, each with a key ki∈Rd\mathbf{k}_i \in \mathbb{R}^{d} and a value vi∈Rdv\mathbf{v}_i \in \mathbb{R}^{d_v}. Here dd is the length of the query and key vectors, dvd_v is the length of the value vectors, and ii runs from 1 to nn.

Definition: Soft attention

Given a query q\mathbf{q}, keys k1,…,kn\mathbf{k}_1, \dots, \mathbf{k}_n and values v1,…,vn\mathbf{v}_1, \dots, \mathbf{v}_n, the output is

Attention(q)=∑i=1nαivi,αi=exp⁡(si)∑j=1nexp⁡(sj),si=score(q,ki),\mathrm{Attention}(\mathbf{q}) = \sum_{i=1}^{n} \alpha_i \mathbf{v}_i, \qquad \alpha_i = \frac{\exp(s_i)}{\sum_{j=1}^{n} \exp(s_j)}, \qquad s_i = \mathrm{score}(\mathbf{q}, \mathbf{k}_i),

where each sis_i is a single real number. The weights αi\alpha_i 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 αi\alpha_i 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

score(q,k)=q⊤kd.\mathrm{score}(\mathbf{q}, \mathbf{k}) = \frac{\mathbf{q}^\top \mathbf{k}}{\sqrt{d}}.

A dot product measures alignment. Vectors that point the same way give a large positive score. The division by d\sqrt{d} matters. If the entries of q\mathbf{q} and k\mathbf{k} are independent with mean 0 and variance 1, each product has variance 1, so the sum q⊤k\mathbf{q}^\top\mathbf{k} has variance dd and typically grows like d\sqrt{d}. Large scores push softmax towards a one-hot output, where its gradients are nearly zero and learning stalls. Dividing by d\sqrt{d} 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:

score(q,k)=w⊤tanh⁡(Wqq+Wkk).\mathrm{score}(\mathbf{q}, \mathbf{k}) = \mathbf{w}^\top \tanh(W_q \mathbf{q} + W_k \mathbf{k}).

Here WqW_q and WkW_k are learned matrices that project the query and key into a shared hidden space, tanh⁡\tanh is the bend applied there, and w\mathbf{w} 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 mm queries into a matrix Q∈Rm×dQ \in \mathbb{R}^{m \times d}, the nn keys into K∈Rn×dK \in \mathbb{R}^{n \times d}, and the values into V∈Rn×dvV \in \mathbb{R}^{n \times d_v}. Then all outputs are computed at once:

Attention(Q,K,V)=softmax ⁣(QK⊤d)V.\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{Q K^\top}{\sqrt{d}}\right) V.

The softmax is applied to each row separately. The score matrix QK⊤QK^\top has size m×nm \times n, so the work is O(mnd)O(mnd) and the memory for scores is O(mn)O(mn). 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:

qt=WQxt,ki=WKxi,vi=WVxi.\mathbf{q}_t = W_Q \mathbf{x}_t, \qquad \mathbf{k}_i = W_K \mathbf{x}_i, \qquad \mathbf{v}_i = W_V \mathbf{x}_i.

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

Example
A tiny query by hand

Use d=2d = 2 and three inputs:

  • k1=(1,0)\mathbf{k}_1 = (1, 0) with v1=(2,0)\mathbf{v}_1 = (2, 0)
  • k2=(0,1)\mathbf{k}_2 = (0, 1) with v2=(0,4)\mathbf{v}_2 = (0, 4)
  • k3=(1,1)\mathbf{k}_3 = (1, 1) with v3=(6,2)\mathbf{v}_3 = (6, 2)

The query is q=(1,0)\mathbf{q} = (1, 0). Use the scaled dot product, so the divisor is 2≈1.4142\sqrt{2} \approx 1.4142.

  1. Raw dot products: q⊤k1=1\mathbf{q}^\top\mathbf{k}_1 = 1, q⊤k2=0\mathbf{q}^\top\mathbf{k}_2 = 0, q⊤k3=1\mathbf{q}^\top\mathbf{k}_3 = 1.
  2. Scores after dividing by 2\sqrt{2}: s=(0.7071,0,0.7071)s = (0.7071, 0, 0.7071).
  3. Exponentials: e0.7071≈2.0281e^{0.7071} \approx 2.0281, e0=1e^{0} = 1, e0.7071≈2.0281e^{0.7071} \approx 2.0281. Their sum is ≈5.0562\approx 5.0562.
  4. Weights: α=(0.4011,0.1978,0.4011)\alpha = (0.4011, 0.1978, 0.4011). They sum to 1.
  5. Output: 0.4011 (2,0)+0.1978 (0,4)+0.4011 (6,2)=(0.8022,0)+(0,0.7912)+(2.4066,0.8022)=(3.209,1.593)0.4011\,(2, 0) + 0.1978\,(0, 4) + 0.4011\,(6, 2) = (0.8022, 0) + (0, 0.7912) + (2.4066, 0.8022) = (3.209, 1.593).

The query matches k1\mathbf{k}_1 and k3\mathbf{k}_3 equally and gives k2\mathbf{k}_2 little weight. The output leans towards v1\mathbf{v}_1 and v3\mathbf{v}_3, and v2\mathbf{v}_2 contributes only through its small weight of 0.1978.

Example
Translating one word

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, s=(0.2,2.1,−0.5)s = (0.2, 2.1, -0.5). These numbers are illustrative; a trained model learns its own.

  1. Exponentials: e0.2≈1.2214e^{0.2} \approx 1.2214, e2.1≈8.1662e^{2.1} \approx 8.1662, e−0.5≈0.6065e^{-0.5} \approx 0.6065. Their sum is ≈9.9941\approx 9.9941.
  2. Weights: α≈(0.122,0.817,0.061)\alpha \approx (0.122, 0.817, 0.061).
  3. Context vector: 0.122 hthe+0.817 hcat+0.061 hsat0.122\,\mathbf{h}_{\text{the}} + 0.817\,\mathbf{h}_{\text{cat}} + 0.061\,\mathbf{h}_{\text{sat}}.
  4. 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

SituationWhat goes wrongBetter choice
Very long sequences, such as whole booksThe score matrix grows with the square of length, so memory and time explodeSparse, windowed or linear-attention variants
Streaming input with a tight memory budgetAttention keeps every past key and value in a cacheA recurrent model with a fixed-size state
Small data with strong local structureAttention has no built-in sense of order or locality and needs learned positionsA Convolutional Neural Network
You need a hard, discrete choiceSoft weights blur the choice across inputsTop-k selection, or hard attention trained with a score-function estimator
Thousands of similar candidatesWeights spread thin and the output averages out the signalSharper 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 d\sqrt{d} 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 s=(0,0,0)s = (0, 0, 0). Their values are (3,0)(3, 0), (0,3)(0, 3) and (3,3)(3, 3). What are the weights and the output?Show answer

Each exponential is e0=1e^0 = 1, so the weights are 1/31/3 each. The output is 13((3,0)+(0,3)+(3,3))=13(6,6)=(2,2)\tfrac{1}{3}\big((3,0) + (0,3) + (3,3)\big) = \tfrac{1}{3}(6, 6) = (2, 2). Equal scores give a plain average of the values.

QuestionWhy do we divide the dot product by d\sqrt{d}?Show answer

If the entries of the query and key are independent with mean 0 and variance 1, their dot product has variance dd. Large dot products push softmax into a near one-hot output, where gradients are nearly zero. Dividing by d\sqrt{d} 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 50,0002=2.5×10950{,}000^2 = 2.5 \times 10^9 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