Skip to content

The Transformer

Stack attention, residuals, layer norm, and feed-forward blocks into a language model

Quick recap
  • A transformer block combines multi-head self-attention with a position-wise feed-forward network.
  • Residual connections and layer norm keep deep stacks trainable.
  • Stack blocks, project to the vocabulary, and softmax to get next-token probabilities.

This lesson follows Attention and completes the published recommended path. The Attention Playground is the live companion.

1. From attention to a block

Attention mixes information across tokens, but it is not a complete network. It has no nonlinear feature transformation, no residual path, and no normalization. A transformer block adds those pieces around attention.

The block below is the basic unit. Attention reads the sequence, the residual adds the original signal, layer norm stabilizes the result, and the feed-forward network transforms each position independently. A residual and norm wrap the feed-forward part too.

The order is important, but implementations differ. The original transformer used post-norm: add the residual, then normalize. Many modern models use pre-norm: normalize before the sublayer, then add the residual. Both appear in practice; the block diagram is a family, not a single immutable recipe.

2. Multi-head attention

One attention operation produces one weighted mix. Multi-head attention runs several in parallel, each with its own learned query, key, and value projections:

One head

The heads are concatenated and projected back to the model dimension:

Combine the heads

Different heads can learn different relationships: one may connect a pronoun to its noun, another may track nearby punctuation, and another may spread attention broadly. The split is not assigned by hand; it emerges from training.

A head is not a human-readable “concept detector.” It is a learned subspace of the model, and interpretability claims need evidence beyond a pretty attention heatmap.

3. Position and order

Self-attention is permutation-equivariant: if you reorder the tokens, the outputs reorder with them. The operation itself has no idea which token came first. That is fine for a bag of words and wrong for a sentence.

Transformers add positional information. The original paper used fixed sinusoidal encodings; later models used learned position embeddings, relative position biases, or rotary position embeddings (RoPE). The details differ, but the goal is the same: make position available to the attention and feed-forward computations.

A causal language model also needs a mask. Without it, the model could read the token it is supposed to predict. The mask sets future scores to −∞ before softmax:

Causal mask

Turn on Causal mask in the Attention Playground to see the future keys disappear and the weights renormalize.

4. Residuals and layer norm

A residual connection adds a sublayer’s input to its output. Instead of learning a complete replacement, the sublayer learns a change. The original signal has a direct path through the network, which helps gradients flow through deep stacks.

Layer norm re-centers and rescales each token vector across its feature dimension. It subtracts the mean, divides by the standard deviation, and applies a learned scale and shift:

Layer normalization

μ and σ² are computed over the features of one token, not over the batch. γ and β are learned, and ε avoids division by zero when the vector is nearly constant.

5. Feed-forward and depth

After attention mixes positions, a feed-forward network transforms each position separately. It is usually two linear layers with a nonlinearity, and the hidden layer is often four times wider than the model:

Position-wise feed-forward

Attention is the only operation that moves information between positions. The feed-forward network does the per-token computation. Stacking blocks alternates the two: mix, transform, mix, transform.

The stack is deep in two senses. Each block has multiple layers, and the model repeats the block many times. A small model may have 12 blocks; a large one may have dozens or more. Depth increases capacity and cost.

6. Worked block by hand

Use a three-dimensional toy token vector (1, 2, 3). Suppose a toy attention sublayer returns (1, −1, 1). The residual adds the input back:

Residual

The mean of (2, 1, 4) is 7/3 and the variance is 14/9. Layer norm with ε = 0.00001 gives:

Layer norm

Worked example: residual then layer norm

stepvector
input x(1, 2, 3)
attention output(1, -1, 1)
x + attention(2, 1, 4)
mean2.333
variance1.556
layer norm(-0.267, -1.069, 1.336)

The normalized vector has mean 0 and variance about 1. The feed-forward network would transform it next, then another residual and layer norm would follow. The attention output here is a toy value, not a claim about a trained model.

Notice what layer norm did not do: it did not change the direction of the vector in any semantic sense. It rescaled the coordinates so the next layer sees a consistent magnitude.

7. Encoder, decoder, generation

The original transformer had an encoder and a decoder. The encoder reads the input with bidirectional attention; the decoder generates the output with causal attention and can also attend to the encoder. Translation is the classic encoder-decoder task.

A decoder-only model such as GPT uses only the causal stack. It takes a prompt, predicts the next token, appends it, and repeats. An encoder-only model such as BERT uses bidirectional attention and is trained to fill masked tokens or compare sentences. The architecture follows the objective.

At generation time, a decoder can cache the keys and values of earlier tokens instead of recomputing them. That is the KV cache. It saves compute but still costs memory, and the cache grows with the context length.

The final linear layer maps each hidden vector to a logit per vocabulary token. Softmax turns those logits into the next-token distribution. In the toy output, the probabilities are:

candidateprobability
mat66.5%
floor24.5%
moon9.0%

The same next-token machinery from the language-model lesson sits on top of the stack. The transformer is the context mixer; the vocabulary projection and softmax turn its output into a choice.

8. Where it fails

Full attention is quadratic in sequence length. Doubling the context roughly quadruples the attention matrix, which is why long-context serving is expensive even when the model “supports” a large window.

A transformer has little built-in inductive bias for images, graphs, or physics. It can learn useful structure from data, but it needs enough data and compute to do so. A convolutional model may be a better fit when locality is the right prior.

Fluency is not truth. A transformer can produce a confident sentence that is false, repeat memorized text, or follow a prompt injection hidden in retrieved content. A large context window does not guarantee that the model attends to the right evidence.

The published recommended path ends here. The practical next step is to connect a base model to retrieval, tools, evaluation, and safety constraints — and to keep measuring behavior instead of trusting the architecture label.

9. Going deeper

Pre-norm and post-norm change the optimization landscape. RMSNorm drops the mean subtraction and uses the root mean square. These choices look small but affect stability at scale.

Mixture-of-experts models replace the dense feed-forward network with several experts and a router. The parameter count grows while the compute per token grows more slowly. Routing is learned, and load balancing becomes part of the training problem.

Efficient attention kernels, KV caching, quantization, and speculative decoding are systems techniques that make transformers practical. They do not change the fact that the model is predicting a distribution and that the distribution can be wrong.

10. Practice

Try it

What would happen to a transformer block if you removed every residual connection?

Try it

Why is a causal mask necessary for next-token training?

Try it

Does multi-head attention mean the model reads the same sentence several times?

11. Resources

The MIT chapter covers the transformer block and its training. The Illustrated Transformer builds the encoder and decoder visually, and the Illustrated GPT-2 connects the block to autoregressive generation. All three links were opened and checked for this lesson.

Continue the track

Open the playground for this topic

Attention Playground →

Pick a query token, move its two-dimensional query and key vectors, and watch scores become softmax weights and an output vector.

All Machine Learning lessons

Site soundtrack