Where all this sits
The machine first, then the box we open.
The paper is from 2017 and its job was translation: read a sentence in German, write one in English. What made it notable was a removal. Every competitive model at the time read a sentence roughly the way you do — one token after another, carrying a running summary forward — a recurrent network. This one does not. It takes the whole sequence at once and lets every position look directly at every other.
A transformer is what you get from that. Text is cut into tokens and each token becomes a vector. A stack of identical layers then takes that sequence of vectors and returns a sequence of vectors of the same shape, over and over, and the only step in a layer that moves information between positions is attention — everything else works on each position on its own. Words go in knowing nothing about their neighbours and come out having read them.
Before the diagram, the thing that makes all of it click: the shape never changes. Every layer takes a sequence of vectors and hands back a sequence of the same size, so a stack is just that operation applied again and again. Sizes below are the paper's base model.
That is the whole shape of it. Six by 512 goes in, six by 512 comes out, twelve times in a row, and the only step in that column that lets one position see another is attention. Everything else — the feed-forward network, the normalisation — works on each row separately and would give the same answer if you shuffled the sentence.
Attention is therefore one sub-layer inside a larger machine, and reading about it without that frame is most of what makes it hard. Here is the whole architecture from the paper's Figure 1, with the parts this page takes apart marked. Click any amber block to jump to the section that opens it.
The architecture as published: an encoder reads the source sentence, a decoder writes the target and attends back to the encoder.
Both stacks are six identical layers deep. An encoder layer is two sub-layers — multi-head self-attention, then a position-wise feed-forward network. A decoder layer is three: masked self-attention, then attention over the encoder's output, then feed-forward. Every one of those sub-layers is wrapped as LayerNorm(x + Sublayer(x)), a residual connection followed by layer normalisation, which is what makes a stack this deep trainable at all.
The steel blocks are real and load-bearing; they are simply not what the paper is named after.
And why you stack six of them
One layer lets a token read its neighbours. Two layers let it read what its neighbours had already read. Compose the attention matrices across layers — WL · … · W1, each row still summing to one — and you get exactly how much of each original token is present in a vector after L layers.
Pick a token above, then set the depth. The bars are the composed mixing matrix, so they are the real arithmetic of stacked attention — residual connections included, feed-forward left out because it never mixes positions.
Where its content came from
What changes with depth
Why this is the thing under a language model
The diagram has two columns because translation has two sequences: one you are given and one you are producing. A language model has only one. So what came after this paper — and this is later work, not the paper itself — largely kept the right-hand column and dropped the left: no encoder, no cross-attention, just masked self-attention and a feed-forward network, repeated. A decoder-only stack.
That is why the mask carries more weight than its size suggests. In a model that generates text, masked self-attention is the entire mechanism by which a token is allowed to consider what came before it and forbidden from seeing what comes after — which is what makes predicting the next word a prediction rather than a lookup. Every prompt you have ever sent to a model went through the weighted average this page takes apart, once per head per layer, all the way up a stack far taller than six, at a dmodel well past 512 and with heads counted in dozens rather than eight.
What follows opens the amber blocks, starting with a single attention head.
One head, hands on
A weighted average whose weights the data chooses.
In a self-attention layer — the case this page works through — every token produces three vectors, all three from the same input, through three learned projections: a query (what am I looking for), a key (what do I offer) and a value (what do I pass on if chosen). Token i scores every token j by qi · kj, softmaxes those scores into weights that sum to one, and takes that weighted average of the values.
"From the same input" is what makes it self-attention, and the paper is careful that this is not the only arrangement. Its decoder also carries an encoder–decoder layer where the queries come from the previous decoder layer while the keys and values come from the encoder's output — the same arithmetic below, with the three projections reading two different places.
Attention(Q, K, V) = softmax( Q KT / √dk ) V
Pick the querying token above, or click its row in the grid — the two do the same thing.
Because the score is qi · kj with q = xWQ and k = xWK, it is a bilinear form: xi (WQWKT) xjT. So a head is characterised by one matrix saying which kinds of token attend to which. Below, that matrix is yours to pick. Click a row of the grid to see what that token attends to.
Attention weights — row i is where token i looks
Row distribution
Head — pick the affinity it carries
The projections here are toy values chosen so the arithmetic is inspectable — a real model learns them, and its dmodel is 512, not 4. What is real is every operation you can see: the dot products, the division, the softmax, the weighted average.
Why divide by √dk
The one line in the paper that is a statistical argument, not a design choice.
Two claims here, and the paper keeps them apart, so this page should too. What was observed: additive attention beats unscaled dot-product attention at larger dk. What is suspected — the paper's own word — is the reason: “we suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients.”
What is neither observed nor suspected but simply true is the arithmetic underneath, which the paper puts in a footnote: if the components of q and k are independent with mean 0 and variance 1, then q · k has mean 0 and variance dk. Scores spread out as the head gets wider, and the softmax of a wide spread is a spike. That part you can measure, and the sandbox below does.
Nothing below is simulated. Drag dk and the page samples fresh Gaussian vectors, takes real dot products, and softmaxes them both ways.
dk is how wide one head is — the paper's is 64. Drag it and the page draws fresh random q and k of that width and takes real dot products; resample draws a new set at the same width.
softmax(q·k) — unscaled
softmax(q·k / √dk) — as published
Watch the left column as you pass roughly dk = 64, the paper's actual head width. One key takes essentially all the mass; the rest get numbers with a lot of zeros after the decimal point. The right column keeps its shape at every width, because dividing by √dk puts the variance back to 1 no matter how wide the head is.
Many heads, one budget
Not more attention. The same attention, cut into subspaces.
A single head averages everything into one distribution, and an average is exactly where distinct relations get blurred together. The fix is to run h attentions in parallel over narrower projections and concatenate:
MultiHead(Q, K, V) = Concat(head1, …, headh) WO
where headi = Attention(Q WiQ, K WiK, V WiV)
The budget is the point. The paper uses h = 8 and dk = dv = dmodel/h = 64, so eight heads of width 64 cost about what one head of width 512 would. You are not buying more computation; you are spending the same computation on more than one question at a time.
How many attentions run in parallel. Each gets a different affinity and a projection of width dmodel/h, so more heads means narrower ones, not more work.
Each head here carries a different affinity, so each produces a different pattern over the same sentence: one tracks what a verb acts on, another ties a determiner to its noun. Concatenating them and projecting through WO is how those separate readings get recombined into one vector per token.
The mask
How a decoder is stopped from reading ahead.
Attention as defined lets every token see every other token, which is what you want when encoding a sentence you already have. Generating one is different: while predicting position i the model must not have seen i+1, or training would be a lookup rather than a prediction.
The fix is arithmetic, not architecture. Before the softmax, set every illegal score to −∞. Softmax sends those to exactly zero, so the row renormalises over the positions that remain — no weight leaks from the future.
Sets every score above the diagonal to −∞ before the softmax, so no token can attend to one that comes after it.
Attention weights
Row 4 — on
Notice that the first row is unchanged whatever you do: the first token never had a future to look at. And every row still sums to one, because masking happens before the softmax rather than after it. Masking after would leave rows summing to less than one, which is a quietly different model.
Attention cannot see order
The problem positional encoding exists to solve.
This is the part that surprises people, and it follows from the formula alone. Attention takes a set of vectors and returns a set: permute the inputs and every output permutes with them, unchanged. There is no recurrence walking left to right and no convolution with a window, so nothing in the mechanism knows that cat came before sat.
Shuffle reorders the tokens and recomputes. Add positional encoding adds the sinusoid for each slot to the token's vector, so the same word in a different place is no longer the same input.
Output vector for cat
Verdict
With positional encoding off, shuffle as often as you like: the output computed for cat is bit-for-bit the one it had before, because its neighbours are the same set. Turn the encoding on and the same shuffle changes it, because position is now part of the input rather than of the mechanism.
The sinusoids
The paper adds a fixed pattern to the embeddings rather than learning one, using sine and cosine at geometrically spaced wavelengths:
PE(pos, 2i) = sin(pos / 100002i/dmodel) PE(pos, 2i+1) = cos(pos / 100002i/dmodel)
Wavelengths run from 2π up to 10000·2π, so low dimensions flip quickly and high ones barely move across a whole sentence — a positional signal at every scale at once. The stated reason for choosing sinusoids is relative position: for any fixed offset k, PEpos+k is a linear function of PEpos, which makes "three tokens back" a thing the model can learn to look for.
PE(pos, dim) for dmodel = 64 — rows are positions, columns are dimensions
Below: the dot product between the encoding of the position you picked and the encodings three slots either side of it — how alike two positions look to the model.
What this buys
Table 1 of the paper, with your own numbers in it.
The argument for replacing recurrence is not that attention is cheaper. It is that attention is shallow. Two tokens at opposite ends of a sequence are one operation apart, not n operations apart, and gradients that travel a short path survive better than gradients that travel a long one.
n is how many tokens are in the sequence, d how wide each token's vector is. Both sliders recompute the table below with those numbers put into the paper's formulas.
| Layer type | Complexity per layer | Sequential ops | Max path length |
|---|
Slide n and the crossover moves. Self-attention is O(n2·d) against recurrence's O(n·d2), so attention is the cheaper layer exactly while n < d — which, as the paper notes, is the common case for sentence-length sequences in translation. Beyond that it costs more per layer and keeps winning anyway, because the columns that matter for learning are the other two: constant sequential work, and a constant path between any two positions.
One row of that table is a proposal rather than a result. Restricting self-attention to a neighbourhood of size r is offered for very long sequences, with the note that it raises the maximum path length to O(n/r) and that the authors planned to investigate it in future work — the model the paper actually trains attends over everything.
What this page leaves out
The mechanism, not the model. A full encoder–decoder stacks N = 6 of these layers on each side, and every layer wraps its attention and its position-wise feed-forward network in a residual connection and layer normalisation — LayerNorm(x + Sublayer(x)) — which is what makes a stack that deep trainable at all. The decoder adds a second attention per layer, over the encoder's output rather than its own. And the whole training recipe is elsewhere: the warmup schedule, label smoothing, the beam search. Those are in the paper; this page is about the part that gave it its title.