Attention Is All You Need, Dissected: The 2017 Figure, Box by Box

Attention Is All You Need, Dissected: The 2017 Figure, Box by Box

Attention Is All You Need is a thirteen-page paper about machine translation, and its Figure 1 is the most reproduced diagram in machine learning. It gets pasted into explainers, admired for a sentence, and then abandoned in favour of a paragraph about queries and keys. The boxes themselves stay unexplained.

The previous seven parts of this series traced a modern decoder-only model from raw text to expert routing, which is exactly one of the three architectures that grew out of that figure. This part goes back to the original and takes it apart.

By the end you should be able to open the paper, look at Figure 1, and read it without hesitating: which tower is which, what the crossing arrow carries, why there are three attention blocks and not one, what “shifted right” means, and which boxes a 2026 model still contains.

Inside the Inference Stack · Part 8 of 11
  1. Part 1. How an LLM Answers a Question: The Complete Inference Path
  2. Part 2. Byte-Pair Encoding Explained: How LLMs Turn Text Into Tokens
  3. Part 3. Inside One Transformer Block: The Residual Stream and Its Seven Matrices
  4. Part 4. Multi-Head Attention Explained: Why 64 Heads Instead of One
  5. Part 5. The Output Projection: How 64 Attention Heads Become One Thought
  6. Part 6. The Feed-Forward Network: Where a Transformer Keeps What It Knows
  7. Part 7. Mixture of Experts Explained: Conditional Computation From Zero
  8. Part 8. Attention Is All You Need, Dissected: The 2017 Figure, Box by Box (you are here)
  9. Part 9. The Roofline Model: Why LLM Decode Is Memory-Boundcoming 17 Aug
  10. Part 10. Continuous Batching and PagedAttention: How vLLM Keeps a GPU Busycoming 18 Aug
  11. Part 11. Benchmark Your Own LLM Serving Stack: Two Measurements, One Afternooncoming 19 Aug

Start here: it is a translation model

Attention Is All You Need is not about chatbots, or generation, or scaling laws. It is about translating English into German and English into French, and it exists to remove recurrence from the encoder-decoder translation systems of the time. Recurrent networks processed one word per step, so the time to train on a sentence grew with the sentence. That serialisation was the bottleneck, and attention was the way around it.

Definition

Encoder-decoder architecture

Two networks trained as one: the first reads the whole source sequence and turns it into a set of vectors, the second writes the target sequence one token at a time while consulting those vectors. In the 2017 paper both halves are six layers deep and both work at d_model 512.

Origin: introduced for neural machine translation in 2014, by Sutskever and colleagues and by Cho and colleagues, to replace multi-stage phrase-based translation pipelines with a single trainable network. Those first versions squeezed the entire source sentence into one fixed-length vector, and Bahdanau and colleagues added attention later that same year because that vector was losing long sentences.

Why it matters: every box in Figure 1 is placed to serve two sequences with different rules. Read the diagram without that frame and the second tower looks like duplication.

Read Figure 1 as a translation architecture and it makes immediate sense. Read it as “an LLM” and half of it looks inexplicable, because the task has one property that shapes the whole diagram: the source sentence is fully known before you start, while the target sentence is produced one word at a time and must never see its own future. Two sequences with different rules, so two towers.

the task “the cat sat” “die Katze saß” source — fully known up front target — produced one word at a time two sequences with different properties → two different towers in the diagram the source can be read in both directions; the target cannot see its own future that single asymmetry explains most of Figure 1

The source can be read in both directions. The target cannot. That single asymmetry accounts for most of what you see in Figure 1.

Analogy

A translator with the English sentence on the desk, written out in full, producing the German one word at a time on a second sheet. The English can be read forwards and backwards at any moment. The German sheet only ever holds what has already been written on it.

Where it breaks: a human translator revises, crosses words out and re-reads their own draft in any order. The decoder commits every token as it emits it, and at training time it is handed the correct German and never sees its own mistakes at all.

How to read the diagram

Data flows upward. The left tower is the encoder, the right tower is the decoder, and the thick arrow crossing between them is the single most important line in the picture. The dashed boxes with “N x” beside them mean the block inside repeats six times, so what you are looking at is one layer drawn once rather than the whole stack.

N × N × Inputs Outputs (shifted right) Input Embedding Output Embedding + + positional encoding positional Multi-Head Attention Add & Norm Feed Forward Add & Norm Masked Multi-Head Attention Add & Norm Multi-Head Attention Add & Norm Feed Forward Add & Norm encoder output → K and V Linear Softmax Output Probabilities ENCODER — bidirectional reads the source sentence DECODER — causal writes the translation data flows upward · red arrows are residual connections

