Foundations of Reinforcement Learning
- Sutton & Barto (1988, 2018) formalized RL as the study of agents maximizing cumulative reward through environment interaction
- Q-learning (Watkins, 1989) and policy gradient methods (Williams, 1992) are the two algorithmic families
- DQN (Mnih et al. 2015) combined Q-learning with deep networks, beating humans at Atari games
Reinforcement learning trains an agent by having it take actions in an environment, receive rewards, and update a policy (action selection strategy) to maximize long-term cumulative reward. Unlike supervised learning, there are no labeled examples - only scalar reward signals that may be delayed.
- Markov Decision Processes (MDPs) are the mathematical framework for RL problems
- RLHF (Reinforcement Learning from Human Feedback) uses RL to align LLMs - making RL central to ChatGPT and Claude
- Connects to control theory, game theory, and dynamic programming (Bellman equations)
- Formalize a sequential decision problem as a Markov decision process $(\mathcal{S}, \mathcal{A}, P, R, \gamma)$ and write the Bellman expectation and optimality equations for $V^\pi$, $Q^\pi$, $V^*$, and $Q^*$.
- Prove that the Bellman optimality operator is a $\gamma$-contraction in the sup norm and conclude that value iteration converges geometrically to the unique fixed point $V^*$.
- Distinguish dynamic programming, Monte Carlo, and temporal-difference targets, and explain why TD with bootstrapping plus function approximation plus off-policy data is the deadly triad behind tabular-to-deep instability.
- Derive the policy gradient theorem $\nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta}[\nabla_\theta \log \pi_\theta(a \mid s)\, Q^{\pi_\theta}(s, a)]$ from the discounted-return objective.
- Explain why PPO clips the importance ratio $\rho_t = \pi_\theta(a_t \mid s_t) / \pi_{\theta_\mathrm{old}}(a_t \mid s_t)$ and how the clip implements a coarse trust region without TRPO-style second-order solves.
TL;DR
Reinforcement learning treats decision making as an MDP and asks for a policy that maximizes expected discounted return [1]. Tabular methods (dynamic programming, Monte Carlo, SARSA, Q-learning) work when states fit in a table; once they do not, function approximation breaks the convergence proofs and the deadly triad (bootstrapping + function approximation + off-policy data) becomes a real engineering problem. DQN [2] tames the triad with a replay buffer and a slowly-updated target network; Double DQN [3], Dueling DQN [4], and Rainbow [5] sand off the remaining failure modes. Policy-gradient methods optimize by following [6]; TRPO [7] bounds the per-step KL with a trust region, and PPO [8] implements that trust region with a clipped importance ratio. SAC [10] and TD3 [12] dominate continuous control off-policy; AlphaZero [13] and MuZero [14] show what model-based RL with deep tree search can do at scale. The same machinery (PPO with a KL penalty against a frozen reference) is what RLHF [15] later borrows to align language models.
Intuition
Supervised learning gets a label for every input. Reinforcement learning gets a scalar reward that arrives several decisions later, and the agent must figure out which of those decisions were responsible. The agent observes a state , picks an action , the environment returns a next state and a reward , and the loop continues. The agent never sees the optimal action; it only sees the consequences of the action it tried. Two problems make this hard. First, credit assignment: a reward at step depends on every action between and . Second, exploration vs exploitation: to learn what is good, the agent must sometimes try things it suspects are bad.
The framing that makes the math tractable is the Markov decision process. Pretend the world is memoryless: the next state and reward depend only on the current state and the chosen action, not on the history. Define a discount factor so that distant rewards count for less, and an objective . The Bellman equations relate the value of a state to the values of its successors and turn the infinite-horizon planning problem into a fixed-point equation.
A policy maps states to actions; a value function tells you what each state (or state-action pair) is worth under that policy; the Bellman equations connect the two, and every algorithm in this chapter is a way to estimate or improve them when the state space is too big to enumerate.
- 1957Bellman: dynamic programmingfoundation
Richard Bellman names the framework, writes the recursion V(s) = max_a [R(s,a) + gamma * E[V(s prime)]], and gives value iteration as the canonical solver. The whole field is downstream of this equation.
- 1989Watkins: Q-learningpaper
Q-learning is the off-policy temporal-difference rule that converges to Q* under mild conditions even when the behavior policy differs from the greedy one. Becomes the workhorse of tabular RL.
- 1992Williams: REINFORCEpaper
The first usable Monte Carlo policy-gradient estimator: nabla J = E[nabla log pi(a|s) * G_t]. Unbiased, high variance, and the ancestor of every modern policy-gradient method.
- 2013DQN (Atari from pixels)paper
DeepMind shows a single Q-network with experience replay and a target network learns 49 Atari games end-to-end from raw pixels at human-level performance on most of them.
- 2015TRPOpaper
Schulman et al. constrain each policy-gradient step to stay within a KL-divergence trust region, eliminating the catastrophic step problem of vanilla policy gradient.
- 2016AlphaGo defeats Lee Sedolmilestone
Policy + value networks plus Monte Carlo tree search beat a 9-dan professional 4-1. Demonstrates that deep RL plus search can solve a problem widely believed to be a decade away.
- 2017PPOpaper
A first-order, clipped-ratio surrogate that approximates the TRPO trust region with no Hessian-vector products. Becomes the default policy-gradient algorithm in practice.
- 2017AlphaGo Zeromilestone
Same architecture as AlphaGo, trained purely from self-play with no human games. Surpasses every prior version of AlphaGo within 40 days.
- 2018SACpaper
Soft Actor-Critic adds a maximum-entropy bonus to the standard actor-critic objective. Strong sample efficiency and stability on continuous-control benchmarks; widely deployed in robotics.
- 2019MuZeropaper
Model-based RL where the model is learned end-to-end with the value and policy heads, with no ground-truth simulator. Matches AlphaZero on board games and DQN on Atari with no environment model handed in.
Markov decision processes and the Bellman equations
A finite-horizon Markov decision process is a tuple where is the state set, is the action set, is the transition kernel, is the (expected) reward, and is the discount factor. A policy is a (possibly stochastic) mapping from states to actions. The infinite-horizon discounted return from time is
and the agent maximizes over policies. Because and rewards are bounded, is always finite.
Two value functions encode “how good is it to be here”. The state-value function is
and the action-value function is
By conditioning on the next state and reward and using the Markov property, both satisfy a one-step recurrence (the Bellman expectation equation):
The optimal value functions are and , and they satisfy the Bellman optimality equation:
Once is known, the optimal policy is the deterministic greedy policy .
Bellman optimality and the contraction proof
The Bellman optimality equation looks like a definition; it is in fact a fixed-point equation for an operator on the space of value functions. Define the Bellman optimality operator by
The claim is that is the unique fixed point of , and value iteration converges to it from any starting point at rate .
Step 1: is a contraction in the sup norm. Take any two value functions and any state . Pick to be the maximizer in at . Then
because using the same in gives a lower bound on the max. The reward terms cancel, leaving
since the absolute value of the inner sum is bounded by (the transition probabilities sum to one). The same argument with the roles of and swapped gives the matching lower bound, so
Step 2: existence and uniqueness via Banach. with the sup norm is complete, and is a -contraction with , so the Banach fixed-point theorem gives a unique fixed point and for any , with
Convergence is geometric. Picking close to makes the contraction weak and the iteration slow, which is the discount-factor trade-off in practice.
Step 3: identifying the fixed point with the optimal value. A separate argument (policy improvement) shows that as defined above (the supremum over policies of ) satisfies the Bellman optimality equation, so it is a fixed point. Uniqueness then forces the fixed point of . The greedy policy is optimal.
What the proof buys you. Value iteration is the canonical tabular planning algorithm because the contraction proof guarantees convergence at a known rate. Policy iteration converges in finitely many steps for finite MDPs, with each step a contraction in the same sense. Asynchronous, prioritized, and sample-based variants (TD, Q-learning) inherit the proof structure as long as every state is updated infinitely often [1].
Tabular methods: DP, MC, TD, SARSA, Q-learning
When is small enough to fit in a table and are known, dynamic programming solves the MDP exactly. Value iteration repeats until convergence; policy iteration alternates evaluation ( from the linear Bellman expectation system) and improvement (). Both are off-policy in the sense that the agent never has to interact with the environment; the model is given.
DP fails the moment the model is unknown or the state space is too large. The next two ideas relax those assumptions.
Monte Carlo (MC) methods estimate from sampled returns. Run a full episode under , accumulate the actual discounted return , and update . MC is unbiased (the target is the true return) but high-variance and only updates at the end of an episode, so it is wasteful in long-horizon problems.
Temporal-difference (TD) methods sit between DP and MC. Instead of waiting for , bootstrap from the current value estimate at the next step:
The bracketed term is the TD error . TD updates every step, which is why it dominates MC in practice; the cost is bias from bootstrapping off an inexact .
For control (estimating rather than ), the same TD idea splits into two flavors that differ only in how they pick the next-step action used in the bootstrap. SARSA uses the action the agent actually took:
so it learns the value of the behavior policy. Q-learning uses the greedy action:
so it learns even when the data is collected by an exploratory policy. SARSA is on-policy; Q-learning is off-policy. Under tabular conditions and a Robbins-Monro learning-rate schedule, both converge to the right fixed point.
Three things are individually fine, but all three together break tabular convergence guarantees and almost always destabilize training:
- Bootstrapping (TD targets that depend on the current estimate),
- Function approximation (a neural net, not a table), and
- Off-policy data (the data was generated under a policy other than the one being evaluated).
Sutton and Barto call this combination the deadly triad [1]. Every successful deep-RL algorithm pays its tax to one of the three: DQN keeps the bootstrap and the function approximator and tames off-policy data with a replay buffer plus a slow-moving target network; on-policy methods like A2C and PPO keep bootstrapping and approximation and avoid the off-policy axis by discarding data after a single update; offline-RL methods (CQL, IQL) keep all three and add explicit pessimism.
DQN: deep Q-learning
Once the state is a stack of game-frames there is no table. Mnih et al. [2] replaced the Q-table with a convolutional network and trained it by minimizing the mean-squared TD error on a replay buffer of past transitions, with a target network whose weights lag by thousands of steps:
The replay buffer breaks temporal correlations: consecutive game frames are highly correlated and would make minibatch SGD biased; sampling a random minibatch from a million-transition buffer recovers an approximately i.i.d. estimate. The target network breaks the moving-target problem: if both sides of the TD error used , every gradient step would shift the target as well as the estimate, and the value would chase its own tail. Freezing for steps (typically ) and then copying stabilizes training to roughly the same degree the target network is “stale” relative to .
Three follow-ups cleaned up DQN’s known failure modes. Double DQN [3] noticed that the same network is used to both pick the action and evaluate it inside , which biases the bootstrap upward (the Q-overestimation bug). The fix decouples them: pick the action with the online network, evaluate it with the target network. Dueling DQN [4] splits into a state-value head and an advantage head with , which decouples “is this state any good” from “which action is best here” and learns faster on states where actions are nearly tied. Rainbow [5] stacks Double DQN, Dueling DQN, prioritized replay, multi-step returns, distributional RL, and noisy nets, and shows that all six together beat any subset on the Atari-57 benchmark.
Policy gradients
DQN learns a value function and reads a policy off it. The other half of the field optimizes the policy directly. Parameterize as a neural net (a softmax for discrete actions, a Gaussian for continuous ones) and follow the gradient of the expected return .
The policy gradient theorem
Let be a trajectory under , and let . The objective is where .
Step 1: log-derivative trick. . Use the identity :
Step 2: only the policy depends on . . The initial-state and transition terms do not depend on , so . The transition model has dropped out, which is why policy-gradient methods are model-free.
Step 3: per-step credit assignment. Plugging back in,
The full return multiplies the gradient of every action, including actions that happened after rewards already received. Those past rewards contribute only noise to the gradient. The standard fix uses the reward-to-go :
A short causality argument (the gradient of has zero expectation when conditioned on ) shows that replacing with for any state-only baseline leaves the gradient unbiased but reduces its variance. The optimal-variance baseline is approximately . Using the value baseline gives the advantage and the canonical form of the policy gradient theorem:
REINFORCE [6] is the special case where is replaced by the Monte Carlo return (or minus a constant baseline). Actor-critic methods replace with a learned estimate from a value-network critic. GAE [9] blends -step TD residuals via an exponentially-weighted sum to trade bias for variance smoothly.
The unbiasedness of the policy gradient is a real result; the practical issue is variance. A REINFORCE estimator on a single trajectory has variance proportional to the squared range of returns, which is enormous in any non-trivial environment. Three variance-reduction tools are routinely stacked on top of plain REINFORCE: a learned value baseline (turns return into advantage), bootstrapped TD targets (replace with ), and GAE with tuning the bias-variance trade-off.
Actor-critic, TRPO, and PPO
Actor-critic combines a parametric policy (“actor”, trained by policy gradient) with a parametric value function (“critic”, trained by TD). A2C is the synchronous, batched form: collect environment steps under , fit the critic to bootstrapped returns, take one policy-gradient step on the actor, repeat. Vanilla A2C works when the steps are small; once they are too aggressive the on-policy assumption breaks and the run blows up.
TRPO [7] explicitly bounds the KL divergence between successive policies:
The constraint defines a trust region inside which the linearized objective is reliable. Solving it requires a Hessian-vector product per iteration; TRPO works well but is fiddly to implement.
PPO clipped surrogate objective
PPO [8] replaces the hard KL constraint with a clipped surrogate that approximates the same trust region using only first-order information. Define the per-step probability ratio
The unclipped surrogate is the importance-weighted policy gradient and is unbiased only when . PPO objective:
The clip works as follows. Suppose (this action was better than average). Increasing above stops contributing to the objective: the clipped term becomes constant in , and the picks that flat term once it is below . The gradient on that token zeros out. Symmetrically, when , decreasing below stops contributing.
The effect is a first-order trust region: any update direction that pushes a token’s probability ratio outside in the rewarding direction stops generating gradient. The policy can still drift in the conservative direction, which is what makes the objective an underestimate (and therefore safe) of the true unclipped surrogate.
Tuning . The standard value is , which corresponds to roughly a multiplicative change in any per-step probability before the clip kicks in. Smaller (down to ) is more conservative; larger (above ) breaks the trust-region intuition and training oscillates. Combining the clip with a value-function MSE loss and an entropy bonus is the standard PPO recipe:
The entropy bonus encourages exploration; and are typically and . PPO is the default policy-gradient algorithm in nearly every deep-RL benchmark from 2018 onward, including the policy-update stage of RLHF for language models [15].
Continuous control: DDPG, TD3, SAC
In continuous-action spaces, is no longer a finite enumeration; you cannot scan the action set every step. DDPG [11] handles this with a deterministic actor trained by the chain rule through : take the gradient of with respect to . The critic is trained off-policy via a target network and replay, exactly as in DQN. DDPG is sample-efficient but notoriously unstable: the actor and critic can chase each other into Q-overestimation territory.
TD3 [12] patches the three known DDPG failure modes. Twin critics: maintain two Q-networks and use the minimum of the two in the bootstrap target, which combats overestimation just like Double DQN does in the discrete case. Delayed policy updates: update the actor every critic updates (typically ), which lets the critic catch up before the actor moves. Target-policy smoothing: add Gaussian noise to the target action when computing the bootstrap, which regularizes the value estimate against narrow peaks. The combination is the standard off-policy continuous-control baseline.
SAC [10] takes a different angle: maximum-entropy RL. Augment the reward with the policy entropy:
The entropy bonus encourages the agent to keep its options open: among policies with the same expected return, prefer the one that hedges across actions. This makes exploration automatic (no separate -greedy or noisy-net mechanism), produces robust policies that transfer better, and gives a soft Q-learning rule whose Bellman backup mixes the standard with a softmax weighted by entropy. SAC dominates TD3 on most MuJoCo benchmarks and is the default choice for robotics simulation and sim-to-real.
| Family | On / off-policy | Sample efficiency | Continuous actions? | Stability | Hallmark paper |
|---|---|---|---|---|---|
| Tabular DP / SARSA / Q-learning | On-policy (SARSA), off-policy (Q-learning) | Excellent in tabular size; impossible at scale | Discrete only | Provably convergent in tabular setting | Sutton & Barto 2018 (textbook) |
| DQN family (DQN, Double, Dueling, Rainbow) | Off-policy via replay | High (every transition reused) | Discrete only | Stable with target net + Double + Dueling | Mnih et al. 2015 (Nature) |
| Policy gradient (REINFORCE, A2C) | On-policy | Low (data discarded after one update) | Yes (Gaussian policy) | Variance-limited; needs baseline | Williams 1992 |
| Trust-region (TRPO, PPO) | On-policy | Low to medium | Yes | High (KL or clip bounds the step) | Schulman et al. 2017 (PPO) |
| Off-policy actor-critic (DDPG, TD3, SAC) | Off-policy via replay | High | Yes | High for TD3 / SAC; DDPG is fragile | Haarnoja et al. 2018 (SAC) |
| Strategy | Mechanism | Best fit | Pitfall |
|---|---|---|---|
| Epsilon-greedy | With probability epsilon pick a uniform random action; else greedy | Discrete actions, simple baselines, DQN | Wasteful in large action spaces; constant epsilon never anneals exploration away |
| UCB (upper-confidence bound) | Pick a = argmax [Q(s,a) + c sqrt(log t / N(s,a))] | Bandit and tabular MDPs with visit counts | Visit counts do not generalize to neural-net features; pseudo-counts are needed for deep RL |
| Thompson sampling | Sample Q from a posterior, act greedily under the sample | Bayesian bandits and contextual bandits in recsys | Posterior over deep nets is hard; bootstrap-DQN approximates it |
| Entropy bonus | Add alpha * H[pi(.|s)] to the objective (SAC, A2C) | Continuous control, on-policy gradient methods | alpha must be tuned or auto-adjusted; too large drives the policy uniform |
Model-based RL and the search frontier
Model-free methods learn or directly from interaction. Model-based methods learn (or are given) a transition model and use it to plan. Classical examples include Dyna (interleave real and model-generated transitions) and PILCO (Gaussian-process dynamics + analytic policy evaluation). The modern poster children are AlphaZero [13] and MuZero [14].
AlphaZero combines a policy-and-value network with Monte Carlo tree search (MCTS). At each move, MCTS expands a tree from the current state, evaluating leaves with the value network and biasing rollouts with the policy network. The search itself is a powerful policy-improvement operator: the move distribution at the root is sharper and stronger than the raw policy network, and self-play between the search policy and itself produces training data that bootstraps both networks toward optimal play. The system reached superhuman strength in Go, Shogi, and Chess from a single architecture trained from scratch.
MuZero drops the assumption of a known simulator. The model is learned end to end with the value and policy heads: it predicts only the quantities the search needs (immediate reward, value, policy logits) given a learned latent dynamics function, not the actual next state. This makes the algorithm work on Atari (where there is no simulator at all from the agent’s point of view) at performance comparable to model-free DQN-class methods, while keeping AlphaZero’s strength on board games. MuZero is the proof of concept that deep model-based RL with learned latent dynamics can scale.
Tabular Q-learning and DQN side by side
import numpy as np
# Toy 4x4 Frozen Lake: 16 states, 4 actions (L, D, R, U).
# In a real run, env = gym.make("FrozenLake-v1"); we simulate the API here.
n_states, n_actions = 16, 4
Q = np.zeros((n_states, n_actions))
alpha = 0.1 # learning rate
gamma = 0.99 # discount
epsilon = 0.1 # epsilon-greedy
n_episodes = 5000
rng = np.random.default_rng(0)
def step(s, a):
# placeholder dynamics: returns (s_next, reward, done)
s_next = (s + a + 1) % n_states
reward = 1.0 if s_next == n_states - 1 else 0.0
done = s_next == n_states - 1
return s_next, reward, done
for ep in range(n_episodes):
s = 0
done = False
while not done:
if rng.random() < epsilon:
a = rng.integers(n_actions) # explore
else:
a = int(np.argmax(Q[s])) # exploit
s_next, r, done = step(s, a)
td_target = r + gamma * np.max(Q[s_next]) * (not done)
Q[s, a] += alpha * (td_target - Q[s, a]) # off-policy TD
s = s_next
policy = Q.argmax(axis=1)Real-world reinforcement learning
RL outside benchmarks is shaped by three forces: where the simulator comes from, how expensive an interaction is, and how much you trust the reward signal. The 2016 AlphaGo match against Lee Sedol was watershed because the simulator (the rules of Go) was free and exact and the reward (winning a game) was unambiguous. AlphaZero and MuZero pushed the same recipe to chess, shogi, and Atari, with MuZero showing that the simulator itself can be learned from interaction. OpenAI Five (Dota 2) and AlphaStar (StarCraft II) scaled up self-play in much larger action and state spaces, with PPO-style updates and curriculum learning over millions of games.
In robotics, the simulator is approximate and the cost of a real-world step is high. The dominant pattern is sim-to-real transfer: train a policy in simulation with domain randomization (vary masses, frictions, lighting, sensor noise, latency), then deploy the resulting policy on hardware. SAC’s entropy regularizer and TD3’s twin critics are the off-policy backbones of choice; domain randomization is the regularizer that makes the simulator-to-reality gap survivable. OpenAI’s in-hand cube manipulation work is the canonical demonstration that this pipeline can deliver dexterous manipulation from a single policy trained entirely in simulation.
In recommender systems and online platforms, the agent picks an item and gets a click or a conversion. The state is summarized by user features, the action set is the catalog, and the reward is sparse and delayed. The dominant tool is contextual bandits: at each step, observe a context, pick an arm, see a reward; treat each round as independent (no transitions). Thompson sampling and LinUCB dominate when the action set is bounded and stationary; for very large action sets, two-stage ranking (candidate generation + bandit-style re-ranker) is the standard production pattern. Full MDP-style RL appears mainly when there is meaningful long-horizon credit assignment (slate recommendation that must steer toward eventual subscription, not just next click).
In dialog systems and language models, the technique that crossed the chasm is RLHF. Christiano et al. [15] introduced the recipe: collect human preferences on pairs of trajectories, fit a reward model, and optimize the policy with PPO under a KL penalty against a frozen reference. The same machinery is the backbone of InstructGPT and ChatGPT; the dedicated chapter on RLHF and alignment walks through the full pipeline.
Pitfalls
The discounted return is , not with initialized as the last reward. At terminal step you set (no future) and . Off-by-one bugs here usually look like a policy that performs about right when episode lengths are similar but degrades badly with episode-length variance.
Adding a shaping reward to your environment does not change if and only if is potential-based: for some scalar potential . Anything else (a per-step penalty, a “reward for being near the goal”) can produce policies that exploit the shaping signal at the cost of the true objective. If your agent is “doing weirdly well at the proxy reward but failing at the task”, suspect non-potential shaping.
PPO uses a replay buffer of recent rollouts, but unlike DQN it cannot reuse data older than a few epochs: the importance-ratio clip is only valid when the data was collected by a policy not too different from the current one. If you keep a multi-million-step buffer and treat PPO like an off-policy method, the clip becomes a permanent saturation and the gradient is mostly zero. The right number of PPO epochs per buffer is small (typically to ); after that, refill.
is sometimes treated as a free dial. It is not: is a parameter of the objective, not a regularizer. Lowering makes the agent shortsighted; raising it amplifies bootstrap variance and makes the value scale grow without bound. Pick from the problem’s effective horizon ( is the rough horizon in steps) and keep it fixed.
Pop quiz
- 1. The Bellman optimality equation for V* is:
- 2. Q-learning is off-policy because:
- 3. DQN introduces a target network primarily to:
- 4. Generalized Advantage Estimation (GAE) addresses primarily:
- 5. In PPO, the clip function applied to the importance ratio rho_t = pi_theta(a_t|s_t) / pi_old(a_t|s_t) does what?
Interview Q&A
What is a Markov decision process and why does the Markov property matter?phone
An MDP is a tuple : a state set, an action set, a transition kernel , a reward function , and a discount factor . The agent picks actions according to a policy and seeks to maximize the expected discounted return .
The Markov property says that the next state and reward depend only on the current state and action, not on the history. This matters for two reasons. First, it lets you condition on alone when writing the Bellman equations: there is no term that integrates over the trajectory that led to . Second, it lets value functions and exist as well-defined real-valued maps (a non-Markov environment in principle requires a value function over histories, which is intractable). When the property fails, the standard fix is to expand the state to include enough history for it to hold, for example stacking the last four Atari frames in DQN [2]. Once the augmented state is Markov, all the standard machinery applies [1].
Why does DQN need both a replay buffer and a target network?onsite
The two stabilizers address two different pathologies of TD with function approximation.
Replay buffer (decorrelates samples). Online RL produces highly correlated transitions: the next observation looks almost identical to the previous one. SGD’s i.i.d. assumption is violated, so the gradient estimate is biased and the optimizer drifts. The replay buffer holds the last transitions; each minibatch is a uniform random sample. The samples are now approximately independent, the gradient estimate is unbiased, and as a bonus every transition gets reused many times, which is the key to DQN’s sample efficiency relative to on-policy methods.
Target network (kills the moving-target problem). The TD loss is if both sides use the same . Every gradient step changes the prediction and the target simultaneously, so the regression is chasing a moving target. Empirically the value diverges or oscillates wildly. DQN replaces the target side with a frozen copy , updated every steps:
The target is now fixed for steps; the loss is a normal regression problem on a static target; the optimizer makes progress; periodically refreshes the target. Soft target updates ( with ) are an alternative that diffuses the target instead of stepping it, used by DDPG, TD3, and SAC [11][10].
The two stabilizers are complementary. The replay buffer addresses sample correlation; the target network addresses self-bootstrapping. Removing either reliably destabilizes training in the original DQN ablation [2].
Derive the policy gradient theorem from scratch and explain why the transition model drops out.research
Setup. The objective is where is a trajectory and . We want .
Step 1: log-derivative trick. Differentiating under the integral and using the identity :
Step 2: only the policy depends on . Take the log of :
The initial-state distribution does not depend on , and the transition kernel is a property of the environment, not of the policy. Their gradients are zero. The only surviving term is the policy log-likelihood:
This is the reason policy gradient is model-free: the transition kernel’s contribution to has zero gradient, so we never need to know or estimate it.
Step 3: per-step credit and the baseline. Substituting,
The full return multiplies the gradient at every step, including rewards before . A causality argument (rewards before are uncorrelated with given ) lets us replace with the reward-to-go :
Subtracting any baseline that depends only on leaves the expectation unchanged (because ) but reduces variance. The optimal-variance baseline is approximately , which gives the advantage form:
REINFORCE [6] uses Monte Carlo as the advantage; actor-critic methods learn a critic for ; GAE [9] blends -step TD residuals smoothly. PPO [8] implements the same gradient under a clipped importance-ratio surrogate so it can take multiple gradient steps on the same rollout buffer without breaking the on-policy assumption.
Interactive Demo
Q-Learning Grid World
Q-Learning Grid World
Watch an agent learn to navigate a 5x5 grid from Start (top-left) to Goal (bottom-right) using Q-learning.
Value Iteration
Bellman Value Iteration
Watch values propagate backward from the goal state in a 4-state MDP.
References
- Sutton, R. S., and Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press. ISBN 978-0-262-03924-6
- Mnih, V., Kavukcuoglu, K., Silver, D., Rusu, A. A., Veness, J., Bellemare, M. G., Graves, A., Riedmiller, M., Fidjeland, A. K., Ostrovski, G., et al. (2015). Human-level control through deep reinforcement learning. Nature 518, 529-533. doi:10.1038/nature14236
- van Hasselt, H., Guez, A., and Silver, D. (2016). Deep Reinforcement Learning with Double Q-learning. AAAI 2016 (arXiv preprint 2015). arXiv:1509.06461
- Wang, Z., Schaul, T., Hessel, M., van Hasselt, H., Lanctot, M., and de Freitas, N. (2016). Dueling Network Architectures for Deep Reinforcement Learning. ICML 2016 (arXiv preprint 2015). arXiv:1511.06581
- Hessel, M., Modayil, J., van Hasselt, H., Schaul, T., Ostrovski, G., Dabney, W., Horgan, D., Piot, B., Azar, M., and Silver, D. (2018). Rainbow: Combining Improvements in Deep Reinforcement Learning. AAAI 2018 (arXiv preprint 2017). arXiv:1710.02298
- Williams, R. J. (1992). Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning 8, 229-256. doi:10.1007/BF00992696
- Schulman, J., Levine, S., Moritz, P., Jordan, M. I., and Abbeel, P. (2015). Trust Region Policy Optimization. ICML 2015 (arXiv preprint). arXiv:1502.05477
- Schulman, J., Wolski, F., Dhariwal, P., Radford, A., and Klimov, O. (2017). Proximal Policy Optimization Algorithms. arXiv preprint. arXiv:1707.06347
- Schulman, J., Moritz, P., Levine, S., Jordan, M. I., and Abbeel, P. (2015). High-Dimensional Continuous Control Using Generalized Advantage Estimation. ICLR 2016 (arXiv preprint 2015). arXiv:1506.02438
- Haarnoja, T., Zhou, A., Abbeel, P., and Levine, S. (2018). Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor. ICML 2018 (arXiv preprint). arXiv:1801.01290
- Lillicrap, T. P., Hunt, J. J., Pritzel, A., Heess, N., Erez, T., Tassa, Y., Silver, D., and Wierstra, D. (2015). Continuous Control with Deep Reinforcement Learning. ICLR 2016 (arXiv preprint 2015). arXiv:1509.02971
- Fujimoto, S., van Hoof, H., and Meger, D. (2018). Addressing Function Approximation Error in Actor-Critic Methods. ICML 2018 (arXiv preprint). arXiv:1802.09477
- Silver, D., Schrittwieser, J., Simonyan, K., Antonoglou, I., Huang, A., Guez, A., Hubert, T., Baker, L., Lai, M., Bolton, A., et al. (2017). Mastering the game of Go without human knowledge. Nature 550, 354-359. doi:10.1038/nature24270
- Schrittwieser, J., Antonoglou, I., Hubert, T., Simonyan, K., Sifre, L., Schmitt, S., Guez, A., Lockhart, E., Hassabis, D., Graepel, T., et al. (2020). Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model. Nature 588, 604-609 (arXiv preprint 2019). arXiv:1911.08265
- Christiano, P. F., Leike, J., Brown, T., Martic, M., Legg, S., and Amodei, D. (2017). Deep Reinforcement Learning from Human Preferences. NeurIPS 2017 (arXiv preprint). arXiv:1706.03741