Overview
A policy network outputs a probability for each action. REINFORCE plays complete episodes with it, then looks back. An action that was followed by a high total reward is made more likely, and one followed by a low total is made less likely. No value function is learned: the score for an action is simply what happened afterwards in that episode. That makes the estimate honest on average but noisy, because the same action can be followed by very different outcomes from one episode to the next. The template is a small NumPy version with one hidden layer, trained on a 4 by 4 grid.
A short history
Ronald Williams introduced REINFORCE in a 1992 paper in the journal Machine Learning. The name is an acronym for the form of the update: REward Increment = Nonnegative Factor times Offset Reinforcement times Characteristic Eligibility. It showed that a network with random outputs can follow the gradient of expected reward using only sampled episodes, with no model of the environment. Every later policy-gradient method, from actor-critic to PPO, starts from this estimator.
How it works
- Play
batch_episodescomplete episodes by sampling actions from the policy's probabilities. - For every step, compute the return-to-go : the discounted sum of rewards from that step to the end of the episode.
- Optionally standardise the returns in the batch to zero mean and unit variance.
- Form the loss: minus the average of times the log-probability of the action taken.
- Take one gradient step on the policy network and discard the episodes. Fresh data is needed for the next step.
Watch out for
- The gradient estimate has high variance, because each return is one random outcome of a long chain of random actions. Learning is slow and uneven, more so as episodes get longer.
- It can only learn from complete episodes. A task that never ends, or ends rarely, gives it nothing to update on.
- Each batch is used for one step and then thrown away, since the gradient is only valid for the policy that collected the data. That makes it costly in environment steps.
- Standardising returns changes which actions are pushed down. With all-positive returns and no standardising, every action taken is pushed up and only the amounts differ, which slows learning.
Use cases
When to use it
Short episodic tasks, teaching, or a baseline to compare other methods against. It is the method to understand first, because every later policy-gradient method is a variance fix on top of it.
In industry
- Research and teaching
- The first policy-gradient method students implement, on small tasks such as CartPole, because the whole algorithm is one line of loss.
- Sequence models
- Training models with discrete, non-differentiable choices, for example optimising a text generator directly for an evaluation score.
- Architecture search
- Early neural architecture search trained a controller network with this estimator, using the accuracy of each sampled design as the reward.
Choosing it: what must hold
- Tasks split into episodes that end, because updates wait for the full return.
- Short episodes and cheap simulation, since the gradient estimate is very noisy.
- A policy that outputs action probabilities you can differentiate.
When to choose something else
| If | Use instead |
|---|---|
| The noise in the updates makes learning too slow | Vanilla policy gradient with a baseline, or A2C |
| You want a strong general-purpose on-policy method | PPO |
| The task never ends or episodes are very long | A2C or another method that bootstraps from a value estimate |
Math foundations
The return-to-go
The discounted reward collected from step to the end of the episode. Only later rewards count, because an action cannot affect what came before it.
The objective
The expected return of a whole episode when actions are drawn from the policy . This is the quantity to increase.
The policy gradient
The gradient of the expected return can be written without knowing how the environment works. Only the policy's own log-probabilities are differentiated.
The loss that is minimised
A sample average over the steps in the batch. Its gradient is minus the Monte Carlo estimate of the policy gradient, so descending it ascends .
Gradient at the logits of a softmax policy
Raising the log-probability of the taken action pushes its logit up and every logit down in proportion to its probability. This is what
policy_gradient_logitscomputes, weighted by the returns.
Symbols
- state, action and reward at step t
- number of steps in the episode
- discount factor
- return-to-go from step t
- probability the policy with weights theta gives to action a in state s
- expected return of an episode
- the network's logit (pre-softmax output) for action j
- total number of steps in the batch of episodes
Worked by hand
An episode on the grid lasts three steps with rewards , and , and . Compute the return-to-go backwards from the last step.
The three actions are credited with 0.7811, 0.89 and 1.0. The last action, closest to the goal reward, gets the largest push.
Visual example
Loading the example.
Try this
- Press Play one episode a few times: every step of a long wandering episode gets a negative return and is made less likely.
- Click a bar to see which cell that step was in and how the update changed the probability of the move.
- Run 200 episodes and look at the plot: the returns improve, but they jump around from one episode to the next.
Code sample
from impl import REINFORCE, GridWorld
from config import REINFORCEConfig
env = GridWorld(size=4)
agent = REINFORCE(env.obs_dim, env.n_actions, REINFORCEConfig(episodes=600))
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 (238 lines)
"""REINFORCE (Monte Carlo policy gradient) in NumPy, with a small gridworld to learn on.
A softmax policy network is improved by gradient ascent on the expected return: after a complete
episode, the log-probability of every action taken is pushed up in proportion to the discounted return
that followed it. No value function is learned. The network is a small MLP with hand-written
backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import REINFORCEConfig
except ImportError: # run from the template's own folder
from config import REINFORCEConfig
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 discounted_returns(rewards, gamma: float) -> np.ndarray:
"""Return-to-go G_t = r_t + gamma * r_{t+1} + gamma^2 * r_{t+2} + ... for one episode. (n,) -> (n,)."""
out = np.zeros(len(rewards))
running = 0.0
for t in reversed(range(len(rewards))):
running = rewards[t] + gamma * running
out[t] = running
return out
class REINFORCE:
"""REINFORCE agent with a softmax MLP policy.
obs_dim: length of an observation vector. n_actions: number of discrete actions.
"""
def __init__(self, obs_dim: int, n_actions: int, config: REINFORCEConfig | None = None) -> None:
cfg = self.config = config or REINFORCEConfig()
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.learning_rate)
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 run_episode(self, env):
"""Play one episode with the sampled policy. Returns (obs (n, obs_dim), actions (n,), rewards (n,))."""
obs_list, actions, rewards = [], [], []
obs, done = env.reset(), False
while not done:
action = self.act(obs)
next_obs, reward, terminated, truncated = env.step(action)
obs_list.append(obs)
actions.append(action)
rewards.append(reward)
obs, done = next_obs, terminated or truncated
return np.array(obs_list), np.array(actions), np.array(rewards)
def update(self, episodes) -> float:
"""One policy-gradient step from a list of episodes (obs, actions, rewards). Returns the loss."""
cfg = self.config
obs = np.concatenate([e[0] for e in episodes])
actions = np.concatenate([e[1] for e in episodes])
returns = np.concatenate([discounted_returns(e[2], cfg.gamma) for e in episodes])
if cfg.normalize_returns and len(returns) > 1:
returns = (returns - returns.mean()) / (returns.std() + 1e-8)
probs = self.policy(obs)
grads, _ = self.actor.backward(policy_gradient_logits(probs, actions, returns))
self.actor.step(grads)
log_probs = np.log(probs[np.arange(len(actions)), actions] + 1e-12)
return float(-np.mean(returns * log_probs))
def train(self, env, episodes: int | None = None) -> list[float]:
"""Play `episodes` episodes, updating after every `batch_episodes` of them. Returns the episode returns."""
cfg = self.config
returns, batch = [], []
for _ in range(cfg.episodes if episodes is None else episodes):
episode = self.run_episode(env)
returns.append(float(episode[2].sum()))
batch.append(episode)
if len(batch) == cfg.batch_episodes:
self.update(batch)
batch = []
return returns- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Using the template, call discounted_returns on the rewards from the worked example and check the three numbers. Then train REINFORCE on GridWorld(size=4) with normalize_returns true and false, plot the list that train returns for each, and compare how quickly evaluate reaches the best return of 0.5.
Check on learning
- Why is it correct to weight an action by the rewards after it but not the rewards before it, even though both are part of the same episode?
A way to think about it
Ask whether changing the action at step could have changed a reward at step . Then consider what including those earlier rewards would add to the estimate: signal or only noise.
- If you added 100 to every reward, the best policy would not change. Would REINFORCE without return normalisation learn equally well?
A way to think about it
Look at the loss. With all returns large and positive, every taken action is pushed up strongly. Think about the size of the random part of the gradient compared with the part that tells actions apart.
- Why can this method not reuse last week's episodes the way a replay buffer does?
A way to think about it
The expectation in the policy gradient is taken over actions drawn from the current policy. Consider what an average over actions drawn from a different, older policy would be estimating.
- Predict how the variance of changes as episodes grow from 6 steps to 600 steps, and what that does to learning.
A way to think about it
is a sum of many random terms, each depending on a random action. Think about how the spread of a sum grows with the number of terms, and what a noisy weight does to a gradient step.