A3C: Asynchronous Advantage Actor-Critic in PyTorch

Build A3C from scratch in PyTorch: a critic cuts REINFORCE's gradient variance, and asynchronous workers train it without a replay buffer, on CartPole.

Cover Image for A3C: Asynchronous Advantage Actor-Critic in PyTorch

You're training an agent to balance a pole, and two episodes can give it very different rewards even when its behaviour has changed little. Learning from those outcomes can make the updates noisy. A3C explores ways to make that learning steadier, using an estimate of expected reward and several workers gathering experience. Mnih and colleagues' 2016 A3C reached leading Atari results using CPU actors and no replay buffer.

We add a critic so a short run can use its estimate of future reward. The resulting five-step returns have about half the variance of full-episode returns. Asynchronous workers then supply experience to the CartPole learner, letting us compare both changes.

Let's Build It

Open this in Google Colab and run it top to bottom. It trains an actor-critic with four asynchronous worker threads and watches the pole come upright.

Open In Colab

Here is a worker balancing the pole after training. Every worker updates the same shared network, so this policy is the sum of four parallel streams of experience.

Animation of the CartPole environment. A black cart slides left and right along a track and a brown pole hinged on top stays balanced upright for the full episode, corrected by small continuous movements of the cart.

The whole algorithm is one network with two heads and a worker loop that repeats four ideas: roll a few steps, estimate the return with the critic, form the advantage, and push the gradient to a shared network.

import threading, numpy as np, torch, torch.nn as nn
from torch.distributions import Categorical
import gymnasium as gym

GAMMA, N_STEP, LR, WORKERS = 0.9, 5, 1e-4, 4

class ActorCritic(nn.Module):
    def __init__(self, obs=4, acts=2, h=128):
        super().__init__()
        self.pi = nn.Sequential(nn.Linear(obs, h), nn.Tanh(), nn.Linear(h, acts))  # actor
        self.v  = nn.Sequential(nn.Linear(obs, h), nn.Tanh(), nn.Linear(h, 1))     # critic
    def forward(self, x):
        return self.pi(x), self.v(x)          # action logits, state value V(s)

def worker(global_net, opt, lock, counter, stop, max_frames):
    env = gym.make("CartPole-v1", max_episode_steps=200)
    local = ActorCritic()
    s, _ = env.reset()
    while not stop[0]:
        local.load_state_dict(global_net.state_dict())        # pull the latest weights
        states, actions, rewards, done = [], [], [], False
        for _ in range(N_STEP):                               # roll up to n steps
            logits, _ = local(torch.as_tensor(s, dtype=torch.float32))
            a = Categorical(logits=logits).sample().item()
            s2, r, term, trunc, _ = env.step(a); done = term or trunc
            states.append(s); actions.append(a); rewards.append(r); s = s2
            if done: break

        # n-step target: real reward for n steps, then trust the critic for the rest
        R = 0.0 if done else local(torch.as_tensor(s, dtype=torch.float32))[1].item()
        targets = []
        for r in reversed(rewards):
            R = r + GAMMA * R; targets.insert(0, R)

        S  = torch.as_tensor(np.array(states), dtype=torch.float32)
        A  = torch.as_tensor(actions)
        Rt = torch.as_tensor(targets, dtype=torch.float32)
        logits, V = local(S); V = V.squeeze(1)
        advantage = Rt - V                                    # A = n-step return - V(s)
        m = Categorical(logits=logits)
        loss = advantage.pow(2).mean() \
             - (m.log_prob(A) * advantage.detach()).mean()    # critic loss + actor loss

        with lock:                                            # apply to the shared network
            opt.zero_grad(); local.zero_grad(); loss.backward()
            for gp, lp in zip(global_net.parameters(), local.parameters()):
                gp.grad = lp.grad
            opt.step(); counter[0] += len(rewards)
        if done: s, _ = env.reset()

Launch four of these on four threads, point them at one shared global_net, and the pole is balanced within about forty thousand frames. You just trained an asynchronous actor-critic. Now let us take it apart.

What Just Happened?

An actor and a critic, one network

