11  Transformers

Chapter 10 developed attention as a mechanism for exchanging information between positions. A transformer places attention inside a block with a position-wise feed-forward network, residual connections, and normalization. Stacking these blocks yields models for machine translation, language modeling, images, audio, and protein structure. Although these applications differ, most current transformer models can be described by a small set of architectural choices.

We therefore begin by building a configurable GPT class: normalization type and placement, activation, positional scheme, and the attention and feed-forward modules are all constructor arguments. Subsequent sections vary one component at a time and measure the resulting difference. At the end of the chapter, the configurations in a table of current models can be expressed as constructor arguments. The training runs finish in minutes on a single GPU. We state when conclusions depend on this small scale and compare the computational cost with that of production training.

We first develop the transformer block and compare normalization placement, RMSNorm, QK-norm, and gated feed-forward networks. We then assemble a GPT, train it on a small text corpus, and load the published GPT-2 weights into the same implementation. The section on generation derives the KV cache and compares grouped-query attention, low-rank compression, and sliding windows with attention sinks.

The remaining sections examine encoder, decoder, and encoder–decoder architectures; apply an encoder to image patches; and replace dense feed-forward networks with mixture-of-experts layers. The chapter concludes by deriving parameter and FLOP counts, conducting a small scaling study, and comparing the configurations of several current models.

The original 2017 Transformer was an encoder–decoder for translation, with post-sublayer normalization, sinusoidal positions, and ReLU feed-forward networks. The model configurations tabulated at the end of this chapter, reported from 2023 through 2025, retain the residual attention–FFN block but vary normalization, position encoding, cache layout, and expert routing. This shared interface motivates the configurable implementation used here; it is not a claim that all transformer families have converged on one design.

This chapter assumes the tokenization methods of Chapter 8 and the optimizers of Chapter 9. It covers base-model architecture, not corpus construction, instruction tuning, or downstream adaptation. Vision applications beyond ViT appear in Chapter 20; kernels, parallelism, quantization, and serving are deferred to Chapter 13. State-space alternatives to a growing key–value cache are developed in Chapter 12.

Resources and Further Reading

The resources are grouped into model construction, architecture, and scaling. All are freely available unless noted.

Build-alongs

The architecture record

The arithmetic of scale