Follow the crossing line first. Everything else in the diagram is a variation on one operation, and that line is the only place two different sequences meet.

Count the attention boxes before going further. There are three, not one. Encoder self-attention at the bottom left. Decoder masked self-attention at the bottom right. And decoder cross-attention in the middle right, the one fed by the crossing line. They run the same arithmetic and differ only in where their queries, keys and values come from.

Definition

Self-attention

Attention in which the queries, keys and values are all projections of the same sequence, so every position scores every other position of its own sequence. Both towers in Figure 1 begin with a self-attention block.

Origin: attention came from Bahdanau and colleagues in 2014 as a fix for the fixed-length sentence vector in translation. Applying it within a single sequence, then called intra-attention, appeared in 2016 work on reading comprehension and textual entailment. The 2017 paper’s move was to delete the recurrence around it and keep only this.

Why it matters: it is what makes a whole sentence trainable in one parallel pass. Recurrence forced one sequential step per token, so a 40-token sentence took 40 steps before the next one could start.

Section takeaways

  • The paper is machine translation, English to German and English to French, and every box in Figure 1 serves two sequences with different rules.
  • Recurrent translation models took one step per word, so training time on a sentence grew with its length. Deleting recurrence is the paper’s entire subtraction.
  • The source is fully available before decoding starts and the target is produced one token at a time, which is why there are two towers and only one of them is masked.
  • The “N x” labels mean each tower is one layer drawn once and repeated six times, so the diagram describes 12 layers while showing 2.
  • There are three attention blocks in the figure. They run identical arithmetic and differ only in the source of Q, K and V and whether a mask applies.

The model that was actually trained

The base configuration is small enough to hold in your head, which is worth doing before you look at anything modern. Set it beside the Llama-3-70B class model this series has been using as its running example.

Dimension 2017 base transformer 70B-class model (this series)
Encoder layers 6 0
Decoder layers 6 80
d_model 512 8,192
Heads h 8 query, 8 KV 64 query, 8 KV
d_k = d_v 64 128
d_ff 2,048 (4 x d_model) 28,672 (3.5 x d_model)
Vocabulary about 37,000 BPE tokens 128,256
Parameters about 65M about 70B
Training hardware 8 x NVIDIA P100 H100 clusters
Base training run about 12 hours millions of GPU-hours

You can check the parameter count by hand, which is a good way to confirm you have understood the shapes. Each attention block holds four square matrices of 512 x 512, so about 1.05M parameters. Each feed-forward block holds 512 x 2048 plus 2048 x 512, so about 2.10M. An encoder layer has one attention block and one feed-forward block, giving 3.15M, and six of them give 18.9M. A decoder layer has two attention blocks plus a feed-forward block, giving 4.20M, and six of them give 25.2M. The shared embedding table is 37,000 x 512, another 18.9M. Add those and you land at roughly 63M, which is the paper’s 65M once you count the biases and layer norms.

The whole base model trained in about 96 GPU-hours on Pascal cards, three GPU generations before an H100. The big model took three and a half days. That is the entire compute budget behind the architecture every model in production today descends from.

Section takeaways

  • The base model is about 65M parameters: 6 encoder layers, 6 decoder layers, d_model 512, 8 heads of 64.
  • An attention block is four 512 x 512 matrices, about 1.05M parameters, and a feed-forward block is 512 x 2048 twice, about 2.10M.
  • An encoder layer comes to 3.15M and a decoder layer to 4.20M, the difference being the decoder’s second attention block.
  • The shared embedding table of 37,000 x 512 is 18.9M on its own, close to 29 percent of the model.
  • The base run took about 12 hours on 8 P100s, so 96 GPU-hours produced the architecture every production model descends from.

The bottom of each tower

Input embedding, and the multiply by the square root of d_model

A lookup table, exactly as you would expect: token ID in, 512 numbers out. The detail most redrawings drop is that one matrix does three jobs. The encoder’s embedding table, the decoder’s embedding table and the final Linear layer before the softmax are all the same weights, which is why a single 18.9M-parameter table covers all three in a 65M-parameter model.

The second dropped detail is that the embeddings are multiplied by sqrt(d_model), which for d_model 512 is about 22.6. The reason is a scale mismatch. Embeddings initialised with variance 1/d_model have entries around 0.04, while the positional encodings that get added next are sinusoids bounded between minus one and one. Without the scaling, position would swamp identity. Modern models dropped this along with the weight tying, because they normalise the residual stream at the entrance to every block anyway.

lookup 512 numbers × √512 + positional without the scaling, embeddings ≈ 0.05 would be swamped by positions in [−1, 1] weight sharing: encoder table = decoder table = final Linear — one matrix, three uses modern models mostly dropped both: no √d scaling, and Llama unties the output layer

The multiplier exists only to make two signals comparable before they are summed. It is a scaling fix rather than a modelling idea.

Sinusoidal positional encoding, not learned

Attention has no notion of order. Permute the input and the output permutes with it. Something has to carry position, and the 2017 paper does not learn it. It computes it from a fixed formula: alternating sine and cosine waves at geometrically spaced frequencies, added once, at the bottom, and never again.

Definition

Sinusoidal positional encoding

A fixed 512-number vector per position, built from sine and cosine waves at geometrically spaced frequencies and added to the token embedding once, at the bottom of each tower. Nothing in it is learned and it costs zero parameters.

Origin: the 2017 transformer paper. With recurrence deleted, nothing in the model carried word order any more, since attention treats its input as a set. The authors also tried learned position embeddings, reported nearly identical results, and picked the sinusoids because a formula is defined at positions longer than anything seen in training.

Why it matters: it is added into the residual stream, where it occupies the same dimensions as content and is smeared by every matrix above it. That is the flaw the rotary replacement was designed around.

The frequency ladder is the part worth understanding. Dimension pair 0 has a wavelength of about 6.3 positions, so it cycles every few tokens. Each successive pair divides the frequency by a constant factor, so by the last pair the wavelength is around 62,000 positions and the wave is effectively a straight ramp. Every position therefore gets a unique fingerprint: fast dimensions resolve local order, slow dimensions resolve where you are in the document.

PE(pos, 2i) = sin( pos / 10000^(2i/512) ) PE(pos, 2i+1) = cos( pos / 10000^(2i/512) ) dim 0 — fastest dim 128 dim 510 — slowest position → each position = a unique fingerprint across all 512 waves

The fast dimensions carry local order, the slow ones carry global position. Together they give every index a unique signature without a table.

The authors had a specific hope for this. Because the encoding is a smooth function of position rather than a lookup table, it is defined at position 5,000 even if training only ever saw 100. And for any fixed offset, the encoding at pos + k is a linear function of the encoding at pos, so a model could in principle learn to attend by relative distance.

It did not extrapolate well in practice. Modern models use rotary embeddings instead, which Part 4 covered alongside the head layout. Rotation beat addition for two reasons. Added position occupies dimensions of the residual stream, where it competes with content and gets smeared by every matrix above it, whereas rotation only turns q and k inside the attention score, leaving the residual stream untouched. And because rotating both vectors by their absolute positions makes their dot product depend only on the difference, relative distance falls out of the arithmetic instead of having to be learned.

Definition

Rotary position embedding (RoPE)

Position applied by rotating each query and key vector by an angle proportional to its index, inside the attention score, instead of adding a vector to the embedding. It is reapplied in every layer, and the residual stream carries no positional term at all.

Origin: introduced in 2021 in RoFormer by Su and colleagues, to fix the two things sinusoids did badly: extrapolating past the trained length, and making relative distance something the model had to learn rather than something the arithmetic produced.

Why it matters: it is the most visible replacement of a 2017 box in a modern model. If you look for a positional term at the bottom of a Llama-class stack you will not find one, because it moved into every attention block instead.

Section takeaways

  • One matrix serves as the encoder embedding, the decoder embedding and the pre-softmax Linear, which is how 18.9M parameters cover all three jobs.
  • Embeddings are multiplied by sqrt(512), about 22.6, because entries near 0.04 would otherwise be swamped by sinusoids bounded at plus and minus one.
  • The sinusoid frequency ladder runs from a wavelength of about 6.3 positions to about 62,000, so fast dimensions resolve local order and slow ones resolve global position.
  • The paper reported learned position embeddings scoring about the same and chose sinusoids for extrapolation, which did not hold up in practice.
  • RoPE rotates q and k inside the attention score, so position never occupies residual-stream dimensions and relative distance falls out of the dot product.

Three attention blocks, not one

Encoder self-attention, unmasked

The encoder’s attention is the operation you already know with the causal mask removed. Every source token attends to every other source token, including the ones to its right. That is legitimate here, because the whole source sentence exists before translation begins and nothing is being predicted. Bidirectional context is free.

encoder — full attention thecatsatdown every token sees every token decoder — masked the future is blanked to −∞ same operation, one line of difference — and it is why one tower can be bidirectional BERT later kept only the left square; GPT kept only the right

One line of code separates these two squares. BERT later kept only the left one, GPT kept only the right one.

Decoder masked self-attention

The decoder’s first attention block is the same operation with the future set to negative infinity before the softmax. Position 3 may see positions 1, 2 and 3, and nothing beyond. This is the block that survived into every generative model, unchanged. Its job is to track what has been written so far.

Cross-attention, where the two towers meet

