Experience Replay in Depth
Prioritization, the replay ratio and what makes replay work.
A replay buffer looks like plumbing: store transitions, sample minibatches. It quietly decides what the agent learns from: how old and how off-policy its data are, how often each experience is reused, whether early experience is overweighted, and, once sampling is prioritized, which loss is really being minimized. This lesson makes each of these precise, then shows that replay is planning with a non-parametric model, sometimes a better one than a learned model, and how replay scales to hundreds of actors.
What you’ll learn
- Write the expected update of uniform replay as an update under the buffer's empirical distribution, and derive reuse counts, data age and the overweighting of early data from the replay ratio and capacity.
- Prove that prioritized replay with is unbiased, and that in general it follows the expected gradient of a uniformly sampled loss .
- Summarize what varying replay capacity, data age and replay ratio independently revealed, including the role of -step returns and the explanations that were ruled out.
- Explain when replay is equivalent to planning with a model, why generating transitions from replayed states with a learned model can diverge, and how distributed and hindsight replay extend the idea.
The update replay actually performs
Experience replay goes back to Lin (1992), who stored an agent's past experiences and presented them to the learner again, to get more out of costly interaction. Make it precise. Let the buffer hold the last transitions. A uniformly drawn minibatch gives an unbiased estimate of
the expected semi-gradient under the buffer's empirical distribution over state–action pairs, with rewards and next states as they were observed. Two consequences follow. Learning becomes regression on a slowly changing dataset, and minibatches are independent draws from the buffer, not from the MDP. And is a mixture of the state–action distributions of every policy that filled the buffer, so a replaying learner is off-policy even when it acts with the policy it is evaluating: the on-policy stability guarantees of linear TD (The Deadly Triad) no longer apply.
Steady state. A full buffer holds transitions. Each environment step adds one, and the learner draws samples uniformly, where is the replay ratio (updates per step) and the minibatch size. A transition stays for steps, and each draw picks it with probability :
Age. The oldest transition in the buffer was generated steps, that is gradient updates, ago: the age of the oldest policy of Fedus et al. (2020).
A growing buffer. Before the buffer fills (in short runs it never does), at step it holds transitions, so the transition stored at step has been drawn, by step ,
An agent starts learning at once and, after every environment step, does one update on 32 transitions drawn uniformly from everything stored so far; in 100,000 steps its buffer never fills. In expectation, how many times has the transition stored at step 1,000 been drawn by step 100,000?
Show the answer
147
; the exact harmonic sum gives 147.4. The transition stored at step 90,000 is drawn only about times. Early experience, collected by the worst policies, is overweighted about 40-fold, purely because it sat in the buffer while the buffer was small. This is one mechanism behind the primacy bias (Plasticity Loss & Scaling Deep RL).
Is a bigger buffer always better? Not necessarily: older data are more off-policy. Zhang and Sutton (2017) found tasks in which a large buffer clearly hurt, and proposed combined experience replay, which always adds the newest transition to each minibatch, at only extra cost. On Atari, though, Fedus et al. found that giving DQN a ten times larger buffer changed nothing material, while for other agents it helped a lot (step 3).
Prioritized replay, and the loss it really minimizes
Most transitions drawn uniformly are ones the network already fits well, so most updates teach it little. Schaul et al. (2016) motivate prioritization with the Blind Cliffwalk: states, a reward only at the end, and a wrong action anywhere ending the episode, so a random action sequence succeeds with probability and the rare informative transitions drown among failures. Replaying in a good order speeds learning up exponentially there. Their practical scheme samples transition with probability
where is uniform. New transitions enter with the largest priority so that each is replayed at least once, and a priority is refreshed only when its transition is replayed, so most priorities are stale. For the proportional variant, a sum-tree, whose nodes store the sum of their children's priorities, samples and updates in ; the rank-based variant keeps an approximately sorted binary heap.
Schaul et al. annealed from to 1 over training, arguing that unbiasedness matters most near convergence, when the policy and the targets stop moving; they used (proportional) or (rank-based), with a step size four times smaller than DQN's. With these settings, prioritization raised Double DQN's median normalized score from 111% to 128% (57 games, proportional variant). An earlier rank-based version without importance weights, which annealed to 0 instead, improved DQN on 41 of 49 games, raising its median from 48% to 106%. But what does the update optimize before reaches 1? Fujimoto, Meger and Precup (2020) answered with a change of variables.
Write , use the loss (so ), priorities , and let . The expected weighted gradient is
Collect the powers of . The remaining factor is the same for every transition:
So prioritized replay follows, in expectation, the gradient of the uniformly sampled loss , scaled by a positive factor common to all transitions. With the squared loss (), exactly when ; for any , . (This is Fujimoto et al.'s equivalence, specialized to power losses; the small constant in the priorities is ignored.)
Proportional prioritization starts with and , with the squared loss. Early in training, prioritized replay follows the expected gradient of which power ?
Show the answer
2.36
. Why it matters: if one state–action pair has several stored targets (random rewards or next states), minimizing gives their mean for , their median for , and drifts toward the extreme targets as grows. Fujimoto et al. argue that this bias explains why prioritized replay often hurt actor–critic agents that use the squared loss.
The same change of variables runs the other way. An loss sampled with priorities has the expected gradient of uniformly sampled squared error, with lower variance, since every step then has the same size; Fujimoto et al. prove that among all loss–priority pairs with a given expected gradient this one minimizes the variance. Their loss-adjusted prioritized replay (LAP) uses the Huber loss with priorities , so that transitions in the quadratic region of the Huber loss are sampled uniformly. A caution from the other direction: in van Hasselt et al.'s (2018) study of the deadly triad, stronger prioritization went with more soft divergence (The Deadly Triad).
Capacity, age and the replay ratio
Changing the buffer size changes two things at once: how much data the agent has, and how old the oldest data are. Fedus et al. (2020) separated them by varying the capacity (0.1 to 10 million transitions) and the age of the oldest policy (25,000 to 25 million updates) independently, which forces the replay ratio to change with them. Their agent was Dopamine's Rainbow, which is DQN with prioritized replay, -step returns, Adam and C51 (no double, dueling or noisy components). Their main findings:
- At a fixed age, more capacity helped; at a fixed capacity, fresher data helped, except on the sparse-reward games Montezuma's Revenge and Private Eye, where data from older policies helped.
- DQN did not benefit from a ten times larger buffer; Rainbow did (table below).
- -step returns were the reason. Of the four components added to DQN one at a time, only -step returns let it profit from more capacity, and removing them from Rainbow removed the benefit; prioritization made no significant difference with large buffers.
- Two explanations failed or half-failed. If -step returns helped only by shrinking the bootstrap's weight to , a one-step update with discount should profit too; it did not. A variance explanation got partial support: with sticky actions turned off, so that returns were less random, the gains from capacity shrank.
| Agent | 1M → 10M at a fixed replay ratio | 1M → 10M at a fixed oldest-policy age |
|---|---|---|
| DQN | +0.1% | −0.4% |
| Rainbow (Dopamine) | +28.7% | +18.3% |
The other dial is the replay ratio itself. More updates per environment step reuse each transition more, and data-efficient agents push it hard: data-efficient Rainbow (below) does one update per step, SR-SPR up to 16, BBF 8, against DQN's . Each increase buys sample efficiency until the network stops being able to learn from new data; Plasticity Loss & Scaling Deep RL is about that limit, and the overweighting of early data computed in step 1 is part of it.
Replay as planning, and replay at scale
A model lets an agent spend computation instead of new experience; so does a replay buffer. van Hasselt, Hessel and Aslanides (2019) make the comparison exact. Queried at state–action pairs that were actually observed, in a deterministic environment, replay is indistinguishable from a perfect model. They also recall two linear results: fitting a linear model to the data and solving it gives the LSTD solution (Parr et al., 2008), and replaying all data exhaustively with linear TD() is equivalent to one pass of LSTD() (van Seijen & Sutton, 2015). Replay's limit is that it cannot be queried anywhere else.
The mechanism is the deadly triad's: the model can lead to states that are rare or impossible under the replay distribution, which are never updated directly but move through generalization, with the model playing the role of off-policy data. On Atari 100k the authors tested their prediction that replay should match or beat a model used only to generate transitions from observed states. Data-efficient Rainbow (DER: one update of 32 per step, , learning from step 1,600) used 3.2 million replayed samples, against 15.2 million model samples for the model-based SimPLe. It matched SimPLe after 70,000 interactions, scored about 25% higher at 100,000, and beat it on 17 of 26 games. Their conclusion is about how to use models: for planning backward, for credit assignment, or forward, to choose actions, rather than as a substitute for replay.
Replay is also only as current as its contents. In the maze's shortcut variant (Sutton & Barto, Example 8.3), a shorter route opens after 3,000 steps. Dyna-Q with 5 or more replays per step never switched to it in any of 30 runs per setting, while plain Q-learning found it in 25 of 30: heavy replay of experience saying the route is blocked keeps the agent from looking again (Dyna: Learning, Planning & Acting).
At scale, Ape-X (Horgan et al., 2018) separated acting from learning: 360 actors, actor acting -greedily with , compute initial priorities for their own transitions and feed one shared prioritized buffer of about 2 million transitions, from which a single GPU learner samples. Ape-X DQN reached a median of 434% human-normalized after 5 days, but on 22.8 billion frames per game, over 100 times Rainbow's 200 million: a gain in wall-clock time, not in data. R2D2 extended distributed replay to recurrent networks, replaying sequences with stored recurrent states and a burn-in period (Memory in Deep RL).
Replay can also rewrite what it stores. Hindsight experience replay (Andrychowicz et al., 2017) replays an attempt to reach goal that failed as a success at reaching the state actually reached, so that sparse failures become informative data for goal-conditioned values (Goal-Conditioned RL & Hindsight Relabeling).
Key takeaways
- Uniform replay follows the expected semi-gradient under the buffer's empirical distribution, a mixture of past policies' data; each transition is drawn about times (8 for DQN), the oldest data are updates old, and while a buffer grows, the transition from step is drawn about times, overweighting early experience.
- Importance weights with make prioritized sampling unbiased; in general, prioritized replay with priorities follows the expected gradient of the uniformly sampled loss , so with the squared loss and it is pulled toward outlying targets.
- Separating capacity from data age: more capacity and fresher data both helped Rainbow, a ten times larger buffer did nothing for DQN, and uncorrected -step returns were the component that made capacity pay, for reasons only partly understood.
- Replay is a non-parametric model: in deterministic tabular problems it is Dyna's model, and with linear TD exhaustive replay solves LSTD. Learned models that generate transitions from replayed states can diverge, and data-efficient Rainbow beat model-based SimPLe on Atari 100k.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does prioritized replay anneal its importance exponent to 1 by the end of training, instead of using throughout?
- makes the expected update equal to uniform replay's, which matters most near convergence; early on, targets move anyway, and weights below 1 trade some bias for smaller weight variance
- gives the strongest prioritization
- controls how often new transitions are replayed
- With the sum-tree is no longer needed
Show the answer
A. makes the expected update equal to uniform replay's, which matters most near convergence; early on, targets move anyway, and weights below 1 trade some bias for smaller weight variance
Only cancels the sampling distribution exactly. Before that the update follows a different loss ( with the squared loss), a bias Schaul et al. accepted while the policy, the state distribution and the targets were all changing anyway.
An agent replays from a buffer that has not yet filled. Compared with a transition stored late in training, how often is a transition stored early drawn in total?
- Equally often: uniform sampling treats all transitions alike
- Less often, because newer transitions crowd it out
- Much more often: it is drawn with probability at every step since it was stored, about times in all
- It depends only on the size of its TD error
Show the answer
C. Much more often: it is drawn with probability at every step since it was stored, about times in all
Each draw is uniform over the current buffer, but an early transition has been available for many more draws, while the buffer was small and each draw likely to pick it. With one update of 32 per step, the transition stored at step 1,000 is drawn about 147 times by step 100,000, the one from step 90,000 about 3 times.
Fedus et al. grew the buffer from 1 million to 10 million transitions at a fixed replay ratio. What happened?
- Both DQN and Rainbow improved about equally: more data always helps
- Rainbow improved (+28.7%) and DQN did not (+0.1%), and -step returns made the difference: adding them let DQN profit, removing them stopped Rainbow from profiting
- DQN improved because it lacks prioritization, which wastes large buffers
- Rainbow improved because prioritized replay finds the relevant transitions in a large buffer
Show the answer
B. Rainbow improved (+28.7%) and DQN did not (+0.1%), and -step returns made the difference: adding them let DQN profit, removing them stopped Rainbow from profiting
The additive and ablative studies isolate -step returns. Prioritization made no significant difference with large buffers, and a one-step update with the smaller weight on the bootstrap did not reproduce the effect.
When is uniform replay of stored transitions indistinguishable from planning with a perfect model?
- Always: a buffer and a model are two names for the same thing
- Never, since replay involves no model
- Whenever the model is linear
- When the environment is deterministic and the model would only be queried at state–action pairs that were actually observed
Show the answer
D. When the environment is deterministic and the model would only be queried at state–action pairs that were actually observed
A stored transition is then exactly what a perfect model would return for that pair; Dyna-Q's tabular model in a deterministic maze is literally a replay buffer. A model can do more, being queried at unseen pairs, and that is where its errors can make learning diverge.
Further reading
- L.-J. Lin, "Self-improving reactive agents based on reinforcement learning, planning and teaching", Machine Learning 8(3–4), 293–321 (1992).
- T. Schaul, J. Quan, I. Antonoglou & D. Silver, "Prioritized experience replay", ICLR (2016).
- W. Fedus, P. Ramachandran, R. Agarwal, Y. Bengio, H. Larochelle, M. Rowland & W. Dabney, "Revisiting fundamentals of experience replay", ICML (2020).
- H. van Hasselt, M. Hessel & J. Aslanides, "When to use parametric models in reinforcement learning?", NeurIPS (2019).
- S. Fujimoto, D. Meger & D. Precup, "An equivalence between loss functions and non-uniform sampling in experience replay", NeurIPS (2020).