AnyLearn
All lessons
AIadvanced

Policy Gradients and Deep RL

Tabular methods break down when the state space is continuous or astronomical in size. Learn how neural networks extend RL via DQN, how the policy gradient theorem makes it possible to differentiate through stochastic policies, and where actor-critic, PPO, and the deadly triad fit into the picture.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 10

Why tabular methods don't scale

Every algorithm in the previous lessons stores one number per state (or state-action pair). For Atari, the raw pixel state space has roughly 1056,00010^{56{,}000} distinct frames — storing a table is physically impossible. For continuous control (robot joints, financial portfolios), the state space isn't even countable.

Function approximation replaces the table with a parameterised function V^(s;θ)\hat{V}(s;\theta) or Q^(s,a;θ)\hat{Q}(s,a;\theta), where θ\theta are the weights of a neural network. The network generalises from visited states to nearby unseen ones.

The shift introduces new failure modes: the value function is no longer guaranteed to converge, updates can destabilise each other, and the "deadly triad" can cause divergence. Understanding these risks is as important as understanding the algorithms.

Full lesson text

All 10 steps on one page — for reading, reference, and search.

Show

1. Why tabular methods don't scale

Every algorithm in the previous lessons stores one number per state (or state-action pair). For Atari, the raw pixel state space has roughly 1056,00010^{56{,}000} distinct frames — storing a table is physically impossible. For continuous control (robot joints, financial portfolios), the state space isn't even countable.

Function approximation replaces the table with a parameterised function V^(s;θ)\hat{V}(s;\theta) or Q^(s,a;θ)\hat{Q}(s,a;\theta), where θ\theta are the weights of a neural network. The network generalises from visited states to nearby unseen ones.

The shift introduces new failure modes: the value function is no longer guaranteed to converge, updates can destabilise each other, and the "deadly triad" can cause divergence. Understanding these risks is as important as understanding the algorithms.

2. DQN: deep Q-learning that actually works

Deep Q-Network (DQN) — Mnih et al., 2015 — brought Q-learning to Atari using two stabilising tricks:

1. Experience replay. Transitions (s,a,r,s)(s,a,r,s') are stored in a replay buffer of size 10610^6. Mini-batches are sampled uniformly at training time. This breaks temporal correlations that make online updates diverge and allows each transition to be reused many times.

2. Target network. A separate copy of the Q-network θ\theta^- is frozen for CC steps and used to compute TD targets: yt=r+γmaxaQ(s,a;θ)y_t = r + \gamma \max_{a'} Q(s', a'; \theta^-) Without freezing, the target yty_t moves every update step, chasing a moving target — a major source of instability. Every CC steps, θθ\theta^- \leftarrow \theta.

3. DQN training loop

Experience flows through the replay buffer; the target network provides stable TD targets.

flowchart TD
  A["Agent acts with epsilon-greedy policy"]
  B["Store transition (s, a, r, s') in replay buffer"]
  C["Sample random mini-batch from buffer"]
  D["Compute TD target using frozen target network"]
  E["Minimise MSE loss, update online network theta"]
  F["Every C steps: copy theta to target network theta-"]
  A --> B
  B --> C
  C --> D
  D --> E
  E --> F
  F --> A

4. The policy gradient theorem

Value-based methods derive a policy by taking the argmax of QQ. But argmax is not differentiable, and it collapses to deterministic policies — bad for games requiring mixed strategies or continuous action spaces.

Policy gradient methods directly parameterise the policy πθ(as)\pi_\theta(a \mid s) and optimise the objective J(θ)=Eτπθ[G0]J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[G_0].

The policy gradient theorem (Sutton et al., 1999) gives the exact gradient:

θJ(θ)=Eπθ ⁣[tθlogπθ(atst)Qπθ(st,at)]\nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta}\!\left[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot Q^{\pi_\theta}(s_t, a_t)\right]

The logπθ\log \pi_\theta term is the score function — tractable even when the reward function is non-differentiable. This is the REINFORCE estimator at its core.

5. REINFORCE and the baseline trick

REINFORCE replaces Qπθ(st,at)Q^{\pi_\theta}(s_t, a_t) with the sampled return GtG_t:

θJ1Ttθlogπθ(atst)Gt.\nabla_\theta J \approx \frac{1}{T} \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot G_t.

This is unbiased but extremely high variance. The standard fix: subtract a baseline b(s)b(s), typically Vπ(s)V^\pi(s):

θJ1Ttθlogπθ(atst)(GtV(st))advantage At.\nabla_\theta J \approx \frac{1}{T} \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot \underbrace{(G_t - V(s_t))}_{\text{advantage } A_t}.

Subtracting any function of ss alone doesn't bias the gradient (the expectation of the subtracted term is zero), but it can massively reduce variance. The quantity At=GtV(st)A_t = G_t - V(s_t) is the advantage — how much better action ata_t was than the average.

# Minimal REINFORCE with baseline
for ep_states, ep_actions, ep_rewards in episodes:
    returns = compute_discounted_returns(ep_rewards, gamma)
    baselines = value_net(ep_states)          # V(s)
    advantages = returns - baselines.detach() # A_t
    log_probs = policy_net.log_prob(ep_states, ep_actions)
    policy_loss = -(log_probs * advantages).mean()
    value_loss = F.mse_loss(baselines, returns)
    (policy_loss + value_loss).backward()
    optimizer.step(); optimizer.zero_grad()

6. Actor-critic methods

Actor-critic replaces the Monte Carlo return GtG_t with a bootstrapped estimate, combining the low-variance benefit of TD with the policy gradient framework:

θJtθlogπθ(atst)(rt+γVϕ(st+1)Vϕ(st))TD error=A^t\nabla_\theta J \approx \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot \underbrace{\left(r_t + \gamma V_\phi(s_{t+1}) - V_\phi(s_t)\right)}_{\text{TD error} = \hat{A}_t}

Two networks: the actor πθ\pi_\theta chooses actions; the critic VϕV_\phi estimates value and provides the advantage signal. They share a common feature extractor in many implementations.

Actor-critic methods sit at the intersection of policy gradient (for the actor) and value-based methods (for the critic). A2C (synchronous), A3C (asynchronous), and PPO are all actor-critic variants. The main hyperparameter tension: a critic that is too noisy introduces bias; a critic that is too old introduces staleness.

7. PPO: the workhorse of modern deep RL

Proximal Policy Optimization (PPO) — Schulman et al., 2017 — is the de-facto standard for continuous control and the algorithm behind most instruction-tuned LLMs (RLHF).

The core idea: after collecting a batch of experience with πθold\pi_{\theta_{old}}, update θ\theta multiple times on that batch, but clip the probability ratio rt(θ)=πθ(atst)/πθold(atst)r_t(\theta) = \pi_\theta(a_t|s_t) / \pi_{\theta_{old}}(a_t|s_t) to stay within [1ϵ,1+ϵ][1-\epsilon, 1+\epsilon]:

LCLIP(θ)=Et ⁣[min(rt(θ)A^t,clip(rt(θ),1 ⁣ ⁣ϵ,1 ⁣+ ⁣ϵ)A^t)].L^{\text{CLIP}}(\theta) = \mathbb{E}_t\!\left[\min\left(r_t(\theta)\hat{A}_t, \text{clip}(r_t(\theta), 1\!-\!\epsilon, 1\!+\!\epsilon)\hat{A}_t\right)\right].

The clip prevents destructively large policy updates without the complexity of a KL-constrained trust region (TRPO). PPO is stable, parallelises trivially over CPU workers, and achieves near-TRPO sample efficiency at a fraction of the implementation cost.

8. The deadly triad

Sutton and Barto name three ingredients that, combined, can cause Q-learning with function approximation to diverge:

IngredientExample
BootstrappingTD targets use the current value estimate
Off-policy dataReplay buffer from old policies
Function approximationNeural network for QQ

Each alone is fine. Pairs are usually fine. All three together can produce runaway updates: the value function spirals to infinity even as the policy appears to be improving.

DQN succeeds despite using all three because the target network partially breaks the bootstrapping feedback loop, and uniform replay partially compensates for distributional shift. Rainbow, C51, and IQN add further stabilisers. This is why RL engineering feels fragile — you're navigating the deadly triad by luck and engineering discipline, not by theoretical guarantees.

9. Value-based vs policy gradient: when to use which

Neither family dominates across all tasks:

Value-based (DQN family)Policy gradient (PPO family)
Action spaceDiscreteDiscrete or continuous
Sample efficiencyHigher (replay)Lower (on-policy)
StabilityTricky (deadly triad)More stable with clipping
Stochastic policiesNot naturallyYes, by design
Off-policy learningYesNo (PPO is on-policy)
RLHF / LLM fine-tuningRarePPO is standard

Practical guidance: for discrete action Atari-style games, DQN/Rainbow; for continuous control (MuJoCo, robotics), PPO or SAC; for LLM alignment, PPO or GRPO.

10. Where deep RL is heading

Four active frontiers:

  • Offline RL (CQL, IQL): learn from a fixed dataset with no online interaction — closes the gap between RL and supervised learning pipelines.
  • Model-based RL (DreamerV3, MuZero): learn a world model and plan inside it, dramatically improving sample efficiency.
  • Multi-agent RL (MARL): multiple agents share an environment; equilibria replace optimal policies.
  • RLHF and RLAIF: reward models trained from human or AI feedback drive policy optimization for language models. PPO's clipping trick scales surprisingly well to billion-parameter actors.

The Bellman equation you learned in lesson 1 is still the core of every frontier above. The innovations sit in the approximate infrastructure built around it — function approximators, replay, exploration, and credit assignment.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. DQN uses a target network that is periodically frozen. What instability does this address?
    • Without a target network, the replay buffer becomes correlated with the current policy.
    • Without a target network, the TD target $y_t$ shifts every gradient step, creating a moving-target problem that destabilises learning.
    • The target network prevents the Q-values from becoming negative during training.
    • Without a target network, the agent cannot perform epsilon-greedy exploration.
  2. The policy gradient theorem gives $\nabla_\theta J = \mathbb{E}[\nabla_\theta \log \pi_\theta(a|s) \cdot Q^\pi(s,a)]$. Why use $\log \pi_\theta$ rather than $\pi_\theta$ directly?
    • Log probabilities are numerically more stable and prevent underflow in long episodes.
    • The score function $\nabla_\theta \log \pi_\theta$ is tractable even when the reward is non-differentiable, via the log-derivative trick.
    • Taking the log converts the policy gradient from a sum into a product, simplifying computation.
    • $\log \pi_\theta$ ensures the gradient is always non-negative, making optimization easier.
  3. Subtracting a baseline $b(s)$ from the REINFORCE return $G_t$ is valid because:
    • It reduces bias by correcting for the mean reward in each state.
    • The gradient of $\mathbb{E}[\nabla_\theta \log \pi_\theta \cdot b(s)]$ is zero, so the baseline doesn't change the expected gradient.
    • The baseline normalises the returns to have unit variance.
    • It converts the on-policy estimator into an off-policy one, enabling replay.
  4. What is the 'deadly triad' in deep RL, and why does it cause divergence?
    • High learning rate, large batch size, and non-linear activation functions destabilise gradient descent.
    • Bootstrapping, off-policy data, and function approximation together can cause value estimates to spiral unboundedly.
    • Exploration noise, reward sparsity, and long horizons make credit assignment impossible.
    • Replay buffer, target network, and epsilon-greedy exploration interfere with each other's convergence guarantees.
  5. PPO clips the probability ratio $r_t(\theta) = \pi_\theta(a|s) / \pi_{\theta_{old}}(a|s)$. What problem does this solve compared to vanilla policy gradients?
    • It converts the on-policy gradient into an off-policy one, allowing replay buffer reuse.
    • It prevents destructively large policy updates that can collapse performance when advantages are large.
    • It removes the need for a value network by normalising returns directly.
    • It ensures the policy entropy stays above a minimum threshold, preventing premature convergence.

Related lessons