The middle block in the decoder is the only place in the architecture where the queries and the keys come from different sequences. Be precise about this, because it is the thing most summaries get vague about:

  • Queries come from the decoder. They encode “what does the German word I am about to write need to know?”
  • Keys and values come from the encoder’s final output. They encode “here is everything the English sentence contains.”
  • There is no mask. The decoder may look at the entire source at every step. Masking applies only to the decoder’s own past, in the block below.

The encoder output is computed once per sentence and reused by all six decoder layers, which is the 2017 ancestor of caching. Cross-attention is where translation actually happens: the query for the position about to emit “Katze” lands mostly on the encoder vector for “cat”.

ENCODER output “the cat sat down” 4 vectors, 512 each computed once, reused by all 6 decoder layers DECODER position 2 about to write “Katze” 1 vector, 512 attention no mask K, V Q “Katze” attends mostly to “cat” no causal mask here — the decoder may look at the ENTIRE source, always masking applies only to the decoder’s own past output, in the block below

Queries from the right tower, keys and values from the left. This is the only asymmetric attention block in the entire paper.

Definition

Cross-attention

The decoder’s middle attention block, taking queries from the decoder’s own state and keys and values from the encoder’s final output, with no mask on it.

Origin: the 2017 paper, where it generalises the 2014 Bahdanau attention that let a recurrent translation decoder look back at every encoder state instead of at one summary vector. It is also the block decoder-only models deleted, because a single stream of text has no second sequence to consult, and the masked self-attention below it already represents everything written so far.

Why it matters: it is the only block whose removal changes what the architecture can express rather than only how well it trains. Everything else in Figure 1 survived in some form.

All three blocks run the same arithmetic, so the differences fit in three columns: where Q comes from, where K and V come from, and whether a mask applies.

Block Q from K, V from Masked Purpose
Encoder self-attention Source Source No Understand the source
Decoder self-attention Target Target Yes Track what has been written
Cross-attention Target Source No Consult the source

One primitive, wired three ways. That is the paper’s real claim.

Analogy

The decoder is the person writing, and the encoder’s output is a reference document lying open on the desk. Before putting down each word, the writer puts a question to the document and gets an answer back.

Where it breaks: a reader turns to one page. Cross-attention returns a weighted blend of every page at once, and the weights are thrown away as soon as the blend is formed, so nothing in the model records which page was consulted.

Section takeaways

  • Encoder self-attention is decoder self-attention with the causal mask removed, so one line of code separates the two towers’ first blocks.
  • Decoder self-attention sets every future score to minus infinity before the softmax, so position 3 sees positions 1 to 3 and nothing else.
  • Cross-attention takes queries from the decoder and keys and values from the encoder’s final output, with no mask on it at all.
  • The encoder’s output is computed once per sentence and read by all six decoder layers, which is the paper’s version of a cache.
  • Three blocks, one primitive, differing only in the source of Q, the source of K and V, and the mask.

Add and Norm, and the feed-forward block

Why the order was wrong

Each “Add and Norm” box does two things in sequence: add the sub-block’s input back in, then normalise the sum. That ordering is post-norm, and it is the paper’s most consequential mistake.

Definition

LayerNorm and RMSNorm

LayerNorm rescales a vector by subtracting its mean and dividing by its standard deviation, then applies a learned gain and bias. RMSNorm keeps only the division, by the root mean square of the entries, and drops the mean subtraction and the bias.

Origin: LayerNorm was introduced by Ba, Kiros and Hinton in 2016 to get the training benefits of batch normalisation without depending on batch statistics, which made it usable in recurrent networks and at small batch sizes. RMSNorm followed from Zhang and Sennrich in 2019, on the finding that the re-centring was doing almost none of the work and the re-scaling was doing all of it.

Why it matters: the running 70B-class model normalises an 8,192-wide vector twice per layer across 80 layers, so 160 times per token. Dropping the mean and the bias removes two passes over that vector every time.

Putting the normalisation after the add means the normalisation sits on the residual path. A gradient travelling back down the encoder tower crosses two of them in every layer, twelve in all, and each one rescales what passes through. The decoder tower has three per layer, so eighteen more. Six layers a side survived that. Eighty would not have.

Definition

Post-norm and pre-norm

Post-norm computes LayerNorm(x + Sublayer(x)), the 2017 arrangement, which places the normalisation on the residual path. Pre-norm computes x + Sublayer(LayerNorm(x)), which moves it inside the branch and leaves the residual path a plain sum from input to output.

Origin: post-norm is what Figure 1’s “Add and Norm” boxes describe. Pre-norm became the default around 2019, and the 2020 analysis by Xiong and colleagues explained why: with post-norm the expected gradient near the output layer is large at initialisation, so a warmup stage is required, while pre-norm keeps it well scaled and does not need one.

