Deep Reinforcement Learning: DQN, Policy Gradients and PPO
How neural networks let RL scale to pixels and huge state spaces: DQN, REINFORCE and policy gradients, actor-critic methods, PPO, AlphaGo/AlphaZero, and how the same machinery powers RLHF for language models.
Tabular Q-learning needs a separate entry for every state. An Atari screen has more possible pixel configurations than atoms in the universe, and Go has ~10¹⁷⁰ legal positions. Deep RL replaces the table with a neural network that *generalises*: similar states get similar values or actions. This combination produced superhuman Atari and Go players, agile robot controllers, and the RLHF stage that turns a raw language model into a helpful assistant — but it also inherits all of RL's instability plus the quirks of deep learning.
1. Value-based: Deep Q-Networks (DQN)
DQN (Mnih et al., 2013/2015)[1] feeds the last 4 game frames into a CNN that outputs one Q-value per joystick action, and trains it with the Q-learning target. Naively this diverges, so DQN added two stabilisers: experience replay (store transitions in a large buffer and train on random mini-batches, breaking the correlation between consecutive frames) and a target network (a frozen copy of the Q-network, refreshed every few thousand steps, used to compute targets so they do not move with every update). With one architecture and the same hyperparameters it reached human-level performance on many of 49 Atari games, learning directly from pixels and score.
- L(θ)
- the loss as a function of the online network's weights
- θ
- weights of the online Q-network (updated every step)
- θ⁻
- weights of the target network: a copy of θ refreshed every C steps
- E_(s,a,r,s′)~buffer
- average over transitions sampled at random from the replay buffer
- r
- reward of the sampled transition
- γ
- discount factor (0.99 in DQN)
- maxₐ′ Q(s′, a′; θ⁻)
- best next-state value according to the target network
- Q(s, a; θ)
- the online network's prediction for the action actually taken
- ²
- squared error: big mistakes are penalised much more than small ones
▸Worked example
2. Policy-based: policy gradients and REINFORCE
Instead of learning values and acting greedily, Policy gradient methods parametrise the policy directly, π_θ(a | s) — e.g. a network outputting action probabilities (or the mean of a Gaussian for continuous actions like joint torques) — and do gradient ascent on expected return. REINFORCE (Williams, 1992)[2] gives the simplest estimator: run an episode, then increase the log-probability of each action in proportion to the return that followed it. Good actions become more likely, bad ones less. It handles continuous and stochastic policies naturally but has high variance; subtracting a baseline b(s) (often a learned V(s)) reduces variance without adding bias.
- ∇_θ
- gradient with respect to the policy parameters θ
- J(θ)
- the objective: expected return when following π_θ
- E_π
- average over episodes generated by the policy π
- Σₜ
- sum over the time steps of an episode
- log π_θ(aₜ | sₜ)
- log-probability the policy gave to the action it took at step t
- Gₜ
- the return that followed step t
- b(sₜ)
- baseline, e.g. a learned value V(sₜ); subtracting it lowers variance without bias
▸Worked example
3. Actor-critic and advantages
Actor-critic methods combine both worlds: an actor (the policy) chooses actions, and a critic (a Value function network) evaluates them. Instead of waiting for the full return, the actor is updated with the advantage — how much better an action was than expected: Â ≈ r + γ·V(s′) − V(s). Generalized Advantage Estimation (GAE) blends one-step and multi-step estimates with a parameter λ, trading bias against variance. A2C/A3C, SAC, and PPO are all actor-critic algorithms.
4. PPO: the workhorse
Policy-gradient steps that are too large can wreck a good policy in one update, and because the data came from the old policy, you cannot simply recover. Proximal Policy Optimization (PPO) (Schulman et al., 2017)[3] limits how far the new policy may move from the one that collected the data. It computes the probability ratio rₜ(θ) between new and old policy and clips it to [1 − ε, 1 + ε], so there is no incentive to push the ratio further. This allows several epochs of mini-batch updates on each batch of experience — simple, robust, and the default choice for robotics, games and RLHF.
- L^CLIP(θ)
- the clipped surrogate objective (maximised)
- Eₜ[
- average over the time steps in the collected batch
- min(
- take the smaller of the two terms (the pessimistic bound)
- rₜ(θ)
- probability ratio new / old policy for the action taken; 1 = unchanged
- Âₜ
- advantage estimate (e.g. from GAE): > 0 better than expected, < 0 worse
- clip(
- clip(x, lo, hi) limits x to the range [lo, hi]
- ε
- epsilon, the clip range (typically 0.1–0.2)
- π_θ(aₜ|sₜ)
- probability of the action under the policy being trained
- π_θold(aₜ|sₜ)
- probability under the policy that collected the data
▸Worked example
| Family | Examples | Learns | Good for | Watch out |
|---|---|---|---|---|
| Value-based | DQN, Double DQN, Rainbow | Q(s, a) | Discrete actions; sample-efficient (off-policy replay) | Overestimation, instability; awkward for continuous actions |
| Policy gradient | REINFORCE | π(a | s) | Simple, any action space, stochastic policies | High variance, needs many samples |
| Actor-critic | A2C, PPO, SAC | π(a | s) + V(s) or Q(s, a) | Robotics, games, RLHF; the modern default | More hyperparameters; critic errors mislead the actor |
5. AlphaGo and AlphaZero: learning plus search
AlphaGo (Silver et al., 2016)[4] combined a policy network (which moves look promising), a value network (who is winning) and Monte Carlo Tree Search (MCTS) that uses both to look ahead. The networks were first trained on human expert games, then improved by self-play RL; AlphaGo beat European champion Fan Hui 5–0 and, in March 2016, world champion Lee Sedol 4–1. AlphaZero (Silver et al., 2017)[5] removed human data entirely: starting from random play and knowing only the rules, a single algorithm learned chess, shogi and Go through self-play, where MCTS acts as a policy improvement operator — the network is trained to imitate the stronger search results and to predict the game outcome.
6. The link to LLMs: RLHF
In RLHF, the language model is the policy: the state is the prompt plus text so far, an action is the next token, and an episode is one full response. A Reward model trained on human preference comparisons scores the finished response. PPO then updates the LLM to increase that score, with a KL penalty that keeps it close to the supervised starting model — otherwise it would drift into gibberish that happens to fool the reward model (reward hacking). Newer methods such as DPO optimise the same preference objective without an explicit RL loop. See the *fine-tuning & alignment* lesson in the LLM module for details.
- max_π
- choose the policy (the LLM's weights) that maximises the expression
- E_x,y~π
- average over prompts x and responses y sampled from the policy
- r_φ(x, y)
- score from the reward model with parameters φ, trained on human preferences
- β
- beta, strength of the KL penalty (e.g. 0.01–0.1)
- KL(
- Kullback–Leibler divergence: how different two probability distributions are (0 = identical)
- ‖
- separates the two distributions being compared in the KL
- π(· | x)
- the policy's distribution over responses for prompt x
- π_ref(· | x)
- the frozen reference model (the SFT model before RL)
▸Worked example
The knobs
- What it is
- Step size of the optimizer (usually Adam) for policy and value networks.
- ↑ If you increase it
- Faster early progress, but RL is far more fragile than supervised learning: returns can collapse suddenly and never recover.
- ↓ If you decrease it
- Stable but slow; may need many more environment steps.
- Typical values
- 3e-4 for PPO (often linearly annealed); 1e-4 to 6.25e-5 for DQN on Atari; ~1e-6 for RLHF on large LLMs.
- What it is
- How far the probability ratio between new and old policy may move before the objective stops rewarding it.
- ↑ If you increase it
- Bigger policy updates per batch: faster but riskier, approaching unclipped policy gradient behaviour.
- ↓ If you decrease it
- Very conservative updates; stable but slow learning.
- Typical values
- 0.1–0.3; 0.2 is the common default.
- What it is
- Mixes short (λ = 0, one-step TD) and long (λ = 1, full Monte Carlo return) advantage estimates.
- ↑ If you increase it
- Less bias from an imperfect critic, but higher variance.
- ↓ If you decrease it
- Lower variance, but relies more on the critic's (possibly wrong) estimates.
- Typical values
- 0.9–0.99; 0.95 is standard.
- What it is
- Weight of a bonus for keeping the policy's action distribution spread out — the deep-RL counterpart of ε for exploration.
- ↑ If you increase it
- More exploration, slower convergence; too high keeps the policy near-random.
- ↓ If you decrease it
- Faster commitment to a strategy; risk of premature convergence to a poor one.
- Typical values
- 0–0.01 (0.01 for Atari PPO).
- What it is
- How many past transitions DQN stores, and how often the target network is synced with the online network.
- ↑ If you increase it
- Larger buffer: more diverse, decorrelated data, but older (staler) experience. Less frequent target updates: more stable but slower-moving targets.
- ↓ If you decrease it
- Small buffer: the agent overfits to recent experience and forgets. Frequent target syncs: targets chase themselves and training may diverge.
- Typical values
- Buffer 10⁵–10⁶ transitions; target sync every 1k–10k steps.
- What it is
- Strength of the penalty for drifting away from the reference (SFT) model.
- ↑ If you increase it
- Output stays fluent and close to the original model, but improves less on the reward.
- ↓ If you decrease it
- Higher reward-model scores, but more reward hacking: verbose, sycophantic or odd text that games the reward model.
- Typical values
- ≈ 0.01–0.1, sometimes adapted to hit a target KL.
In code: PPO with Stable-Baselines3
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
env = gym.make("CartPole-v1")
model = PPO("MlpPolicy", env,
learning_rate=3e-4, n_steps=2048, batch_size=64, n_epochs=10,
gamma=0.99, gae_lambda=0.95, clip_range=0.2, ent_coef=0.0,
seed=0, verbose=1)
model.learn(total_timesteps=100_000)
mean_r, std_r = evaluate_policy(model, env, n_eval_episodes=20)
print(f"return: {mean_r:.1f} +/- {std_r:.1f}") # CartPole max is 500import torch
def ppo_policy_loss(logp_new, logp_old, adv, clip=0.2):
ratio = torch.exp(logp_new - logp_old) # r_t(theta)
unclipped = ratio * adv
clipped = torch.clamp(ratio, 1 - clip, 1 + clip) * adv
return -torch.min(unclipped, clipped).mean() # minimise the negative▸Go deeper: why the log-derivative trick works
We want ∇_θ E_{τ~π_θ}[R(τ)], but the expectation is over trajectories sampled from the policy itself, and the environment is not differentiable. Using ∇p = p·∇log p, the gradient becomes E[R(τ)·∇_θ log p_θ(τ)]. The environment's transition probabilities do not depend on θ, so they drop out of ∇log p_θ(τ), leaving Σₜ ∇_θ log π_θ(aₜ | sₜ). We can therefore estimate the gradient purely from sampled episodes — no model of the environment needed. Replacing R(τ) with the reward-to-go and subtracting a baseline keeps the estimate unbiased while cutting variance[6].
Quiz
References
- [1]Human-level control through deep reinforcement learningPaperMnih et al.2015doi.orgNature DQN paper; first version: arXiv 1312.5602 (2013).
- [2]Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement LearningPaperWilliams1992doi.orgREINFORCE.
- [3]Proximal Policy Optimization AlgorithmsPaperSchulman et al.2017arxiv.org
- [4]Mastering the game of Go with deep neural networks and tree searchPaperSilver et al.2016doi.orgAlphaGo (Nature).
- [5]Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning AlgorithmPaperSilver et al.2017arxiv.orgAlphaZero.
- [6]Spinning Up in Deep RL — Part 3: Intro to Policy OptimizationCourseOpenAI (Achiam)spinningup.openai.com