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
- Builds on
- 22 concepts →
- Quiz
- 5 questions ↓
This leads to
Self-Attention and Multi-Head AttentionThe full path from zero — 22 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- LSTMs and GRUs
- Sequence-to-Sequence Models
- 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:
- Score. Compare what you need right now (the decoder's current state) with each input word, and give each a relevance score.
- Normalise. Turn the scores into attention weights: positive numbers that add up to 1, like percentages of your attention.
- 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.
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 , call the decoder's current state and the encoder's vectors for the source words . A scoring function gives one number per source word:
The simplest good choice is the dot product, : 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.
The first is Euler's number (about 2.718), and in the exponent is the score from step 1. The Greek letter ("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:
The decoder then uses , 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":
The decoder is about to produce "chat", and its state is .
Scores (dot products):
- the:
- black:
- cat:
Softmax. , , . Their sum is . Dividing:
- the:
- black:
- cat:
The weights add up to 1, and two thirds of the attention goes to "cat".
Weighted sum:
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 , 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 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:
Here and are learned Matrices and Matrix Multiplication that map both vectors into a shared space, squashes the result, and the learned vector turns it into one number. The ("transpose") turns into a row so that is a dot product.
Dot-product attention (Luong et al., 2015) is simpler: , or with a learned matrix in between, . 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 : what I am looking for. (Here, from the decoder state.)
- The keys : what each item offers to be matched against. Scores are .
- The values : what each item actually hands over if attended to. The output is .
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: , and , 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 and all values as the rows of . Then the whole mechanism is one line:
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. is infinity in floating point. Always subtract the largest score before exponentiating, as
softmaxabove 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 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 , 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 inputs and outputs that is scores. In self-attention, where a sequence attends to itself, it is , which is why long contexts are expensive (Long Context and Efficient Attention).
Where it leads
- Self-Attention and Multi-Head Attention: let every word of a sequence attend to every other word of the same sequence, with queries, keys and values all computed from it. Add several "heads" in parallel. This is the Transformer's core.
- Positional Encodings: attention ignores order (it is a weighted sum), so position has to be added in.
- The Transformer: attention plus small feed-forward networks, stacked dozens of times.
- Cross-attention, the encoder-decoder attention of this chapter, survives inside Transformer translation models, in Text-to-Image in Practice models where image features attend to the text prompt, and in Speech Recognition systems like Whisper.
- Attention over images and graphs appears in vision Transformers and Graph Neural Networks.
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
- By hand, redo the worked example with the query . Which word gets the most attention, and what is the output vector?
- 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?- Add a padding mask: append a fourth key
[3., 3.]that should be ignored, and set its score to-np.infbefore 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.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The Illustrated Transformer
The famous picture-by-picture walk through the Transformer architecture.
Neural Networks (video series)
Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.
Attention? Attention!
A careful survey of attention mechanisms from Bahdanau to self-attention and the Transformer, with the equations side by side.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Neural Machine Translation by Jointly Learning to Align and Translate
Introduced attention to let a decoder look back at every input word.
Effective Approaches to Attention-based Neural Machine Translation
Introduced simpler multiplicative (dot-product) attention scores and global versus local attention.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/attention.md