Sign in

A3C

Asynchronous Advantage Actor-Critic

An asynchronous actor-critic: several workers each play their own environment and update shared networks without waiting for one another.

Overview

Training on consecutive steps of one episode is unstable, because those steps look alike. A replay buffer is one cure. A3C uses another: run several workers at once, each in its own copy of the environment. Each worker copies the shared actor and critic, plays a few steps, works out the gradients on its copy and applies them to the shared networks. Workers are at different points of different episodes, so the stream of updates is varied even though no experience is stored. Nobody waits, which means a worker's gradient may be computed from weights that are already slightly out of date. The template runs its workers as Python threads in one process, so it shows the behaviour but does not train faster than a single thread.

A short history

Volodymyr Mnih and colleagues at DeepMind introduced A3C in the 2016 paper Asynchronous Methods for Deep Reinforcement Learning. DQN needed a replay buffer and a GPU. A3C instead ran many actor threads on one multi-core CPU, each with its own environment, and let their different experiences decorrelate the updates. It beat DQN on Atari in less training time and showed that parallel actors could replace replay.

How it works

  1. Start n_workers threads. Each owns an environment and a private copy of the actor and critic.
  2. A worker copies the shared weights into its private networks.
  3. It plays up to n_steps steps with its copy, stopping early if the episode ends.
  4. It computes n-step returns, bootstrapping with its critic's value of the last state, or with zero if that state is terminal.
  5. It computes the actor and critic gradients of the actor-critic loss on its own copy.
  6. It applies those gradients to the shared networks through the shared optimiser, then goes back to copy the weights again.
  7. All workers repeat this until together they have taken total_steps environment steps.

Watch out for

  • A worker's gradient is computed at weights that other workers may have changed since it copied them. With many workers or a large step size those stale gradients can point the wrong way.
  • With more than one worker the order of updates depends on thread timing, so two runs with the same seed give slightly different results.
  • The template's workers are threads that share one interpreter lock. They interleave like real asynchronous workers but give no speed-up, which is why the template is a model and not a fast trainer.
  • Each update uses one short rollout from one worker, so single updates are noisy. The method relies on many small, varied updates averaging out.

Use cases

When to use it

To study or prototype asynchronous actor-critic training, or as the model for a multi-process version. For reproducible runs on one machine, A2C gives the same kind of update in a synchronous form.

In industry

Games and simulation
Training agents on Atari games and 3D maze navigation, the tasks the original paper reported.
Research and teaching
Explaining how parallel actors decorrelate experience, and as the historical step between DQN and PPO.
CPU-only training
Learning policies on a multi-core machine with no GPU, where each worker thread runs its own simulator.

Choosing it: what must hold

  • A multi-core machine and a simulator that is cheap to copy per worker.
  • A model small enough that lock-free updates from several workers remain useful.
  • Acceptance that runs are harder to reproduce, because update order depends on thread timing.

When to choose something else

IfUse instead
You have a GPU and want reproducible batched updatesA2C
You want better stability and sample use from the same dataPPO
Environment steps are expensiveDQN or SAC, which reuse data from a replay buffer

