An explorable explanation of Attention Is All You Need (Vaswani et al., 2017)
Build a Transformer, one block at a time
Every large language model you have used is built on one idea from a 2017 paper. Scroll down and the architecture assembles itself, block by block. Click any block to open its explanation, the exact formulas with every symbol explained, and a small visual you can try.
Running example: translating the black cat sleeps on the mat into French, le chat noir dort sur le tapis. You only need basic matrix multiplication.
QueryKeyValueAttentionEncoderDecoder
Scroll to start building
Cheat sheet
Every formula on one screen, plus the paper's hyperparameters.
Source: Vaswani, A. et al. Attention Is All You Need, NeurIPS 2017, arXiv:1706.03762. Decoder-only models such as GPT keep only the right half of the diagram (masked self-attention and FFN), while BERT keeps only the left half.
Resources
The only links on this page. Each opens in a new tab.
The step that turns text into numbers. A tokenizer chops the sentence into tokens, each token gets an integer ID, and each ID looks up a learned vector of d_model = 512 numbers.
How it works
A neural network can only multiply numbers, so words have to become vectors first. The embedding matrix has one row per vocabulary entry, and training nudges those rows so that tokens used in similar ways end up with similar vectors. Real models use subword tokenizers such as Byte-Pair Encoding, so a rare word like unbelievably becomes un + believ + ably. The paper used a shared vocabulary of about 37,000 subword tokens.
the embedding matrix, size \(|V| \times d_{\text{model}}\): one learned row per vocabulary entry
\(E[t_i]\)
row number \(t_i\) of \(E\), a vector of length \(d_{\text{model}}\). Looking it up is the same as multiplying a one-hot vector by \(E\)
\(\sqrt{d_{\text{model}}}\)
a constant scale (\(\sqrt{512} \approx 22.6\)). Embedding entries are small, so scaling keeps them from being drowned out by the positional encoding added next
See it
TokenIDEmbedding vector (first 16 of 512 dimensions)
-1+1
Each strip is one row of \(E\). Hover a cell to read its value. Repeated words (the) get exactly the same vector, because an embedding knows nothing about position yet.
What it is
A fixed pattern of sine and cosine waves added to each embedding so the model knows the order of the words.
How it works
Attention treats its input as a set: shuffle the words and it computes the same thing, yet "dog bites man" is not "man bites dog". Each position therefore gets a unique fingerprint. Early dimensions oscillate quickly and later ones slowly, a bit like the hands of a clock. The encoding of position \(pos + k\) is a fixed linear function of the encoding of \(pos\), which makes relative positions easy to learn.
the position of the token in the sentence: 0, 1, 2, ...
\(i\)
the dimension pair index, from 0 to \(d_{\text{model}}/2 - 1\). Even dimensions \(2i\) use sine and odd dimensions \(2i+1\) use cosine
\(10000^{2i/d_{\text{model}}}\)
sets the wavelength, which grows geometrically from \(2\pi\) (dimension 0) to \(10000 \cdot 2\pi\) (last dimension)
See it
dimension →
position ↓
Hover the heatmap
-1+1
Top: the full matrix \(PE\), one row per position. Bottom: individual dimensions plotted against position. Toggle the dimensions to compare their wavelengths. The vertical line follows your cursor on the heatmap.
Worked example, \(d_{\text{model}} = 4\), position 1
For \(i = 0\) the divisor is \(10000^{0} = 1\). For \(i = 1\) it is \(10000^{2/4} = 100\).
The mechanism that lets every token look at every other token in the same sentence and pull in the information it needs. In "the cat sleeps because it is tired", it borrows meaning from cat.
How it works
Each token makes three vectors from its embedding:
Query what am I looking for?
Key what do I contain, for anyone searching?
Value what will I hand over if someone attends to me?
A token compares its query with every key. The scores become percentages through softmax, and the token's new vector is the percentage-weighted average of all the values, like a soft dictionary lookup. Multi-head attention runs \(h = 8\) of these in parallel with smaller \(d_k = 64\) projections so that different heads can track different relationships, then concatenates the results and mixes them with \(W^O\).
the input matrix, \(n \times d_{\text{model}}\): one row per token (embedding plus position)
\(W^{Q}, W^{K}, W^{V}\)
learned weight matrices, \(d_{\text{model}} \times d_k\). The same three matrices are used for every token
\(QK^{\top}\)
an \(n \times n\) matrix of dot products. Entry \((i, j)\) says how well the query of token \(i\) matches the key of token \(j\)
\(\sqrt{d_k}\)
if the entries of \(q\) and \(k\) have variance 1, their dot product has variance \(d_k\). Dividing by \(\sqrt{d_k}\) brings it back to 1, so softmax does not saturate and gradients stay healthy
\(\text{softmax}\)
applied to each row: \(\text{softmax}(s)_j = e^{s_j} / \sum_m e^{s_m}\). Each row becomes positive weights that sum to 1
head \(i\)'s own projections, each \(d_{\text{model}} \times d_k = 512 \times 64\)
\(\text{Concat}\)
places the \(h\) outputs (each \(n \times 64\)) side by side, giving \(n \times 512\)
\(W^{O}\)
output projection, \(h\,d_v \times d_{\text{model}} = 512 \times 512\), which mixes information across heads
See it
Who does attend to?
Click a token on the left. Line thickness is the attention weight.
The numbers for
Every number here is computed live in your browser with \(d_{\text{model}} = 4\) and \(d_k = 3\). The weights are random, not trained, so the pattern itself means nothing; what matters is the mechanics.
Click a word to see how each head reads it
Swipe sideways to see the whole diagram.
The four patterns are hand-made to resemble behaviour seen in trained models (positional heads, a pronoun head, a syntax head). A real model has 8 heads in every one of its layers.
What it is
A residual connection followed by layer normalisation. It wraps every attention and feed-forward sub-layer in both stacks.
How it works
First the sub-layer output is added to its input. This gives gradients a direct path through all the layers and means each sub-layer only has to learn a small correction. Then each token vector is normalised to mean 0 and variance 1, followed by a learned scale \(\gamma\) and shift \(\beta\), which keeps the numbers in a stable range through dozens of layers.
With \(\gamma = 1, \beta = 0\) that is the output. Its mean is 0 and its variance is 1.
What it is
A small two-layer neural network applied to each token separately, with the same weights at every position.
How it works
Attention moves information between tokens; the feed-forward network then processes each token on its own. It expands the vector to four times its width, applies ReLU (keep positives, zero out negatives) and compresses it back to 512. These layers hold about two thirds of the model's parameters and are thought to store much of its learned knowledge.
Drawn at 1/64 scale: 8 inputs stand for 512, 32 hidden units stand for 2048. Grey hidden units had negative pre-activations and were set to zero by ReLU.
What it is
Six identical encoder layers stacked on top of each other, and six identical decoder layers next to them. Each layer has its own weights.
How it works
One layer is not enough to build rich meaning. Layer 1 sees the raw embeddings and every later layer refines the previous layer's output. Only the output of the last encoder layer, called the memory, is used by the decoder, and it feeds the cross-attention of every decoder layer. Every sub-layer keeps the width at \(d_{\text{model}} = 512\), so layers stack like bricks.
Each stack has N identical layers with their own weights. The encoder memory feeds the cross-attention of every decoder layer.
What it is
The decoder's input: the translation written so far, preceded by a start token <s>, embedded and position-encoded exactly like the encoder input.
How it works
The decoder predicts the next word from the words before it. Shifting the target right by one position lines everything up: at position \(t\) the decoder sees \(y_{<t}\) and must predict \(y_t\). During training the whole shifted sentence goes in at once (teacher forcing) and the causal mask stops each position from cheating. During inference the decoder is run again after every new word. The paper shares one embedding matrix between the encoder input, the decoder input and the final linear layer.
the \(t\)-th word of the target (French) sentence; the last target is the end token \(\langle eos\rangle\)
See it
Each column is one position. The decoder reads the top row and is trained to output the bottom row, so every position predicts the word one step ahead.
What it is
Self-attention over the French words written so far, with a causal mask that hides every future position.
How it works
When the decoder predicts word 3 it must not peek at words 3, 4, 5 of the answer. Because training feeds the whole target at once, the future has to be hidden explicitly: before the softmax we add \(-\infty\) to every score where a token would look ahead. Since \(e^{-\infty} = 0\), those positions get exactly zero weight and the attention matrix becomes lower-triangular.
The maths
$$\text{MaskedAttention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}} + M\right)V$$
$$M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases}$$
\(M\)
the mask: zero on and below the diagonal (past and present), \(-\infty\) above it (future)
\(i, j\)
row \(i\) is the token asking, column \(j\) is the token being looked at
See it
Rows are the decoder input <s> le chat noir dort, shifted right by one start token. Each row can only see itself and earlier columns, so the matrix is lower-triangular.
What it is
The bridge between the two halves. Queries come from the decoder, keys and values come from the encoder memory.
How it works
This is where translation happens. When the decoder is about to write noir, its query matches the key of black and it pulls in that word's value. No mask is needed because the whole source sentence is known. Attention also handles reordering: French puts the adjective after the noun, so chat noir crosses over black cat.
the decoder's current vectors, \(m \times d_{\text{model}}\) (\(m\) target tokens)
\(H\)
the encoder's final output, \(n \times d_{\text{model}}\) (\(n\) source tokens). It is computed once and reused by every decoder layer
\(QK^{\top}\)
now \(m \times n\): one row per target word, one column per source word. No mask is needed, since the whole source is known
See it
Click a French word
Attention matrix (target × source)
Notice how chat noir crosses over black cat: French puts the adjective after the noun, and attention handles the reordering. The weights are illustrative, similar to alignments in trained translation models.
What it is
The final linear layer scores every vocabulary word, softmax turns the scores into probabilities, and a decoding rule picks the next word.
How it works
The top decoder vector at each position is multiplied by \(W_{\text{vocab}}\) to get one logit per word in the vocabulary. Softmax converts the logits to probabilities. At inference, greedy decoding takes the most likely word, appends it to the decoder input and runs again until <eos>. In training the model is scored with cross-entropy: the average of \(-\log\) of the probability it gave to the correct word. The paper also uses label smoothing of 0.1.
\(d_{\text{model}} \times |V|\). The paper shares it with the embedding matrix (transposed)
\(y^{*}_t\)
the correct target word at position \(t\)
\(\mathcal{L}\)
cross-entropy: the average of \(-\log\) of the probability given to the right word. It is 0 if the model is certain and right, and large if it is confidently wrong
See it
In training we already know the answer, so the decoder input is the correct sentence shifted right by one. All positions are predicted in one parallel pass; the mask from section 06 stops each position from seeing its own answer.
The logits are illustrative values for a 12-word toy vocabulary; a real model scores about 37,000 tokens. Temperature divides the logits before softmax: below 1 sharpens the distribution, above 1 flattens it.