Policy gradient and REINFORCE
Be able to derive the policy gradient theorem and implement REINFORCE.
Prerequisites
- EThe chain rule in several variablesrequired
- EMarkov decision processesrequired
Intuition
Q-learning learns values and derives the policy from them. Policy gradient skips the middle step and optimises the policy directly.
The policy is a neural network that gives probabilities over actions. We want to adjust so that good outcomes become more likely.
The idea in one sentence:
It went well — do more of what you did. It went badly — do less.
Mathematically: multiply the log probability of every action by how well the episode turned out, and walk up the gradient.
Why care, when Q-learning exists?
| Value-based | Policy gradient | |
|---|---|---|
| Continuous actions | hard (a max over infinitely many) | natural |
| A stochastic policy | no | yes — needed in games with bluffing |
| Convergence | can oscillate with function approximation | more stable guarantees |
| Sample efficiency | better (off-policy, replay) | worse (on-policy) |
The last row is the price: REINFORCE throws away all its data after every update.
Derivation
The objective is the expected return over trajectories :
The problem: the gradient lands on the probability distribution, which we cannot differentiate through directly.
The log-derivative trick solves it. Since :
Now it is an expectation again — and expectations can be estimated from samples.
The next step: the probability of a trajectory is
Take the logarithm and it becomes a sum, and everything that does not depend on disappears on differentiation — including the environment's dynamics . That is the whole point: we need no model of the world.
Two improvements that do not change the expectation but greatly reduce the variance:
- Causality. An action cannot affect what has already happened. Swap for the return forwards from step : .
- A baseline. For any function we have , since . So we can subtract for free.
With , becomes the advantage — and then we have arrived at actor–critic.
Why the variance is the problem: the estimate is built on the random outcomes of whole episodes. Without a baseline the gradient can point in different directions between two runs with the same policy. The baseline removes the part of the signal that is common to every action in a state — and that part is nothing but noise.
Code
import torch, torch.nn as nn
class Policy(nn.Module):
def __init__(self, obs, actions, hidden=128):
super().__init__()
self.f = nn.Sequential(nn.Linear(obs, hidden), nn.Tanh(), nn.Linear(hidden, actions))
def forward(self, s):
return torch.distributions.Categorical(logits=self.f(s))
def returns(rewards, gamma=0.99):
out, G = [], 0.0
for r in reversed(rewards):
G = r + gamma * G
out.append(G)
return list(reversed(out))
def reinforce(env, policy, opt, episodes=1000, gamma=0.99):
for _ in range(episodes):
s, done = env.reset()[0], False
logp, rews = [], []
while not done:
d = policy(torch.as_tensor(s, dtype=torch.float32))
a = d.sample()
logp.append(d.log_prob(a))
s, r, term, trunc, _ = env.step(int(a))
rews.append(r); done = term or trunc
G = torch.tensor(returns(rews, gamma))
G = (G - G.mean()) / (G.std() + 1e-8) # a baseline: greatly reduces the variance
loss = -(torch.stack(logp) * G).sum() # the minus sign: we are maximising J
opt.zero_grad(); loss.backward()
nn.utils.clip_grad_norm_(policy.parameters(), 1.0)
opt.step()
Three things that usually go wrong:
| Symptom | Cause |
|---|---|
| The policy quickly becomes deterministic and stops improving | the entropy has collapsed — add an entropy bonus |
| No learning at all | the minus sign is missing, or the normalisation removed all the signal |
| Very shaky learning | normalising over a single short episode; batch several |
The normalisation on line 24 is standard but not innocent: do it over a single episode and you are only comparing actions within that episode, and the information that the whole episode was bad is lost.
Mastery means
- Derives the policy gradient theorem with the log-derivative trick
- Implements REINFORCE with a baseline
- Explains the variance problem and the countermeasures
Sign in to do the exercises and build your mastery up.
Sources
- Sutton & Barto — Reinforcement Learning: An Introduction (2:a uppl.) — free to read online (authors' edition)
- OpenAI Spinning Up in Deep RL (MIT) — MIT
- Sutton m.fl. — Policy Gradient Methods (NeurIPS 1999) — NeurIPS open access