Chapter 3 · Book pages 125–137
Introduction to Reinforcement Learning
The big picture
Supervised learning needs labeled input-output pairs. Reinforcement learning needs none: an agent learns by acting in an environment, receiving rewards as feedback, and adjusting its behavior to maximize cumulative reward — trial and error, not answer keys. This chapter is the toolkit the whole of Part II stands on: the MDP formalism, value functions, TD learning, Q-learning, policy gradients, actor-critic, GAE, and reward shaping — each one ending with "and here is what it means for LLMs."
Stop 1 — The MDP: rules of the game
RL's playing field is the Markov Decision Process, a 5-tuple (S, A, P, R, γ): the state space S (all configurations of the environment), the action space A (everything the agent can do), the transition function P(s′|s,a) (the physics: what state follows an action), the reward function R(s,a,s′) (immediate scalar feedback), and the discount factor γ ∈ [0,1] (how much future rewards count versus immediate ones).
The loop never changes: at each step t the agent observes state st, picks action at from its policy, the environment transitions to st+1 ~ P(·|st,at), the agent receives reward rt, and this repeats until a terminal state or horizon T.
Go deeper: the 5-tuple in the book's words
S: all possible environment configurations. A: all actions available to the agent. P(s′|s,a): probability of reaching s′ from s after a. R(s,a,s′): immediate scalar feedback for a transition. γ ∈ [0,1]: how much future rewards are valued relative to immediate ones. γ near 0 makes the agent myopic; γ near 1 makes it far-sighted — and for LLMs the book later fixes γ = 1.0 (all tokens matter equally in a single turn, stop 8). Book §3.1, p. 125–126.
Stop 2 — Policy, value, and the Bellman equations
Five definitions carry the whole field. A policy π(a|s) maps states to action probabilities (deterministic: a = π(s); stochastic: a ~ π(·|s)). The return Gt is the cumulative discounted reward from step t onward:
Gt = Σk=0∞ γk rt+k = rt + γrt+1 + γ²rt+2 + ⋯ (3.1)
The value function Vπ(s) = Eπ[Gt | st = s] is the expected return from a state; the Q-function Qπ(s,a) = Eπ[Gt | st=s, at=a] is the expected return after taking a specific action first; and the advantage Aπ(s,a) = Qπ(s,a) − Vπ(s) measures how much better that action is than average (3.2–3.4).
Go deeper: the full Bellman recursions
Vπ(s) = Σa π(a|s) Σs′ P(s′|s,a)[R(s,a,s′) + γVπ(s′)] (3.5); Qπ(s,a) = Σs′ P(s′|s,a)[R(s,a,s′) + γ Σa′ π(a′|s′)Qπ(s′,a′)] (3.6). Optimality: Q*(s,a) = Σs′ P(s′|s,a)[R(s,a,s′) + γ maxa′ Q*(s′,a′)] (3.8). The expectation versions average over what the policy would do; the optimality versions assume the best action every time — that single word, max, is the seed of Q-learning in stop 5. Book §3.2, p. 126.
Stop 3 — The taxonomy map
Every RL algorithm answers three questions. Do you model the world? Model-free methods learn a policy or value function directly from experience; model-based methods learn the transition dynamics P(s′|s,a) and can plan ahead — more sample-efficient, but model errors compound. What do you learn? Value-based methods learn Q or V and derive the policy as arg maxa Q(s,a) — great for small discrete action spaces (Atari), hopeless for huge ones. Policy-based methods optimize πθ(a|s) directly — essential for LLMs, where the vocabulary is 32K–128K actions. Actor-critic combines both: the actor proposes, the critic evaluates. Whose data do you learn from? On-policy learns only from the current policy's fresh data (stable, wasteful); off-policy learns from any policy's data, old or foreign (sample-efficient, harder to stabilize).
Go deeper: the book's taxonomy with examples
On-policy examples: REINFORCE, PPO, A2C — more stable but less sample-efficient. Off-policy: Q-learning, DQN, SAC — can reuse past experience but harder to stabilize. Value-based struggles with continuous or large action spaces; policy-based is natural for them. PPO for LLMs is actor-critic: a policy network steered by a value network's judgment. Book §3.3, p. 127.
Stop 4 — TD learning: surprise as a signal
Temporal Difference (TD) learning bootstraps: it updates value estimates using other value estimates, without waiting for the episode to end. The engine is the TD error — the gap between what you thought would happen and what actually happened plus what you expect next. The book's driving analogy: you predict a 30-minute drive; 10 minutes in, construction hits and the GPS says 35 minutes remain. The new total estimate is 45 minutes, so the TD error is +15 — pure surprise, and exactly the signal that updates your expectations.
δt = Rt+1 + γV(St+1) − V(St) (3.9) · V(St) ← V(St) + α·δt (3.11)
The first two terms form the TD target — the "better estimate" we move toward — so TD error = TD target − old estimate. δ > 0: better than expected, raise the value; δ < 0: worse, lower it; δ = 0: perfect prediction, nothing to learn. Try it:
Interactive · TD-error calculator (the driving analogy)
Set your predicted drive time, the elapsed time, and the GPS's new remaining estimate — watch δ and the value update.
Go deeper: multi-step returns
The n-step return Gt(n) = rt + γrt+1 + ⋯ + γn−1rt+n−1 + γnV(st+n) (3.12) looks n real steps ahead before bootstrapping. n = 1 is one-step TD; n = ∞ is Monte Carlo. TD(λ) averages over all n with exponentially decaying weights instead of picking one (standard result, beyond the book's scope here) — the same trick GAE later applies to advantages. Book §3.4, p. 127–129.
Stop 5 — Q-learning, DQN, and replay buffers
Q-learning is the foundational off-policy, value-based algorithm — it learns the optimal Q* directly, regardless of the policy being followed:
Q(st,at) ← Q(st,at) + α [ rt + γ maxa′ Q(st+1,a′) − Q(st,at) ] (3.13)
Watch it learn on a tiny gridworld:
Interactive · Q-learning gridworld
Step an ε-greedy agent through a 4×4 grid and watch Q-values converge via the update rule above.
DQN replaces the Q-table with a neural network and adds two stabilizers. A replay buffer stores transitions et = (st,at,rt,st+1,dt) and trains on random mini-batches — consecutive steps are highly correlated and neural nets generalize poorly on sequential data, so random sampling makes training approximately i.i.d., prevents catastrophic forgetting, and reuses every transition many times. A target network Qθ̄ — a frozen copy updated only every C steps (e.g. 10,000) — prevents the moving-target problem where prediction and target shift together and diverge. See the buffer work:
Interactive · Replay-buffer sampler
Stream correlated transitions into a buffer, then sample a mini-batch uniformly or with prioritization by |δ|.
Go deeper: the DQN training loop, step by step
Per training step: (1) act ε-greedily, annealing ε from 1.0 → 0.01 over the first 1M steps; (2) store (s,a,r,s′,d) in a buffer of capacity ~1M; (3) sample a mini-batch of 32 uniformly; (4) compute target y = r + γ(1−d) maxa′ Qθ̄(s′,a′) — zero future value if terminal; (5) gradient descent on (y − Qθ(s,a))², clipping gradients to [−1,1]; (6) every C steps, copy θ̄ ← θ. The loss is the mean squared TD error over the batch (3.15), and no gradient flows through the frozen target (3.16–3.17). Book §3.5, p. 129–130.
Stop 6 — REINFORCE: optimizing the policy directly
Instead of learning values and deriving a policy, policy gradient methods optimize the policy parameters θ directly to maximize expected return J(θ) = Eτ~πθ[R(τ)]. The policy gradient theorem delivers:
∇θ J(θ) = Eπθ [ Σt=0T ∇θ log πθ(at|st) · Gt ] (3.19)
REINFORCE (Williams, 1992) turns this into an algorithm: sample a full trajectory under πθ, compute the return Gt at each step, and update θ ← θ + α Σt ∇θ log πθ(at|st) · Gt. Read it as reward-weighted maximum likelihood: ∇ log π is the direction that raises the probability of the action taken, and multiplying by Gt means high-reward trajectories get all their actions reinforced, low-reward ones suppressed (negative Gt after a baseline). Supervised learning where the labels are your own actions, weighted by how well they turned out.
Go deeper: the 5-step derivation of the policy gradient theorem
(1) Write the objective as an expectation over trajectories: J(θ) = Στ P(τ|θ)R(τ). (2) Differentiate — only the πθ factors depend on θ, the environment dynamics don't. (3) Apply the log-derivative trick ∇P = P∇ log P to get an expectation again: ∇J = E[∇ log P(τ|θ) R(τ)]. (4) Expand log P(τ|θ) — the log p(s₀) and log p(st+1|st,at) terms vanish under ∇θ, leaving Σt ∇θ log πθ(at|st). (5) By causality, future rewards don't depend on past actions, so each ∇ log π pairs only with the future return Gt. The beauty: the gradient never requires differentiating through the environment. Book §3.6, p. 131–132.
Stop 7 — Actor-critic: two networks, one learner
Actor-critic combines the policy gradient with a learned value function to cut variance while keeping policy optimization's flexibility. The actor πθ(a|s) proposes actions; the critic Vφ(s) or Qφ(s,a) judges them, providing a low-variance baseline. The actor updates with the critic's TD-based advantage, the critic trains by minimizing squared TD error:
∇θJ = E[ ∇θ log πθ(at|st) · Ât ], Ât = rt + γVφ(st+1) − Vφ(st) (3.21) · Lcritic = E[ (rt + γVφ(st+1) − Vφ(st))² ] (3.22)
Go deeper: why the critic helps
REINFORCE's Gt comes from a single full trajectory — thousands of samples needed for a stable gradient. The critic replaces it with a one-step bootstrapped estimate rt + γVφ(st+1) − Vφ(st): lower variance (one random step instead of a whole rollout), some bias (Vφ may be wrong). Trading that bias and variance well is exactly stop 8's subject. Book §3.7, p. 132.
Stop 8 — GAE: the bias-variance dial
Actor-critic needs a good advantage estimate, and the two extremes both hurt: 1-step TD (rt + γV(st+1) − V(st)) has low variance but is biased whenever V is wrong; Monte Carlo (Gt − V(st)) is unbiased but the sum of many random rewards swings wildly between episodes. Generalized Advantage Estimation (Schulman et al., 2016) blends them with one parameter λ — an exponentially-weighted average of all n-step advantage estimates:
ÂtGAE = Σl=0T−t (γλ)l δt+l, δt = rt + γV(st+1) − V(st) (3.23)
Recent TD errors get full weight; distant ones decay by (γλ)l. Drag λ and watch the blend:
Interactive · GAE λ slider
Slide λ from 0 to 1 over a fixed stream of TD errors and watch the weights, the advantage, and the bias/variance balance shift.
Go deeper: diagnostics for tuning λ
High-variance indicators: policy entropy drops precipitously while the value function's explained variance goes highly negative or erratic → noisy policy updates; remedy: lower λ to smooth targets. High-bias indicators: training stabilizes early but the agent never discovers complex delayed-reward sequences → bootstrapping hides long-horizon dependencies; remedy: raise λ toward 1.0 to expose the policy to real downstream signals. Book §3.8, p. 133–135.
Stop 9 — On-policy vs off-policy, and why LLM RL is model-free
The comparison that decides your training bill. On-policy learns only from the current policy's data: after each update the old data is invalid and must be regenerated — low sample efficiency, high stability. Off-policy learns from any policy's data, reusing it many times — high sample efficiency, but distribution mismatch can diverge. For RLHF: PPO and GRPO are on-policy (generate responses, compute advantages, update, discard, regenerate — which is why generation is 60% of compute). DPO is off-policy (a fixed preference dataset, no generation during training — much cheaper, but the data goes stale as the policy drifts). Online DPO is the hybrid: fresh on-policy generation with DPO's supervised-style loss.
Go deeper: the comparison tables
On-policy (REINFORCE, PPO, A2C, GRPO): consistent data distribution, more stable, data used once. Off-policy (Q-learning, DQN, SAC, DPO): replay-buffer reuse, can diverge from distribution mismatch. Model-free (PPO, DQN, SAC): no model bias, must experience everything. Model-based: can simulate futures, high sample efficiency, best when dynamics are simple and efficiency matters. Book §3.9–3.10, p. 135–136.
Stop 10 — Reward shaping: dense rewards without the hacking
Reward shaping modifies the environment's reward to turn a sparse signal (feedback only at final completion) into a dense one (intermediate signals), accelerating convergence: R′(s,a,s′) = R(s,a,s′) + F(s,a,s′) (3.26). The danger is reward hacking: a naive F invites loopholes — a navigation agent rewarded for intermediate landmarks learns to loop around one checkpoint forever without reaching the goal; an LLM rewarded for "sounding confident" learns to always open with "Absolutely!" regardless of accuracy.
Potential-Based Reward Shaping removes the danger by constraining F to the difference of a scalar potential function Φ across states:
F(s,a,s′) = γΦ(s′) − Φ(s) (3.27) ⇒ R′ = R + γΦ(s′) − Φ(s) (3.28)
Go deeper: why the telescope collapses
Sum the shaping terms along a trajectory and they telescope: (γΦ(s₁) − Φ(s₀)) + (γ²Φ(s₂) − γΦ(s₁)) + ⋯ — every intermediate Φ cancels, leaving only −Φ(s₀) plus the discounted final potential. Progress toward genuinely higher-potential states is rewarded; sideways wandering nets zero. That is the mechanical reason behind both policy invariance and loop immunity (the telescoping derivation itself is standard RL canon, beyond the book's scope). Book §3.11, p. 136–137.