Transformer Architecture
A transformer is a stack of identical blocks. Each block reads an matrix , one row per token, and returns a matrix of the same shape. A block has two parts, and each part sits on a residual connection:
- Multi-head attention mixes information across tokens. It is the only part of the block in which a token can read other tokens.
- MLP, or feedforward network, transforms each token on its own. Every token passes through the same two-layer network, usually with a hidden width of .
Modern transformers normalize at the start of each part. This is the pre-LN layout:
The original transformer of Vaswani et al. (2017) normalized after each addition instead. This post-LN layout computes , and likewise for the MLP. is LayerNorm or RMSNorm, applied to each token separately. The MLP is
The full model wraps the stack with an input layer and an output layer:
- Input: an embedding layer turns each token into a vector. A positional encoding gives the model the order of the tokens.
- Output: a linear layer maps each final vector to one score per vocabulary entry. A softmax turns the scores into probabilities for the next token.
The model in “Attention Is All You Need” is an encoder-decoder with blocks on each side. A decoder block has three parts: causal self-attention, cross-attention that reads the encoder output, and the MLP. During training the decoder receives the target sequence shifted right by one place, starting with
<start>. At inference it starts from<start>alone and generates one token at a time.
Intuition
The Spring 2023 lecture 18 notes build the transformer from the RNN encoder-decoder in five steps:
- Add cross-attention, so that each decoder step can look up the relevant part of the input.
- Add causal self-attention to the decoder, so that it can look up its own earlier outputs.
- Remove the RNN from the decoder. Attention already gives access to the input and to the outputs so far. The state has nothing left to carry.
- Add self-attention to the encoder and remove its RNN too. At first this self-attention is causal, like the RNN it replaces.
- Remove the causal mask from the encoder. The whole input is known in advance, so every input token may read every other one.
What remains are attention parts, MLPs, residual connections and normalization. Each token’s vector flows up the stack along the residual path. Every part reads that vector, computes a change, and adds the change back. Attention moves information between tokens, and the MLP processes each token’s information on its own.
The weights are shared across positions, as in an RNN and a CNN. Every token in one layer uses the same projections and the same MLP. Each layer has its own weights and fills its own attention table. Some models also share weights across layers.
Properties
(Why the MLP Is Needed) Attention outputs weighted averages of value vectors, so the block needs a separate part with a stronger nonlinearity.
The value vectors are linear in the input, and the attention weights are positive and sum to . The softmax is a nonlinearity, but it only chooses how to average. Each output therefore lies in the convex hull of the values. The MLP applies a ReLU to a -wide hidden layer of every token. The Fall 2022 lecture 19 notes give this reason for the MLP. The MLP also holds most of the weights. With width , its two matrices have weights, against in attention. That is two thirds of the block.
(How to Wire the Two Parts) Attention and MLP must each get their own residual connection, either in series or in parallel.
The Spring 2023 lecture 18 notes compare several wirings. In the serial wiring, the attention part has its own skip and so does the MLP. The parallel wiring computes from the same input. It behaves much like the serial one, since the next layer’s attention follows this MLP. It is also simpler to run at large scale. One wiring fails. It places attention and the MLP inside a single residual connection. The skip then jumps over both parts, so the pair may learn little. The MLP also sees only the attention output and loses the token’s own vector .
(Pre-LN Versus Post-LN) Placing the normalization inside each residual branch keeps a clean identity path from the output back to the input.
In pre-LN, passes from the bottom of the stack to the top with only additions on the way. The gradient along this path is the identity, as in a pre-activation ResNet. Pre-LN models add one more normalization after the last block, before the output layer. In post-LN, every block ends with a normalization on the main path, so the gradient passes through normalizations. The lecture notes that normalization now typically comes before the attention part.
Not Taught in Lecture
The effect on training follows the notes to Prince chapter 12 and Xiong et al. (2020).
In post-LN, the gradients shrink as they pass back through the network at initialization. Training then needs a learning-rate warm-up, and in practice Adam. Xiong et al. show that pre-LN transformers can train without the warm-up.
(Normalize the Query, Not Its Mean) The query should have a stable size, so the norm rescales each token but needs no centering.
The Fall 2022 lecture 19 notes argue from the query’s point of view. A query picks a direction, and its inner products rank the keys along it. Its size sets how sharp the softmax is, so it should not vary much between tokens. A key may stay short, which says “this direction, but weakly”. The notes therefore normalize the queries and let the keys keep their sizes. Only the scale matters for exploding or vanishing values, so the mean need not be removed. This is RMSNorm, with . The Spring 2023 lecture 18 notes mention a recent paper that normalizes both queries and keys before their inner product.
(Parallel Training, Sequential Generation) A decoder trains on all positions of a sequence in one pass, but it generates one token per pass.
During training, the causal mask lets each position see only earlier positions. One pass therefore computes all next-token losses, as shown in 7.1. Attention. An RNN must run its steps one after another even during training. At inference, each new token depends on the one before, so generation is sequential in any model. A transformer decoder stores past keys and values in a KV cache, so each step only processes the new token.
(Parameter and Compute Count) A block with an MLP of width has weights and costs about operations per token.
Attention has weights and the MLP has , so per block, with biases ignored. Each weight does one multiply and one add per token, which gives operations. The scores over all heads take operations per token, and the weighted sum of values takes another . The weight term dominates when . As a check, GPT-3 has blocks with . That gives weights, close to its billion parameters. The embedding table adds the rest.
(Weak Inductive Bias) A transformer assumes little about its input, so it needs much more training data than a CNN or an RNN.
A CNN assumes that nearby pixels matter together and that patterns can appear anywhere. An RNN assumes that the past matters through a summary state. Self-attention lets any token read any token with weights that it learns. The Spring 2023 lecture 18 notes and the Fall 2022 lecture 19 notes stress the consequence. Transformers are trained on huge amounts of unlabeled text with self-supervision. They are then adapted to the task that matters, as in 7.5. Encoder and Decoder Models. Prince makes the same point for images, where transformers must learn what convolution builds in.
(Sequence Length) Attention costs grow as , and the positional encoding decides whether a model can read sequences longer than in training.
Attention over tokens computes scores per head and layer, which limits the context length. 7.1.2. Efficient Attention covers ways around this. A model with learned absolute position vectors has none beyond its largest training position, so it cannot read longer inputs. Sinusoidal encodings, relative biases and RoPE can be computed for any position. Their quality beyond the training length is a separate question, discussed in 7.4. Positional Encoding.
Examples
(Easy) Shapes Through One Block
A pre-LN block has , heads and an MLP of width . It reads tokens.
List the shape after each step of the block. is , and so is . Each head forms queries, keys and values and a attention matrix. The eight head outputs side by side form , and keeps that shape. Adding the input gives . The MLP lifts each token to numbers, a matrix, and maps back to . The second addition gives the block output, again . The shape never changes, so blocks can be stacked.
The input
(Medium) Counting BERT's Parameters
Prince describes BERT with blocks, and MLP width . It has a vocabulary of tokens and inputs of up to tokens. Prince quotes about million parameters.
Count the weights of the blocks and the embeddings, then add the biases and normalization parameters. weights, so blocks have . The token embedding table has entries. Learned position vectors add . Each block also has attention biases, MLP biases and normalization parameters. That is per block and in total. The sum is , about million. The remaining few million come from smaller parts, such as the output head and the slightly larger real vocabulary. The blocks hold of the parameters.
Each block has
(Hard) When Attention Dominates the Cost
Take one GPT-3 block, with , and use the count of operations per token.
Find the share of the attention scores in the cost for contexts of and tokens. At what do the two terms match? The weight term is operations per token. For , the attention term is . Its share is . For the attention term is and its share is .
The terms match when , that is, at tokens. Below this length the matrix multiplications with weights dominate the arithmetic. This is why the cost of attention mattered little for GPT-3’s context of tokens. Memory is a different story, since a stored attention matrix grows as at any width.
See Also
- 7.1. Attention, the lookup inside every block.
- 7.1.1. Multi-Head Attention, the attention part of the block.
- 7.3. Token Embeddings, the input and output layers around the stack.
- 7.4. Positional Encoding, which adds token order to the input.
- 7.5. Encoder and Decoder Models, the three ways to use the stack.
- 5.3.3. Sequence-to-Sequence Models, the RNN model that the transformer replaced.
- 5.2.5. Residual Networks, for residual connections and pre-activation.
- 4.5.2. Layer Normalization, the normalization in each block.