◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

Attention

Attention lets a network, at every step, look back over all of its inputs and take a weighted mix of the ones that matter most right now. It was invented to fix machine translation and became the core of every Transformer.

Level
●●●●● Intermediate
Reading
11 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

Sequence-to-Sequence ModelsDot Product, Norms and Similarity

This leads to

Self-Attention and Multi-Head Attention
The full path from zero — 22 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Vanishing and Exploding Gradients
  21. LSTMs and GRUs
  22. Sequence-to-Sequence Models
  23. Attention

Read them roughly in this order. See it on the concept map →

Why it matters

In 2014 the best neural translation systems worked like this: an encoder network read the whole source sentence and squeezed it into one vector of a few hundred numbers, and a decoder network unpacked that vector into the translation, word by word (Sequence-to-Sequence Models). It worked surprisingly well for short sentences and fell apart for long ones. Imagine summarising a 50-word sentence into one fixed list of numbers and then translating from the summary alone, never looking at the original again.

Attention removed that bottleneck. Instead of one summary, the decoder keeps access to the encoder's vector for every source word, and at each step it decides which of them to look at. Translation quality on long sentences jumped, and the idea turned out to be far more general than translation.

Three years later the The Transformer threw away the recurrent network altogether and kept only attention. Every large language model today (GPT and Decoder-Only Models, BERT and Encoder Models, Claude, Gemini, Llama), every Vision Transformers and most image generators is built from stacks of attention layers. This chapter explains the mechanism in its original setting. The next one, Self-Attention and Multi-Head Attention, turns it into the Transformer's engine.

The intuition

You are translating "the black cat" into French. When you write "chat" you glance back at "cat". When you write "noir" you glance at "black". You never re-read the whole sentence with equal care; your eyes jump to the part that matters for the word you're writing now.

