Overview
An actor-critic keeps two networks. The actor is the policy, and the critic predicts how much return a state is worth. A2C does not wait for an episode to end. It runs a few steps, then asks the critic to estimate everything beyond them, and updates at once. To keep each update from depending on one lucky or unlucky run, it steps several copies of the environment side by side and pools their experience into a single batch. An entropy bonus rewards the actor for keeping its action probabilities spread out, which stops it from committing too early. The template is a small NumPy version. Its environment copies are stepped in a plain loop inside one process.
A short history
A2C is the synchronous form of A3C, the asynchronous method that Volodymyr Mnih and colleagues at DeepMind published in 2016. In 2017 OpenAI released it in its Baselines library and reported that waiting for every environment and applying one batched update worked as well as the asynchronous version, while using a GPU more effectively. Its simplicity made it a common teaching example and the structure that PPO builds on.
How it works
- Create
n_envscopies of the environment and reset them. - For
n_stepssteps, sample one action per copy from the actor, step every copy, and record states, actions and rewards. - Ask the critic for the value of the state each copy has reached. That value stands in for all later rewards.
- Work backwards to get the n-step return for every recorded step, stopping the sum where an episode ended.
- Compute the advantage for each step.
- Update the critic to reduce its squared error against , and update the actor along the advantage-weighted policy gradient plus the entropy bonus.
- Discard the batch and continue from where each copy stands.
Watch out for
- Short rollouts lean heavily on the critic. When the critic is wrong, the n-step return is biased and the actor is pushed in the wrong direction.
- The advantage must be treated as a fixed number in the actor's loss. If gradients flowed through the critic there, the two objectives would interfere.
- With too few environment copies the batch is small and strongly correlated, since consecutive steps of one episode look alike. The update then becomes noisy.
- An entropy weight that is too large keeps the policy close to uniform and it never commits to the good actions. One that is too small lets it collapse onto a poor action early.
Use cases
When to use it
A fast, simple on-policy method for discrete actions when several environment copies are cheap to run. It is reproducible given a seed, unlike A3C. PPO is usually more sample-efficient because it reuses each batch.
In industry
- Games and simulation
- Training agents on Atari-style games or grid worlds with many copies of the environment stepping together.
- Research and teaching
- A first actor-critic implementation, since the whole update fits in a few lines and shows the roles of the actor and the critic.
- Operations research
- Learning scheduling or resource allocation policies in a fast simulator where many parallel runs are cheap.
Choosing it: what must hold
- A fast simulator that can run several copies in parallel.
- Tolerance for using each batch of experience only once, which costs many environment steps.
- Discrete or continuous actions are both fine, with a matching policy head.
When to choose something else
| If | Use instead |
|---|---|
| You want more learning from each batch and more stable updates | PPO |
| Each environment step is expensive, so data must be reused | DQN for discrete actions, SAC or TD3 for continuous actions |
| You are training on many CPU cores without a GPU | A3C |
Math foundations
The n-step return
Real rewards for the steps that were played, then the critic's estimate for the rest. The flag is 1 where an episode ended at step , so that nothing from the next episode leaks in.
The advantage
How much better the rollout turned out than the critic predicted from that state. It is the weight on each action in the actor's update.
The actor's gradient
The policy gradient with the advantage as the weight, averaged over all steps from all environment copies. is
n_stepstimesn_envs.The entropy bonus
Largest when all actions are equally likely and zero when one action is certain. Adding it to the objective keeps the policy exploring.
The combined loss
Policy term, entropy term and value term. In the template the actor and critic are separate networks, so only scales the critic's step.
Symbols
- state, action and reward at step t of a rollout
- rollout length (n_steps)
- cut flag: 1 if an episode ended at step t, else 0
- bootstrapped n-step return
- the actor: a softmax policy with weights theta
- the critic: predicted return from a state, with weights phi
- advantage estimate
- entropy of the action probabilities in a state
- weight of the entropy bonus (entropy_coef)
- weight of the value loss (value_coef)
- discount factor
- number of steps in the batch
Worked by hand
One environment copy plays three steps with reward each and no episode end. The critic values the state reached at and the first state at . Use and work backwards.
The first action did slightly better than the critic expected, so its probability is raised a little and the critic's value for that state is pulled up toward 0.4792.
Visual example
Loading the example.
Try this
- Press Update once and read the table: the return is built backwards from the critic's estimate of the last cell.
- Click another copy of the grid: every copy contributes its own short rollout to the same batch.
- Train with 1 copy, then with 8, and compare how steady the curve is.
Code sample
from impl import A2C, GridWorld
from config import A2CConfig
env = GridWorld(size=4)
agent = A2C(env.obs_dim, env.n_actions, A2CConfig(n_envs=8, updates=400))
returns = agent.train(GridWorld) # 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 (266 lines)
"""Advantage Actor-Critic (A2C, synchronous) in NumPy, with a small gridworld to learn on.
Several copies of the environment are stepped in lockstep. Every `n_steps` steps the actor (a softmax
policy network) and the critic (a value network) are updated together from the whole batch: the
critic regresses on bootstrapped n-step returns, the actor follows the policy gradient weighted by
the advantage (return minus value), plus an entropy bonus that keeps it exploring. Both networks are
small MLPs with hand-written backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import A2CConfig
except ImportError: # run from the template's own folder
from config import A2CConfig
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 n_step_returns(rewards: np.ndarray, cuts: np.ndarray, last_values: np.ndarray, gamma: float) -> np.ndarray:
"""Bootstrapped returns for a rollout of T steps in N parallel environments.
rewards: (T, N). cuts: (T, N), 1.0 where the episode ended at that step (nothing after it counts).
last_values: (N,) critic values of the observations after the last step.
Returns (T, N): R_t = r_t + gamma * (1 - cut_t) * R_{t+1}, with R_T = last_values.
"""
returns = np.zeros_like(rewards, dtype=float)
running = np.asarray(last_values, dtype=float)
for t in reversed(range(len(rewards))):
running = rewards[t] + gamma * (1.0 - cuts[t]) * running
returns[t] = running
return returns
class A2C:
"""Synchronous advantage actor-critic agent.
obs_dim: length of an observation vector. n_actions: number of discrete actions.
"""
def __init__(self, obs_dim: int, n_actions: int, config: A2CConfig | None = None) -> None:
cfg = self.config = config or A2CConfig()
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)
self.critic = MLP((obs_dim, cfg.hidden_size, 1), 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 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, obs: np.ndarray, actions: np.ndarray, returns: np.ndarray) -> dict:
"""One joint actor and critic step. obs: (n, obs_dim), actions: (n,), returns: (n,) n-step returns."""
cfg = self.config
values = self.value(obs)
advantages = returns - values
grads, _ = self.critic.backward((cfg.value_coef * 2.0 * (values - returns) / len(returns))[:, None])
self.critic.step(grads)
probs = self.policy(obs)
grad_logits = policy_gradient_logits(probs, actions, advantages)
grad_logits -= cfg.entropy_coef * entropy_gradient_logits(probs)
grads, _ = self.actor.backward(grad_logits)
self.actor.step(grads)
return {"value_loss": float(np.mean(advantages**2)), "entropy": float(entropy(probs).mean())}
def train(self, make_env, updates: int | None = None) -> list[float]:
"""Train on `n_envs` environments built by calling `make_env()`. Returns the finished episodes' returns."""
cfg = self.config
envs = [make_env() for _ in range(cfg.n_envs)]
obs = np.array([env.reset() for env in envs])
episode_returns = np.zeros(cfg.n_envs)
finished: list[float] = []
shape = (cfg.n_steps, cfg.n_envs)
for _ in range(cfg.updates if updates is None else updates):
obs_buf = np.zeros(shape + (self.obs_dim,))
act_buf = np.zeros(shape, dtype=int)
rew_buf, cut_buf = np.zeros(shape), np.zeros(shape)
for t in range(cfg.n_steps):
probs = self.policy(obs)
obs_buf[t] = obs
for i, env in enumerate(envs):
action = sample_action(probs[i], self.rng)
next_obs, reward, terminated, truncated = env.step(action)
episode_returns[i] += reward
if truncated: # time limit: the episode is cut but the state still has value
reward += cfg.gamma * float(self.value(next_obs)[0])
if terminated or truncated:
finished.append(float(episode_returns[i]))
episode_returns[i] = 0.0
next_obs = env.reset()
cut_buf[t, i] = 1.0
act_buf[t, i], rew_buf[t, i] = action, reward
obs[i] = next_obs
returns = n_step_returns(rew_buf, cut_buf, self.value(obs), cfg.gamma)
self.update(obs_buf.reshape(-1, self.obs_dim), act_buf.ravel(), returns.ravel())
return finished- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 10, run with
python3 -m unittest -v
Practice
Using the template, call n_step_returns with a (3, 1) array of rewards equal to -0.1, cuts of zero and last_values of 0.8, and check the worked numbers. Then set the middle cut to 1 and explain the change. Finally train A2C by passing the GridWorld class to train with n_envs set to 1 and to 8, and compare the returns.
Check on learning
- Why does pooling eight environment copies into one batch help more than taking eight times as many steps from a single copy?
A way to think about it
Compare how similar consecutive states of one episode are with how similar the states of eight separate episodes are at the same moment. A gradient averaged over near-duplicates carries less information.
- What happens to the bias and the variance of as you raise
n_stepsfrom 1 toward the full episode length?A way to think about it
Each extra real reward replaces part of the critic's guess with something that actually happened. Real rewards are random, the critic's guess is steady but may be wrong.
- The template adds to the reward when an episode is cut by the time limit, but not when the goal is reached. What would the agent learn about the time limit if it did not?
A way to think about it
Without the correction, running out of time looks like a state after which no reward ever comes. Think about how that would distort the value of states visited late in an episode.
- During training the entropy reported by
updatefalls to nearly zero while the return is still well below the best possible. What has probably happened, and which setting would you change first?A way to think about it
Near-zero entropy means the policy has become almost deterministic. Ask whether it can still discover a better action from there, and which term in the loss resists that collapse.