Sign in

Buffers

Replay and rollout buffers

Three stores for an agent's experience: a uniform replay ring, a prioritized replay ring on a sum tree, and an on-policy rollout buffer that computes advantages.

Overview

An agent learns from transitions: what it saw, what it did, what reward came back and what it saw next. A replay buffer keeps the most recent transitions in a fixed block of memory and hands back random batches, so one experience can be learned from many times and neighbouring steps do not dominate a batch. Prioritized replay draws surprising transitions more often, where surprise is the size of the last prediction error, and then down-weights them so the learning target is not distorted. A rollout buffer is different: it holds one short stretch of fresh experience in time order, works out how much better each action was than expected, and is then emptied.

A short history

Long-Ji Lin introduced experience replay in 1992 so that an agent could reuse past steps. It became central when DQN used a large uniform replay buffer in 2013 and 2015. Tom Schaul and colleagues at DeepMind added prioritised replay in 2015, sampling steps with large errors more often using a sum tree. Rollout buffers come from the on-policy line of work, and the advantage calculation most of them use is generalised advantage estimation, published by John Schulman and colleagues in 2015.

How it works

  1. ReplayBuffer.add writes one transition (s,a,r,s′,d)(s, a, r, s', d) into the row at pos, then moves pos forward. When the ring is full the oldest row is overwritten.
  2. ReplayBuffer.sample draws batch_size row numbers uniformly, with replacement, and returns the matching arrays.
  3. PrioritizedReplayBuffer.add also stores the largest priority seen so far for the new row, so every transition is replayed at least once.
  4. Its sample cuts the total priority mass into batch_size equal slices, draws one point in each, and uses SumTree.find to locate the row under each point in O(log⁡N)O(\log N) steps.
  5. It returns importance-sampling weights with each batch. Multiply each sample's loss by its weight, then call update_priorities with the new TD errors.
  6. RolloutBuffer.add stores step tt with the value estimate V(st)V(s_t). When the rollout is complete, compute_returns_and_advantages walks backward through it to fill advantages and returns.
  7. batches yields shuffled minibatches that cover every stored step once. Call reset before the next rollout.

Watch out for

  • Replaying old data with an on-policy method biases the gradient, because the data no longer comes from the current policy. The rollout buffer must be reset after every update.
  • Skipping the importance-sampling weights in prioritized replay changes the expected update: rarely sampled transitions are under-counted and the value estimates drift toward the frequently sampled ones.
  • Here β\beta stays at the configured value unless you pass beta to sample. The original method raises it to 1 over training, so the correction is only partial if you never change it.
  • RolloutBuffer treats every done as a true end and drops the bootstrap value. If the episode was only cut by a time limit, the advantage of the last steps is underestimated.
  • A capacity that is too small forgets useful old experience, and one that is too large keeps data from a policy that no longer exists. Both slow learning.

Use cases

When to use it

Use ReplayBuffer for off-policy methods such as DQN, DDPG and SAC, PrioritizedReplayBuffer when a few transitions carry most of the learning signal, and RolloutBuffer for on-policy methods such as A2C and PPO.

In industry

Games and simulation
DQN-style agents store millions of past frames in a replay ring and sample random minibatches from it for every update.
Robotics
Off-policy methods such as SAC keep all robot experience in a replay buffer, so that costly real-world steps are reused many times.
Large-scale training
On-policy systems such as PPO fill a rollout buffer from many parallel simulators, compute advantages once, then discard the data.

Choosing it: what must hold

  • Enough memory for the buffer: image observations and millions of steps add up quickly.
  • A match between buffer and algorithm: replay for off-policy methods, a rollout buffer for on-policy methods.
  • For prioritised replay, importance weights in the loss to correct the bias from uneven sampling.

When to choose something else

IfUse instead
The algorithm is on-policy, such as A2C or PPOThe rollout buffer, never a replay buffer of old data
Prioritised sampling adds cost without a clear gainThe uniform replay ring
The problem is tabular and tinyNo buffer: update from each step as in Q-learning or SARSA

Math foundations

  1. Uniform replay

    P(i)=1NP(i) = \frac{1}{N}

    Every stored transition is equally likely to be drawn. Sampling at random breaks the correlation between consecutive steps of one episode.

  2. Prioritized sampling

    P(i)=piα∑kpkα,pi=∣δi∣+ϵP(i) = \frac{p_i^{\alpha}}{\sum_{k} p_k^{\alpha}}, \qquad p_i = |\delta_i| + \epsilon

    A transition is drawn in proportion to its priority raised to α\alpha. The priority is the size of its last TD error plus a small constant, so nothing has probability zero. With α=0\alpha = 0 this is uniform replay.

  3. Importance-sampling weight

    wi=(N P(i))−βmax⁡j(N P(j))−βw_i = \frac{\big(N \, P(i)\big)^{-\beta}}{\max_j \big(N \, P(j)\big)^{-\beta}}

    Drawing some transitions more often changes the average the learner sees. This weight undoes that change, fully when β=1\beta = 1. Dividing by the largest possible weight keeps all weights in (0,1](0, 1] so the step size never grows.

  4. TD residual

    δt=rt+γ V(st+1) (1−dt)−V(st)\delta_t = r_t + \gamma \, V(s_{t+1}) \, (1 - d_t) - V(s_t)

    How much better step tt turned out than the value estimate predicted. The factor (1−dt)(1 - d_t) removes the future value when the episode ended at step tt.

  5. Generalized advantage estimate

    At=δt+γλ (1−dt) At+1A_t = \delta_t + \gamma \lambda \, (1 - d_t) \, A_{t+1}

    The advantage is a discounted sum of TD residuals, computed backward from the last step. λ=0\lambda = 0 gives the one-step estimate (low variance, more bias). λ=1\lambda = 1 gives the full Monte Carlo estimate (no bias from VV, more variance).

  6. Return target

    Rt=At+V(st)R_t = A_t + V(s_t)

    The value network is trained toward this target. It is the advantage added back onto the value estimate that was subtracted to form it.

Symbols

NN
number of transitions currently stored
P(i)P(i)
probability that transition i is drawn
pip_i
priority of transition i
α\alpha
how strongly priority shapes sampling (0 is uniform)
ϵ\epsilon
small constant added to every priority (priority_eps)
β\beta
strength of the importance-sampling correction (1 is full)
wiw_i
importance-sampling weight of a sampled transition
δt\delta_t
TD residual (temporal-difference error) at step t
rtr_t
reward received at step t
dtd_t
1 if the episode ended with step t, otherwise 0
V(s)V(s)
estimated value of state s
γ\gamma
discount factor
λ\lambda
GAE mixing parameter (gae_lambda)
At,  RtA_t,\; R_t
advantage and return target at step t

Worked by hand

A rollout of three steps, each with reward 1 and value estimate 0.5, followed by a state of value 0.5. No step ends the episode. Use the defaults γ=0.99\gamma = 0.99 and λ=0.95\lambda = 0.95, so γλ=0.9405\gamma\lambda = 0.9405.

δ0=δ1=δ2=1+0.99×0.5−0.5=0.995\delta_0 = \delta_1 = \delta_2 = 1 + 0.99 \times 0.5 - 0.5 = 0.995
A2=0.995A_2 = 0.995
A1=0.995+0.9405×0.995=1.9308A_1 = 0.995 + 0.9405 \times 0.995 = 1.9308
A0=0.995+0.9405×1.9308=2.8109A_0 = 0.995 + 0.9405 \times 1.9308 = 2.8109
R0=2.8109+0.5=3.3109R_0 = 2.8109 + 0.5 = 3.3109

Earlier steps get larger advantages because they collect more of the surprise that follows them. This is the rollout in the template's own usage example, so you can compare with roll.advantages.

Visual example

Loading the example.

Try this

  • Press Sample a batch several times: the widest segments are drawn, their errors halve, and they shrink.
  • Slide α to 0 and the segments become equal, which is uniform replay.
  • Add transitions until the ring is full and watch the next write overwrite the oldest row.
  • Move the point along the mass and follow the path find takes down the tree.

Code sample

import numpy as np
from impl import PrioritizedReplayBuffer, RolloutBuffer
from config import BuffersConfig

cfg = BuffersConfig(capacity=100, obs_dim=2, batch_size=4)
buf = PrioritizedReplayBuffer(cfg)
for i in range(10):
    buf.add(np.ones(2) * i, [0], float(i), np.ones(2) * (i + 1), False)
batch = buf.sample()                        # dict with obs, actions, rewards, next_obs, dones, weights, indices
buf.update_priorities(batch["indices"], np.abs(batch["rewards"]))

roll = RolloutBuffer(BuffersConfig(obs_dim=2), n_steps=3)
for r in (1.0, 1.0, 1.0):
    roll.add(np.zeros(2), [0], r, done=False, value=0.5)
roll.compute_returns_and_advantages(last_value=0.5)
print(roll.advantages, roll.returns)
Read the implementation (227 lines)
"""Replay and rollout buffers: uniform replay, prioritized replay (sum tree) and an on-policy rollout with GAE.

NumPy only. Every buffer stores flat float observation and action vectors in preallocated arrays.
"""
from __future__ import annotations

import numpy as np

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


class ReplayBuffer:
    """Fixed-size ring buffer of transitions, sampled uniformly at random."""

    def __init__(self, config: BuffersConfig | None = None) -> None:
        self.config = config or BuffersConfig()
        n = self.config.capacity
        self.obs = np.zeros((n, self.config.obs_dim))
        self.actions = np.zeros((n, self.config.action_dim))
        self.rewards = np.zeros(n)
        self.next_obs = np.zeros((n, self.config.obs_dim))
        self.dones = np.zeros(n)
        self.pos = 0  # row the next transition is written to
        self.size = 0  # number of valid rows
        self.rng = np.random.default_rng(self.config.seed)

    def __len__(self) -> int:
        return self.size

    def add(self, obs, action, reward: float, next_obs, done: bool) -> int:
        """Store one transition and return the row it went to.

        obs, next_obs: shape (obs_dim,). action: shape (action_dim,) or a scalar. Overwrites the oldest row when full.
        """
        i = self.pos
        self.obs[i] = obs
        self.actions[i] = action
        self.rewards[i] = reward
        self.next_obs[i] = next_obs
        self.dones[i] = float(done)
        self.pos = (self.pos + 1) % self.config.capacity
        self.size = min(self.size + 1, self.config.capacity)
        return i

    def _gather(self, idx: np.ndarray) -> dict:
        return {
            "obs": self.obs[idx],
            "actions": self.actions[idx],
            "rewards": self.rewards[idx],
            "next_obs": self.next_obs[idx],
            "dones": self.dones[idx],
            "indices": idx,
        }

    def sample(self, batch_size: int | None = None) -> dict:
        """Draw `batch_size` transitions uniformly with replacement.

        Returns a dict of arrays: obs (B, obs_dim), actions (B, action_dim), rewards (B,), next_obs (B, obs_dim),
        dones (B,), indices (B,).
        """
        if self.size == 0:
            raise ValueError("cannot sample from an empty buffer")
        b = batch_size or self.config.batch_size
        return self._gather(self.rng.integers(0, self.size, size=b))


class SumTree:
    """Binary tree over `capacity` leaves where each inner node holds the sum of its children.

    Setting a leaf and finding the leaf at a given cumulative sum both cost O(log capacity).
    """

    def __init__(self, capacity: int) -> None:
        self.capacity = capacity
        self.n_leaves = 1
        while self.n_leaves < capacity:
            self.n_leaves *= 2
        self.nodes = np.zeros(2 * self.n_leaves)  # node 1 is the root, leaves start at n_leaves

    @property
    def total(self) -> float:
        return float(self.nodes[1])

    def get(self, index: int) -> float:
        return float(self.nodes[self.n_leaves + index])

    def set(self, index: int, value: float) -> None:
        """Set leaf `index` to `value` and refresh the sums above it."""
        i = self.n_leaves + index
        self.nodes[i] = value
        i //= 2
        while i >= 1:
            self.nodes[i] = self.nodes[2 * i] + self.nodes[2 * i + 1]
            i //= 2

    def find(self, mass: float) -> int:
        """Return the leaf index i such that sum(leaves[:i]) <= mass < sum(leaves[:i + 1])."""
        i = 1
        while i < self.n_leaves:
            left = self.nodes[2 * i]
            if mass < left:
                i = 2 * i
            else:
                mass -= left
                i = 2 * i + 1
        return min(i - self.n_leaves, self.capacity - 1)


class PrioritizedReplayBuffer(ReplayBuffer):
    """Proportional prioritized replay: P(i) = p_i ** alpha / sum_k p_k ** alpha."""

    def __init__(self, config: BuffersConfig | None = None) -> None:
        super().__init__(config)
        self.tree = SumTree(self.config.capacity)
        self.max_priority = 1.0  # new transitions get the largest priority seen, so each is replayed at least once

    def add(self, obs, action, reward: float, next_obs, done: bool) -> int:
        i = super().add(obs, action, reward, next_obs, done)
        self.tree.set(i, self.max_priority**self.config.alpha)
        return i

    def probabilities(self) -> np.ndarray:
        """Sampling probability of every stored row, shape (size,)."""
        leaves = self.tree.nodes[self.tree.n_leaves : self.tree.n_leaves + self.size]
        return leaves / self.tree.total

    def sample(self, batch_size: int | None = None, beta: float | None = None) -> dict:
        """Draw a batch by priority (stratified: one draw per equal slice of the total mass).

        Returns the same dict as `ReplayBuffer.sample` plus `weights` (B,), the importance-sampling weights
        `(size * P(i)) ** -beta` divided by the largest possible weight so they lie in (0, 1].
        """
        if self.size == 0:
            raise ValueError("cannot sample from an empty buffer")
        b = batch_size or self.config.batch_size
        beta = self.config.beta if beta is None else beta
        total = self.tree.total
        edges = np.linspace(0.0, total, b + 1)
        masses = self.rng.uniform(edges[:-1], edges[1:])
        idx = np.array([min(self.tree.find(m), self.size - 1) for m in masses])
        probs = self.probabilities()
        weights = (self.size * probs[idx]) ** (-beta)
        weights = weights / (self.size * probs.min()) ** (-beta)
        batch = self._gather(idx)
        batch["weights"] = weights
        return batch

    def update_priorities(self, indices, td_errors) -> None:
        """Set the priority of each sampled row to |TD error| + priority_eps."""
        for i, err in zip(np.asarray(indices).ravel(), np.asarray(td_errors, dtype=float).ravel()):
            priority = abs(float(err)) + self.config.priority_eps
            self.max_priority = max(self.max_priority, priority)
            self.tree.set(int(i), priority**self.config.alpha)


class RolloutBuffer:
    """One on-policy rollout of `n_steps` transitions with value estimates, for A2C or PPO."""

    def __init__(self, config: BuffersConfig | None = None, n_steps: int = 128) -> None:
        self.config = config or BuffersConfig()
        if n_steps < 1:
            raise ValueError(f"n_steps must be at least 1, got {n_steps}")
        self.n_steps = n_steps
        self.obs = np.zeros((n_steps, self.config.obs_dim))
        self.actions = np.zeros((n_steps, self.config.action_dim))
        self.rewards = np.zeros(n_steps)
        self.dones = np.zeros(n_steps)
        self.values = np.zeros(n_steps)
        self.log_probs = np.zeros(n_steps)
        self.advantages = np.zeros(n_steps)
        self.returns = np.zeros(n_steps)
        self.pos = 0

    @property
    def full(self) -> bool:
        return self.pos == self.n_steps

    def reset(self) -> None:
        self.pos = 0

    def add(self, obs, action, reward: float, done: bool, value: float, log_prob: float = 0.0) -> None:
        """Store step t. `done` says the episode ended with this step; `value` is V(obs)."""
        if self.full:
            raise ValueError("rollout buffer is full; call reset() first")
        t = self.pos
        self.obs[t] = obs
        self.actions[t] = action
        self.rewards[t] = reward
        self.dones[t] = float(done)
        self.values[t] = value
        self.log_probs[t] = log_prob
        self.pos += 1

    def compute_returns_and_advantages(self, last_value: float = 0.0) -> None:
        """Fill `advantages` with GAE(gamma, lambda) and `returns` with advantages + values.

        last_value: V of the observation that follows the final stored step (ignored if that step ended an episode).
        delta_t = r_t + gamma * V_{t+1} * (1 - done_t) - V_t;  A_t = delta_t + gamma * lambda * (1 - done_t) * A_{t+1}.
        """
        gamma, lam = self.config.gamma, self.config.gae_lambda
        gae = 0.0
        for t in reversed(range(self.pos)):
            next_value = last_value if t == self.pos - 1 else self.values[t + 1]
            not_done = 1.0 - self.dones[t]
            delta = self.rewards[t] + gamma * next_value * not_done - self.values[t]
            gae = delta + gamma * lam * not_done * gae
            self.advantages[t] = gae
        self.returns[: self.pos] = self.advantages[: self.pos] + self.values[: self.pos]

    def batches(self, batch_size: int, rng: np.random.Generator | None = None):
        """Yield dicts of shuffled minibatches covering every stored step exactly once."""
        rng = rng or np.random.default_rng(self.config.seed)
        order = rng.permutation(self.pos)
        for start in range(0, self.pos, batch_size):
            idx = order[start : start + batch_size]
            yield {
                "obs": self.obs[idx],
                "actions": self.actions[idx],
                "values": self.values[idx],
                "log_probs": self.log_probs[idx],
                "advantages": self.advantages[idx],
                "returns": self.returns[idx],
                "indices": idx,
            }
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
13, run with python3 -m unittest -v

Practice

Build a PrioritizedReplayBuffer with BuffersConfig(capacity=8, obs_dim=2, alpha=1.0), add 8 transitions, and call update_priorities on rows 0 to 7 with errors 1 to 8. Check that probabilities() equals each priority divided by their sum. Then call sample(batch_size=8, beta=1.0) many times, count how often each row appears, and confirm that weight times probability is the same for every row.

Check on learning

  1. New transitions enter the prioritized buffer with the largest priority seen so far, not with priority zero or the average. What would go wrong with each of the other two choices?
    A way to think about it

    A transition has no TD error until it has been sampled once. Ask how a row with a tiny starting priority could ever get its error measured.

  2. With α=1\alpha = 1 and β=0\beta = 0 a DQN learns faster at first but ends with worse value estimates than uniform replay. Explain both halves.
    A way to think about it

    Think about which transitions fill the batches early on, and then about what average the loss is taken over when no weights are applied.

  3. You set λ=1\lambda = 1 and training becomes noisy. You set λ=0\lambda = 0 and it becomes stable but learns the wrong thing while the value network is still poor. Why?
    A way to think about it

    Write AtA_t for both settings. One uses only real rewards along the whole rollout, the other trusts V(st+1)V(s_{t+1}) after a single step.

  4. A sum tree makes sampling cost O(log⁡N)O(\log N). What would the cost be with a plain array of priorities, and at what buffer size would you start to notice?
    A way to think about it

    To sample from an array you need a running total up to the chosen point. Count the operations per sample for a buffer of one million rows and a batch of 32.

  5. An episode is cut off by a 200-step time limit while the agent is doing well. How does treating that cut as a real ending change what the agent learns about late states?
    A way to think about it

    Look at the factor (1−dt)(1 - d_t) in the TD residual. What value does it assign to everything after the cut, and is that true of the environment?