Overview
A plain policy gradient uses a batch once, because the data only describes the policy that collected it. Reusing it would let the policy drift to a place the data says nothing about. PPO reuses the batch anyway, but with a guard. For every action it tracks the ratio of the new probability to the old one. While that ratio stays near 1 the update proceeds as normal. Once it leaves a small band around 1 in the direction that would improve the objective, the gain is cut off and the gradient for that sample becomes zero. The policy therefore improves on the batch only as far as the batch can be trusted. The template is a small NumPy version with two one-hidden-layer networks, trained on a 4 by 4 grid.
A short history
John Schulman and colleagues at OpenAI published PPO in 2017. TRPO had shown that limiting how far the policy moves in each update makes training stable, but it needed second-order calculations that were awkward to implement. PPO got a similar effect with a simple clipped objective and ordinary gradient descent. It became the default on-policy method, and OpenAI used it at large scale for its Dota 2 agents and for a robot hand that manipulated objects.
How it works
- Collect
steps_per_epochsteps with the current policy and record the log-probability of every action taken. - Estimate advantages with GAE from the value network, and standardise them if
normalize_advantagesis set. - Shuffle the batch and split it into minibatches of
minibatch_size. - For each minibatch, compute the ratio of new to old action probability and the clipped surrogate objective.
- Step the policy network up the clipped objective plus the entropy bonus, and step the value network toward its return targets.
- Repeat the pass over the batch
update_epochstimes, then discard the batch and collect a new one.
Watch out for
- The clip limits each sample's contribution, not the policy's total movement. With many passes the policy can still drift far, so watch the reported KL divergence.
- The old log-probabilities must be the ones recorded at collection time. Recomputing them after an update makes every ratio 1 and removes the guard.
- Advantages are standardised per batch. With very small batches the mean and standard deviation are noisy, and the scaling itself adds variance.
- It is still on-policy. Each batch is thrown away after its passes, so it needs more environment steps than replay-based methods.
Use cases
When to use it
The usual first choice among on-policy methods: robust to the step size, simple to implement, and it gets several updates from each batch. Prefer an off-policy method such as DQN or SAC when environment steps are expensive.
In industry
- Games
- OpenAI Five, the system that beat professional Dota 2 players, was trained with a scaled-up version of PPO over a very large amount of self-play.
- Robotics
- Training walking and manipulation policies in massively parallel physics simulators, then transferring them to real robots.
- Language models
- Fine-tuning language models from human preference feedback, where PPO has been a common choice of optimiser for the policy.
- Operations research
- Learning scheduling, routing or resource allocation policies when a fast simulator of the system exists.
Choosing it: what must hold
- A simulator fast enough to produce fresh experience for every update, since old data is thrown away.
- Many parallel environments, which is where the method works best.
- Care with implementation details such as advantage normalisation and learning rate schedule, which affect results a lot.
When to choose something else
| If | Use instead |
|---|---|
| Each environment step is expensive and actions are continuous | SAC or TD3 |
| Each environment step is expensive and actions are discrete | DQN or Rainbow |
| You need a hard, explicit limit on policy change | TRPO |
Math foundations
The probability ratio
How much more or less likely the new policy makes the action that was actually taken. It equals 1 before the first update on a batch.
The advantage estimate (GAE)
A discounted sum of one-step surprises . It says how much better the action turned out than the value network expected.
The unclipped surrogate
At its gradient equals the ordinary policy gradient. Maximised without limit, it would push the ratios far from 1 and the estimate would stop being valid.
The clipped surrogate
The smaller of the plain term and a version with the ratio held inside the band. Taking the minimum makes it a pessimistic estimate: gains beyond the band are ignored, losses are counted in full.
Its slope with respect to the ratio
A sample keeps pushing only while the plain term is the smaller one. This is the second value returned by
clipped_surrogate.The full policy objective and the value loss
The entropy bonus keeps the policy exploring. The value network is fitted by regression onto , the advantage plus the value recorded at collection time.
Symbols
- state, action and reward at step t
- the policy being updated and the policy that collected the batch
- probability ratio of new to old policy for the action taken
- advantage estimate
- one-step temporal-difference residual
- the value network with weights phi
- regression target for the value network
- half-width of the clip band (clip_ratio)
- discount factor and GAE mixing parameter
- weight of the entropy bonus (entropy_coef)
- entropy of the action probabilities in a state
- number of samples in a minibatch
Worked by hand
Take , so the band is . Evaluate the clipped objective for three samples: a good action already made much more likely, a good action made less likely, and a bad action made more likely.
In the first case the clipped term wins and the slope is 0: no further reward for pushing a good action. In the other two the plain term wins and the slope is , so the policy is still pulled back toward the right direction.
Visual example
Loading the example.
Try this
- Press One pass several times: the dots leave ρ = 1, and those that cross the band in the helpful direction turn orange and stop pulling.
- Switch the objective to unclipped and repeat the passes on one batch: the ratios run away and the KL grows.
- Narrow the clip range ε to 0.05 and see how little one batch is then allowed to change the policy.
Code sample
from impl import PPO, GridWorld
from config import PPOConfig
env = GridWorld(size=4)
agent = PPO(env.obs_dim, env.n_actions, PPOConfig(epochs=30))
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 (315 lines)
"""Proximal Policy Optimization (PPO, clipped objective) 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), then makes several passes of minibatch gradient steps on the clipped surrogate
objective. The clip keeps the new policy close to the one that collected the data, which is what
makes reusing the batch safe. Both networks are small MLPs with hand-written backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import PPOConfig
except ImportError: # run from the template's own folder
from config import PPOConfig
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 entropy(probs: np.ndarray) -> np.ndarray:
"""Entropy of each row of probs, (n, n_actions) -> (n,)."""
return -np.sum(probs * np.log(probs + 1e-12), axis=-1)
def entropy_gradient_logits(probs: np.ndarray) -> np.ndarray:
"""Gradient with respect to the logits of the mean entropy of the rows of probs. Returns (n, n_actions)."""
log_p = np.log(probs + 1e-12)
return -probs * (log_p + entropy(probs)[:, None]) / len(probs)
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}
def clipped_surrogate(ratio: np.ndarray, advantages: np.ndarray, clip: float):
"""PPO objective per sample, min(ratio * A, clip(ratio, 1 - clip, 1 + clip) * A), and its slope.
ratio: (n,) pi_new(a|s) / pi_old(a|s). advantages: (n,).
Returns (objective, d objective / d ratio), both (n,). The slope is the advantage where the
unclipped term is the smaller one and zero where the clip is active.
"""
unclipped = ratio * advantages
clipped = np.clip(ratio, 1.0 - clip, 1.0 + clip) * advantages
return np.minimum(unclipped, clipped), np.where(unclipped <= clipped, advantages, 0.0)
class PPO:
"""PPO agent with a softmax policy network and a value network.
obs_dim: length of an observation vector. n_actions: number of discrete actions.
"""
def __init__(self, obs_dim: int, n_actions: int, config: PPOConfig | None = None) -> None:
cfg = self.config = config or PPOConfig()
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:
"""V(s). obs: (batch, obs_dim) or (obs_dim,) -> (batch,)."""
return self.critic.forward(obs)[:, 0]
def update(self, batch: dict) -> dict:
"""`update_epochs` passes of minibatch steps over a `collect_steps` batch.
Returns the mean clipped objective, the value loss and the mean KL(old || new) after the update.
"""
cfg = self.config
obs, actions, old_log_probs = batch["obs"], batch["actions"], batch["log_probs"]
advantages, returns = batch["advantages"], batch["returns"]
if cfg.normalize_advantages:
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
old_probs = self.policy(obs)
n = len(actions)
objective = value_loss = 0.0
for _ in range(cfg.update_epochs):
order = self.rng.permutation(n)
for start in range(0, n, cfg.minibatch_size):
idx = order[start:start + cfg.minibatch_size]
probs = self.policy(obs[idx])
log_probs = np.log(probs[np.arange(len(idx)), actions[idx]] + 1e-12)
ratio = np.exp(log_probs - old_log_probs[idx])
surrogate, slope = clipped_surrogate(ratio, advantages[idx], cfg.clip_ratio)
# d ratio / d logits = ratio * (onehot - probs), the same form as a log-probability gradient
grad_logits = policy_gradient_logits(probs, actions[idx], slope * ratio)
grad_logits -= cfg.entropy_coef * entropy_gradient_logits(probs)
grads, _ = self.actor.backward(grad_logits)
self.actor.step(grads)
errors = self.value(obs[idx]) - returns[idx]
grads, _ = self.critic.backward((2.0 * errors / len(idx))[:, None])
self.critic.step(grads)
objective, value_loss = float(surrogate.mean()), float(np.mean(errors**2))
new_probs = self.policy(obs)
kl = float(np.mean(np.sum(old_probs * (np.log(old_probs + 1e-12) - np.log(new_probs + 1e-12)), axis=1)))
return {"objective": objective, "value_loss": value_loss, "kl": kl}
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
- 11, run with
python3 -m unittest -v
Practice
Using the template, call clipped_surrogate with the three ratios and advantages of the worked example and clip 0.2, and check both returned arrays. Then train PPO on GridWorld(size=4) with update_epochs set to 1, 4 and 16, and for each record the kl value returned by update and the return from evaluate.
Check on learning
- The clip removes the gradient when a good action's ratio is above , but not when it is below . Why is that asymmetry the right design?
A way to think about it
In one case the policy has already moved in the helpful direction further than the data supports. In the other it has moved the wrong way. Ask which of those you want the update to be able to undo.
- With
update_epochsset to 1 and a very small step, how does PPO differ from vanilla policy gradient on the first minibatch?A way to think about it
Evaluate the ratio and the slope of the clipped objective at . Then ask at what point during a pass the two methods begin to differ.
- You raise
update_epochsfrom 4 to 40 and the reported KL climbs while the return gets worse. Explain the mechanism.A way to think about it
The clip acts per sample and is evaluated on a batch from the old policy. Think about states the old policy rarely visited, and about how many small moves the policy can make before the batch stops describing it.
- Why does PPO store log-probabilities at collection time instead of recomputing them from the network when the update begins?
A way to think about it
Within one call to update they would match. Consider the second and later minibatches, after the network has already changed, and what ratio you would then compute.