TL;DR
A transformer is a neural network that processes a sequence by repeatedly letting every position look at every other position through attention, and then passing each position through a small feedforward network. It uses no recurrence and no convolution. Because all positions are handled at the same time, training parallelises well on modern hardware, and stacking many of these blocks gives the large language and vision models in use today.
Where you'll see it: inside chat models such as GPT, encoder models such as BERT used for search and classification, machine translation systems, and vision transformers that treat image patches as tokens.
Intuition
A meeting where everyone can hear everyone
Older sequence models read a sentence one word at a time and carry a memory forward, like a relay where each runner hands a baton to the next. A word near the end of a long paragraph has to survive many hand-offs to influence the words at the start, and details fade on the way. Recurrent networks work this way.
A transformer works more like a meeting. Every word gets to speak, and every word listens to every other word at the same moment, deciding how much attention to pay to each. After one round, each word's representation contains a blend of the context it needs. A word like "bank" can pull in "river" or "money" depending on the sentence. Several rounds of this, each followed by a small private computation per word, build up meaning layer by layer.
Why it exists
A recurrent model must compute position t before position t plus 1, so the work cannot be spread across positions on a GPU. Information between distant words also has to travel through many steps, which makes long-range dependencies hard to learn. In 2017 Vaswani and colleagues asked whether attention alone was enough, with no recurrence at all. For machine translation the answer was yes: the model trained faster, scored higher, and every position could be computed in parallel.
One block
Each block has the same shape. The input is a set of vectors, one per token. Attention mixes information between positions. A feedforward network then transforms each position separately. Residual connections and layer normalization wrap both steps so that deep stacks stay trainable.
flowchart TB X[Input vectors] --> A[Multi-head self-attention] A --> R1[Add and layer norm] X --> R1 R1 --> F[Feedforward network, same for each position] F --> R2[Add and layer norm] R1 --> R2 R2 --> Y[Output vectors, same shape as input]
The original paper placed layer normalization after each residual addition. Many later models move it before the sublayer, which often trains more smoothly at large depth.
The math
Setup
Suppose a sequence has tokens, and each token is represented by a vector of size . The paper uses . Stack the vectors as the rows of a matrix . Every operation below takes a matrix like this and returns one of the same shape.
Scaled dot-product attention
The core operation is the one from Attention Mechanism. Three learned projections turn into queries, keys and values:
Here , and are weight matrices learned during training. Attention is then
where is the size of each query and key vector. The softmax is applied row by row, so each row of weights sums to 1. The division by keeps the scores from growing with the dimension, as explained in the attention lesson, and keeps Softmax out of its flat, low-gradient regime.
Multi-head attention
One attention pattern is rarely enough. A transformer runs attention operations in parallel, each with its own projections of size . The paper uses , so . The outputs are concatenated and mixed by one more matrix:
Each head is free to specialise. In trained models some heads track the previous word, some track matching brackets, and some track the subject of a verb. This is a pattern seen in analysis, not a rule built into the design.
Position-wise feedforward network
After attention, each position passes through the same two-layer network on its own:
The inner width is in the base model. The feedforward step holds about two thirds of each layer's parameters ( million, against million for attention in the base model), and interpretability work suggests it stores much of the factual knowledge in large models. Attention moves information between positions; this step processes the information at each position.
Residual connections and layer normalization
Each sublayer, attention or feedforward, is wrapped the same way:
The term is the residual connection. The gradient can flow straight through the addition, so deep stacks train. The layer norm rescales each token's vector to mean 0 and variance 1, then applies a learned scale and shift.
Positional encoding
Attention on its own treats its input as a set. Shuffling the tokens shuffles the outputs in the same way, so word order is invisible. The original paper fixes this by adding a sinusoidal vector to each token embedding before the first block:
Each pair of dimensions is a sine and cosine at a different frequency, so every position gets a distinct pattern. Many later models learn the position vectors instead. See Positional Encoding for the details and the trade-offs.
Encoder and decoder stacks
The base model has encoder layers and decoder layers. An encoder layer is one multi-head self-attention step followed by the feedforward step. A decoder layer has three steps: masked self-attention, where position may only attend to positions up to , then cross-attention over the encoder output, then the feedforward step. The mask sets the scores for future positions to negative infinity before the softmax, so their weights become 0. This is what lets a decoder generate text one token at a time without peeking. The overall shape is the one described in Encoder-Decoder Architecture.
Worked examples
Take the token vector and ignore the small constant that is added in practice for numerical safety.
- Mean: .
- Deviations from the mean: .
- Variance: .
- Standard deviation: .
- Normalised vector: .
- Check: the mean is 0, and the variance is .
The result depends only on this token's four numbers. A learned scale and shift would follow in a real layer.
Two tokens have embeddings and . To keep the arithmetic visible, set , the identity matrix, so queries, keys and values equal the inputs. The divisor is .
- Token 1, query . Scores against the keys: and .
- Exponentials: and . Sum .
- Weights: and .
- Output: .
- Token 2, query . Scores: and . Weights: and .
- Output: .
Each token moved toward the other one, and neither output equals its original input. That mixing is the whole job of the attention step. The residual connection then adds the original input back, so token 1 becomes .
Attention builds an matrix of scores. Consider a realistic model with heads and a sequence of tokens, stored as 4-byte floats.
- Entries per head: .
- Entries for all 8 heads: .
- Bytes: , about 8 MB for one layer.
Now take a single head and a document of tokens.
- Entries: .
- Bytes: , about 10 GB for one head in one layer, before any other memory.
Doubling the length quadruples this cost. That is why long-context models use memory-efficient attention such as FlashAttention or other approximations.
Tradeoffs and failure modes
| Situation | Problem | Better choice |
|---|---|---|
| Very long inputs, hundreds of thousands of tokens | Score matrix grows with the square of length | Memory-efficient exact attention, sparse or linear attention, or a state-space model |
| Small dataset, strong local patterns (for example, short sensor signals) | Transformers are data hungry and can overfit | A convolutional or recurrent model, or gradient-boosted trees for tabular data |
| Streaming input on a tiny device | Attention needs the whole context to be kept | A recurrent or state-space model with constant memory per step |
| Any task with a pretrained model available | Training from scratch is expensive | Fine-tune a pretrained transformer |
Other failure modes are worth knowing:
- Length generalisation. Sinusoidal or learned positions trained on short sequences often degrade on much longer ones. Methods such as rotary position embeddings were designed to help.
- Training instability. Post-layer-norm stacks at large depth need careful learning-rate warmup. Pre-layer-norm placement is more forgiving.
- Quadratic cost in practice. Even when the math fits, the memory traffic dominates speed, so the bottleneck is often moving data rather than arithmetic.
- Attention is not an explanation. High weight on a token does not prove the model relied on it, as the attention lesson notes.
History
In 2014 Bahdanau, Cho and Bengio added an attention step to a recurrent encoder-decoder for machine translation, so the decoder could look back at the source words it needed. The problem was that the encoder still ran one word at a time.
In 2017 Vaswani and colleagues at Google published "Attention Is All You Need" at NeurIPS. They removed recurrence entirely and built the encoder-decoder from attention and feedforward layers. On the WMT 2014 English-to-German and English-to-French translation tasks the large model reached BLEU scores of 28.4 and 41.8 (the paper's abstract and results table; its running text gives 41.0 for English-to-French), above the best prior systems at the time, at a small fraction of their training cost. The base model trained for about 12 hours on eight GPUs and the large one for 3.5 days.
The design caught on quickly. In 2018 BERT used only the encoder stack, trained to fill in masked words, and became a standard tool for language understanding. The same year GPT used only the decoder stack, trained to predict the next word, which led to the generative line of models. Vision transformers, from about 2020, applied the same block to image patches. Most of the work since has been about scale, efficient attention, and training stability rather than changing the basic block.
Check yourself
QuestionIn one sentence, what does the attention step compute for each position, and what replaces recurrence as the way information moves between positions?Show answer
For each position, attention computes a weighted average of the value vectors of all positions, with weights from the softmax of scaled query-key scores. Information moves between positions in one step through these weighted averages, rather than being passed from one position to the next through a hidden state over many steps.
QuestionA query is and two keys are and . The dimension is , so the divisor is . What are the two attention weights?Show answer
Scores: and . Exponentials: and . Sum . Weights: and . The two weights sum to 1, as they must.
QuestionWhy does the decoder need a causal mask during training, and what would go wrong without it?Show answer
When the decoder is trained to predict token from the tokens before it, the target tokens are all known in advance. Without the mask, position could attend to token and simply copy the answer, so the training loss would be very low but the model would learn nothing usable for generation. The mask sets the scores for future positions to negative infinity, so they get weight 0 and the model has to predict from the past.
QuestionA model with a single attention head processes 20,000 tokens with 4-byte floats. Roughly how large is the score matrix for one layer, and how does it change if the length doubles to 40,000?Show answer
The matrix has entries, so about bytes, or 1.6 GB. Doubling the length to 40,000 gives entries and about 6.4 GB. The cost grows with the square of the length, so doubling the length multiplies it by four.