Advanced
At the close of the Basics part, we trained a recurrent neural network on H. G. Wells’s The Time Machine. Prompted with the words “The Time Traveller”, that small model produces recognizable English words and punctuation, yet its grammatical coherence unravels after a dozen characters. By contrast, today’s frontier foundation models—built from the very same elementary primitives of parameterized layers, loss functions, automatic differentiation, and gradient-based optimizers—hold extended technical conversations, write and debug software, solve competitive mathematics problems, and synthesize photorealistic images and video from a sentence of text.
What separates a classroom prototype from a modern frontier system? Crossing that gap requires solving four fundamental challenges that small models on toy datasets never encounter:
- Optimization stability and scaling. In Basics, we treated minibatch stochastic gradient descent, learning-rate schedules, and batch sizes largely as convenient recipes. As networks grow to millions or billions of parameters, however, a learning rate that trains a narrow layer smoothly can cause a wider or deeper network to diverge instantly, and poorly conditioned loss surfaces can stall progress for millions of steps.
- Long-range memory and parallel sequence processing. A classical recurrent network is forced to compress everything it has read into a single fixed-width hidden vector before knowing which details will matter later—and because each time step waits for the previous one, recurrent training cannot exploit the massive parallelism of modern GPUs.
- Hardware bottlenecks and distributed systems. Modern accelerators perform floating-point arithmetic far faster than they can move tensors between off-chip memory and on-chip registers, or across network links between GPUs. At scale, a model’s real-world training and inference speed is governed as much by memory bandwidth, numerical precision, and communication topology as by its raw operation count.
- Learning beyond static labels. Supervised cross-entropy works whenever every input has a unique ground-truth label. Yet an autonomous agent acting in an environment must learn from delayed, sparse scalar rewards whose distribution shifts as the agent’s own policy changes; and a generative model synthesizing high-resolution images has no single target label to match, requiring objectives that compare entire probability distributions or reverse continuous corruption processes.
The nine chapters of this part—implemented in both PyTorch and JAX—tackle these four challenges systematically:
- Optimization and Scaling (9 Optimization Algorithms). We begin by examining what makes high-dimensional, nonconvex optimization hard—ill-conditioned curvature, saddle points, and minibatch gradient noise—and how modern optimizers overcome these obstacles. We trace the progression from stochastic gradient descent to momentum, AdaGrad, RMSProp, Adam, and decoupled weight decay (AdamW), paired with warmup and cosine learning-rate schedules, and conclude with the empirical neural scaling laws that govern how test loss falls as model capacity, dataset size, and compute budget grow together.
- Attention Mechanisms and Transformers (10 Attention and 11 Transformers). 10 Attention breaks the fixed-vector memory bottleneck of classical sequence models by introducing attention: a differentiable content-addressable lookup over keys, values, and queries. Starting from Nadaraya–Watson kernel regression, we develop additive and scaled dot-product attention, Bahdanau attention for sequence-to-sequence alignment, and multi-head self-attention. 11 Transformers then dispenses with recurrence altogether, assembling self-attention, positionwise feed-forward networks, layer normalization, residual connections, and positional encodings (including rotary position embeddings, RoPE) into the three foundational Transformer paradigms: bidirectional encoders (BERT), causal autoregressive decoders (GPT), and Vision Transformers (ViT). We also examine the computational bottlenecks of long-context attention, key–value caching during generation, and sparse Mixture-of-Experts (MoE) layers.
- Modern Recurrent Networks and State Space Models (12 State Space Models). While quadratic self-attention dominates when every token must attend to every other token, maintaining a growing key–value cache over hundreds of thousands of tokens becomes expensive at inference time. 12 State Space Models returns to recurrence with a fresh question: how can we keep a fixed-size state at inference time while still training across all sequence positions in parallel? We show how removing the nonlinear state recurrence enables exact parallel evaluation via associative scans, connect linear recurrences to continuous-time state space models (SSMs) and HiPPO polynomial projections, and progress to matrix-valued states (linear attention), input-dependent selective state space models (Mamba), and error-correcting delta rules (DeltaNet).
- Computational Performance (13 Computational Performance). 13 Computational Performance asks where the time and memory of a training step go. The roofline model separates operations limited by arithmetic from those limited by memory traffic, and a third limit, the host that issues every operation, explains why small operations leave a GPU idle. Compilation (
torch.compileandjax.jit), bf16 arithmetic, larger minibatches, and activation checkpointing then about double the throughput of a GPT training step on one GPU. We then add GPUs: data parallelism written by hand and with production libraries, the allreduce and its cost model, the overlap of communication with the backward pass, and the sharding of weights, gradients, and optimizer state (ZeRO and FSDP) that trains a model no single card holds. - Reinforcement Learning and Deep RL (14 Reinforcement Learning and 15 Deep Reinforcement Learning). 14 Reinforcement Learning builds the mathematical and algorithmic foundations of decision-making under uncertainty: Markov decision processes, Bellman optimality equations, value and policy iteration, model-free temporal-difference learning (Q-learning), exploration strategies in multi-armed bandits, imitation learning, continuous optimal control with known dynamics (LQR, iLQR, and Model Predictive Control on the inverted pendulum), direct policy optimization via REINFORCE and variance-reducing baselines, and neural policy gradients. 15 Deep Reinforcement Learning then scales reinforcement learning to deep function approximation, addressing the deadly triad of instability through experience replay and target networks in Deep Q-Networks (DQN), and developing Actor–Critic architectures with Generalized Advantage Estimation (GAE), Proximal Policy Optimization (PPO), maximum-entropy Soft Actor–Critic (SAC), offline and model-based reinforcement learning, KL-regularized control, and RL for autoregressive language models (GRPO).
- Generative Adversarial Networks and Diffusion Models (16 Generative Adversarial Networks and 17 Diffusion Models). The final two chapters develop modern deep generative modeling. 16 Generative Adversarial Networks treats generation as a game between a generator and a critic that learns to tell generated samples from real ones: it asks which divergence each critic’s loss measures (Jensen–Shannon, other \(f\)-divergences, MMD, \(W_1\)) and whether a far generator still gets a gradient, compares a critic that scores real and generated samples in pairs, shows on small games why the zero-centered gradient penalties \(R_1\) and \(R_2\) make gradient training converge near the data, builds and scores image generators, conditional ones included, and ends with the adversarial terms that still train vocoders, image autoencoders and one-step generators distilled from diffusion models. 17 Diffusion Models develops the continuous-time generative paradigm behind today’s flagship image, audio, and video models: corrupting data along a Gaussian probability path parameterized by its signal-to-noise ratio, training a deep denoiser to predict the clean data, the noise, or the velocity field (score), and generating new samples by integrating the reverse-time stochastic differential equation or probability-flow ODE. Along the way, we unify denoising diffusion (DDPM/DDIM) and flow matching, build U-Net and Diffusion Transformer (DiT) backbones with classifier-free guidance, and accelerate sampling to a handful of steps via consistency and average-velocity distillation.
These chapters do not need to be read strictly in linear order; the dependency diagram in the Preface (Figure 1) maps out which chapters build on which. Together, they provide the architectural, mathematical, and systems toolkit that the Language Models and Image Models parts apply to large-scale foundation models.