Why it matters: the 2017 model was 6 layers a side and modern models are 80. Most of that depth was bought by moving one normalisation from one side of an addition to the other.

The placement is also why the original recipe needed a learning-rate warmup schedule to train at all. Without the ramp, the early updates near the output layer are large enough to destabilise the run.

Definition

Learning-rate warmup

Starting training at a very small learning rate and raising it over the first few thousand steps before decaying it. The 2017 recipe ramps up linearly for 4,000 steps, then decays in proportion to the inverse square root of the step number.

Origin: specified in the 2017 transformer paper as part of the published recipe, at 4,000 warmup steps. The reason it was needed is post-norm: the schedule exists to protect a specific architectural choice during the first few thousand updates.

Why it matters: warmup gets copied into new training recipes as folklore. With a pre-norm model it is close to optional, so a run that only converges with warmup is telling you something about where its norms sit.

Pre-norm moves the normalisation inside the branch, so the residual spine becomes a clean sum from input to output and gradients pass through it untouched. Warmup becomes optional. Depth becomes cheap. Nearly every model since 2019 made this switch, and it is the single change most responsible for transformers that are 80 layers deep instead of 6.

2017 · post-norm sublayer + LayerNorm ← sits ON the path gradients must cross every norm on the way back today · pre-norm Norm sublayer + the spine is a clean sum — gradients pass untouched 6 layers worked in 2017 · 80 layers would not have pre-norm is the single change that made very deep transformers trainable

The only difference is where the norm sits relative to the addition. That placement is what capped the original at six layers.

Analogy

Pre-norm puts the checkpoint on the slip road, so through traffic on the motorway never has to stop. Post-norm puts it on the main carriageway, so all through traffic is stopped twice in every layer.

Where it breaks: a checkpoint delays traffic and hands it back unchanged. A normalisation rescales what passes through it, so the twelve on the encoder path compound multiplicatively on the backward pass, which is why the thing that gives way is depth rather than speed.

In practice

If you train a transformer from scratch and it diverges in the first few hundred steps, look at where the normalisation sits before you touch the learning rate. Post-norm with no warmup is the classic version of that failure. The reverse check is worth doing too: if you inherit a recipe with a warmup schedule in it, confirm the model is post-norm, because on a pre-norm stack the schedule may be copied habit rather than a requirement.

Feed forward: two matrices and a ReLU

The 2017 feed-forward network is the ungated ancestor of the block Part 6 pulled apart. Widen 512 to 2,048, apply ReLU, narrow back to 512. Two matrices, two bias vectors, one nonlinearity, applied independently at every position.

Two details date it. The biases are there, and modern models drop them because they buy nothing measurable. And d_ff is exactly 4 x d_model, a ratio that held for years. SwiGLU broke it by adding a third matrix, a gate that multiplies the up-projection elementwise. To keep the parameter budget equal against three matrices instead of two, the inner width came down to roughly 3.5 x d_model, which is exactly where the 70B model’s 28,672 sits against its 8,192.

2017 512 W₁ ReLU W₂ 512 inner width 2048 = 4 × 512 today three matrices — W_gate and W_up in parallel, then W_down SiLU instead of ReLU · no biases · inner width ≈ 3.5× to keep the budget equal the gate is the addition; everything else is the same idea

The gate is the whole difference. Everything else about the block, including its position after attention, is unchanged since 2017.

Section takeaways

  • Post-norm computes LayerNorm(x + Sublayer(x)), putting a rescaling on the residual path that every gradient must cross, twice per encoder layer and three times per decoder layer.
  • The original recipe needed a 4,000-step learning-rate warmup to train at all, and that requirement is a symptom of the norm placement.
  • Pre-norm leaves the residual path a plain sum and is the change that makes 80-layer stacks trainable, where 6 a side was the practical limit.
  • RMSNorm drops LayerNorm’s mean subtraction and bias, cutting work in a kernel that runs 160 times per token in an 80-layer model.
  • The 2017 feed-forward block is 512 to 2,048 to 512 with ReLU and two bias vectors, at exactly 4 x d_model.
  • SwiGLU added a third matrix and the width came down to about 3.5 x d_model, which is where 28,672 against 8,192 comes from.

“Shifted right”, the phrase that confuses everyone

The decoder’s input in Figure 1 is labelled “Outputs (shifted right)”, which reads like a typo the first several times you see it. It means something simple. Prepend a start token, drop the last target token, and feed that as the decoder input. Position i of the input is then the token that came immediately before the token position i has to predict.

If the target is “die Katze sass <eos>”, the decoder receives “<sos> die Katze sass”. Position 1 sees <sos> and must produce “die”. Position 2 sees “die” and must produce “Katze”. Without the shift, position 2 would be handed the very token it is being asked to predict, and the task would be a copy.

