11  Transformers

Chapter 10 developed the multi-head attention layer, positional encodings, and attention variants that scale to long contexts. Attention alone, however, is only a token-mixing operator: without per-token nonlinear transformations, residual connections, and normalization, stacking attention layers does not yield a trainable deep network. This chapter assembles attention into complete Transformer architectures (Vaswani et al. 2017) and studies how they are trained, served, and scaled.

We begin by building and training the causal stack from the ground up. Section 11.1 pairs multi-head attention with a position-wise feed-forward network inside a pre-norm residual stream (RMSNorm and SwiGLU), showing why residual projection scaling (\(1/\sqrt{2L}\)) and query–key normalization keep signal norms and attention logits bounded across depth. Section 11.2 stacks these causal blocks between token embeddings and a weight-tied language-modeling head, trains a byte-level GPT on WikiText-103 against a matched recurrent baseline, loads pretrained GPT-2 weights (124M) to examine temperature and top-\(k\) sampling, and distills the architectural recipe shared by modern open-weights LLMs (Section 11.2.6). Because naive autoregressive generation recomputes the entire prefix at every step, Section 11.3 introduces the key–value cache, contrasts compute-bound prefill with memory-bandwidth-bound decode on the hardware roofline, and compresses the cache across head count (grouped-query and multi-query attention), channel width (low-rank key–value projections), and sequence length (sliding windows with attention sinks).

Not every task is causal text generation. Section 11.4 contrasts causal decoders with bidirectional encoders trained via masked language modeling (Devlin et al. 2018) and sequence-to-sequence encoder–decoders coupled by cross-attention, including fixed-size latent bottlenecks (Jaegle et al. 2021). Section 11.5 then applies the bidirectional encoder directly to images by projecting non-overlapping pixel patches into token embeddings (Dosovitskiy et al. 2021), comparing learned 2D positional structure and data efficiency against a parameter-matched ResNet.

Finally, we turn to scaling and conditional computation. Section 11.6 counts parameters (\(N \approx 12 L d^2\)) and training FLOPs (\(C \approx 6 N D\)), fits power-law IsoFLOP curves (Kaplan et al. 2020; Hoffmann et al. 2022), and explains why lifetime inference cost pushes modern pretraining toward smaller models trained far past the Chinchilla token-per-parameter ratio. Section 11.7 decouples stored parameter capacity from per-token FLOPs by replacing the dense feed-forward network with a bank of routed experts (Shazeer et al. 2017; Fedus et al. 2022), comparing auxiliary-loss balancing against loss-free router bias control (Wang et al. 2024), and Section 11.8 surveys extensions across normalization placement, latent attention, and speculative decoding.