[2.2.2] - VPG

Colab: exercises | solutions

Please send any problems / bugs on the #errata channel in the Slack group, and ask any questions on the dedicated channels for this chapter of material.

If you want to change to dark mode, you can do this by clicking the theme toggle button (sun / moon icon) in the top navigation bar.

Links to all other chapters: (0) Fundamentals, (1) Transformer Interpretability, (2) RL, (3) LLM Evaluations, (4) Alignment Science.

System RequirementsGPU⬜ Not neededTime⏱️ CPU <1 minColab🟩 Free (T4)Download⬜ <10 MBKeys🔑 None
  • 🖥️ GPU: ⬜ Not needed. CPU is faster.
  • ⏱️ Runtime (ex. downloads/API): CPU <1 min
  • ☁️ Colab? 🟩 Free (T4)
  • 💾 Downloads: ⬜ Under 10 MB
  • 🔑 API keys:
    • 🟩 Optional: Weights & Biases, for logging training runs (use_wandb)
  • 🐏 RAM: ~1.5 GB at peak

GPU times measured on a 16 GB RTX A4000. Compare every day →

Introduction

In this section, you'll implement Vanilla Policy Gradient (VPG), the first policy gradient algorithm upon which more advanced RL algorithms like PPO are based.

Content & Learning Objectives

1️⃣ Policy Gradient Theorem

The Policy Gradient Theorem is what all policy gradient methods are based on: it allows us to compute the gradient of the return, something that would naively not have a well defined gradient. You'll then build the policy network.

Learning Objectives
  • Understand the Policy Gradient Theorem
  • Understand the VPG algorithm: how to perform on-policy policy gradient

2️⃣ Rollouts

You'll write a rollout buffer and an agent that steps a batch of GPU CartPole environments with the current policy.

Learning Objectives
  • Collect on-policy experience from many environments in parallel

3️⃣ Loss

You'll compute returns, log-probabilities and importance weights, and combine them into the REINFORCE objective with a baseline.

Learning Objectives
  • Turn the policy gradient theorem into a loss you can backpropagate through
  • Understand why a baseline reduces variance without biasing the gradient

4️⃣ Training

You'll write the training loop, test it on probe environments, and train Vanilla Policy Gradient (VPG) on CartPole.

Learning Objectives
  • Debug a policy gradient implementation with probe environments
  • Train an agent that balances the pole for the full 500 steps

Optional Reading

Setup (don't read, just run!)

import arena_lib

exercises_dir, section_dir = arena_lib.setup("2.2.2")
import time
import warnings
from collections import namedtuple
from dataclasses import dataclass
from typing import Any, Callable, Optional

import gymnasium as gym
import numpy as np
import torch as t
import torch.nn.functional as F
import wandb
from eindex import eindex
from gymnasium.spaces import Box, Discrete
from jaxtyping import Bool, Float, Int
from torch import Tensor, nn
from torchinfo import summary
from tqdm.auto import tqdm

warnings.filterwarnings("ignore")


from gpu_env import CartPole, MountainCar
from gpu_probe import Probe1, Probe2, Probe3, Probe4, Probe5
from rl_utils import ENVS, AtariEnvs, LiveVideo, log_greedy_rollout_video, log_grid_video, make_envs
import part22_vpg.tests as tests
from part1_intro_to_rl.utils import set_global_seeds
from arena_lib.plot import line
from plotly_utils import plot_cartpole_obs_and_dones

# The networks in this section are tiny, and if you train on the CPU with
# PyTorch's default of one thread per core, threads spend longer
# coordinating than computing. Adjust if needed.
t.set_num_threads(min(4, t.get_num_threads()))

# CartPole will train just fine on a CPU as we need few parallel environments, and the neural network is very small
# Feel free to change this to "cpu" if you find it runs faster
device = t.device("mps" if t.backends.mps.is_available() else "cuda" if t.cuda.is_available() else "cpu")


MAIN = __name__ == "__main__"