Every policy-gradient method needs an actor: a policy πθ(a∣s)\pi_\theta(a \mid s) that maps a state to a distribution over actions. Actor-critic methods add a second output, a critic V(s)V(s) that estimates the expected return from a state. The actor decides what to do; the critic judges how good the situation was. In our network they are two small heads, self.pi and self.v, reading the same four-number CartPole observation.

The critic is not there to pick actions. Its only job is to make the actor's gradient less noisy, and that turns out to be the difference between a method that works on toy problems and one that works on Atari.

The advantage replaces the raw return

REINFORCE nudges the policy in the direction of actions that led to high return. Its gradient is an expectation over the full Monte-Carlo return GtG_t:

∇θJ(θ)=E[ ∇θlog⁡πθ(at∣st)  Gt ]\nabla_\theta J(\theta) = \mathbb{E}\big[\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\; G_t \,\big]

GtG_t is a sum of every discounted reward to the end of the episode. On CartPole that is the whole balancing act, and it swings wildly: the same policy might drop the pole at step 20 in one episode and hold it to step 200 in the next.

Histogram of episode lengths from a single partly-trained CartPole policy sampled 400 times. The lengths spread almost uniformly from about 15 steps to the 200-step cap, with a mean near 90, showing that the same stochastic policy produces very different episode outcomes.

Actor-critic replaces GtG_t with the advantage, how much better an action did than the critic expected:

A(st,at)=Rt(n)−V(st)A(s_t, a_t) = R_t^{(n)} - V(s_t)

Subtracting V(st)V(s_t) is subtracting a baseline. Because the baseline does not depend on the action taken, it does not change the direction of the gradient in expectation (the score function ∇θlog⁡πθ\nabla_\theta \log \pi_\theta has mean zero), but it does shrink the variance. Instead of asking "did this whole episode go well", the actor asks "did this action beat the average from here", a question with a far steadier answer. That is the entire reason the critic exists.

N-step returns trade bias for variance

The advantage still needs an estimate of the return, Rt(n)R_t^{(n)}. We could use the full Monte-Carlo return (all the way to the end, unbiased but high variance) or the critic's one-step guess (low variance but biased by the critic's error). The n-step return sits in between: take nn real rewards, then bootstrap from the critic.

Rt(n)=∑k=0n−1γk rt+k  +  γn V(st+n)R_t^{(n)} = \sum_{k=0}^{n-1} \gamma^k\, r_{t+k} \;+\; \gamma^n\, V(s_{t+n})

Larger nn means more real reward and less reliance on the critic: less bias, more variance. In the limit n→∞n \to \infty you recover the Monte-Carlo return that REINFORCE uses. Measuring the variance of the return estimate on a fixed policy makes the trade-off concrete.

Line chart of the variance of the return estimate against n, the number of real-reward steps before bootstrapping from the critic. Variance rises monotonically from near zero at n=1 to its maximum at the Monte-Carlo return. The n=5 point used by A2C and A3C is circled, sitting at roughly half the Monte-Carlo variance.

The curve climbs steadily. The Monte-Carlo return REINFORCE relies on sits at the top; the five-step return our actor-critic uses has about half the variance. Push to a one-step return and the variance nearly vanishes, but the estimate now leans almost entirely on an imperfect critic. Five steps is a common middle ground, and it is what A2C and A3C use here.

Going Deeper

From one learner to many: the asynchronous part

Everything so far describes A2C: a single learner stepping one environment, updating after every nn steps. A3C changes one thing. It runs several workers at once, each with its own copy of the environment and its own local network, and each one computes gradients on its own recent experience and applies them to a shared global network without waiting for the others.

That asynchrony solves a problem specific to on-policy learning. A single learner sees a stream of highly correlated states (consecutive frames of one episode look almost identical), and correlated gradients make training wobble. DQN breaks that correlation with a replay buffer of old transitions. A3C cannot use a replay buffer, because policy gradients must be computed on data from the current policy, so it breaks the correlation a different way: at any instant the workers are in different parts of different episodes, so the mix of gradients hitting the global network is diverse. Parallel actors replace the replay buffer.