Attention gives a network the same ability, in three moves:

  1. Score. Compare what you need right now (the decoder's current state) with each input word, and give each a relevance score.
  2. Normalise. Turn the scores into attention weights: positive numbers that add up to 1, like percentages of your attention.
  3. Mix. Take the weighted average of the input vectors. The result, the context vector, is mostly made of the relevant words, with a little of the rest.
Without attention The decoder sees only one summary vector c. h₁ the h₂ black h₃ cat c bottleneck s₁ le s₂ chat s₃ noir Long sentences must squeeze into the same fixed-size c, so details get lost. With attention At each output step, mix all encoder states. h₁ the weight 0.245 h₂ black weight 0.090 h₃ cat weight 0.665 context weighted sum s₂ chat decoder state = the query Line thickness = attention weight while producing “chat”.
Fig. 1 Left: a plain encoder-decoder squeezes the whole sentence into one vector c. Right: with attention, the decoder builds a fresh mix of all encoder states at every step. While producing "chat", most of the weight goes to "cat".

A second analogy helps for what comes later. A Python dictionary is a hard lookup: you give a key, and you get exactly the value stored under a matching key, or nothing. Attention is a soft lookup. You give a query; every stored item has a key and a value; you get back a blend of all the values, weighted by how well each key matches your query. Because the blend is smooth, the network can learn where to look with ordinary Gradient Descent.

Key idea Attention = score every input against what you need now, turn the scores into weights with softmax, and return the weighted average of the inputs. A soft, learnable lookup.

How it works

Step 1: scores

At decoder step tt, call the decoder's current state st\mathbf{s}_t and the encoder's vectors for the nn source words h1,…,hn\mathbf{h}_1, \dots, \mathbf{h}_n. A scoring function gives one number per source word:

et,i=score(st,hi)e_{t,i} = \text{score}(\mathbf{s}_t, \mathbf{h}_i)

The simplest good choice is the dot product, st⋅hi\mathbf{s}_t \cdot \mathbf{h}_i: multiply matching entries and add them up. It is large when the two vectors point the same way and small or negative when they don't. These raw numbers are the attention scores.

Step 2: weights with softmax

Scores can be any real number. To turn them into weights that are positive and sum to 1 we use the softmax function: exponentiate each score, then divide by the total.

αt,i=e et,i∑j=1ne et,j\alpha_{t,i} = \frac{e^{\,e_{t,i}}}{\sum_{j=1}^{n} e^{\,e_{t,j}}}

The first ee is Euler's number (about 2.718), and et,ie_{t,i} in the exponent is the score from step 1. The Greek letter α\alpha ("alpha") is the attention weight. Exponentiating makes every number positive and exaggerates differences: a score that is larger by 1 gets about 2.7 times the weight. Dividing by the sum makes the weights add up to 1. Softmax is also the last layer of every classifier (Activation Functions).

Step 3: the weighted sum

The context vector is the weighted average of the encoder vectors:

ct=∑i=1nαt,i hi\mathbf{c}_t = \sum_{i=1}^{n} \alpha_{t,i}\, \mathbf{h}_i

The decoder then uses ct\mathbf{c}_t, together with its own state, to predict the next output word. At the next step it computes completely new weights, so every output word gets its own view of the input.

A worked example by hand

Keep everything two-dimensional so you can follow each number. The encoder has produced three vectors for "the black cat":

hthe=(1,0),hblack=(0,1),hcat=(1,1)\mathbf{h}_{\text{the}} = (1, 0), \qquad \mathbf{h}_{\text{black}} = (0, 1), \qquad \mathbf{h}_{\text{cat}} = (1, 1)

The decoder is about to produce "chat", and its state is s=(2,1)\mathbf{s} = (2, 1).

Scores (dot products):

  • the: 2×1+1×0=22 \times 1 + 1 \times 0 = 2
  • black: 2×0+1×1=12 \times 0 + 1 \times 1 = 1
  • cat: 2×1+1×1=32 \times 1 + 1 \times 1 = 3

Softmax. e2=7.389e^2 = 7.389, e1=2.718e^1 = 2.718, e3=20.086e^3 = 20.086. Their sum is 30.19330.193. Dividing:

  • the: 7.389/30.193=0.2457.389 / 30.193 = 0.245
  • black: 2.718/30.193=0.0902.718 / 30.193 = 0.090
  • cat: 20.086/30.193=0.66520.086 / 30.193 = 0.665

The weights add up to 1, and two thirds of the attention goes to "cat".

Weighted sum:

c=0.245 (1,0)+0.090 (0,1)+0.665 (1,1)=(0.245+0.665,  0.090+0.665)=(0.910, 0.755)\mathbf{c} = 0.245\,(1, 0) + 0.090\,(0, 1) + 0.665\,(1, 1) = (0.245 + 0.665,\; 0.090 + 0.665) = (0.910,\, 0.755)
Attention in four steps, with the numbers from the worked example query q = (2, 1), the decoder's current state 1. key kᵢ 2. score q·kᵢ 3. softmax → weight 4. weight × value the (1, 0) 2·1 + 1·0 = 2 0.245 0.245 × (1, 0) = (0.245, 0) black (0, 1) 2·0 + 1·1 = 1 0.090 0.090 × (0, 1) = (0, 0.090) cat (1, 1) 2·1 + 1·1 = 3 0.665 0.665 × (1, 1) = (0.665, 0.665) (0.910, 0.755) output: sum of rows weights add up to 1 e², e¹, e³ divided by their sum, 30.19 The query matched “cat” best, so the output is mostly cat's value, with a little of the others mixed in.
Fig. 2 The four steps of the worked example. Each key is scored against the query, softmax turns the scores into weights, and the output is the weighted sum of the values.

Notice how sharp the weights are depends on the size of the scores. Multiply the query by 5 and the scores become 10, 5 and 15; the weights become 0.007, 0.000 and 0.993, nearly all on "cat". Divide it by 10 and the weights flatten to 0.33, 0.30 and 0.37. This sensitivity to scale is why the Transformer divides its scores by d\sqrt{d}, as Self-Attention and Multi-Head Attention explains.

Where do good scores come from? Learning

In a real network nobody chooses the vectors. The encoder, decoder and scoring function are trained together on millions of sentence pairs, end to end. Whenever attending to the right word helps predict the correct translation, Backpropagation nudges the parameters so that word's score goes up next time. No one ever tells the model which French word goes with which English word. The alignment between them emerges as a by-product. Plotting the weights αt,i\alpha_{t,i} as a grid, output words against input words, shows a mostly diagonal pattern that bends where word order differs, for example where French puts the adjective after the noun.

Two classic scoring functions

Additive attention (Bahdanau et al., 2014) scores with a tiny one-hidden-layer network:

score(s,h)=v⊤tanh⁡(W1s+W2h)\text{score}(\mathbf{s}, \mathbf{h}) = \mathbf{v}^\top \tanh(\mathbf{W}_1 \mathbf{s} + \mathbf{W}_2 \mathbf{h})

Here W1\mathbf{W}_1 and W2\mathbf{W}_2 are learned Matrices and Matrix Multiplication that map both vectors into a shared space, tanh⁡\tanh squashes the result, and the learned vector v\mathbf{v} turns it into one number. The ⊤^\top ("transpose") turns v\mathbf{v} into a row so that v⊤x\mathbf{v}^\top \mathbf{x} is a dot product.

Dot-product attention (Luong et al., 2015) is simpler: score(s,h)=s⊤h\text{score}(\mathbf{s}, \mathbf{h}) = \mathbf{s}^\top \mathbf{h}, or with a learned matrix in between, s⊤Wh\mathbf{s}^\top \mathbf{W} \mathbf{h}. It works about as well and is much faster, because scoring every pair at once becomes a single matrix multiplication, which GPUs are built for. The Transformer uses dot products.

Queries, keys and values

Look again at the worked example. Each source vector played two roles: it was compared with the decoder state (to compute a score) and it was mixed into the output. Nothing says these must be the same vector. The modern formulation separates three roles:

  • The query q\mathbf{q}: what I am looking for. (Here, from the decoder state.)
  • The keys ki\mathbf{k}_i: what each item offers to be matched against. Scores are q⋅ki\mathbf{q} \cdot \mathbf{k}_i.
  • The values vi\mathbf{v}_i: what each item actually hands over if attended to. The output is ∑iαivi\sum_i \alpha_i \mathbf{v}_i.

Think of a library catalogue. Your query is "books about cats". Each book's key is its catalogue entry (title, subject tags), and its value is the book's contents. You match on the catalogue but read the contents. Each of the three is usually computed from the underlying vectors by its own learned matrix: q=WQs\mathbf{q} = \mathbf{W}_Q \mathbf{s}, ki=WKhi\mathbf{k}_i = \mathbf{W}_K \mathbf{h}_i and vi=WVhi\mathbf{v}_i = \mathbf{W}_V \mathbf{h}_i, so the network can learn what to look for, what to advertise and what to pass on separately.

Stack all keys as the rows of a matrix K\mathbf{K} and all values as the rows of V\mathbf{V}. Then the whole mechanism is one line:

Attention(q,K,V)=softmax(Kq)⊤V\text{Attention}(\mathbf{q}, \mathbf{K}, \mathbf{V}) = \text{softmax}(\mathbf{K}\mathbf{q})^\top \mathbf{V}

In code

The whole mechanism in NumPy, with the worked example:

import numpy as np

def softmax(x):
    e = np.exp(x - x.max(axis=-1, keepdims=True))   # subtract max for numerical safety
    return e / e.sum(axis=-1, keepdims=True)

def attention(q, K, V):
    scores = K @ q              # one score per input: how well each key matches the query
    weights = softmax(scores)   # positive, sum to 1
    return weights @ V, weights # weighted average of the values

# Three encoder states for "the black cat" (keys) and what they carry (values)
K = np.array([[1.0, 0.0],      # the
              [0.0, 1.0],      # black
              [1.0, 1.0]])     # cat
V = np.array([[1.0, 0.0],
              [0.0, 1.0],
              [1.0, 1.0]])
q = np.array([2.0, 1.0])       # decoder state while producing the next word

out, w = attention(q, K, V)
print("scores ", K @ q)
print("weights", w.round(3))
print("output ", out.round(3))

for scale in [0.1, 1, 5]:      # a stronger query gives sharper attention
    print(scale, attention(scale * q, K, V)[1].round(3))

# scores  [2. 1. 3.]
# weights [0.245 0.09  0.665]
# output  [0.91  0.755]
# 0.1 [0.332 0.301 0.367]
# 1 [0.245 0.09  0.665]
# 5 [0.007 0.    0.993]

The same in PyTorch, where gradients flow through every step so the vectors can be learned:

import torch

K = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
V = K.clone()
q = torch.tensor([2., 1.], requires_grad=True)

weights = torch.softmax(K @ q, dim=-1)
out = weights @ V
print(weights.detach().numpy().round(3), out.detach().numpy().round(3))
# [0.245 0.09  0.665] [0.91  0.755]

Common pitfalls

  • Overflowing softmax. e1000e^{1000} is infinity in floating point. Always subtract the largest score before exponentiating, as softmax above does. It doesn't change the result, because the factor cancels in the division. Library softmax functions do this for you.
  • Attending to padding. Batches of sentences are padded to the same length with dummy tokens. Unless you mask them, by setting their scores to −∞-\infty before the softmax so their weight becomes exactly 0, the model wastes attention on padding and results change with batch composition.
  • Scores that grow with dimension. Dot products of long vectors have large magnitudes, which pushes softmax towards one-hot weights and tiny gradients. The fix, scaling by 1/d1/\sqrt{d}, is in Self-Attention and Multi-Head Attention.
  • Reading too much into attention maps. Attention weights are tempting to treat as an explanation ("the model looked here, so that's why"). They show where information was mixed from, not why the model decided anything. Research has shown that quite different attention patterns can produce the same predictions.

Watch out Attention compares every query with every key. For nn inputs and mm outputs that is n×mn \times m scores. In self-attention, where a sequence attends to itself, it is n2n^2, which is why long contexts are expensive (Long Context and Efficient Attention).

Where it leads

A bit of history

The word "attention" in neural networks goes back decades, but the version that mattered arrived in 2014, when Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio published Neural Machine Translation by Jointly Learning to Align and Translate. Their encoder-decoder learned to "soft-search" the source sentence at every step and fixed the long-sentence problem of earlier Sequence-to-Sequence Models models. Around the same time Alex Graves used a related differentiable "soft window" to generate handwriting. In 2015 Minh-Thang Luong, Hieu Pham and Christopher Manning compared simpler multiplicative (dot-product) scores, and Kelvin Xu and colleagues applied attention to image captioning in Show, Attend and Tell. Google's production translation system adopted attention in 2016. In 2017 Vaswani et al.'s Attention Is All You Need removed recurrence entirely and built the The Transformer from attention alone.

Try it

  1. By hand, redo the worked example with the query q=(0,2)\mathbf{q} = (0, 2). Which word gets the most attention, and what is the output vector?
  2. In the NumPy code, give the values different numbers from the keys, for example V = np.array([[10., 0.], [0., 10.], [5., 5.]]). Does the weight change? Does the output?
  3. Add a padding mask: append a fourth key [3., 3.] that should be ignored, and set its score to -np.inf before the softmax. Check its weight is exactly 0.

Hint for 1: the scores are 0, 2 and 2, so "black" and "cat" share the attention equally.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Before attention, a seq2seq translator squeezed the whole source sentence into one vector. What did attention change?

  2. Attention scores for three words are 2, 1 and 3. After softmax, roughly what weight does the word with score 3 get?

  3. You multiply the query vector by 5, so all scores become five times larger. What happens to the attention weights?

  4. In the query, key, value formulation, what is the difference between a key and a value?

  5. A batch pads short sentences with dummy tokens, and results change depending on what else is in the batch. What is the likely bug?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Illustrated Transformer

Jay Alammar · Beginner · Free

The famous picture-by-picture walk through the Transformer architecture.

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Article

Attention? Attention!

Lilian Weng · 2018 · Intermediate · Free

A careful survey of attention mechanisms from Bahdanau to self-attention and the Transformer, with the equations side by side.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/attention.md