Attention Is All You Need
The Transformer — the architecture behind modern AI
Before this paper, the best translation systems read sentences one word at a time, carrying a running memory forward (recurrent networks). That was slow — you can't process word 5 until word 4 is done — and forgetful over long sentences. The 2017 Transformer threw out that sequential machinery entirely and replaced it with attention: a mechanism that lets every word look directly at every other word and decide which ones matter. Because nothing waits its turn, the model trains fully in parallel on GPUs, captures long-range relationships in a single step, and set new translation records while training in a fraction of the time. This design became the foundation of GPT, BERT, Claude, and essentially all modern AI.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, et al.
28.4
BLEU · English→German
New state of the art on WMT 2014, beating prior best results (including ensembles) by over 2 BLEU.
41.8
BLEU · English→French
Outperformed all previously published single models on WMT 2014 — at under a quarter of the prior state-of-the-art training cost.
3.5 days
Training time (big model)
On 8 NVIDIA P100 GPUs — a small fraction of competing models' training cost.
6 + 6
Layers per stack
6 encoder layers and 6 decoder layers (N = 6 each).
8
Attention heads
Each head runs in a 64-dim subspace (d_k = d_v = 64) in the base model, where d_model = 512.
65M / 213M
Parameters (base / big)
Base model vs the larger 'big' model used for the headline scores.
O(1)
Sequential ops per layer
Constant, versus O(n) for RNNs — this is what unlocks fully parallel training.
2048
Feed-forward inner size
4× d_model; each token's vector expands then contracts (d_ff in the base model).
The one-line version
Everything you know as “AI” started here
GPT, Claude, Gemini, BERT, AlphaFold — they are all, under the hood, Transformers. This is the paper that introduced them. Its radical idea was to delete the machinery everyone assumed you needed to understand language, and replace it with one elegant mechanism: attention. Let's build up to what that means, one idea at a time — no math background required.
The problem
Why reading word-by-word was too slow
Before 2017, the best translators read a sentence one word at a time, left to right, keeping a running summary of everything seen so far. This caused two problems.
First, it's slow by design: you can't start processing word 5 until words 1–4 are done, so you can't speed up a single sentence just by adding more computers. Second, it's forgetful: by the time the machine reaches the end of a long sentence, the beginning has faded, so it loses connections between far-apart words.
The Transformer's boldest move was to dispense with both of the era's dominant designs — not just recurrent networks, but also the convolutional sequence models (like ConvS2S and ByteNet) that were the other way to parallelize. It relies on attention alone.
Think of it like…
Translating a book by whispering it down a line of people: each person can only speak after hearing the one before them, and details from chapter 1 are hopelessly garbled by the time the message reaches chapter 20.
Sequential vs. parallel — press Go
Sequential steps vs. sentence length
it → animal
RNN: 7 hops (signal fades)
Transformer: 1 direct hop
For the curious
Recurrent networks (RNNs, including LSTMs/GRUs) compute a hidden state hₜ from the previous state hₜ₋₁ and the current input. This chain of length n forces O(n) sequential operations that can't be parallelized within a training example, and long-range dependencies must traverse O(n) steps — causing signal and gradient decay. Classic seq2seq models made it worse by squeezing the whole source sentence into a single fixed-size vector.
The core idea
Let every word look at every other word
Attention is a mechanism where, to understand one word, the model looks at all the other words and decides how much each one matters right now. Take the sentence “The animal didn't cross the street because it was too tired.” To resolve what “it” refers to, attention lets the model glance at “animal” and “street” and figure out that “it” means the animal.
The magic: in the encoder, every word does this looking at the same time, in one step. (In the decoder, a word can only look at earlier words — more on that when we reach masking.)
Tap or hover any word to see what it attends to
“it” attends to →
A note on this example
The “it → animal” sentence is a well-known illustration popularized by later attention visualizations, not a figure from the 2017 paper itself. We use it because it makes the idea click instantly — the mechanism it demonstrates is exactly the paper's.
The mechanism
Queries, Keys, and Values
How does a word decide what to look at? Each word generates three things:
- a Query — “what am I looking for?”
- a Key — “how do I describe myself?”
- a Value — “the actual information I'll hand over.”
A word's Query is compared against every word's Key to produce match scores, and those scores decide how much of each word's Value gets mixed into the final answer for that position. Separating what decides relevance (Query·Key) from what information is passed on (Value) is the single most clarifying idea in the whole paper.
Think of it like…
A library search. Your Query is your search request; every book has a Key printed on its spine (its title and description); the Value is the book's actual contents. You match your request against all the spines, then read most heavily from the books whose spines matched best.
Match the Query against every Key
My Queryasks: “what am I about?” I compare it against every word's Key.
✦ Notice “it” matches “animal”most strongly — so most of animal's Valuegets mixed into the output for “it”. That's attention as a soft lookup.
The formula
Scaled dot-product attention (and the mysterious ÷√dₖ)
The match scores can get very large when the Query/Key vectors are long. When scores are too large, the softmax that turns them into percentages becomes overconfident — it dumps almost all the weight onto a single word. The problem isn't that numbers overflow; it's that softmax saturates, and in that regime its gradients shrink toward zero, so the model can barely learn. To prevent this, every score is divided by the square root of the vector length, keeping softmax in a healthy, learnable range.
Attention(Q, K, V) = softmax( (Q Kᵀ) / √dₖ ) · V
If Query and Key components are independent with mean 0 and variance 1, then q·k = Σ qᵢkᵢ has variance dₖ, so its magnitude grows like √dₖ. Dividing by √dₖ renormalizes the variance back to ~1, keeping softmax out of its saturated, near-zero-gradient region. In the base model dₖ = 64.
Step through the four stages
1 · Raw scores
Dot-product the Query with every Key. Bigger dot product = better match.
Two flavors
Self-attention vs. cross-attention
Self-attention is a sentence looking at itself — every word gathering context from its own neighbors. Cross-attention is the translation half looking back at the original: as the model writes each German word, it looks at all the English words to decide what to say next. Same machinery — the difference is only where the three vectors come from.
In self-attention, Q, K, and V all derive from the same sequence. In cross-attention, the Queries come from the decoder while the Keys and Values come from the encoder's final output.
Think of it like…
Self-attention is proofreading your own paragraph — each word checking the others for consistency. Cross-attention is a translator glancing back at the source text after every word they write, to stay faithful to the original.
More perspectives
Multi-head attention: many lenses at once
Instead of doing attention just once, the model does it several times in parallel using different learned “lenses.” One head might track which word is the grammatical subject, another which words are related in meaning, another long-distance references like pronouns. Their findings are then combined, so a single layer can capture many kinds of relationships simultaneously.
With 8 heads and d_model = 512, each head works in a 64-dimensional subspace — splitting the dimension keeps the total compute close to a single full-size attention while giving the model multiple distinct viewpoints.
Compare the heads
Focused word: “it” — each head looks at it differently.
Verbs seek their subject and object (cross → animal, was → it).
Pronouns resolve to what they refer to (it → animal).
Each word attends to its immediate neighbors — local context.
Focus on pivotal linking tokens like “because”.
Think of it like…
A panel of specialist editors all reading the same sentence — a grammarian, a fact-checker, a poet — each highlighting different words for different reasons, then merging their annotations into one combined review.
Restoring order
Positional encoding: teaching order without reading in order
Because attention looks at all words at once, it has no built-in sense of order — “dog bites man” and “man bites dog” would look identical to it. So the model adds a special pattern of numbers to each word's embedding that encodes its position, like a subtle timestamp, letting attention recover who came before whom. (Note it's added, not glued on the side.)
PE(pos, 2i) = sin( pos / 10000^(2i/d) ) · PE(pos, 2i+1) = cos( pos / 10000^(2i/d) )
Wavelengths form a geometric progression from 2π to ~10000·2π. For any fixed offset k, PE(pos+k) is a linear (rotation) function of PE(pos) — which makes relative positions easy to attend to. Learned positional embeddings performed nearly identically; sinusoids were chosen partly because they may extrapolate to longer sequences than seen in training.
Explore the position fingerprints
Dimension 4
sine wave · wavelength ≈ 11
Low dimensions oscillate fast; high dimensions oscillate slowly. Stacked together, every position gets a unique “barcode” — and because the wavelengths are smooth, the model can compute relative offsets like “3 positions back.”
Think of it like…
Giving every seat in a stadium a unique blend of colored lights — some blinking fast, some slow. From the exact color mix you can read off not just the seat number, but also easily compute “three seats to the left.”
The full picture
A stack of encoders and decoders
The Transformer has two towers. The encoder reads the whole input sentence and builds a rich, context-aware representation of it. The decoder writes the output one word at a time, consulting both what it has written so far and the encoder's representation. Each tower stacks 6 identical layers, so understanding gets refined step by step.
Each encoder layer = multi-head self-attention + a feed-forward network. Each decoder layer adds a third sub-layer: masked self-attention, then cross-attention into the encoder, then feed-forward.
Figure 1 in the original paper
The original Transformer architecture diagram — the encoder (left) and decoder (right) stacks, with multi-head attention, feed-forward, and add-&-norm layers.
Vaswani et al., 2017 · view on arXiv
Watch a sentence flow through
Encoder×6
Decoder×6
Press Play to watch “The cat sat” become “Le chat s'est assis”, stage by stage.
Think of it like…
An assembly line. The encoder side is 6 stations that each add more context to the input; the decoder side is 6 stations that, using the finished input plus the words written so far, produce the next word.
Keeping it trainable
Residual connections + layer norm
Stacking many layers can cause the signal to fade away or blow up. Two fixes work together. A residual connection adds each sub-layer's input back onto its output, giving information (and the learning signal) a shortcut straight through. Layer normalization then rescales the numbers to a consistent range at each step. Together they let a deep stack train smoothly. In the original design each sub-layer computes LayerNorm(x + Sublayer(x)) — the norm comes after the residual add.
Think of it like…
The residual connection is an express bypass lane, so the original message always reaches the end even if one station garbles it. Layer norm is a volume leveler that resets every signal to a standard loudness before it enters the next station.
Per-word thinking
The feed-forward sublayer
After each attention step, every word passes through the same wide two-layer network by itself — no looking at neighbors here. It expands each word's 512-dim vector to 2048, applies a ReLU, then contracts back to 512. Attention mixes information between words; this feed-forward step then does extra per-word processing on the mixed result. Far from a minor detail, this sublayer actually holds the majority of each layer's parameters.
FFN(x) = max(0, x·W₁ + b₁) · W₂ + b₂
Two linear transformations with a ReLU between, applied identically and independently to every position (“position-wise”). Inner dimension d_ff = 2048 = 4× d_model. Weights are shared across positions within a layer but differ between layers. Equivalent to two 1×1 convolutions.
No peeking
Masking: how the decoder avoids seeing the future
While learning to write a translation, the model must predict each next word using only the words before it — not by cheating and looking at the answer that comes later. Masking blocks each position in the decoder from attending to any word that comes after it, so generation stays honest and strictly left-to-right.
Concretely: in the decoder's self-attention, the pre-softmax scores for all future positions are set to −∞, so after softmax their weights are exactly 0. The encoder uses no such mask — it may attend to the entire input.
Think of it like…
An exam where each answer must be written before the answer key for the later questions is revealed — a sheet of paper covers everything to the right of your pen.
The payoff
Better translations, trained in a fraction of the time
The Transformer beat the best previous systems while training dramatically faster because everything runs in parallel. On WMT 2014 English→German it reached 28.4 BLEU, improving over all prior results — including ensembles — by more than 2 BLEU. On English→French it reached 41.8 BLEU, outperforming all previously published single models, at under a quarter of the prior state-of-the-art training cost. The big model trained in 3.5 days on 8 P100 GPUs. Efficiency this good is a major reason the whole field pivoted to this design.
By the numbers
28.4
BLEU · English→German
New state of the art on WMT 2014, beating prior best results (including ensembles) by over 2 BLEU.
41.8
BLEU · English→French
Outperformed all previously published single models on WMT 2014 — at under a quarter of the prior state-of-the-art training cost.
3.5 days
Training time (big model)
On 8 NVIDIA P100 GPUs — a small fraction of competing models' training cost.
O(1)
Sequential ops per layer
Constant, versus O(n) for RNNs — this is what unlocks fully parallel training.
How the era's models compared
| Model | EN→DE BLEU | EN→FR BLEU |
|---|---|---|
| GNMT + RL | 24.6 | 39.9 |
| ConvS2S | 25.2 | 40.5 |
| Transformer (base) | 27.3 | 38.1 |
| Transformer (big) | 28.4 | 41.8 |
The lasting idea
The paper didn't just win a benchmark — it handed the field an architecture that scales. Remove the sequential bottleneck, and you can throw ever more data and compute at the model. Every large language model since is a descendant of this one design.
Key takeaways
- Attention lets every word directly consult every other word in one step — no word-by-word recurrence.
- Query·Key decides *relevance*; Value carries the *information* — that separation is the heart of attention.
- Dividing scores by √dₖ keeps softmax out of its saturated, low-gradient regime so the model can actually learn.
- Multiple attention heads capture different relationships in parallel, then get fused together.
- Positional encodings are *added* to embeddings so an order-blind mechanism can still know word order.
- Removing recurrence made training fully parallel — the property that launched the era of large-scale AI.
References
- Vaswani et al. (2017). Attention Is All You Need. NeurIPS
- Bahdanau, Cho, Bengio (2014). Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015
- Gehring et al. (2017). Convolutional Sequence to Sequence Learning (ConvS2S). ICML
- Ba, Kiros, Hinton (2016). Layer Normalization
Keep exploring
Chain-of-Thought Prompting Elicits Reasoning in Large Language Models
Ask a big model to show its work — and it starts to reason
Big language models were surprisingly bad at multi-step problems — grade-school math, logic puzzles — often blurting a wrong final answer. This paper found a shockingly simple fix that requires no training at all: in the few examples you show the model (the “prompt”), don't just show it question-and-answer pairs — show it the *reasoning in between*. Write out the step-by-step thinking that leads to each answer. The model then imitates that pattern on new problems, producing its own “chain of thought” before answering — and accuracy leaps. The headline result: prompting a 540-billion-parameter model with just eight worked examples hit 56.9% on the GSM8K math benchmark — up from 17.9% with ordinary prompting — beating the previous best (a model specially fine-tuned for the task and paired with a separate verifier, at 55%). The twist: this only works in *large* models. In small ones, showing the steps does little or even hurts. Reasoning-by-prompting is an ability that *emerges* with scale — a discovery that reshaped how people use LLMs.
QLoRA: Efficient Finetuning of Quantized LLMs
Fine-tune a 65-billion-parameter model on one gaming GPU
LoRA already made fine-tuning cheaper by training tiny add-on matrices instead of the whole model. But there was still a wall: you had to fit the giant frozen base model in GPU memory just to run it — and a 65-billion-parameter model needs over 780 GB, far beyond any single GPU. QLoRA smashes that wall by squashing the frozen base model down to 4 bits per number (instead of the usual 16), roughly a 4× shrink, so the whole thing fits in under 48 GB — a single high-end GPU. It does this without hurting quality, using three clever tricks: a new 4-bit number format (NF4) tuned to how weights are actually distributed, “double quantization” that even compresses the compression bookkeeping, and “paged optimizers” that spill memory to the CPU during brief spikes instead of crashing. The tiny LoRA add-ons still train in full precision on top. To prove it works, they fine-tuned a chatbot called Guanaco in 24 hours on one GPU — and it reached 99.3% of ChatGPT's score on a popular benchmark. QLoRA is why hobbyists and small labs can now fine-tune enormous models at home.
Retrieval-Augmented Generation for Large Language Models: A Survey
RAG — giving a language model an open book to read from
A language model only knows what it saw during training. So it can confidently make things up (“hallucinate”), it can't know anything recent, and it can't see your private documents. Retrieval-Augmented Generation (RAG) fixes this with a simple, powerful idea: before the model answers, go fetch relevant text from an external library and hand it to the model along with the question — like turning a closed-book exam into an open-book one. The basic recipe has three steps: (1) Indexing — chop your documents into chunks and store them so they're searchable by meaning; (2) Retrieval — when a question comes in, pull the few most relevant chunks; (3) Generation — feed those chunks plus the question to the model so its answer is grounded in real sources. This survey organizes the whole field into three generations of increasingly sophisticated RAG — Naive, Advanced, and Modular — and breaks every system into three parts: what you retrieve, how you use it, and how the model generates. RAG is now one of the most widely used techniques in real-world AI, because it makes answers more accurate, up-to-date, and traceable to a source.