The basic Monte Carlo policy gradient. push up the log-probability of actions in proportion to the return that followed them (concepts in Policy Gradient). The general idea is to differentiate the probability distribution over trajectories as you cannot backprop directly through the sampling step for stochastic policies.
Objective
A trajectory has probability under policy :
Objective is to maximize expected total return: , where .
To find the gradient, we pull the gradient inside the integral.
We want to turn this integral back into an expectation so we can estimate it by sampling rollouts. Using the calculus identity , we substitute :
From scratch
import torch
import torch.nn as nn
from torch.distributions import Categorical
policy = nn.Sequential(nn.Linear(obs_dim, 128), nn.ReLU(), nn.Linear(128, n_actions))
opt = torch.optim.Adam(policy.parameters(), lr=1e-3)
def update(states, actions, rewards, gamma=0.99):
returns, G = [], 0.0
for r in reversed(rewards): # discounted return-to-go
G = r + gamma * G
returns.append(G)
returns = torch.tensor(list(reversed(returns)), dtype=torch.float32)
dist = Categorical(logits=policy(torch.stack(states)))
logp = dist.log_prob(torch.stack(actions))
loss = -(logp * returns).sum() # negate: optimizers descend
opt.zero_grad()
loss.backward()
opt.step()Notes
- On-policy and unbiased, but the variance grows with horizon, so it needs many episodes per update or a baseline, see REINFORCE with Baseline.
- Strictly the term should carry ; almost every implementation drops it, which biases the gradient toward later timesteps but works better empirically.
- The gradient is not a loss gradient:
lossabove is a surrogate whose gradient equals the policy gradient, and its numeric value is meaningless. - Works directly with continuous actions by swapping
Categoricalfor a Gaussian Policy.