Modelcore
Transformer
Also called transformer architecture, Vaswani transformer.
A network of stacked blocks of self-attention and feedforward layers with residual connections and normalization, with no recurrence.
The transformer is a neural network that maps a sequence of token vectors to a sequence of output vectors. It is a stack of identical layers. Each layer has a multi-head attention sublayer, which lets every position read from every other position, and a feedforward sublayer, which acts on each position alone. Each sublayer is wrapped in a residual connection and layer normalization. There is no recurrence, so all positions of a layer are computed in parallel, and word order enters only through a positional encoding. Vaswani and colleagues built it as an encoder-decoder model for translation. Encoder-only stacks such as BERT and decoder-only stacks such as GPT are now the base of most language models.
The machine
Input. The tokens come from a vocabulary of size . An embedding matrix of shape maps each token to a row, which is multiplied by , and a position vector is added: . The original model uses the fixed sinusoidal positional encoding; later models use learned position vectors, rotary position embedding or ALiBi.
Feedforward sublayer. For one position of size ,
with of shape and of shape . The original uses ReLU and .
Encoder layer, post-LN. The original places the normalization after the residual sum:
Encoder layer, pre-LN. Most later models normalize the input of each sublayer and keep the residual path free:
with one more LN after the last layer. In both forms dropout is applied to each sublayer output before the sum, and to the input sum of embeddings and positions.
Decoder layer. It has three sublayers: masked self-attention, where the causal mask stops position from seeing positions after ; cross-attention, , with queries from the decoder and keys and values from the final encoder output; and the feedforward sublayer. Each has the same residual and LN wrapping.
Output. After layers, the output at position is mapped to a distribution over the vocabulary, . The original shares between the two embeddings and this output map.
Three forms. The encoder-decoder form reads a source with the encoder and generates the target with the decoder. The encoder-only form has no causal mask and gives a vector for each input position, trained for example by masked language modeling. The decoder-only form has the causal mask and no cross-attention, and is trained by causal language modeling.
Training. The weights are trained by backpropagation on the cross-entropy loss of the next target token, with teacher forcing. The original used Adam with , , , the learning rate at step with warmup steps, dropout 0.1 and label smoothing 0.1.
The base model has layers in each stack, , and heads of size 64.
What it counts
Count multiply-adds and weights, ignoring biases and LN parameters, for one layer on positions with and .
- Weights. An encoder layer has in attention and in the feedforward sublayer, so . A decoder layer has two attention sublayers, so . The embedding has . For the base model with a shared vocabulary of about 37000 tokens this gives million, close to the 65 million listed in Table 3 of the paper, where the biases and LN parameters are included.
- Arithmetic. Attention costs for the projections and for the scores and the weighted sums; the feedforward sublayer costs . An encoder layer costs about . The term dominates when .
- Memory. The activations of a layer are numbers, plus if the attention weights are stored; FlashAttention avoids the second term.
- Generation. A decoder that has seen tokens computes the next one in per layer with a key-value cache of numbers per layer.
- Depth. Each layer is one parallel step: sequential operations, and a path of length between any two positions, against for a recurrent layer.
Relation to other models
- Recurrent language models carry a state of size from step to step, at per layer with sequential steps. The transformer replaces the recurrence by attention, which costs but runs in one step; at generation time it keeps all past keys and values instead of a fixed-size state.
- Encoder-decoder models with additive attention are the direct ancestor: the transformer keeps the cross-attention and adds self-attention in place of the recurrent encoder and decoder.
- BERT is an encoder-only transformer; GPT is a decoder-only one.
- Selective state space models such as Mamba replace attention by a recurrence with input-dependent parameters, which is linear in and has a fixed-size state at generation time.
- Conformer adds convolution modules to the transformer layer for speech; wav2vec 2.0 uses a transformer over speech features.
Known results in the model
- Permutation equivariance (theorem). Without positional information and without a mask, the whole encoder is permutation equivariant: permuting the input rows permutes the output rows. This follows from the same property of multi-head attention and the fact that the feedforward and LN sublayers act on each row alone. It is why a positional encoding is needed.
- Universal approximation (theorem). Yun and colleagues (2020) proved that transformers can approximate any continuous permutation equivariant sequence-to-sequence function with compact support to any accuracy, and, with positional encodings, any continuous sequence-to-sequence function on a compact domain. The constructions use many layers and are not what training finds.
- Turing completeness (theorem). Pérez, Barceló and Marinkovic (2021) proved that the encoder-decoder transformer with hard attention and rational values of arbitrary precision can simulate a Turing machine, by letting the decoder write out the steps of the computation. The construction needs the unbounded precision.
- Limits of self-attention (theorem). Hahn (2020) proved that transformers with hard attention cannot recognize parity or balanced bracket languages for all lengths, and that with soft attention the effect of one input symbol on the output shrinks as the input grows, so the confidence on such tasks must fall toward chance.
- Where to normalize (theorem and measurement). Xiong and colleagues (2020) showed that at initialization the post-LN form has large expected gradients for the parameters near the output, which explains why it needs the warmup stage; the pre-LN form has well-behaved gradients and trained without warmup in their experiments.
- Translation results (measurement). The big model reached 28.4 BLEU on WMT 2014 English to German and 41.8 BLEU on English to French, after 3.5 days of training on 8 P100 GPUs. Learned position vectors gave nearly the same results as the sinusoidal encoding (Table 3, row E).
- Scaling (measurement). Loss falls as a power law in model size, data and compute over many orders of magnitude; see neural scaling laws.
References
- Vaswani et al. 2017, Section 3.1 (the stacks and LayerNorm(x + Sublayer(x))), Section 3.3 (the feedforward network, d_ff = 2048), Section 3.4 (shared embeddings, scaling by sqrt(d_model)), Section 4 and Table 1 (cost per layer), Sections 5.3 and 5.4 (Adam, warmup, dropout, label smoothing), Tables 2 and 3 (BLEU and model sizes)
- Xiong et al. 2020, the gradient analysis at initialization for the post-LN and pre-LN forms, and the training experiments without the warmup stage
- Yun et al. 2020, Theorem 2 (permutation equivariant functions) and Theorem 3 (with positional encodings)
- Pérez, Barceló and Marinkovic 2021, the main theorem (Turing completeness with hard attention and rational values of arbitrary precision)
- Hahn 2020, the results on parity and Dyck languages for hard and soft attention
- Simon J. D. Prince, Understanding Deep Learning, MIT Press 2023, Chapter 12 (Transformers)
- Christopher M. Bishop and Hugh Bishop, Deep Learning, Foundations and Concepts, Springer 2024, Chapter 12 (Transformers)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag M3R9PT Edit this page History Report an error Markdown