Overview
REINFORCE scores an action by everything that happened after it, which is noisy. Vanilla policy gradient adds a second network that predicts how much return a state is worth on average. An action is then scored by its advantage: the return it led to minus that prediction. A good outcome in a state that is always good earns little credit, and a good outcome in a poor state earns a lot. Subtracting the prediction does not change the gradient on average, but it removes much of the noise. The advantages here are computed with GAE, which blends short and long views of the future. The template is a small NumPy version with two one-hidden-layer networks, trained on a 4 by 4 grid.
A short history
The method rests on two results. Ronald Williams's 1992 REINFORCE paper gave the basic estimator and showed that subtracting a baseline keeps it unbiased. In 2000 Richard Sutton, David McAllester, Satinder Singh and Yishay Mansour published the policy gradient theorem, which justified using a learned value function with a parameterised policy. Vanilla policy gradient is the plain combination of the two, and it is the reference point against which TRPO and PPO are explained.
How it works
- Collect
steps_per_epochsteps with the current policy, restarting episodes as they end. - Run the value network on every visited state to get .
- Compute the one-step surprise at each step: reward plus discounted next value, minus the current value.
- Combine the surprises into advantages with GAE, working backwards through each episode segment.
- Take one gradient step on the policy that raises the log-probability of actions with positive advantage and lowers it for negative ones.
- Fit the value network to the targets with
value_itersregression steps.
Watch out for
- It takes one policy step per batch and then needs new data, so it uses more environment steps than PPO, which reuses each batch for several steps.
- A poor value network gives poor advantages. Early in training the baseline is nearly random, so the variance reduction only appears once the value fit improves.
- A step that is too large can move the policy to a place where the collected data no longer describes it. Nothing in this method limits the step, which is the gap TRPO and PPO close.
- With below 1 the advantage leans on the value network's predictions. That lowers variance but adds bias whenever those predictions are wrong.
Use cases
When to use it
A simple on-policy baseline for discrete actions, and the clearest place to see what a value baseline and GAE do. PPO builds directly on it and is usually the better choice in practice.
In industry
- Research and teaching
- The standard first step in deep reinforcement learning courses, showing how a baseline cuts the variance of REINFORCE.
- Games and simulation
- Solving small control tasks such as CartPole or LunarLander when a simple, readable implementation matters more than speed.
- Algorithm development
- A clean baseline for testing new ideas such as a different advantage estimator before adding them to PPO.
Choosing it: what must hold
- A cheap simulator, since every batch of experience is used for a single update.
- A policy with differentiable action probabilities, discrete or continuous.
- A careful, small learning rate, because nothing limits the size of each policy step.
When to choose something else
| If | Use instead |
|---|---|
| Training collapses after large updates, or you want to reuse each batch | PPO |
| You want updates every few steps across parallel environments | A2C |
| Environment steps are expensive | DQN for discrete actions, SAC for continuous actions |
Math foundations
The advantage
How much better taking action in state is than acting as the policy usually does there. Positive means better than average, negative means worse.
Policy gradient with a baseline
The same gradient as REINFORCE with the return replaced by the advantage. The expected value is unchanged and the variance is much lower.
Why the baseline adds no bias
Any quantity that depends on the state but not the action drops out, because the probabilities always sum to one and the gradient of a constant is zero.
The one-step TD residual
The surprise at one step: what was received plus what is now expected, minus what was expected before. It is a low-variance but biased estimate of the advantage.
Generalised advantage estimation
A discounted sum of surprises. With it is the one-step residual. With it is the full return minus the value. Values in between trade bias against variance.
The value network's loss
Ordinary regression onto a return estimate. The target is built from the values the network gave when the data was collected and is held fixed during the fit.
Symbols
- state, action and reward at step t
- the policy network with weights theta
- the value network with weights phi: predicted return from a state
- true action value, state value and advantage under the policy
- a baseline: any function of the state alone
- one-step temporal-difference residual
- estimated advantage from GAE
- regression target for the value network
- discount factor
- GAE mixing parameter (gae_lambda), between 0 and 1
- number of steps in the batch
Worked by hand
A two-step segment ends at the goal. Rewards are and , the value network gave and , and the value after the terminal step is . Use and , and work backwards.
Both actions did better than the value network expected, so both are made more likely. The value targets are 0.8801 and 1.0, above the old predictions of 0.5 and 0.8.
Visual example
Loading the example.
Try this
- Press Update a few times and compare the grey bars with the blue ones: the advantages are the returns with the prediction taken out.
- Run the training and compare the two curves: the same policy gradient, with and without the baseline.
- Move λ to 0 and then to 1 and watch the advantages change from one-step surprises to full returns minus V.
Code sample
from impl import VPG, GridWorld
from config import VPGConfig
env = GridWorld(size=4)
agent = VPG(env.obs_dim, env.n_actions, VPGConfig(epochs=60))
returns = agent.train(env) # return of every training episode
print(agent.evaluate(GridWorld(size=4))) # return of the most likely actions; 0.5 is the best possibleRead the implementation (276 lines)
"""Vanilla policy gradient with a learned value baseline, in NumPy, with a small gridworld to learn on.
Each epoch collects a batch of steps with the current softmax policy, estimates advantages with
GAE(lambda) from a value network, takes one gradient step on the policy and several regression steps
on the value network. Subtracting the baseline leaves the gradient unbiased and lowers its variance
compared with REINFORCE. Both networks are small MLPs with hand-written backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import VPGConfig
except ImportError: # run from the template's own folder
from config import VPGConfig
class GridWorld:
"""Square grid: the agent starts in the top-left cell and must reach the bottom-right cell.
Observation: one-hot vector of the agent's cell, shape (size * size,).
Actions: 0 up, 1 right, 2 down, 3 left. A move into a wall leaves the agent where it is.
Reward: +1.0 for the step that reaches the goal, -0.1 for every other step.
`step` returns (obs, reward, terminated, truncated): terminated at the goal, truncated after
`max_steps` steps. The best return is `optimal_return`, 0.5 for the default 4 x 4 grid.
"""
n_actions = 4
_MOVES = ((-1, 0), (0, 1), (1, 0), (0, -1))
def __init__(self, size: int = 4, max_steps: int = 30) -> None:
if size < 2:
raise ValueError(f"size must be at least 2, got {size!r}")
self.size = size
self.max_steps = max_steps
self.obs_dim = size * size
self.row = self.col = self.t = 0
@property
def optimal_return(self) -> float:
"""Return of a shortest path: 2 * (size - 1) moves, the last one worth +1."""
return 1.0 - 0.1 * (2 * (self.size - 1) - 1)
def _obs(self) -> np.ndarray:
obs = np.zeros(self.obs_dim)
obs[self.row * self.size + self.col] = 1.0
return obs
def reset(self) -> np.ndarray:
"""Put the agent back on the start cell and return the observation, shape (obs_dim,)."""
self.row = self.col = self.t = 0
return self._obs()
def step(self, action: int):
"""Apply one action (0..3). Returns (obs, reward, terminated, truncated)."""
d_row, d_col = self._MOVES[int(action)]
self.row = min(max(self.row + d_row, 0), self.size - 1)
self.col = min(max(self.col + d_col, 0), self.size - 1)
self.t += 1
terminated = self.row == self.size - 1 and self.col == self.size - 1
truncated = not terminated and self.t >= self.max_steps
return self._obs(), (1.0 if terminated else -0.1), terminated, truncated
class MLP:
"""Fully connected network with tanh hidden layers and a linear output, trained by manual backprop.
sizes: layer widths, for example (16, 32, 4) is 16 inputs, one hidden layer of 32 units, 4 outputs.
rng: NumPy generator used for the initial weights.
lr: Adam step size used by `step`.
"""
def __init__(self, sizes, rng: np.random.Generator, lr: float = 1e-3) -> None:
self.sizes = tuple(int(s) for s in sizes)
self.weights = [rng.normal(0.0, np.sqrt(1.0 / m), size=(m, n)) for m, n in zip(self.sizes[:-1], self.sizes[1:])]
self.biases = [np.zeros(n) for n in self.sizes[1:]]
self.lr = lr
self._m = [np.zeros_like(p) for p in self.params()]
self._v = [np.zeros_like(p) for p in self.params()]
self._t = 0
self._acts: list[np.ndarray] = []
def params(self) -> list[np.ndarray]:
"""All parameter arrays: the weight matrices, then the bias vectors."""
return self.weights + self.biases
def forward(self, x: np.ndarray) -> np.ndarray:
"""x: (batch, n_in) or (n_in,) -> (batch, n_out). Keeps the activations for `backward`."""
h = np.atleast_2d(np.asarray(x, dtype=float))
self._acts = [h]
last = len(self.weights) - 1
for i, (w, b) in enumerate(zip(self.weights, self.biases)):
h = h @ w + b
if i < last:
h = np.tanh(h)
self._acts.append(h)
return h
def backward(self, grad_out: np.ndarray):
"""Backpropagate through the most recent `forward` call.
grad_out: d loss / d output, shape (batch, n_out).
Returns (grads, grad_in): grads in the order of `params()`, grad_in = d loss / d input (batch, n_in).
"""
g = np.asarray(grad_out, dtype=float)
n_layers = len(self.weights)
grad_w: list = [None] * n_layers
grad_b: list = [None] * n_layers
for i in reversed(range(n_layers)):
if i < n_layers - 1:
g = g * (1.0 - self._acts[i + 1] ** 2)
grad_w[i] = self._acts[i].T @ g
grad_b[i] = g.sum(axis=0)
g = g @ self.weights[i].T
return grad_w + grad_b, g
def step(self, grads) -> None:
"""One Adam step that moves the parameters against `grads` (same order as `params()`)."""
self._t += 1
for p, g, m, v in zip(self.params(), grads, self._m, self._v):
m *= 0.9
m += 0.1 * g
v *= 0.999
v += 0.001 * g * g
p -= self.lr * (m / (1.0 - 0.9**self._t)) / (np.sqrt(v / (1.0 - 0.999**self._t)) + 1e-8)
def copy_from(self, other: "MLP", tau: float = 1.0) -> None:
"""Polyak update: params <- tau * other + (1 - tau) * params. tau = 1 is a plain copy."""
for p, q in zip(self.params(), other.params()):
p *= 1.0 - tau
p += tau * q
def softmax(logits: np.ndarray) -> np.ndarray:
"""Row-wise softmax. logits: (batch, n_actions) -> probabilities of the same shape."""
z = logits - logits.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def sample_action(probs: np.ndarray, rng: np.random.Generator) -> int:
"""Draw one action index from a probability vector, shape (n_actions,)."""
return min(int(np.searchsorted(np.cumsum(probs), rng.random())), len(probs) - 1)
def policy_gradient_logits(probs: np.ndarray, actions: np.ndarray, weights: np.ndarray) -> np.ndarray:
"""Gradient with respect to the logits of the loss -mean(weights * log pi(action | state)).
probs: (n, n_actions) softmax outputs. actions: (n,) taken actions. weights: (n,) returns or advantages.
Returns (n, n_actions).
"""
n = len(actions)
grad = probs * weights[:, None]
grad[np.arange(n), actions] -= weights
return grad / n
def gae(rewards: np.ndarray, values: np.ndarray, last_value: float, gamma: float, lam: float) -> np.ndarray:
"""Generalised advantage estimates for one trajectory segment.
rewards: (n,) rewards r_0..r_{n-1}. values: (n,) critic values V(s_0)..V(s_{n-1}).
last_value: V(s_n), 0.0 when s_n is terminal. Returns advantages, shape (n,).
lam = 1 gives (discounted return - value), lam = 0 gives the one-step TD error.
"""
next_values = np.append(values[1:], last_value)
deltas = rewards + gamma * next_values - values
advantages = np.zeros(len(rewards))
running = 0.0
for t in reversed(range(len(rewards))):
running = deltas[t] + gamma * lam * running
advantages[t] = running
return advantages
def collect_steps(env, actor, critic, n_steps: int, gamma: float, lam: float, rng: np.random.Generator) -> dict:
"""Run the stochastic policy for n_steps environment steps, restarting episodes as they end.
actor maps observations to action logits, critic maps observations to a value, both (batch, obs_dim) in.
Returns a dict: obs (n, obs_dim), actions (n,), log_probs (n,), advantages (n,) from GAE,
returns (n,) = advantages + values (the critic's regression target) and episode_returns, the list
of returns of the episodes that ended inside this batch. A segment cut by the time limit or by the
end of the batch is bootstrapped with the critic's value of the next observation.
"""
obs_buf, act_buf, rew_buf, logp_buf, segments, episode_returns = [], [], [], [], [], []
obs, episode_return = env.reset(), 0.0
for t in range(n_steps):
probs = softmax(actor.forward(obs))[0]
action = sample_action(probs, rng)
next_obs, reward, terminated, truncated = env.step(action)
obs_buf.append(obs)
act_buf.append(action)
rew_buf.append(reward)
logp_buf.append(np.log(probs[action] + 1e-12))
episode_return += reward
obs = next_obs
if terminated or truncated or t == n_steps - 1:
segments.append((t + 1, None if terminated else next_obs))
if terminated or truncated:
episode_returns.append(episode_return)
obs, episode_return = env.reset(), 0.0
obs_arr, rewards = np.array(obs_buf), np.array(rew_buf)
values = critic.forward(obs_arr)[:, 0]
advantages = np.zeros(n_steps)
start = 0
for end, bootstrap_obs in segments:
last_value = 0.0 if bootstrap_obs is None else float(critic.forward(bootstrap_obs)[0, 0])
advantages[start:end] = gae(rewards[start:end], values[start:end], last_value, gamma, lam)
start = end
return {"obs": obs_arr, "actions": np.array(act_buf), "log_probs": np.array(logp_buf),
"advantages": advantages, "returns": advantages + values, "episode_returns": episode_returns}
class VPG:
"""Vanilla policy gradient agent: a softmax policy network and a value network used as baseline.
obs_dim: length of an observation vector. n_actions: number of discrete actions.
"""
def __init__(self, obs_dim: int, n_actions: int, config: VPGConfig | None = None) -> None:
cfg = self.config = config or VPGConfig()
self.obs_dim, self.n_actions = obs_dim, n_actions
self.rng = np.random.default_rng(cfg.seed)
self.actor = MLP((obs_dim, cfg.hidden_size, n_actions), self.rng, cfg.policy_lr)
self.critic = MLP((obs_dim, cfg.hidden_size, 1), self.rng, cfg.value_lr)
def policy(self, obs: np.ndarray) -> np.ndarray:
"""Action probabilities. obs: (batch, obs_dim) or (obs_dim,) -> (batch, n_actions)."""
return softmax(self.actor.forward(obs))
def act(self, obs: np.ndarray, greedy: bool = False) -> int:
"""Sample an action for one observation; greedy=True takes the most likely action instead."""
probs = self.policy(obs)[0]
return int(np.argmax(probs)) if greedy else sample_action(probs, self.rng)
def evaluate(self, env, episodes: int = 1, greedy: bool = True) -> float:
"""Mean return over `episodes` episodes of the greedy (or, with greedy=False, the sampled) policy."""
total = 0.0
for _ in range(episodes):
obs, done = env.reset(), False
while not done:
obs, reward, terminated, truncated = env.step(self.act(obs, greedy=greedy))
total += reward
done = terminated or truncated
return total / episodes
def value(self, obs: np.ndarray) -> np.ndarray:
"""Baseline V(s). obs: (batch, obs_dim) or (obs_dim,) -> (batch,)."""
return self.critic.forward(obs)[:, 0]
def update(self, batch: dict) -> dict:
"""One policy step and `value_iters` value steps from a `collect_steps` batch. Returns the losses."""
cfg = self.config
obs, actions, advantages, returns = batch["obs"], batch["actions"], batch["advantages"], batch["returns"]
if cfg.normalize_advantages:
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
probs = self.policy(obs)
log_probs = np.log(probs[np.arange(len(actions)), actions] + 1e-12)
grads, _ = self.actor.backward(policy_gradient_logits(probs, actions, advantages))
self.actor.step(grads)
value_loss = 0.0
for _ in range(cfg.value_iters):
errors = self.value(obs) - returns
value_loss = float(np.mean(errors**2))
grads, _ = self.critic.backward((2.0 * errors / len(errors))[:, None])
self.critic.step(grads)
return {"policy_loss": float(-np.mean(advantages * log_probs)), "value_loss": value_loss}
def train(self, env, epochs: int | None = None) -> list[float]:
"""Run `epochs` rounds of collect + update. Returns the returns of all finished episodes."""
cfg = self.config
returns: list[float] = []
for _ in range(cfg.epochs if epochs is None else epochs):
batch = collect_steps(env, self.actor, self.critic, cfg.steps_per_epoch, cfg.gamma, cfg.gae_lambda, self.rng)
returns += batch["episode_returns"]
self.update(batch)
return returns- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Using the template, call gae with the rewards, values and last_value of the worked example and check the two advantages. Then repeat with lam set to 0 and to 1 and explain each result. Finally train VPG on GridWorld(size=4) and compare the returns list with what REINFORCE gives on the same grid.
Check on learning
- The baseline does not change the expected gradient. So in what precise sense does it help, and how would you measure that help in an experiment?
A way to think about it
Separate the mean of an estimate from its spread. Think about computing the gradient many times on different batches from the same policy, with and without the baseline, and comparing how much the results scatter.
- With the estimate ignores the value network except as a baseline. With it trusts the network for everything beyond one step. Which would you choose early in training, and why?
A way to think about it
Early on the value network is nearly random. Consider which setting passes that network's errors into the advantage as bias, and which only uses it in a way that cannot bias the gradient.
- Why must a segment that was cut by the step limit be bootstrapped with the value of the next state, while a segment that reached the goal uses zero?
A way to think about it
Ask what return would have followed in each case had the episode been allowed to run on. Using zero after a time limit tells the agent that being cut off is as final as reaching the goal.
- Suppose the value network were perfect. Would the advantages for a batch then all be zero? Explain what they would measure.
A way to think about it
A perfect gives the average over the policy's actions. A single sampled action and its outcome can still be above or below that average. Think about what is left when the predictable part is removed.