the target we want die Katze saß <eos> what the decoder receives <sos> die Katze saß position 1 sees <sos>, must predict “die” · position 2 sees “die”, must predict “Katze” every position is a genuine prediction — the whole sentence trains in one pass this is teacher forcing, and it is training-time only; at inference the decoder feeds itself

Every position becomes a genuine prediction, and all of them train in a single parallel pass. That is the payoff for deleting recurrence.

Definition

Teacher forcing

Feeding the ground-truth previous token as input during training instead of whatever the model itself predicted. “Outputs (shifted right)” is how the transformer implements it: prepend a start token, drop the last target token.

Origin: named in recurrent network training by Williams and Zipser in 1989, to stop a model’s own early mistakes from compounding through a whole sequence and wrecking the training signal. The 2017 paper needs it for a second reason as well, since with the true target in hand every position of a sentence can be supervised in one parallel forward pass.

Why it matters: it builds in a mismatch. In training the decoder always sees correct history, and at inference it sees its own output, which is the asymmetry that makes prefill and decode two different operations.

Teacher forcing is a training-time construct. During training the ground-truth target exists, so the whole sentence can be fed at once and every position supervised in one forward pass. At inference there is no target to shift, so the decoder feeds itself, one token at a time, which is why streaming exists and why time to first token behaves so differently from total latency. That asymmetry is the origin of the prefill and decode split that dominates serving economics later in this series.

The training recipe holds one more counterintuitive piece. The paper trains against a smoothed target distribution rather than a one-hot one, and reports that this made perplexity worse while making accuracy and BLEU better.

Definition

Label smoothing

Training against a target distribution that puts slightly less than all the probability on the correct token and spreads the remainder across the rest of the vocabulary. The 2017 paper used a value of 0.1.

Origin: borrowed from 2016 image classification work on the Inception architecture, where it was introduced to stop a classifier becoming over-confident and to improve generalisation. The transformer paper adopted it and stated plainly that it hurts perplexity, since the model is being taught not to be certain, while improving accuracy and BLEU.

Why it matters: it is a clean case of a training decision that the loss curve alone would reject. Judge it on perplexity and you throw away a change that improved the metric anyone actually cared about.

Section takeaways

  • “Shifted right” means prepend a start token and drop the last target token, so position i receives the token immediately before the one it must predict.
  • For the target “die Katze sass”, the decoder is fed “<sos> die Katze sass” and all four positions are supervised in one forward pass.
  • Teacher forcing dates to 1989 recurrent-network training and exists to stop early mistakes compounding through a sequence.
  • At inference there is no target to shift, so the decoder feeds itself one token at a time, which is where the prefill and decode split comes from.
  • Label smoothing at 0.1 made perplexity worse and accuracy and BLEU better, which is the paper stating outright that the training loss is not the objective.

Figure 2: the mechanism itself

Scaled dot-product attention

Figure 2 left is five boxes stacked bottom to top: MatMul, Scale, an optional Mask drawn as a dashed rectangle, SoftMax, MatMul. The dashed box is the whole encoder-decoder difference, compressed into one optional step in one shared diagram.

QKV MatMul Q · Kᵀ → one score per pair Scale ÷ √d_k = ÷ 8, since d_k = 64 Mask (opt.) decoder only — future set to −∞ SoftMax scores → weights summing to 1 MatMul weights × V → the output Attention(Q,K,V) = softmax( QKᵀ / √d_k ) V

Note that the mask is drawn dashed. One optional step is all that separates the encoder’s attention from the decoder’s.

Definition

Scaled dot-product attention

Score every query against every key with a dot product, divide by sqrt(d_k), softmax the scores, then take the weighted sum of the value vectors. At d_k 64 the divisor is 8.

Origin: the 2017 paper chose dot-product scoring over the additive scoring used by 2014 attention because a dot product is a single matrix multiply and runs far faster on the hardware. The divisor was then added because without it the dot-product version fell behind additive attention at large d_k, which the authors attributed to the softmax being pushed into a region of vanishing gradient.

Why it matters: the divisor tracks d_k and not d_model, so it moves when you change the head count and stays put when you widen the model.

The scale factor deserves an honest explanation, because “for numerical stability” is not one. Take a query and a key whose components are independent with mean 0 and variance 1. Their dot product sums d_k such products, so it has mean 0 and variance d_k, giving a standard deviation of sqrt(d_k). At d_k = 64 that is 8, so raw scores routinely land at plus or minus 16 or 24. Feed a 16-point logit gap into a softmax and you get a ratio of about nine million to one: the distribution collapses onto a single token, and the gradient through a saturated softmax is close to zero. Dividing by 8 pulls the spread back to roughly plus or minus 2, where the softmax is still soft and still differentiable. The scale is there to keep training alive rather than to keep floats in range.

