NLP · Transformer · 2017 / NeurIPS
Attention Is All You Need
A structured reading of the paper that moved attention from a helpful add-on to the main computational engine of modern language models.
Overview
This paper is best understood as a turning point in how sequence models move information. Earlier models processed a sentence through recurrence or local convolution; the Transformer instead lets each token directly look up relevant information from the rest of the sequence. The central question is not simply “what modules does it use?”, but “how does information travel between words?”
Attention Is All You Need introduces the , a model for that removes recurrence and convolution from the main architecture. The paper evaluates this idea on machine translation, but its impact reaches far beyond translation: the same architectural principle later becomes the foundation of BERT, GPT-style models, many vision models, and the modern large language model ecosystem.
The title is intentionally bold, but it should be read carefully. The Transformer is not made of attention alone. It still relies on embeddings, positional encodings, feed-forward networks, residual connections, layer normalization, dropout, and a final softmax layer. What the title really argues is more specific: for modeling relationships between positions in a sequence, attention can replace the recurrent and convolutional machinery that dominated earlier neural sequence models.
Why this paper mattered
Before the Transformer, strong translation systems usually depended on
,
especially and
. These models had a natural way to process order:
read token 1, then token 2, then token 3. That was elegant, and it matched our intuition about language as
a sequence. But it also created a computational bottleneck. The hidden state at position t
could not be fully computed until position t−1 was done, which made long sequences harder to
parallelize during training.
There was already a counter-movement. Models such as , , and tried to reduce sequential computation with . They replaced the step-by-step recurrence of RNNs with convolutional computation that could be applied to many positions at once.
The key difference was how far information could travel in one layer. used stacked convolutions: fast and parallel, but still local, so distant words needed multiple layers to influence each other. used dilated convolutions to expand the receptive field more quickly, reducing the path between faraway positions to a logarithmic scale. belonged to a related line of work that treated sequence processing more like repeated updates over a parallel memory-like grid. These models were important because they showed that sequence modeling did not have to be strictly recurrent. But they still did not make every token globally visible to every other token in a single step.
The Transformer asks a more radical question: if attention already lets a decoder look directly at any source position, why not let every token look directly at every other token? That is the step from attention as an alignment tool to as the core architecture.
There is an interesting twist in the story. The Transformer came from Google, and Google quickly used Transformer-based models in major systems, including BERT for Search. Yet the first Transformer-based product that many people experienced as a cultural event was ChatGPT, released by OpenAI. That did not happen simply because OpenAI had a different architecture. GPT was also a Transformer. The difference was in how the model was scaled, trained as a decoder-only language model, adapted to follow instructions, aligned with human feedback, and finally presented through an extremely simple chat interface. The architecture made the product possible, but product timing, deployment choices, risk tolerance, and alignment work shaped who brought that experience to the public first.
The bottleneck it attacked
The central enemy is not simply that “RNNs are old.” The real problem is sequential dependence. In an RNN, information moves through a chain: the representation at one position depends on the representation before it. If token 1 needs to influence token 30, the signal must pass through many intermediate hidden states. This makes long-distance dependencies harder to learn and prevents the model from fully parallelizing computation across positions.
x₁ → h₁ → h₂ → h₃ → ... → hₙ. The order is natural, but the path is long,
and training has an unavoidable left-to-right dependency.
Convolutions can process positions in parallel, but each layer sees only a local window. Distant tokens meet only after enough layers expand the receptive field.
Any token can attend to any other token in one layer. The path length between two positions is constant, no matter how far apart they are.
Full self-attention costs O(n²) in sequence length because every token is compared
with every other token. For sentence-level translation, n is usually manageable.
The architecture as a whole
The Transformer keeps the familiar encoder-decoder shape of earlier translation systems. The reads the source sentence and builds contextual representations for every source token. The generates the target sentence one token at a time. What changes is not the high-level translation workflow, but the internal mechanism used inside each block.
“Six layers” means six blocks with the same structure, not one block reused with shared weights. Each layer has its own parameters. The encoder stack repeats one kind of block six times; the decoder stack repeats a slightly larger block six times. This stacked design lets the model refine token representations gradually, from surface-level word information toward more task-specific contextual information.
Self-attention → Add & Norm → FFN → Add & Norm
The encoder layer lets every source token gather information from the full source sentence, then uses a to refine each token representation independently.
Masked self-attention → Add & Norm → Cross-attention → Add & Norm → FFN → Add & Norm
The decoder first looks only at previously generated target tokens, then uses to query the encoder output and decide which source positions matter for the next prediction.
Token embeddings represent what a token is; positional encodings represent where it appears.
Each encoder layer lets every source token look at all source tokens, then transforms each position through an FFN.
The decoder sees previous target tokens through a causal mask, then queries the encoder output.
A linear layer and softmax turn decoder states into next-token probabilities.
Around each sublayer, the model applies a
followed by
. This is written as
LayerNorm(x + Sublayer(x)). These details are not decorative: residual connections
preserve information and improve gradient flow, while layer normalization keeps the activations
stable as the model becomes deeper.
Attention, QKV, and square-root scaling
The most useful way to understand is as soft retrieval. A token does not passively receive a hidden state from its neighbor. It asks a question, compares that question to candidate keys, and retrieves a weighted mixture of values.
| Symbol | Name | Interpretation |
|---|---|---|
Q | Query | What this position is looking for. |
K | Key | How each candidate position advertises what it contains. |
V | Value | The information actually retrieved and mixed into the output. |
d_k | Key/query dimension | The width of the query-key matching space for one head. |
The important point is that are learned projections.
Given token representations X, the model forms Q = XWQ,
K = XWK, and V = XWV. The same token can therefore
play three roles: it can ask for information, advertise itself to others, and provide content when selected.
Attention(Q, K, V) = softmax(QKT / √dk)V
The term QKT creates an n × n matrix of compatibility scores.
Row i, column j means: how much should token i attend to token
j? turns each row into attention
weights, and multiplying by V creates weighted averages of value vectors.
Why divide by √dk?
Suppose the components of q and k are independent, with mean 0
and variance 1. Their dot product is:
q · k = Σi=1dk qiki
Since there are dk terms, the variance of the sum grows roughly like
dk. In other words, larger key/query dimensions tend to produce larger and more
extreme dot-product scores.
The problem shows up inside . If the scores are moderately sized, softmax still leaves room for several positions to matter. For example:
softmax([1, 2, 3]) ≈ [0.09, 0.24, 0.67] But if the same pattern is scaled up, the distribution becomes much sharper:
softmax([10, 20, 30]) ≈ [0.00, 0.00, 1.00]
Now one position receives almost all the probability, while gradients for the other positions become tiny.
Dividing by √dk pulls the standard deviation of the dot products back toward a stable
scale, keeping softmax from becoming too saturated. This is the “scaled” part of scaled dot-product attention.
Dot-product attention vs. additive attention
Dot-product attention scores compatibility with a simple vector dot product:
score(q, k) = q · k. In matrix form, this becomes QKT, which is why
it is so efficient: all query-key comparisons can be computed as one large, highly optimized matrix
multiplication.
, associated with Bahdanau attention,
uses a learned scoring network instead of a direct dot product. A common way to write it is
score(q, k) = vT tanh(Wqq + Wkk). In words, the query and key
are first transformed, combined, passed through a nonlinearity, and then scored by another learned vector.
Additive attention can be expressive, and it was very important in earlier neural machine translation.
The Transformer uses dot-product attention because it is much faster and more memory-efficient in practice,
especially when implemented with batched matrix multiplication. The scaling factor √dk
helps dot-product attention avoid the large-score problem that appears when the key/query dimension grows.
Multi-head attention
A single attention distribution gives the model one way to look at the sentence. But language contains many relationships at once: pronouns, modifiers, syntax, local context, long-range dependencies, and translation alignment. The design lets the model learn several views in parallel.
MultiHead(Q, K, V) = Concat(head1, ..., headh)WO
headi = Attention(QWiQ, KWiK, VWiV)
| Symbol | Meaning |
|---|---|
h | The number of attention heads. The base Transformer uses h = 8. |
headi | The output of the i-th attention head. |
WiQ | The learned projection matrix that maps queries into the i-th head's query subspace. |
WiK | The learned projection matrix that maps keys into the i-th head's key subspace. |
WiV | The learned projection matrix that maps values into the i-th head's value subspace. |
WO | The learned output projection that mixes the concatenated heads back into dmodel dimensions. |
Concat(...) | Concatenation of all attention head outputs along the feature dimension. |
In the base model, dmodel = 512, h = 8, and each head uses
dk = dv = 64. Eight heads of 64 dimensions concatenate back to
512 dimensions. This keeps the total cost similar to one full-width head while giving the model
multiple learned subspaces.
Each head receives its own projected Q, K, and V.
It performs scaled dot-product attention independently. The heads are concatenated, then
WO mixes them back into the model's main representation space.
Positional encoding
Self-attention by itself is permutation-friendly: without extra information, the model can see that a set of tokens exists, but not their order. That is why the model adds to token embeddings.
PE(pos, 2i) = sin(pos / 100002i / dmodel)
PE(pos, 2i + 1) = cos(pos / 100002i / dmodel)
Each position gets a dmodel-dimensional vector. Even dimensions use sine;
odd dimensions use cosine. The frequencies differ by dimension. A single sine curve does oscillate
between −1 and 1, but the whole position vector is a multi-frequency fingerprint. One dimension
alone is not the point; the combination is.
Why not just use position numbers like 1, 2, 3? A raw number grows without bound and gives the network a poor representation of local and relative distance. Sinusoidal encodings stay numerically stable and create structured relationships between positions.
What “relative position is easier to learn” means
Many language patterns depend on offsets: previous word, next word, three tokens away, far away.
The paper's sinusoidal choice makes a fixed offset k mathematically regular. Through
trigonometric identities, PE(pos + k) can be represented as a linear function of
PE(pos) for a fixed k.
sin(pos + k) = sin(pos)cos(k) + cos(pos)sin(k) cos(pos + k) = cos(pos)cos(k) − sin(pos)sin(k)
Here, pos plays the role of the current position, and k is the offset.
More precisely, each sinusoidal dimension uses a scaled position such as
pos / wavelength, so the actual expression is closer to
sin((pos + k) / wavelength). But the same idea still holds: for a fixed offset
k, the representation at pos + k can be written as a predictable
combination of the sine and cosine values at pos under the same frequency.
This is why sinusoidal encoding is useful for relative distance. The model is not merely given isolated labels like “position 7” and “position 10.” It receives position vectors whose relationships contain regular patterns. That makes it easier for attention layers to learn ideas like “look one token back,” “look three tokens ahead,” or “prefer nearby tokens,” even though those rules are not hard-coded.
This does not mean the model is handed an alignment table. It means the encoding gives the model a convenient structure for learning “distance-like” relationships. In translation, English and French words often move to different positions. Positional encoding only tells each side its own internal order; the actual cross-language correspondence is learned by encoder-decoder attention.
"the red car": "red" is before "car".
"la voiture rouge": "rouge" is after "voiture".
Represent order inside each sequence.
Learn that "rouge" should retrieve information from "red".
Why self-attention
The case for self-attention rests on three questions. How much computation does one layer need? How many steps must be executed sequentially? And how short is the path between two distant positions? A good sequence layer should be parallelizable and should let faraway tokens exchange information through short paths.
| Layer type | Complexity | Sequential ops | Path length | Why it matters |
|---|---|---|---|---|
| Self-attention | O(n²d) | O(1) | O(1) | All tokens compare with all tokens; every pair can communicate directly. |
| Recurrent | O(nd²) | O(n) | O(n) | Each hidden state depends on the previous hidden state, so computation remains sequential. |
| Convolutional | O(knd²) | O(1) | O(logk n) | Positions are parallel, but distant tokens need enough layers for the receptive field to reach them. |
| Restricted self-attention | O(rnd) | O(1) | O(n / r) | Each token attends only to a neighborhood of size r, reducing cost but increasing the path between faraway positions. |
Where the complexity numbers come from
With n tokens, every token compares itself with every other token. That creates
n × n query-key scores. Each score is a dot product over roughly d
dimensions, so the attention score computation is O(n²d).
The sequential depth is O(1) because all pairwise comparisons can be computed in
parallel as matrix multiplication. The maximum path length is also O(1): token
i can attend directly to token j in one layer.
Restricted self-attention limits each token to a local neighborhood of size r instead
of attending to all n positions. That means there are only n × r
query-key comparisons rather than n².
Each comparison still costs about O(d), so the total is O(rnd). It remains
parallel across positions, but long-distance information now has to hop across neighborhoods.
The maximum path length becomes roughly O(n / r).
A recurrent layer updates one hidden state per token. Each update usually applies a learned
transformation from a d-dimensional hidden state to another d-dimensional
hidden state, which costs about O(d²) per position.
Across n positions, that gives O(nd²). The sequential depth is
O(n) because state ht depends on ht−1.
The path from the first token to the last token also has length O(n).
A convolutional sequence layer applies a kernel of width k at every one of the
n positions. At each position, it combines k neighboring vectors and
maps them through learned transformations over d-dimensional features.
This gives roughly O(knd²). The layer is parallel across positions, so its sequential
depth is O(1). But a single layer only sees a local window. To connect distant tokens,
information must move through multiple convolutional layers. With receptive field expansion, the
maximum path length is written as O(logk n).
When is self-attention cheaper than recurrence?
The key comparison is self-attention versus recurrence. Self-attention costs
O(n²d); recurrence costs O(nd²). Ignoring constant factors, self-attention
is cheaper when:
n²d < nd² ⇒ n < d
In sentence-level translation, the sequence length n is often much smaller than the
representation dimension d, such as dmodel = 512. This is why full
self-attention can be attractive despite the quadratic term in sequence length.
The deeper advantage is not just raw complexity. Self-attention gives every pair of positions a direct route. That short path is especially useful for long-distance dependencies: a word near the beginning of a sentence can influence a word near the end without passing through a long chain of recurrent states or many layers of local convolution.
Training recipe
The paper's result is not architecture alone. It also depends on a careful training setup: subword tokenization, large batches, Adam, learning-rate warmup, dropout, label smoothing, checkpoint averaging, and beam search.
| Item | Configuration |
|---|---|
| Datasets | WMT 2014 English-German: about 4.5M sentence pairs; WMT 2014 English-French: about 36M sentence pairs. |
| Tokenization | English-German uses byte-pair encoding with a shared source-target vocabulary of about 37K tokens; English-French uses a 32K word-piece vocabulary. |
| Batching | Sentence pairs are batched by approximate length; each batch contains about 25K source tokens and 25K target tokens. |
| Hardware | 8 NVIDIA P100 GPUs. |
| Base model | 100K steps, about 12 hours; dmodel = 512, dff = 2048, h = 8. |
| Big model | 300K steps, about 3.5 days; dmodel = 1024, dff = 4096, h = 16. |
| Optimizer | Adam with β1 = 0.9, β2 = 0.98, and ϵ = 10−9. |
| Regularization | Residual dropout, embedding-plus-position dropout, and label smoothing with ϵls = 0.1. |
Learning rate schedule
lrate = dmodel−0.5 · min(step_num−0.5, step_num · warmup_steps−1.5)
The model uses plus
. Early learning rate increases linearly for
4000 steps, then decays roughly like the inverse square root of the step number. Warmup prevents
unstable early jumps; later decay makes updates more precise.
is applied after sublayer outputs and after the sum of embeddings and positional encodings. makes targets less overconfident. The paper notes a subtle trade-off: label smoothing can hurt perplexity because the model is less certain, while improving accuracy and BLEU.
For evaluation, the authors use :
base models average the last 5 checkpoints, and big models average the last 20. They decode with
using beam size 4 and length penalty
0.6.
Results and comparisons
The headline result is simple: the Transformer is both strong and efficient. On WMT 2014
English-German, Transformer big reaches 28.4 BLEU, more than 2 BLEU
above the previous best reported systems, including ensembles. On English-French, it reaches
41.8 BLEU as a single model.
The important comparison is not only “which model has the highest BLEU?” but also “how much computation did it take to get there?” Several earlier systems achieved strong translation quality by using recurrent models, convolutional models, mixture-of-experts layers, reinforcement-learning refinements, or ensembles. The Transformer competes with all of them while using substantially less training cost than many previous high-performing systems.
| Model | EN-DE BLEU | EN-FR BLEU | Training cost | How to read it |
|---|---|---|---|---|
| GNMT + RL Ensemble | 26.30 | 41.16 | High | Strong recurrent Google NMT system with reinforcement-learning tuning and ensembling. |
| ConvS2S Ensemble | 26.36 | 41.29 | High | Convolutional sequence-to-sequence model; highly competitive pre-Transformer baseline. |
| Transformer base | 27.3 | 38.1 | Low | Already beats previous EN-DE systems at a fraction of training cost. |
| Transformer big | 28.4 | 41.8 | Moderate | Best reported results in the paper; EN-DE beats previous ensembles by more than 2 BLEU. |
What the baselines are doing
The baselines are not random older models; they represent the strongest competing directions in neural machine translation at the time. Some are recurrent encoder-decoder systems with attention, some are convolutional sequence models, some use very large sparse computation, and some combine multiple models into an ensemble. This matters because the Transformer is not being compared only against weak RNNs. It is being compared against several serious attempts to make translation models more accurate or more efficient.
ByteNet
A convolutional model using dilated convolutions to process sequences with better parallelism than RNNs.
Deep-Att + PosUnk
A deep attention-based translation system with a technique for handling unknown words by using source positions.
GNMT + RL
Google Neural Machine Translation, a strong recurrent encoder-decoder system, here further tuned with reinforcement learning.
ConvS2S
A convolutional sequence-to-sequence model that replaces recurrent layers with convolutional blocks.
MoE
Mixture-of-Experts, a sparsely gated model that activates different expert subnetworks for different inputs.
Ensemble
A group of models combined at inference time; usually stronger but more expensive than one model.
Read these baselines as a map of the field before the Transformer. GNMT represents the mature recurrent translation pipeline: deep LSTMs, attention, and production-oriented engineering. ConvS2S and ByteNet represent the convolutional push toward better parallelism. Deep-Att + PosUnk represents an attention-heavy recurrent translation line with explicit handling of rare or unknown words. MoE explores scaling model capacity through sparsely activated expert networks. The ensemble rows show what happens when several trained models are combined at inference time, usually improving quality but increasing cost and complexity.
What the model variation experiments teach
The model variation results tell the architectural story behind the headline score. A single attention head is worse than multi-head attention, which supports the idea that different heads learn different relational views of the sentence. But too many heads can also hurt, because if the total model dimension is fixed, each head becomes too narrow to represent rich query-key compatibility.
Reducing the key/query dimension hurts quality, suggesting that deciding whether a query and a key match is not a trivial operation. Larger models generally perform better, dropout is important for preventing overfitting, and learned positional embeddings perform almost the same as sinusoidal encodings on the tested translation task. In other words, the paper’s best result is supported by a set of design choices rather than by one isolated trick.
The paper does not merely report “higher BLEU.” It connects the gain to the earlier architectural argument: shorter paths for long-distance dependency, fewer sequential operations, and better GPU parallelization. The result is persuasive because the same design that explains the speed advantage also delivers state-of-the-art translation quality.
Appendix visualizations
The appendix visualizes encoder self-attention heads. These figures are not strict proof that attention equals linguistic explanation, but they show why the model felt interpretable: some heads visibly focus on meaningful syntactic or semantic relationships.
| Figure | Pattern | Interpretation |
|---|---|---|
| Figure 3 | Long-distance dependency | Heads attending from “making” help connect the phrase “making ... more difficult.” |
| Figure 4 | Anaphora resolution | Attention from “its” sharply points back toward “The Law,” suggesting pronoun resolution. |
| Figure 5 | Sentence structure | Different heads show different structural patterns, supporting the multi-head interpretation. |
Impact and afterlife
The original Transformer is an encoder-decoder translation model. Modern LLMs usually use only part of that template. is encoder-only and emphasizes understanding. is decoder-only and emphasizes next-token generation. is not simply “the Transformer paper turned into a product”; it is a later stack of scale, pretraining, instruction tuning, feedback learning, safety work, and interface design.
| Period | What changed |
|---|---|
| 2014–2016 | Seq2seq, Bahdanau attention, Luong attention, GNMT, ConvS2S make neural translation competitive. |
| 2017 | Google researchers publish Attention Is All You Need and introduce the Transformer. |
| 2018–2019 | BERT and GPT-style models show that Transformers are not just translation models. |
| 2022+ | ChatGPT turns decoder-only Transformers plus instruction tuning and product design into a mass-market interface. |
Why was it called “Transformer”? At the paper level, the name fits the sequence-transduction framing: the model transforms one sequence into another. It also names the architectural transformation happening inside the model: representations are repeatedly transformed by attention and feed-forward blocks rather than updated by recurrence. The name became broader than the original machine-translation setting because the same block turned out to scale across many modalities and tasks.
The Google-versus-OpenAI question is best answered carefully. Google created the architecture and later used Transformer-based models in major products. OpenAI, however, pushed the decoder-only generative line into a public conversational interface. Architecture was necessary, but not sufficient; product timing and alignment strategy mattered too.
Takeaways
- The Transformer keeps encoder-decoder translation but replaces recurrence/convolution with attention-based token communication.
- Attention is soft retrieval: Q asks, K matches, V supplies information.
- Square-root scaling keeps dot-product scores from making softmax too sharp.
- Multi-head attention gives the model multiple learned views of the same sequence.
- Sinusoidal positional encoding gives order information and a convenient structure for relative offsets.
- The paper's empirical claim is not only better BLEU, but better BLEU with far more parallelizable training.
- The modern LLM era begins here architecturally, but ChatGPT required later choices: decoder-only pretraining, scaling, instruction tuning, feedback, and product design.