Lab: Policy Gradients from REINFORCE to Actor-Critic
Implement policy gradient optimization: derive the Policy Gradient Theorem, compute Monte Carlo returns with baseline variance reduction in REINFORCE, and transition to Actor-Critic architectures and Proximal Policy Optimization (PPO) with clipped surrogate objectives.
Contentsand lesson path
On this page
Lessons of Reinforcement Learning Foundations
- Agents, Rewards and Returns: Framing Decisions as an MDP Concept · 20 min
- Worked Example: Explore or Exploit? Bandit Strategies Compared Worked example · 20 min
- Lab: From a Q-Table to a Deep Q-Network Lab · 30 min
- Lab: Policy Gradients from REINFORCE to Actor-Critic Lab · 30 min
- Rewards for Language Models: RLHF, GRPO and Their Failure Modes Concept · 20 min
- Check: Pick and Debug an RL Approach Knowledge check · 8 questions
What you will learn
- Implement a policy-gradient agent (REINFORCE with a baseline) and explain how actor-critic methods and PPO's clipped objective reduce variance and stabilize updates.
Prerequisites: Deep Learning Fundamentals
01. Policy Search, Variance Reduction, and Trust Region Methods
Value-based methods like DQN learn an action-value function $Q(s, a)$ and choose actions indirectly via greedy maximization $\arg\max_a Q(s, a)$. While effective for discrete action spaces, value-based methods struggle in continuous control domains (such as robotics, autonomous driving, or high-dimensional motor torque control) where computing the continuous maximum $\max_a Q(s, a)$ requires solving an expensive non-convex optimization problem at every single environment step. Policy Gradient methods parameterize the policy directly as a neural network $\pi_\theta(a \mid s)$ and optimize parameters $\theta$ via gradient ascent directly on expected return $J(\theta) = \mathbb{E}{\tau \sim \pi\theta}[G(\tau)]$.
- The Policy Gradient Theorem: A naive gradient $\nabla_\theta \mathbb{E}[R(\tau)]$ might seem impossible to compute without knowing environmental transition dynamics $\mathcal{P}(s' \mid s, a)$. The foundational Policy Gradient Theorem (Sutton et al., 1999) proved that environmental transition probabilities vanish entirely from the gradient expression using the log-derivative trick $\nabla_\theta P(\tau) = P(\tau) \nabla_\theta \log P(\tau)$:
$$\nabla_\theta J(\theta) = \mathbb{E}{\tau \sim \pi\theta}\left[ \sum_{t=0}^T \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot G_t \right]$$
This formulation has an intuitive interpretation: if a trajectory yielded a high cumulative return $G_t$, the gradient step increases the log-probability of taking those specific actions in those states; if return was poor or negative, the probability is suppressed.
-
REINFORCE and the High-Variance Limitation: Williams (1992) introduced the REINFORCE algorithm, estimating the gradient via Monte Carlo rollouts. Because REINFORCE relies on empirical sample returns $G_t = \sum_{k=0}^{T-t-1} \gamma^k r_{t+k+1}$, it is an unbiased estimator of the policy gradient. However, because Monte Carlo trajectories accumulate stochasticity across hundreds of steps, the gradient estimate exhibits extreme statistical variance, requiring tens of thousands of sample episodes to converge.
-
Variance Reduction via State-Value Baselines ($b(s)$): Subtracting an arbitrary baseline function $b(s_t)$ that depends only on state (and not on action $a_t$) preserves the mathematical expectation of the gradient: $\mathbb{E}[\nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot b(s_t)] = 0$. By setting $b(s_t) = V_\phi(s_t)$ using a learned critic network, the return weight becomes the Advantage Function:
$$A(s_t, a_t) = Q(s_t, a_t) - V(s_t) \approx G_t - V_\phi(s_t)$$
Subtracting the baseline centers rewards around zero: an action is reinforced only if it performed better than expected for that state, dramatically slashing gradient variance without introducing bias.
- Actor-Critic Architectures: To further eliminate the latency of waiting for full trajectory completion, Actor-Critic models replace Monte Carlo return $G_t$ with single-step bootstrapped TD advantages:
$$\delta_t = r_{t+1} + \gamma V_\phi(s_{t+1}) - V_\phi(s_t)$$
-
The Actor ($\pi_\theta$): Proposes actions conditioned on state, parameterized by policy weights $\theta$.
-
The Critic ($V_\phi$): Evaluates states, parameterized by value weights $\phi$ trained via MSE against bootstrapped Bellman targets. Actor-Critic methods trade slight bias (introduced by bootstrapping from function approximation) for vastly lower variance, enabling online step-by-step policy updates.
-
Proximal Policy Optimization (PPO - Clipped Surrogate Objective): Standard policy gradient methods suffer from catastrophic policy collapse: if a single gradient update takes too large a step, the policy shifts into a dysfunctional parameter regime, collecting corrupted rollouts from which it can never recover. Schulman et al. (2017) introduced Proximal Policy Optimization (PPO). Defining the probability ratio $r_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{\text{old}}}(a_t \mid s_t)}$, PPO optimizes a clipped surrogate objective:
$$L^{\text{CLIP}}(\theta) = \hat{\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 clipping operator (typically with $\epsilon = 0.2$) penalizes large probability ratios whenever the advantage $\hat{A}_t$ would otherwise push parameter updates outside a safe trust region $[1 - \epsilon, 1 + \epsilon]$. PPO combines the sample efficiency and stability of trust region methods (TRPO) with the algorithmic simplicity of standard stochastic gradient descent, establishing itself as the default workhorse across robotics and LLM alignment.
-
Entropy Regularization for Sustained Exploration: Stochastic policy networks often collapse prematurely into deterministic actions before adequately exploring high-value alternatives. Production implementations augment the objective with an entropy bonus: $L(\theta) = L^{\text{CLIP}}(\theta) + c_2 \mathcal{H}(\pi_\theta(\cdot \mid s_t))$, penalizing low policy distribution entropy and preventing premature convergence.
-
Generalized Advantage Estimation (GAE - Calibrating Bias vs Variance): Schulman et al. (2015) unified single-step TD advantages and multi-step Monte Carlo returns through Generalized Advantage Estimation (GAE($\gamma, \lambda$)), defining an exponentially weighted moving average of $k$-step advantage estimators:
$$\hat{A}t^{\text{GAE}(\gamma, \lambda)} = \sum{l=0}^{\infty} (\gamma \lambda)^l \delta_{t+l}^V, \quad \text{where } \delta_t^V = r_{t+1} + \gamma V(s_{t+1}) - V(s_t)$$
The mixing hyperparameter $\lambda \in [0, 1]$ smoothly interpolates between extremes: setting $\lambda = 0$ reduces GAE to the single-step TD residual (lowest variance, highest bias), while $\lambda = 1$ recovers the full Monte Carlo return baseline (unbiased, highest variance). In empirical robotics and game environments, $\lambda \approx 0.95$ yields an optimal empirical trade-off.
-
Parallelism in Asynchronous (A3C) and Synchronous (A2C) Architectures: Unlike value-based DQN which requires an explicit experience replay buffer to decorrelate transitions, Actor-Critic algorithms utilize parallelized environmental workers. In Synchronous Actor-Critic (A2C), a centralized coordinator coordinates $N$ parallel worker environments running simultaneously on separate CPU threads. Workers execute actions, collect step transitions, and synchronously aggregate mini-batch gradients on GPU devices, breaking temporal correlations naturally while maximizing vectorized hardware acceleration.
-
Continuous Action Spaces and Multivariate Gaussian Policies: When controlling physical systems with continuous actuators (such as drone quadrotor thrust or autonomous steering angles), discrete softmax policies cannot be applied. Instead, the Actor neural network outputs the parameters of a multivariate Gaussian distribution: continuous mean vector $\mu_\theta(s)$ and diagonal log-variance vector $\log \sigma^2_\theta(s)$. Action selection samples $a \sim \mathcal{N}(\mu_\theta(s), \Sigma_\theta(s))$, and log-likelihood gradients evaluate analytically: $\nabla_\theta \log \pi_\theta(a \mid s) = \Sigma_\theta^{-1}(a - \mu_\theta(s)) \nabla_\theta \mu_\theta(s)$.
-
Orthogonal Weight Initialization and Global Gradient Clipping: Engineering production stability in deep PPO implementations relies on precise numerical hygiene. Policy and value networks utilize orthogonal weight initialization: hidden layers use gain $\sqrt{2}$ to preserve variance across ReLU activations, while policy output heads use gain $0.01$ to ensure initial action distributions remain near-uniform. Furthermore, implementations strictly enforce global gradient norm clipping (typically $|g|_2 \le 0.5$), shielding neural parameters against transient gradient spikes induced by noisy advantage estimates.
import torch
def compute_ppo_clipped_surrogate(log_probs, old_log_probs, advantages, eps=0.2):
# Probability ratio r_t(theta)
ratio = torch.exp(log_probs - old_log_probs)
# Unclipped surrogate objective
surr1 = ratio * advantages
# Clipped surrogate objective
surr2 = torch.clamp(ratio, 1.0 - eps, 1.0 + eps) * advantages
# Conservative pessimistic lower bound
loss = -torch.min(surr1, surr2).mean()
return loss, ratio.mean().item()
# Test clipped surrogate calculation with positive advantages
adv = torch.tensor([1.5, 0.8, -0.5])
curr_lp = torch.tensor([-0.2, -0.5, -1.2])
old_lp = torch.tensor([-0.4, -0.5, -0.9])
loss, avg_ratio = compute_ppo_clipped_surrogate(curr_lp, old_lp, adv)
print(f"PPO Loss: {loss.item():.4f}, Mean Probability Ratio: {avg_ratio:.4f}")
=== PPO CLIPPED SURROGATE AUDIT ===
Evaluated Step Transitions: 3 action advantages
PPO Loss: -0.6695, Mean Probability Ratio: 1.0965
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.