Multi-head attention

Figure 2 right shows something the modern implementation hides. The paper draws h separate Linear projections, one per head, feeding h independent attention runs, then a Concat and a final Linear. In code those per-head projections are fused into one wide matrix and the result is reshaped, which is why heads are usually explained as slices of a single vector. The two are mathematically identical. The paper’s version is the conceptual one and the fused matrix is the efficient one.

VKQ Linear Linear Linear h = 8 of each 512 → 64 Scaled Dot-Product Attention 8 independent runs Concat 8 × 64 = 512 again Linear this is W_O

The Concat box is where 8 heads of 64 become 512 again, and the Linear above it is W_O, the output projection.

Two boxes here have names from earlier in this series. Concat is where 8 x 64 = 512 reassembles, and the Linear on top is W_O, the mixing matrix that Part 5 was entirely about. The paper’s own argument for multiple heads is one sentence long: a single head averages, and averaging inhibits attending to several positions at once.

Section takeaways

  • Figure 2 left is five boxes: MatMul, Scale, an optional Mask drawn dashed, SoftMax, MatMul. The dashed box is the entire encoder-decoder difference.
  • A dot product of d_k unit-variance terms has standard deviation sqrt(d_k), which is 8 at d_k 64, so raw scores land at plus or minus 16 to 24.
  • A 16-point logit gap becomes a ratio of about nine million to one after the softmax, where the gradient is effectively zero.
  • Dividing by 8 pulls the spread back to roughly plus or minus 2, the range in which the softmax still passes gradient.
  • Figure 2 right draws h separate projections, while implementations fuse them into one wide matrix and reshape, which is arithmetically identical.

The three descendants, and the scorecard

Which tower each family kept

Encoder only. BERT and its descendants kept the left tower. Bidirectional attention, no causal mask, trained by masking tokens and predicting them. These models understand text and cannot generate it left to right. They are not historical: if you run a retrieval pipeline, your embedding model and your reranker are almost certainly from this family, as anyone who has built a retrieval augmented generation stack has discovered.

Encoder and decoder. T5 and BART kept both towers. This still makes sense when there genuinely are two distinct sequences with different modalities or rules: speech to text, image to text, and machine translation itself. Niche for general text work, entirely correct where it applies.

Decoder only. GPT, Llama and everything else this series has traced kept the right tower and deleted cross-attention with it. This family won generation outright.

2017 · encoder + decoder encoder only BERT · embeddings · rerankers understands, cannot generate both T5 · BART niche today decoder only GPT · Llama · Claude won everything a decoder does the encoder’s job by reading the source from its own context one stack, one objective, one set of weights — and it scales more cleanly note the encoder is not dead: your RAG retriever is almost certainly BERT-family

The encoder is not dead, it just moved into retrieval. What died was the architectural separation between reading and writing.

In practice

Pick the family from the shape of the input. One stream of text that you continue: decoder only. Two genuinely different sequences, such as audio to text or a source and target language pair: an encoder-decoder still earns its place. A fixed representation for search, clustering or classification with no generation at all: encoder only, which is what your embedding model and your reranker already are.

Why the encoder was dropped

The reason is not that encoders are bad. It is that in general text generation there is no separate source sequence to encode. There is one stream, and everything before the current token is context. The decoder’s own masked self-attention over a growing context already builds a representation of all of it, so it does the encoder’s job in-band, with the same weights.

Then serving economics finished the argument. One tower means one set of weights, one training objective, one KV cache, and a uniform execution path. Look at what a modern server actually does and you will notice the split came back anyway, in a cheaper form: prefill processes the whole prompt in parallel, exactly as an encoder would, and decode emits one token at a time, exactly as the decoder did. Same two phases, one stack of weights. Anyone running these models in production is paying for that distinction on every request, and the next part explains why the two phases have completely different cost profiles.

What 2017 got right and what it got wrong

Six decisions carry the architecture, and nine years of practice has settled the verdict on each of them.

Decision 2017 choice Verdict Where it went
Replace recurrence with attention Attention only, no RNN, no convolution Right, and it is the whole paper Unchanged, everywhere
Positional information Sinusoids, added once at the bottom Wrong in practice, extrapolated poorly RoPE, applied to q and k in every layer
Norm placement Post-norm, after the residual add Wrong, needed warmup and capped depth Pre-norm, plus RMSNorm instead of LayerNorm
Feed-forward activation ReLU, two matrices, 4x width Superseded, the shape was right SwiGLU, three matrices, 3.5x width
Head sharing Full MHA, one KV head per query head Right for 2017, ruinous at scale GQA, 8 KV heads serving 64 query heads
Encoder-decoder split Two towers joined by cross-attention Right for translation, wrong for generation Decoder only, with prefill and decode as the new split

