Reinforcement learning essentials
Learning from rewards: Bellman equations, Q-learning, policy gradients and PPO
Reinforcement learning is how a model learns from consequences instead of labels. It is optional for a vision engineer and mandatory for anyone who wants to understand modern language models: RLHF (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI) runs PPO with the LLM as the policy, reasoning models are trained with RL on verifiable rewards (8.6 Reasoning models and test-time compute), and an agent choosing tools in a loop is literally an MDP (10.3 Reasoning and planning for agents). This lesson gives you the vocabulary and the three core derivations — Bellman, Q-learning, the policy-gradient theorem — so those later lessons read as applications rather than magic.
You'll be able to
- Define an MDP, returns, policies and value functions and write the Bellman expectation and optimality equations
- Explain dynamic programming, Monte Carlo and TD learning, and perform a Q-learning update by hand
- Describe DQN's two stabilizing tricks and why they are needed
- Derive the policy-gradient theorem (log-derivative trick, causality, baselines) and write REINFORCE and actor–critic
- Explain PPO's clipped objective and how RLHF and GRPO reuse it
Key ideas
- An MDP is (S, A, P, R, γ); the return G_t = Σ γᵏ r_{t+k+1}; the goal is a policy maximizing expected return with no labels, only rewards.
- Bellman expectation: V^π(s) = Σ_a π(a|s) Σ_{s'} P(s'|s,a)[R + γV^π(s')]; optimality: Q*(s,a) = E[r + γ max_{a'} Q*(s',a')], and π* is greedy in Q*.
- TD learning bootstraps with the TD error δ = r + γV(s') − V(s); Q-learning is its off-policy form with a max over next actions.
Show 4 more key ideas
- DQN stabilizes neural Q-learning with experience replay and a frozen target network.
- Policy-gradient theorem: ∇J = E[Σ_t ∇log π(a_t|s_t) · Â_t], derived with the log-derivative trick; dynamics terms vanish; baselines reduce variance without bias.
- Actor–critic uses a learned V as baseline (TD error or GAE as the advantage); REINFORCE uses Monte Carlo returns.
- PPO clips the probability ratio to [1−ε, 1+ε] so the policy improves within a trust region; RLHF runs PPO with the LLM as the policy, and GRPO replaces the critic with a group-mean baseline.
Suggested path through this lesson
The setting
An agent interacts with an environment in discrete steps: it observes a state , chooses an action from a policy , receives a reward and moves to . The environment is a Markov decision process : transition probabilities , reward function and discount factor , with the Markov property that the future depends only on the current state and action. The agent's goal is to maximize the expected return,
where the discount keeps the sum finite for continuing tasks and expresses a preference for sooner rewards ( means a horizon of roughly steps). Unlike supervised learning there is no correct action given to us — only a scalar reward, often delayed and sparse — so the central difficulty is credit assignment: which of the many earlier actions caused this reward?
Value functions and the Bellman equations
The state value is the expected return from when following ; the action value commits to the first action. Because , values satisfy a recursive Bellman expectation equation:
The optimal value functions and satisfy the Bellman optimality equation, which replaces the average over the policy by a max:
Knowing solves the problem: act greedily. Every RL algorithm is a way of estimating (or ), or of improving directly.
Dynamic programming: when you know the model
With and known, policy evaluation iterates the Bellman expectation equation to convergence (it is a contraction with factor ); policy improvement makes greedy with respect to the resulting , which never makes it worse (the policy improvement theorem); alternating the two is policy iteration. Value iteration fuses them: . Dynamic programming is exact but needs the model and a table over states — fine for a gridworld, impossible for Go or language.
Model-free learning: Monte Carlo, TD and Q-learning
Without a model, learn from sampled experience. Monte Carlo methods run whole episodes and average the observed returns: unbiased but high-variance and only usable at episode end. Temporal-difference learning bootstraps from the current estimate after a single step:
The TD error is "what I got plus what I now expect, minus what I expected before" — it is the quantity dopamine neurons appear to encode, and the quantity every modern RL algorithm is built from. Q-learning applies the same idea to directly, using the optimality equation as the target:
It is off-policy: the target uses the greedy action while the data can come from an exploratory behaviour policy (typically -greedy: random with probability , greedy otherwise), so old experience remains useful. SARSA instead uses the action actually taken next, , and is on-policy. In the tabular case Q-learning converges to provided every pair is visited infinitely often and the step sizes satisfy the Robbins–Monro conditions (, ).
Worked example. In a gridworld, , the step gives and lands in where ; with , : target ; TD error ; new . Values propagate backward from the goal one step per visit — watch it happen in the rl-gridworld demo.
Deep Q-networks
Replace the table by a network and regress it toward the Q-learning target with the loss (Huber in practice, 4.3 Loss functions catalog). Naively this diverges: consecutive samples are correlated and the target moves every time the weights do. DQN (Mnih et al., 2013/2015) added two stabilizers — an experience replay buffer sampled uniformly to decorrelate the data and reuse it (possible precisely because Q-learning is off-policy), and a target network that is a frozen copy updated only every few thousand steps — and learned Atari games from pixels. Double DQN, dueling heads, prioritized replay and distributional values followed (combined in Rainbow). DQN handles discrete actions; continuous control and stochastic policies need the policy-gradient family.
The policy-gradient theorem
Parameterize the policy directly, (a softmax over actions, or a Gaussian for continuous actions), and maximize , the expected return of trajectories . We cannot differentiate through the environment, but we can differentiate the probability of the trajectory. Using the log-derivative trick :
Now , and the dynamics terms do not depend on , so they vanish from the gradient of the log:
This is the policy-gradient theorem: increase the log-probability of the actions taken, weighted by how good the trajectory turned out. Two refinements make it usable. Causality: an action cannot affect rewards that came before it, so replace by the reward-to-go . Baselines: subtracting any state-dependent leaves the expectation unchanged because
but it can slash the variance. The natural baseline is , giving the advantage : "how much better than expected was this action?" The resulting estimator is
REINFORCE uses Monte Carlo returns for and (optionally) a learned baseline. Actor–critic methods learn the critic by TD and use the TD error as a one-step advantage estimate (or GAE, an exponentially-weighted mix of -step estimates, ), trading the Monte Carlo variance for a little bias. In code it is startlingly small: compute with the network, multiply by (detached), and call backward() on the negative mean (4.4 Backpropagation, fully derived).
PPO: don't move too far at once
Policy gradients are on-policy (each batch of trajectories is used once) and fragile: one large step can collapse the policy, and the data collected by the old policy becomes useless. Proximal Policy Optimization (Schulman et al., 2017) lets you take several gradient epochs on the same batch while limiting how far the policy moves. With the probability ratio ,
Read it as a pessimistic bound: when the advantage is positive, the objective stops rewarding increases of beyond ; when negative, it stops rewarding decreases below . The policy is improved only within a trust region around the old one. The full loss adds a value-function term and an entropy bonus for exploration. PPO is the workhorse of robotics, games — and language-model alignment.
Why this returns in LLMs
In RLHF (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI) the policy is the language model, a state is the prompt plus the tokens generated so far, an action is the next token, the reward comes from a learned reward model at the end of the response, and a KL penalty to the pre-trained reference model plays the role of the trust region; PPO is run almost exactly as above. GRPO (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI, 8.6 Reasoning models and test-time compute) drops the learned critic and uses the mean reward of a group of sampled responses to the same prompt as the baseline — the baseline trick from the derivation above, applied at the level of whole answers — which is how DeepSeek-R1 learned to reason from verifiable rewards. And an agent (10.3 Reasoning and planning for agents) that chooses tools, observes results and continues is an MDP in which the tool outputs are the environment's transitions; the same credit-assignment problem, reward hacking (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI, 10.10 Agent safety and security) and exploration questions apply.
Where this shows up later
- Huber loss for value regression and the softmax policy head — 4.3 Loss functions catalog; optimizers and clipping — 4.5 Optimizers and learning-rate schedules.
- RLHF with PPO, reward models and KL penalties; DPO as the alternative that avoids RL — 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI; RL with verifiable rewards and GRPO in reasoning models — 8.6 Reasoning models and test-time compute.
- Agents as decision processes, planning as search over actions, reward hacking and safety — 10.3 Reasoning and planning for agents, 10.9 Evaluating agents, 10.10 Agent safety and security.
Common pitfalls (5)
- Forgetting to detach the advantage: the gradient must flow only through log π, not through the value estimate used as baseline.
- Using Q-learning with a neural network but no replay buffer or target network — it usually diverges.
- Treating the reward as a loss to minimize; policy-gradient code maximizes E[log π · A], so the loss is its negative.
- Confusing on-policy (SARSA, REINFORCE, PPO) with off-policy (Q-learning, DQN) and reusing stale on-policy data.
- Assuming higher reward means a better agent — reward hacking exploits the reward function rather than solving the task.
Recap: all 7 key points
- An MDP is (S, A, P, R, γ); the return G_t = Σ γᵏ r_{t+k+1}; the goal is a policy maximizing expected return with no labels, only rewards.
- Bellman expectation: V^π(s) = Σ_a π(a|s) Σ_{s'} P(s'|s,a)[R + γV^π(s')]; optimality: Q*(s,a) = E[r + γ max_{a'} Q*(s',a')], and π* is greedy in Q*.
- TD learning bootstraps with the TD error δ = r + γV(s') − V(s); Q-learning is its off-policy form with a max over next actions.
- DQN stabilizes neural Q-learning with experience replay and a frozen target network.
- Policy-gradient theorem: ∇J = E[Σ_t ∇log π(a_t|s_t) · Â_t], derived with the log-derivative trick; dynamics terms vanish; baselines reduce variance without bias.
- Actor–critic uses a learned V as baseline (TD error or GAE as the advantage); REINFORCE uses Monte Carlo returns.
- PPO clips the probability ratio to [1−ε, 1+ε] so the policy improves within a trust region; RLHF runs PPO with the LLM as the policy, and GRPO replaces the critic with a group-mean baseline.
Watch
MDPs, Bellman equations, value and policy iteration — the first half of this lesson, taught by a master. Lectures 2–6 of the series cover DQN and policy gradients.
Read
Try it live
Interactive demo
runs in your browserExercises
- By hand: Bellman and Q-learning
For a 3-state chain with deterministic transitions and rewards of your choice and , (a) solve the Bellman expectation equations for a fixed policy as a linear system, (b) run value iteration for 5 sweeps, (c) run 10 Q-learning updates with along a sampled trajectory. Expected: (a) and (b) agree once value iteration converges; (c) moves toward the same values.
- NumPy: tabular Q-learning on FrozenLake
Implement -greedy Q-learning on Gymnasium's FrozenLake-v1 (4×4, slippery). Decay from 1.0 to 0.05 over 5,000 episodes. Plot the success rate over time and print the greedy policy as arrows. Expected: success rate rises to ~70% (the environment is stochastic); the policy routes around holes.
- PyTorch: REINFORCE with a baseline on CartPole
Write a policy network (4 → 64 → 2 softmax) and train with REINFORCE using reward-to-go, then add a learned value baseline. Normalize advantages per batch. Expected: average episode length reaches 500 (solved) within a few hundred episodes; the baseline version converges faster and more smoothly.
- Experiment: PPO vs vanilla policy gradient
Using Stable-Baselines3 (or your own implementation), train PPO and A2C on LunarLander-v2 for 500k steps with 3 seeds each. Compare learning curves and variance across seeds. Expected: PPO reaches higher reward with lower variance; try and to see the trust-region effect.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →