Foundations Guide 01 of 25
Attention Is All You Need: the paper that started modern AI
In 2017, eight researchers working at Google replaced recurrence with attention. Here is what they built, why it scaled so well, and why its trade-offs still show up in your latency and GPU bill.
Key takeaways
- Self-attention lets every token look at every other token in one step, so recurrence could go and training became massively parallel on GPUs and TPUs.
- Training is parallel but generation is not: models still write one token at a time, reading a growing cache of keys and values.
- Attention compute grows with the square of prompt length, and the key-value (KV) cache grows with every token in context, so long prompts cost both compute and memory.
- BERT kept the encoder and GPT kept the decoder; the decoder-only branch became the template for today’s general-purpose assistants.
- As of 2026, labs ration attention with local windows, shared key-value heads, and hybrid layers rather than abandon it.
On this page 7 sections
The large language models (LLMs) behind today’s chat assistants, coding tools, and agents descend from a 15-page paper posted to arXiv on 12 June 2017. Its eight authors did the work at Google Brain and Google Research, and the subject was machine translation. Chatbots, agents, and code generation appear nowhere in it.
Why should an engineering leader care in 2026? Because its central mechanism is still what you pay for. It explains why long prompts delay the first token, why answers stream one token at a time, why context windows have a ceiling, and why serving a model is largely a memory problem.
What problem was the Transformer built to solve?
In 2017 most leading translation systems were recurrent neural networks (RNNs), usually the long short-term memory (LSTM) variety, though convolutional models held some of the top scores. An RNN reads a sentence one token at a time, and each step needs the result of the step before it. The authors argued that this chain rules out parallel work inside a single training example, a limit that bites hardest on long sequences (Vaswani et al., 2017).
Attention itself was not new. Translation models already used it to let the decoder look back at relevant source words, but almost always bolted onto a recurrent network. The paper’s bet was to keep the attention and throw away everything else. In the abstract’s own phrasing, the Transformer was:
“based solely on attention mechanisms, dispensing with recurrence and convolutions entirely.” — Vaswani et al., 2017
On the 2014 Workshop on Statistical Machine Translation (WMT) English-to-German test, the Transformer scored 28.4 BLEU (bilingual evaluation understudy, a standard translation-quality score), more than 2 points above the previous best, ensembles included. The large English-to-French model trained in 3.5 days on one machine with eight NVIDIA P100 graphics processing units (GPUs) (Vaswani et al., 2017). Google’s 31 August 2017 announcement put the training speedup at as much as an order of magnitude.
How does self-attention work?
Self-attention lets every token look at every other token and decide which ones matter for its own meaning. Take the sentence “The deploy failed because the migration locked the orders table, so we rolled it back.” To represent “it,” the model must link it to “deploy” or “migration,” not “table.” An RNN carries that signal across a dozen steps; self-attention makes the link in one.
Each token’s vector is projected three ways:
- A query: what this token is looking for.
- A key: what this token advertises to tokens that are searching.
- A value: the information it hands over if picked.
The model scores every query against every key with a dot product, divides by the square root of the key size, and applies a softmax so each token’s weights sum to one. Each token’s new representation is a weighted blend of all the values. The scaling exists because the authors suspected large dot products push the softmax into flat regions where gradients are tiny (Vaswani et al., 2017).
In NumPy, the whole idea fits in a few lines:
import numpy as np
def self_attention(X, Wq, Wk, Wv, causal=False):
# X: one row per token, shape (n, d_model).
# Project every token three ways.
Q, K, V = X @ Wq, X @ Wk, X @ Wv
# (n, n): every token scored against every token.
scores = Q @ K.T / np.sqrt(K.shape[-1])
if causal:
# Decoder: no peeking at later tokens.
mask = np.full_like(scores, -np.inf)
scores += np.triu(mask, k=1)
# Softmax: each row of weights sums to 1.
weights = np.exp(scores - scores.max(-1, keepdims=True))
weights /= weights.sum(-1, keepdims=True)
# Each output is a weighted blend of value vectors.
return weights @ V
That (n, n) score matrix is the heart of the design and its main cost. Every token is compared with every other token, so doubling the input quadruples that matrix and the work to fill it.
The paper’s base model ran eight of these attention “heads” side by side in each layer, each in a 64-dimensional slice of a 512-dimensional representation. That costs about the same as one full-width head, and some heads seemed to specialize in different aspects of sentence structure (Vaswani et al., 2017). Each layer then passes every token, independently, through a feed-forward network four times wider than the representation.
Why did dropping recurrence unlock parallel training?
A recurrent layer needs sequential steps in proportion to sequence length; a self-attention layer needs a constant number, and any two words are one step apart (Vaswani et al., 2017).
Constant sequential steps mean a whole sequence can be processed at once as large matrix multiplications, exactly the workload GPUs and tensor processing units (TPUs) are built for. In training, the decoder sees the whole correct target at once, and a mask stops each position from peeking ahead, so every position learns simultaneously. That property, more than the translation scores, is a big reason later teams could scale models by several orders of magnitude.
There was a catch, and the authors said so. Per layer, self-attention’s compute scales with sequence length squared times representation width, while recurrence scales with length times width squared. Because typical translation sentences had far fewer tokens than the 512 dimensions of each vector, attention was cheaper; with prompts of hundreds of thousands of tokens, the inequality flips. The paper even floated restricting attention to a local neighborhood for long inputs, as future work.
A second catch matters in production. Parallelism applies to training and to reading the prompt, not to writing the answer. Generation is still autoregressive: the model produces one token, appends it, and runs again. That is why responses stream, and why time to first token and tokens per second are separate latency numbers.
Encoder, decoder, and positional encodings: the original design
Each half of the original Transformer was a stack of six identical layers. The encoder reads the whole source sentence, with every word seeing every other word. The decoder writes the translation using masked self-attention over the words so far, then cross-attention, which takes queries from the decoder and keys and values from the encoder’s output.
Self-attention has one blind spot: it ignores word order. Without help, the model would compute the same representation for “dog” in “dog bites man” and “man bites dog.” The fix was a positional encoding added to each token’s embedding, built from sine and cosine waves of different frequencies so every position gets a distinct signature.
The authors also tested learned position embeddings and got nearly identical results. They kept the sinusoids, hoping they would generalize to inputs longer than any seen in training (Vaswani et al., 2017). Position handling has since been heavily reworked. Google’s Gemma 3, for example, uses rotary position embeddings (RoPE), rescaled late in training so its larger models reach a 128K-token context.
What came next: BERT, GPT, and the decoder-only takeover
Within 18 months, two labs had split the Transformer. OpenAI went first, in mid-2018, with the model that became known as GPT (generative pre-trained transformer). It was a 12-layer, decoder-only Transformer, pretrained to predict the next token across more than 7,000 unpublished books, then fine-tuned per task. It set new best scores on nine of the twelve tasks its authors tested (Radford et al., 2018).
Google answered later that year with BERT (Bidirectional Encoder Representations from Transformers), which kept only the encoder and whose open-source release Google announced on 2 November 2018. Instead of predicting the next word, BERT hid random words and learned to fill them in from context on both sides. Google reported state-of-the-art results on 11 natural language processing (NLP) tasks (Google Research, 2018).
| Aspect | Transformer (2017) | BERT (2018) | GPT (2018) | Typical assistant (2025–2026) |
|---|---|---|---|---|
| Halves kept | Encoder and decoder | Encoder only | Decoder only | Decoder only, sometimes hybrid |
| What each token sees | Encoder: all; decoder: earlier tokens plus encoder | All, both directions | Earlier tokens only | Earlier tokens only |
| Training objective | Translate source to target | Fill in masked words | Predict the next token | Next token, then post-training |
| Natural fit | Translation | Classification, search, question answering | Text generation | Chat, code, agents, documents |
Encoders still sit behind many search, classification, and reranking systems. Decoder-only models had the more scalable recipe: one objective works on any text, and one model handles many tasks through prompting. How labs turned that decoder into an assistant — scaling laws, then reinforcement learning from human feedback (RLHF) — is the subject of our next guide.
Why does a 2017 design still set your cost and limits?
The 2017 block is still recognizable in 2025 model reports. Gemma 3 changes details, not the layout, with refinements such as grouped-query attention (GQA), where many query heads share fewer key and value heads (Gemma Team, 2025). The core costs came along too.
Reading the prompt. Processing the input, often called prefill, compares every token with every earlier token, so attention compute grows with the square of prompt length. The rest of the model’s work grows only linearly, so on long prompts the squared term dominates time to first token.
Writing the answer. To avoid recomputing the past at each step, servers store earlier tokens’ keys and values in a key-value (KV) cache. It grows with every token in context, every attention layer, and every concurrent request, and each new token must read all of it. In a 2-billion-parameter test model at a 32K-token context, Gemma 3’s authors measured a KV memory overhead of about 60% for a conventional all-global design.
A back-of-the-envelope formula: KV bytes per token ≈ 2 (keys and values) × attention layers × KV heads × head dimension × bytes per value. The published Qwen3.5 configuration has 15 full-attention layers with 2 KV heads of 256 dimensions. By our arithmetic, with 16-bit values, that is about 30 KB per token, or roughly 8 GB for one sequence at its 262,144-token native context.
Its other 45 layers keep a fixed-size state instead, which does not grow with context. Give all 60 layers full attention, with separate keys and values for each of the 32 query heads, and the same sum passes 500 GB.
The other half of every block is the feed-forward network. In the paper’s base model, by our arithmetic, it holds twice as many parameters per layer as attention does. Many 2025–2026 models swap it for a mixture of experts (MoE): a small router sends each token to a few of many expert networks. The Qwen3.5 model card lists 512 experts per MoE layer, of which each token uses 10 plus one shared expert.
That is what “A17B” in the name means: 397 billion parameters stored, about 17 billion active per token. Memory follows total parameters and compute follows active ones, a split our open-weight models guide turns into hardware math.
Labs have attacked attention’s costs in three ways.
1. Make exact attention faster
FlashAttention changed the memory traffic, not the math: compute stays quadratic, but memory use grows only linearly with sequence length. It computes attention in tiles that fit in the GPU’s fast on-chip memory, so the full score matrix never goes to slower memory. Its authors reported a 3× training speedup for GPT-2 at 1K-token sequences with exact results (Dao et al., 2022).
2. Look at less, cache less
GQA shrinks the cache by sharing keys and values across heads. Local attention limits most layers to a nearby window, the neighborhood idea the 2017 authors had parked. Gemma 3 pairs five local layers, each seeing 1,024 tokens, with every global layer. In its tests, that kind of mix cut KV overhead from about 60% to under 15%.
3. Replace most attention layers
IBM’s Granite 4.0 hybrids, released in October 2025, interleave Mamba-2 state-space layers with transformer blocks at a 9:1 ratio. IBM reports that the hybrids need over 70% less random-access memory (RAM) than conventional transformer models when handling long inputs and concurrent batches. The Qwen team’s Qwen3.5, released in February 2026, pairs 45 Gated DeltaNet linear-attention layers with 15 full-attention layers in a 60-layer stack.
Both keep some attention, and IBM notes that it still has an edge on in-context learning, such as picking up a pattern from a few examples in the prompt. That is the honest state of play as of October 2026: attention is being rationed, not retired, and kept where exact lookup across the whole context pays for itself.
What this means for your team
- Treat context as a budget. Every added token raises prefill compute and KV memory. Put stable instructions and reference material first, where prefix caching can reuse them, and retrieve only what the task needs. A million-token window is not a reason to fill it.
- Measure the two latencies separately. Time to first token tracks prompt length; tokens per second tracks the serial decode loop. Cap what the model writes, since every output token costs a full decode step.
- Size self-hosted GPUs for the KV cache, not just the weights. Run the formula above with your model’s config, real context lengths, and target concurrency; our guide to serving LLMs covers the rest of the memory budget. GQA, local windows, and hybrid layers change the answer by multiples, so read the model card before buying hardware.
- Stay architecture-agnostic. The field is mid-shift from pure Transformers to hybrids. Put models behind a stable interface and keep an evaluation suite, so trying a cheaper or longer-context model takes days, not a rewrite.
Sections 3 and 4 of the original paper repay an hour of any senior engineer’s time. When we scope a retrieval assistant or document pipeline, this arithmetic of context length, cache size, and per-token latency comes before anyone writes a prompt.
Sources
-
Attention Is All You Need (opens in new tab) — Google Brain / Google Research (arXiv), 2017 arxiv.org
-
Transformer: A Novel Neural Network Architecture for Language Understanding (opens in new tab) — Google Research Blog, 2017 research.google
-
Improving Language Understanding by Generative Pre-Training (opens in new tab) — OpenAI, 2018 cdn.openai.com
-
Open Sourcing BERT: State-of-the-Art Pre-training for Natural Language Processing (opens in new tab) — Google Research Blog, 2018 research.google
-
FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (opens in new tab) — Stanford University / University at Buffalo (arXiv), 2022 arxiv.org
-
Gemma 3 Technical Report (opens in new tab) — Google DeepMind (arXiv), 2025 arxiv.org
-
IBM Granite 4.0: Hyper-efficient, High Performance Hybrid Models for Enterprise (opens in new tab) — IBM, 2025 ibm.com
-
Qwen3.5-397B-A17B model card (opens in new tab) — Qwen Team (Hugging Face), 2026 huggingface.co