AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↻Reinforcement Learning
  1. Reinforcement Learning Basics: Agents, Rewards and Q-learning
  2. Deep Reinforcement Learning: DQN, Policy Gradients and PPO
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Reinforcement Learning

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.

Advanced~30 min·6 references
Key terms
Reinforcement learning (RL)Q-learningPolicy gradientProximal Policy Optimization (PPO)Value functionRLHF (Reinforcement Learning from Human Feedback)Reward model

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.

≈
Analogy: from a notebook to intuition
A beginner chess player might keep a notebook: “in exactly this position, this move was good”. That never generalises — the exact position rarely repeats. A strong player instead has intuition: they recognise patterns (an open file, a weak king) and judge new positions by analogy. A deep RL network is that intuition, learned from millions of games.

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(θ) = E_(s,a,r,s′)~buffer [ ( r + γ · maxₐ′ Q(s′, a′; θ⁻) − Q(s, a; θ) )² ]
θ⁻ are the target-network weights. Variants: Double DQN (reduces overestimation), dueling networks, prioritized replay.
In words: “the average squared TD error over transitions sampled from the replay buffer”. The target uses the frozen weights θ⁻, the prediction uses the trained weights θ, and gradient descent on this loss moves Q(s, a; θ) toward the target.
Symbols(hover a symbol in the formula)
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
Minibatch of 2, γ = 0.99 1) r = 1, maxₐ′ Q(s′, a′; θ⁻) = 2.0, Q(s, a; θ) = 2.5 target = 1 + 0.99 · 2.0 = 2.98 error² = (2.98 − 2.5)² = 0.2304 2) terminal, r = 0 → target = 0, Q(s, a; θ) = 0.3 error² = 0.09 L = (0.2304 + 0.09) / 2 = 0.1602
Loading interactive…
DQN as in the Nature paper: acting on the top row, learning below. Walk through the 8 steps and watch how a transition goes into the replay buffer and comes back later in a random minibatch. Tap Target network θ⁻ to see why the targets are computed with a frozen copy.

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.

∇_θ J(θ) = E_π [ Σₜ ∇_θ log π_θ(aₜ | sₜ) · (Gₜ − b(sₜ)) ]
The policy-gradient theorem with a baseline (REINFORCE).
In words: “to increase expected return, push up the log-probability of each action you took, in proportion to how much better its return was than the baseline”. Actions followed by above-average returns become more likely, below-average ones less likely.
Symbols(hover a symbol in the formula)
∇_θ
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
Two actions, logits z = [0, ln 3] → π = [0.25, 0.75]. The agent took “left”, Gₜ = 10, b(sₜ) = 6 → advantage 4 ∇_z log π(left) = onehot − π = [1 − 0.25, 0 − 0.75] = [0.75, −0.75] × 4 = [3, −3]; step 0.01 → z = [0.03, 1.069] new π(left) = 0.261 (was 0.25) → the good action became more likely.

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(θ) = Eₜ[ min( rₜ(θ)·Âₜ , clip(rₜ(θ), 1−ε, 1+ε)·Âₜ ) ], rₜ(θ) = π_θ(aₜ|sₜ) / π_θold(aₜ|sₜ)
The full PPO loss also includes a value-function loss and an entropy bonus.
In words: “improve the policy in the direction of the advantage, but stop counting any improvement once the probability ratio has moved more than ε away from 1”. Taking the minimum makes the objective pessimistic, so there is no reward for overly large policy changes.
Symbols(hover a symbol in the formula)
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
ε = 0.2. Good action: Âₜ = 2, π_θ = 0.6, π_θold = 0.4 → rₜ = 1.5 unclipped 1.5 · 2 = 3.0, clipped 1.2 · 2 = 2.4 → min = 2.4 (no gain from raising rₜ further) Bad action: Âₜ = −1, rₜ = 0.5 unclipped −0.5, clipped 0.8 · (−1) = −0.8 → min = −0.8 (no gain from lowering rₜ below 0.8)
Loading interactive…
PPO end to end: rollout, GAE, then the three loss terms. Walk through it and notice the two phases — the policy first collects data, then learns from that same batch for several epochs. Tap Clipped surrogate and GAE to see where ε and λ act.
FamilyExamplesLearnsGood forWatch out
Value-basedDQN, Double DQN, RainbowQ(s, a)Discrete actions; sample-efficient (off-policy replay)Overestimation, instability; awkward for continuous actions
Policy gradientREINFORCEπ(a | s)Simple, any action space, stochastic policiesHigh variance, needs many samples
Actor-criticA2C, PPO, SACπ(a | s) + V(s) or Q(s, a)Robotics, games, RLHF; the modern defaultMore 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_π E_x,y~π [ r_φ(x, y) ] − β · KL( π(· | x) ‖ π_ref(· | x) )
The RLHF objective: reward minus a KL leash to the reference model.
In words: “make the model's responses score high with the reward model, but pay a penalty for drifting away from the reference model”. β sets how tight the leash is: too small invites reward hacking, too large means little improvement.
Symbols(hover a symbol in the formula)
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
β = 0.1 Response A: r_φ = 2.0, KL = 5 → 2.0 − 0.1 · 5 = 1.5 Response B: r_φ = 2.6, KL = 15 → 2.6 − 0.1 · 15 = 1.1 B fools the reward model a bit more but drifted far from the reference, so A is preferred.

The knobs

knoblearning_rate
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.
knobclip_range (PPO ε)
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.
knobgae_lambda (λ)
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.
knobent_coef (entropy bonus)
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).
knobreplay buffer size / target update (DQN)
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.
knobKL coefficient β (RLHF)
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

python
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 500
The values shown are SB3's PPO defaults. Always report results over several seeds.
python
import 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
The heart of PPO in five lines.
!
Common pitfalls
Seed sensitivity: the same algorithm and hyperparameters can succeed on one seed and fail on another — average over ≥ 5 seeds and show confidence intervals. Sample inefficiency: millions of environment steps are normal; real robots need simulators, and policies then suffer a *sim-to-real gap*. Unnormalised observations and rewards destabilise training — use running normalisation. Reward hacking gets worse with more capable optimisers, including LLMs under RLHF. The deadly triad — function approximation + bootstrapping + off-policy data — can make value estimates diverge; replay, target networks and Double DQN are partial cures.
▸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

1.
What problem does DQN's target network solve?
2.
Why does REINFORCE subtract a baseline b(s) from the return?
3.
In PPO with ε = 0.2, the advantage of an action is positive and the ratio rₜ(θ) is already 1.35. What does the clipped objective do?
4.
What was the key difference between AlphaZero and the original AlphaGo?
5.
During RLHF you set the KL coefficient β to almost zero. What is the most likely outcome?
Score: 0/5

References

  1. [1]
    Human-level control through deep reinforcement learning
    PaperMnih et al.2015doi.org
    Nature DQN paper; first version: arXiv 1312.5602 (2013).
  2. [2]
    Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning
    PaperWilliams1992doi.org
    REINFORCE.
  3. [3]
    Proximal Policy Optimization Algorithms
    PaperSchulman et al.2017arxiv.org
  4. [4]
    Mastering the game of Go with deep neural networks and tree search
    PaperSilver et al.2016doi.org
    AlphaGo (Nature).
  5. [5]
    Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm
    PaperSilver et al.2017arxiv.org
    AlphaZero.
  6. [6]
    Spinning Up in Deep RL — Part 3: Intro to Policy Optimization
    CourseOpenAI (Achiam)spinningup.openai.com
← Previous
Reinforcement Learning Basics: Agents, Rewards and Q-learning
Next → · ML Development & MLOps
The ML development stack