Math foundations

  1. The n-step return of one rollout

    Rt=rt+γ Rt+1,Rn={0if sn is terminalVϕ′(sn)otherwiseR_t = r_t + \gamma\, R_{t+1}, \qquad R_n = \begin{cases} 0 & \text{if } s_n \text{ is terminal} \\ V_{\phi'}(s_n) & \text{otherwise} \end{cases}

    Real rewards for the steps the worker played, then its critic's estimate of the rest. The rollout has nn steps, fewer if the episode ended.

  2. The advantage

    A^t=Rt−Vϕ′(st)\hat{A}_t = R_t - V_{\phi'}(s_t)

    How much better the rollout turned out than the worker's critic predicted. It is treated as a fixed number when the actor's gradient is taken.

  3. The loss on one rollout

    L(θ′,ϕ′)=−1n∑tA^tlog⁡πθ′(at∣st)  −  β 1n∑tH(πθ′(⋅∣st))  +  cv 1n∑t(Vϕ′(st)−Rt)2L(\theta', \phi') = -\frac{1}{n} \sum_{t} \hat{A}_t \log \pi_{\theta'}(a_t \mid s_t) \;-\; \beta\, \frac{1}{n} \sum_{t} \mathcal{H}\bigl(\pi_{\theta'}(\cdot \mid s_t)\bigr) \;+\; c_v\, \frac{1}{n} \sum_{t} \bigl( V_{\phi'}(s_t) - R_t \bigr)^2

    Policy term, entropy bonus and value term, the same three parts as A2C. It is evaluated on the worker's private copies, written with a prime.

  4. The entropy bonus

    H(π(⋅∣s))=−∑aπ(a∣s) log⁡π(a∣s)\mathcal{H}\bigl(\pi(\cdot \mid s)\bigr) = -\sum_{a} \pi(a \mid s)\, \log \pi(a \mid s)

    Largest when all actions are equally likely. It keeps the policy from becoming certain too early.

  5. The asynchronous update

    θ←θ−η ∇θ′L(θ′,ϕ′),ϕ←ϕ−η ∇ϕ′L(θ′,ϕ′)\theta \leftarrow \theta - \eta\, \nabla_{\theta'} L(\theta', \phi'), \qquad \phi \leftarrow \phi - \eta\, \nabla_{\phi'} L(\theta', \phi')

    The gradient is taken at the worker's copy but applied to the shared weights, which may have moved in the meantime. Shown as a plain gradient step. The template passes the gradient through a shared Adam optimiser.

Symbols

θ,ϕ\theta, \phi
shared weights of the actor and the critic
θ′,ϕ′\theta', \phi'
a worker's private copies, taken at its last sync
st,at,rts_t, a_t, r_t
state, action and reward at step t of the worker's rollout
nn
number of steps in the rollout, at most n_steps
RtR_t
bootstrapped n-step return
A^t\hat{A}_t
advantage estimate
H\mathcal{H}
entropy of the action probabilities in a state
β\beta
weight of the entropy bonus (entropy_coef)
cvc_v
weight of the value loss (value_coef)
γ\gamma
discount factor
η\eta
step size (learning_rate)

Worked by hand

A worker's rollout ends at the goal after two steps, with rewards −0.1-0.1 and 1.01.0. Its critic valued the two states at 0.60.6 and 0.90.9. The last state is terminal, so the bootstrap is 00, and γ=0.99\gamma = 0.99.

R1=1.0+0.99×0=1.0R_1 = 1.0 + 0.99 \times 0 = 1.0
R0=−0.1+0.99×1.0=0.89R_0 = -0.1 + 0.99 \times 1.0 = 0.89
A^0=0.89−0.6=0.29,A^1=1.0−0.9=0.10\hat{A}_0 = 0.89 - 0.6 = 0.29, \qquad \hat{A}_1 = 1.0 - 0.9 = 0.10
12(0.292+0.102)=12(0.0841+0.01)=0.04705\tfrac{1}{2}\bigl(0.29^2 + 0.10^2\bigr) = \tfrac{1}{2}(0.0841 + 0.01) = 0.04705

Both actions are made more likely, the first more strongly. The value term of the loss, before the weight cvc_v, is 0.04705.

Visual example

Loading the example.

Try this

  • Press Step several times: one worker moves at a time, and each keeps playing on the copy it took earlier.
  • Click a worker to see how many updates its copy is behind the shared networks.
  • Set the workers to 1 and run again: nothing is ever out of date, and every update comes from the same episode.

Code sample

from impl import A3C, GridWorld
from config import A3CConfig

env = GridWorld(size=4)
agent = A3C(env.obs_dim, env.n_actions, A3CConfig(n_workers=4))
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 possible
print(agent.updates_per_worker)             # gradient updates applied by each thread
Read the implementation (296 lines)
"""Asynchronous Advantage Actor-Critic (A3C) in NumPy and threads, with a small gridworld to learn on.

Several worker threads each own an environment and a private copy of the actor and critic networks.
A worker copies the shared parameters, plays up to `n_steps` steps, computes the actor-critic
gradients on its copy and applies them to the shared networks, without waiting for the other workers.
The workers see different parts of the environment at the same time, which decorrelates the updates
without a replay buffer. Both networks are small MLPs with hand-written backpropagation and Adam.
"""
from __future__ import annotations

import threading

import numpy as np

try:
    from .config import A3CConfig
except ImportError:  # run from the template's own folder
    from config import A3CConfig


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, bootstrap_value: float, gamma: float) -> np.ndarray:
    """Returns for one rollout: R_t = r_t + gamma * R_{t+1}, with R_n = bootstrap_value. (n,) -> (n,).

    bootstrap_value is the critic's value of the state after the last step, 0.0 if that state is terminal.
    """
    returns = np.zeros(len(rewards))
    running = bootstrap_value
    for t in reversed(range(len(rewards))):
        running = rewards[t] + gamma * running
        returns[t] = running
    return returns


def actor_critic_gradients(actor: MLP, critic: MLP, obs: np.ndarray, actions: np.ndarray, returns: np.ndarray,
                           entropy_coef: float, value_coef: float):
    """Gradients of the A3C loss on one rollout.

    obs: (n, obs_dim), actions: (n,), returns: (n,). The loss is
    -mean(advantage * log pi(a|s)) - entropy_coef * mean entropy + value_coef * mean((V - return)^2),
    with the advantage (return - V) treated as a constant in the first term.
    Returns (actor_grads, critic_grads), each in the order of the network's `params()`.
    """
    values = critic.forward(obs)[:, 0]
    critic_grads, _ = critic.backward((value_coef * 2.0 * (values - returns) / len(returns))[:, None])
    probs = softmax(actor.forward(obs))
    grad_logits = policy_gradient_logits(probs, actions, returns - values)
    grad_logits -= entropy_coef * entropy_gradient_logits(probs)
    actor_grads, _ = actor.backward(grad_logits)
    return actor_grads, critic_grads


class A3C:
    """A3C agent: shared actor and critic networks updated by asynchronous worker threads.

    obs_dim: length of an observation vector. n_actions: number of discrete actions.
    After `train`, `updates_per_worker` holds how many gradient updates each worker applied.
    With more than one worker the order of the updates depends on thread timing, so two runs with the
    same seed are close but not identical; with one worker a run is exactly reproducible.
    """

    def __init__(self, obs_dim: int, n_actions: int, config: A3CConfig | None = None) -> None:
        cfg = self.config = config or A3CConfig()
        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)
        self.global_steps = 0
        self.updates_per_worker = [0] * cfg.n_workers
        self._lock = threading.Lock()
        self._returns: list[float] = []

    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 _worker(self, worker_id: int, env, total_steps: int) -> None:
        """Loop of one worker thread: sync, roll out, compute gradients locally, apply them to the shared nets."""
        cfg = self.config
        rng = np.random.default_rng([cfg.seed, worker_id])
        actor = MLP(self.actor.sizes, rng)
        critic = MLP(self.critic.sizes, rng)
        obs, episode_return = env.reset(), 0.0
        while True:
            with self._lock:
                if self.global_steps >= total_steps:
                    return
                self.global_steps += cfg.n_steps
                actor.copy_from(self.actor)
                critic.copy_from(self.critic)
            obs_buf, act_buf, rew_buf, finished = [], [], [], []
            bootstrap = 0.0
            for _ in range(cfg.n_steps):
                action = sample_action(softmax(actor.forward(obs))[0], rng)
                next_obs, reward, terminated, truncated = env.step(action)
                obs_buf.append(obs)
                act_buf.append(action)
                rew_buf.append(reward)
                episode_return += reward
                obs = next_obs
                if terminated or truncated:
                    bootstrap = 0.0 if terminated else float(critic.forward(next_obs)[0, 0])
                    finished.append(episode_return)
                    obs, episode_return = env.reset(), 0.0
                    break
            else:
                bootstrap = float(critic.forward(obs)[0, 0])
            returns = n_step_returns(rew_buf, bootstrap, cfg.gamma)
            actor_grads, critic_grads = actor_critic_gradients(
                actor, critic, np.array(obs_buf), np.array(act_buf), returns, cfg.entropy_coef, cfg.value_coef)
            with self._lock:
                self.actor.step(actor_grads)
                self.critic.step(critic_grads)
                self.updates_per_worker[worker_id] += 1
                self._returns += finished

    def train(self, make_env, total_steps: int | None = None) -> list[float]:
        """Run `n_workers` threads, each on its own `make_env()`, until total_steps steps were taken in all.

        Returns the returns of the episodes finished during this call, in the order they ended.
        """
        cfg = self.config
        budget = self.global_steps + (cfg.total_steps if total_steps is None else total_steps)
        self._returns = []
        threads = [threading.Thread(target=self._worker, args=(i, make_env(), budget)) for i in range(cfg.n_workers)]
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()
        return list(self._returns)
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 on the rewards of the worked example with bootstrap_value 0.0, then call actor_critic_gradients on a tiny rollout and inspect the shapes it returns. Train A3C by passing the GridWorld class to train with n_workers set to 1 and to 4, run each twice with the same seed, and compare the returns and agent.updates_per_worker.

Check on learning

  1. A3C has no replay buffer, yet it avoids the instability of training on consecutive, similar steps. What plays the role of the buffer?
    A way to think about it

    Think about what the shared networks receive over a short stretch of time when four workers are at different places in different episodes, compared with what one worker alone would send.

  2. A worker computes a gradient at weights that are a few updates old. Under what conditions is that harmless, and when would you expect it to hurt?
    A way to think about it

    A gradient is a local direction. Ask how far the shared weights have moved since the copy, which depends on the number of workers, the step size and the rollout length.

  3. With one worker the template is reproducible, with four it is not. Where exactly does the randomness enter, given that every worker has its own seeded generator?
    A way to think about it

    Each worker's own choices are fixed by its seed only if the weights it copies are the same each run. Consider what decides which worker's update reaches the shared networks first.

  4. A2C waits for all environments and makes one update. A3C lets each worker update alone. If both use the same total number of environment steps, which makes more updates, and what is the cost of that?
    A way to think about it

    Count the steps that go into one update in each method. More updates from smaller batches means each one is noisier, and in A3C some are also stale.