Algorithm Search⌘K

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 nn token vectors to a sequence of nn 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 x1,…,xnx_1, \ldots, x_n come from a vocabulary of size VV. An embedding matrix EE of shape V×dV \times d maps each token to a row, which is multiplied by d\sqrt{d}, and a position vector is added: Xi(0)=d Exi+PEiX^{(0)}_i = \sqrt{d}\, E_{x_i} + \mathrm{PE}_i. 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 xx of size dd,

FFN(x)=max⁡(0, xW1+b1) W2+b2,\mathrm{FFN}(x) = \max(0,\, x W_1 + b_1)\, W_2 + b_2,

with W1W_1 of shape d×dffd \times d_{ff} and W2W_2 of shape dff×dd_{ff} \times d. The original uses ReLU and dff=4dd_{ff} = 4d.

Encoder layer, post-LN. The original places the normalization after the residual sum:

Z=LN(X+MHA(X,X)),X′=LN(Z+FFN(Z)).Z = \mathrm{LN}(X + \mathrm{MHA}(X, X)), \qquad X' = \mathrm{LN}(Z + \mathrm{FFN}(Z)).

Encoder layer, pre-LN. Most later models normalize the input of each sublayer and keep the residual path free:

Z=X+MHA(LN(X),LN(X)),X′=Z+FFN(LN(Z)),Z = X + \mathrm{MHA}(\mathrm{LN}(X), \mathrm{LN}(X)), \qquad X' = Z + \mathrm{FFN}(\mathrm{LN}(Z)),

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 ii from seeing positions after ii; cross-attention, MHA(Z,Yenc)\mathrm{MHA}(Z, Y_{\text{enc}}), 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 NN layers, the output at position ii is mapped to a distribution over the vocabulary, softmax⁡(Xi(N)E⊤)\operatorname{softmax}(X^{(N)}_i E^\top). The original shares EE 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 β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98, ϵ=10−9\epsilon = 10^{-9}, the learning rate d−0.5min⁡(s−0.5,s⋅w−1.5)d^{-0.5} \min(s^{-0.5}, s \cdot w^{-1.5}) at step ss with w=4000w = 4000 warmup steps, dropout 0.1 and label smoothing 0.1.

The base model has N=6N = 6 layers in each stack, d=512d = 512, dff=2048d_{ff} = 2048 and h=8h = 8 heads of size 64.

What it counts

Count multiply-adds and weights, ignoring biases and LN parameters, for one layer on nn positions with dk=dv=d/hd_k = d_v = d/h and dff=4dd_{ff} = 4d.

  • Weights. An encoder layer has 4d24d^2 in attention and 2ddff=8d22 d d_{ff} = 8 d^2 in the feedforward sublayer, so 12d212 d^2. A decoder layer has two attention sublayers, so 16d216 d^2. The embedding has VdV d. For the base model with a shared vocabulary of about 37000 tokens this gives 6⋅12d2+6⋅16d2+37000 d≈636 \cdot 12 d^2 + 6 \cdot 16 d^2 + 37000\, d \approx 63 million, close to the 65 million listed in Table 3 of the paper, where the biases and LN parameters are included.
  • Arithmetic. Attention costs 4nd24 n d^2 for the projections and 2n2d2 n^2 d for the scores and the weighted sums; the feedforward sublayer costs 8nd28 n d^2. An encoder layer costs about 12nd2+2n2d12 n d^2 + 2 n^2 d. The n2n^2 term dominates when n>6dn > 6 d.
  • Memory. The activations of a layer are Θ(nd)\Theta(n d) numbers, plus Θ(hn2)\Theta(h n^2) if the attention weights are stored; FlashAttention avoids the second term.
  • Generation. A decoder that has seen tt tokens computes the next one in Θ(d2+td)\Theta(d^2 + t d) per layer with a key-value cache of 2td2 t d numbers per layer.
  • Depth. Each layer is one parallel step: O(1)O(1) sequential operations, and a path of length O(1)O(1) between any two positions, against O(n)O(n) for a recurrent layer.

Relation to other models

  • Recurrent language models carry a state of size dd from step to step, at O(nd2)O(n d^2) per layer with nn sequential steps. The transformer replaces the recurrence by attention, which costs O(n2d)O(n^2 d) 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 nn 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

  1. 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)
  2. 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
  3. Yun et al. 2020, Theorem 2 (permutation equivariant functions) and Theorem 3 (with positional encodings)
  4. Pérez, Barceló and Marinkovic 2021, the main theorem (Turing completeness with hard attention and rational values of arbitrary precision)
  5. Hahn 2020, the results on parity and Dyck languages for hard and soft attention
  6. Simon J. D. Prince, Understanding Deep Learning, MIT Press 2023, Chapter 12 (Transformers)
  7. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M3R9PT/text.yaml