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
ReplayBuffer.addwrites one transition into the row atpos, then movesposforward. When the ring is full the oldest row is overwritten.ReplayBuffer.sampledrawsbatch_sizerow numbers uniformly, with replacement, and returns the matching arrays.PrioritizedReplayBuffer.addalso stores the largest priority seen so far for the new row, so every transition is replayed at least once.- Its
samplecuts the total priority mass intobatch_sizeequal slices, draws one point in each, and usesSumTree.findto locate the row under each point in steps. - It returns importance-sampling weights with each batch. Multiply each sample's loss by its weight, then call
update_prioritieswith the new TD errors. RolloutBuffer.addstores step with the value estimate . When the rollout is complete,compute_returns_and_advantageswalks backward through it to filladvantagesandreturns.batchesyields shuffled minibatches that cover every stored step once. Callresetbefore 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 stays at the configured value unless you pass
betatosample. The original method raises it to 1 over training, so the correction is only partial if you never change it. RolloutBuffertreats everydoneas 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
| If | Use instead |
|---|---|
| The algorithm is on-policy, such as A2C or PPO | The rollout buffer, never a replay buffer of old data |
| Prioritised sampling adds cost without a clear gain | The uniform replay ring |
| The problem is tabular and tiny | No buffer: update from each step as in Q-learning or SARSA |
Math foundations
Uniform replay
Every stored transition is equally likely to be drawn. Sampling at random breaks the correlation between consecutive steps of one episode.
Prioritized sampling
A transition is drawn in proportion to its priority raised to . The priority is the size of its last TD error plus a small constant, so nothing has probability zero. With this is uniform replay.
Importance-sampling weight
Drawing some transitions more often changes the average the learner sees. This weight undoes that change, fully when . Dividing by the largest possible weight keeps all weights in so the step size never grows.
TD residual
How much better step turned out than the value estimate predicted. The factor removes the future value when the episode ended at step .
Generalized advantage estimate
The advantage is a discounted sum of TD residuals, computed backward from the last step. gives the one-step estimate (low variance, more bias). gives the full Monte Carlo estimate (no bias from , more variance).
Return target
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
- number of transitions currently stored
- probability that transition i is drawn
- priority of transition i
- how strongly priority shapes sampling (0 is uniform)
- small constant added to every priority (priority_eps)
- strength of the importance-sampling correction (1 is full)
- importance-sampling weight of a sampled transition
- TD residual (temporal-difference error) at step t
- reward received at step t
- 1 if the episode ended with step t, otherwise 0
- estimated value of state s
- discount factor
- GAE mixing parameter (gae_lambda)
- 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 and , so .
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
- 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.
- With and 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.
- You set and training becomes noisy. You set and it becomes stable but learns the wrong thing while the value network is still poor. Why?
A way to think about it
Write for both settings. One uses only real rewards along the whole rollout, the other trusts after a single step.
- A sum tree makes sampling cost . 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.
- 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 in the TD residual. What value does it assign to everything after the cut, and is that true of the environment?