What survived untouched is a short list: scaled dot-product attention, multiple heads, residual connections, the attention-then-feed-forward block ordering, and Q, K, V as three projections of the same input. That core is nine years old and unamended. Everything in the table above is a fix to the packaging around it.

Section takeaways

  • Three families came out of one figure: encoder only (BERT), encoder and decoder (T5, BART), decoder only (GPT, Llama).
  • Encoder-only models did not die. Embedding models and rerankers in retrieval pipelines are almost all from that branch.
  • Generation dropped the encoder because there is no second sequence to encode, and masked self-attention over a growing context already represents everything before the current token.
  • The two-phase split returned as prefill and decode, which run one set of weights instead of two towers of separate weights.
  • Of the six decisions in the table, two are plainly wrong (sinusoids and post-norm), while the core of scaled dot-product attention, multiple heads and residual connections is unchanged after nine years.

Key takeaways

  • Figure 1 of Attention Is All You Need is a translation architecture. The two towers exist because translation has two sequences with different rules, and the source can be read bidirectionally while the target cannot.
  • There are three attention blocks, not one. They run identical arithmetic and differ only in where Q, K and V come from and whether a mask applies.
  • Cross-attention takes queries from the decoder and keys and values from the encoder output, with no mask. It is the only asymmetric block in the paper, and it does not exist in decoder-only models.
  • “Shifted right” means prepend a start token and drop the last target token, so every position is predicting something it cannot see. It is teacher forcing, and it applies at training time.
  • Dividing by sqrt(d_k) exists because a dot product of d_k unit-variance terms has standard deviation sqrt(d_k). Without the division the softmax saturates and the gradient dies.
  • Post-norm was the paper’s costliest mistake. It forced learning-rate warmup and made depth beyond a dozen layers unreliable, which pre-norm fixed.
  • The encoder was dropped for generation because there is no separate source to encode. One tower is simpler to train, cheaper to serve, and does the encoder’s job in-band.

Frequently asked questions

What is Attention Is All You Need actually about?

It is a machine translation paper. It proposes replacing the recurrent networks used in encoder-decoder translation systems with attention alone, so that training parallelises across all positions in a sentence instead of stepping through them one at a time. The title is a claim about subtraction: recurrence and convolution can be deleted.

Why are there three attention blocks in the transformer diagram?

Encoder self-attention reads the source sentence bidirectionally. Decoder masked self-attention tracks what has been written so far without seeing the future. Cross-attention lets the decoder consult the encoded source. They are the same operation with different wiring for queries, keys and values.

What does “outputs shifted right” mean in the transformer diagram?

It means the decoder input is the target sequence with a start token prepended and the final token dropped, so each position receives the token before the one it must predict. This is teacher forcing. It lets an entire target sentence be supervised in one parallel forward pass during training.

Why divide by the square root of d_k in scaled dot-product attention?

A dot product of two vectors with d_k independent unit-variance components has variance d_k, so a standard deviation of sqrt(d_k). At d_k = 64 that is 8, large enough that the softmax saturates onto one token and its gradient vanishes. Dividing by sqrt(d_k) restores a workable spread.

Why did decoder-only models replace the encoder-decoder transformer?

In general text generation there is no separate source sequence to encode, so the decoder’s masked self-attention over a growing context already does the encoder’s job. One tower means one set of weights, one objective, one KV cache and a simpler serving path, and it scales more cleanly.

Why do modern transformers use pre-norm instead of post-norm?

The 2017 paper normalises after the residual addition, which puts the normalisation on the residual path and forces every gradient to pass through it. That required a learning-rate warmup schedule and made deep stacks unstable. Pre-norm moves the norm inside the branch, leaving a clean residual spine and making 80-layer models trainable.

Sources and further reading

Part 7 covered conditional computation and expert routing, the last structural change to the block itself. Part 9 turns from architecture to hardware and explains why decode is memory-bound while prefill is notcoming 17 Aug, which is where the training-time parallelism this paper won stops helping you.

Next in the seriesPart 9. The Roofline Model: Why LLM Decode Is Memory-Boundcoming 17 Aug

Check your understanding

Take the 8 question quiz on this article

Eight questions are drawn from a pool of 30 and spread across the ideas this article covers, so no two attempts are quite the same. It runs here on the page and keeps your place, so you can go and read a section and come back without losing anything. You get a full report at the end: your score, the correct answer to anything you missed, why it is correct, and a link straight back to the section it came from.

  • 8 questions
  • drawn from 30
  • 8 knowledge areas
  • hint on every question
  • timed, no limit
Previous