The lock in the code makes each gradient application atomic. The original A3C paper drops even that and lets workers overwrite each other (Hogwild-style), but on CartPole a lock is simpler and costs nothing. One practical detail: with several workers pushing gradients into the same network at once, a worker's gradient often lands on weights another worker has already moved, so the updates are noisier than a single learner's. A3C is more stable with a smaller learning rate (10−410^{-4} here) than the single-learner A2C (3×10−43 \times 10^{-4}).

What the training curves show

Train all three from scratch, five seeds each, and evaluate a greedy version of the policy every few thousand frames.

Learning curves of evaluation reward against environment frames for REINFORCE, A2C, and A3C on CartPole capped at 200 steps, showing mean and standard deviation over five seeds. All three rise to the solved line at 195. REINFORCE rises fastest in frames, A2C rises fast but wobbles, and A3C rises more slowly but settles into the tightest, steadiest band near 200.

Three honest observations. First, all three solve CartPole: it is an easy task, and a well-tuned REINFORCE with a normalised-return baseline is genuinely fast on it, reaching the solved bar in the fewest frames. Second, the single-learner A2C reaches the bar quickly but wobbles afterwards, exactly the correlated-gradient instability the asynchronous workers are meant to cure. Third, A3C is the slowest in raw frames but produces the steadiest late training, the tightest band around 200. That is the pattern the A3C paper reports at scale: the async workers buy stability, not sample efficiency.

The honest verdict: synchronous is just as good

A3C spends more frames than a single learner, and it is worth being clear about why anyone accepted that trade. The win was never the asynchrony itself; it was running many actors in parallel, which let A3C soak up CPU cores and skip the replay buffer. In 2017 OpenAI showed that a synchronous version, which waits for all workers, averages their gradients, and applies one update, matches or beats A3C. They named it A2C, "advantage actor-critic", and it is the version most libraries ship. Modern practice reaches for A2C or PPO with a batch of vectorised environments rather than asynchronous threads.

So why learn A3C? Because it introduced the template every one of those methods still uses: an actor and a critic sharing a network, the advantage as the training signal, n-step returns to trade bias for variance, and parallel actors for stable on-policy data. PPO, the default policy-gradient method today, is A3C's advantage objective plus a clipped update. Build A3C once and you have built the core of all of them.

Where This Comes From

The pieces arrived over twenty-five years. Williams (1992) introduced REINFORCE and the score-function gradient. Sutton, McAllester, Singh, and Mansour (1999) proved the policy gradient theorem that makes it all rigorous, and Konda and Tsitsiklis (2000) formalised the actor-critic pairing, with the critic as a learned baseline. The advantage-as-baseline idea, that subtracting V(s)V(s) reduces variance without adding bias, is the thread running through all of them.

A3C itself is Mnih et al. (2016), "Asynchronous Methods for Deep Reinforcement Learning", which showed that with parallel actors you no longer need a replay buffer or a GPU to reach state-of-the-art on Atari. The code this post is built from is a PyTorch rewrite of a TensorFlow 1 implementation following Arthur Juliani's 2016 tutorial series. The synchronous-is-fine result is from OpenAI's 2017 write-up that named A2C.

Further Reading

  • The algorithm: Mnih et al. (2016), "Asynchronous Methods for Deep Reinforcement Learning". The paper that introduced A3C.
  • The foundations: Sutton et al. (1999), "Policy Gradient Methods for Reinforcement Learning with Function Approximation"; Konda & Tsitsiklis (2000), "Actor-Critic Algorithms".
  • Why synchronous: OpenAI (2017), "OpenAI Baselines: ACKTR & A2C", on why A2C matches A3C.
  • Next step: TRPO and PPO from scratch, which take this advantage objective and make the policy update safe.

Interactive Tools

  • Q-Learning Visualizer: Watch a value-based agent bootstrap its estimates, the same temporal-difference idea the critic uses here.
  • Markov Chain Simulator: Build intuition for the state transitions and returns that both the actor and the critic are reasoning about.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions