A walkthrough of arXiv:1706.03762 (Vaswani et al., 2017)

Attention, worked out

This is the paper that language models are built on. Its one idea is that attention is a weighted average where the weights are computed from the data itself — and the scaling, the heads, the mask and the sinusoids are all consequences of that sentence. This page lets you operate each piece.

An architecture map you can click through, and eight sandboxes. Every number on this page is computed in your browser from the paper's own formulas: real softmax, real dot products, real sinusoids, real sampling.

01

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.

“the cat sat on the mat”text
cut into tokens6 tokens
each token becomes a vector, plus its position6 × 512
attention — every position reads every othermixes rows6 × 512
feed-forward — each position on its ownrow by row6 × 512
… and again, six times over6 × 512
linear, then softmax over the vocabulary6 × 37000
when generating, only the last row is read1 × 37000

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.

Encoder Decoder N × 6 N × 6 Multi-Head Attention Add & Norm Feed Forward Add & Norm Masked Multi-Head Attention Add & Norm Multi-Head Attention Add & Norm Feed Forward Add & Norm ⊕ Positional Encoding ⊕ Positional Encoding Input Embedding Output Embedding shifted right by one position Linear Softmax → probabilities K, V

The architecture as published: an encoder reads the source sentence, a decoder writes the target and attends back to the encoder.

opened on this page in the paper, out of scope here

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.

1

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.

03

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.

4

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.

04

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.

3

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.

    05

    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.

    06

    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

    8

    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.

    07

    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.

    64
    512

    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 typeComplexity per layerSequential opsMax 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.