Simple Algorithm
Reinforcement Learning · Fixed Point · 26 min

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 β=1\beta=1 is unbiased, and that in general it follows the expected gradient of a uniformly sampled loss ∣δ∣τ+α−αβ\abs\delta^{\tau+\alpha-\alpha\beta}.
  • Summarize what varying replay capacity, data age and replay ratio independently revealed, including the role of nn-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 Dt\data_t hold the last NN transitions. A uniformly drawn minibatch gives an unbiased estimate of

gˉt(θ)=1∣Dt∣∑(s,a,r,s′)∈Dtδ(s,a,r,s′;θ) ∇θQθ(s,a),\bar g_t(\boldsymbol\theta)=\frac{1}{\abs{\data_t}}\sum_{(s,a,r,s')\in\data_t}\delta(s,a,r,s';\boldsymbol\theta)\,\nabla_{\boldsymbol\theta}Q_{\boldsymbol\theta}(s,a),

the expected semi-gradient under the buffer's empirical distribution μ^t\hat\mu_t 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 μ^t\hat\mu_t 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.

DerivationCounting replays
  1. E[draws of one transition]=N⋅ρB⋅1N=ρB(DQN: 14⋅32=8)\E[\text{draws of one transition}]=N\cdot\rho B\cdot\frac1N=\rho B\qquad(\text{DQN: }\tfrac14\cdot32=8)

    Steady state. A full buffer holds NN transitions. Each environment step adds one, and the learner draws ρB\rho B samples uniformly, where ρ\rho is the replay ratio (updates per step) and BB the minibatch size. A transition stays for NN steps, and each draw picks it with probability 1/N1/N:

  2. agemax⁡=Nρ updates(DQN: 106⋅14=250,000)\text{age}_{\max}=N\rho\ \text{updates}\qquad(\text{DQN: }10^6\cdot\tfrac14=250{,}000)

    Age. The oldest transition in the buffer was generated NN steps, that is NρN\rho gradient updates, ago: the age of the oldest policy of Fedus et al. (2020).

  3. E[draws of transition t by step T]=ρB∑u=tT1u ≈ ρBln⁡Tt\E[\text{draws of transition }t\text{ by step }T]=\rho B\sum_{u=t}^{T}\frac1u\ \approx\ \rho B\ln\frac Tt

    A growing buffer. Before the buffer fills (in short runs it never does), at step uu it holds uu transitions, so the transition stored at step tt has been drawn, by step TT,

Predict before you look

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

32∑u=10001000001/u≈32ln⁡100≈14732\sum_{u=1000}^{100000}1/u\approx32\ln100\approx147; the exact harmonic sum gives 147.4. The transition stored at step 90,000 is drawn only about 32ln⁡(10/9)≈3.432\ln(10/9)\approx3.4 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 O(1)\order{1} 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: nn states, a reward only at the end, and a wrong action anywhere ending the episode, so a random action sequence succeeds with probability 2−n2^{-n} and the rare informative transitions drown among failures. Replaying in a good order speeds learning up exponentially there. Their practical scheme samples transition ii with probability

P(i)=pi α∑kpk α,pi=∣δi∣+ϵ  (proportional)orpi=1rank⁡(i)  (rank-based),P(i)=\frac{p_i^{\,\alpha}}{\sum_kp_k^{\,\alpha}},\qquad p_i=\abs{\delta_i}+\epsilon\ \ \text{(proportional)}\quad\text{or}\quad p_i=\frac{1}{\operatorname{rank}(i)}\ \ \text{(rank-based)},

where α=0\alpha=0 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 O(log⁡N)O(\log N); the rank-based variant keeps an approximately sorted binary heap.

Schaul et al. annealed β\beta from β0\beta_0 to 1 over training, arguing that unbiasedness matters most near convergence, when the policy and the targets stop moving; they used α=0.6,β0=0.4\alpha=0.6,\beta_0=0.4 (proportional) or α=0.7,β0=0.5\alpha=0.7,\beta_0=0.5 (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 α\alpha to 0 instead, improved DQN on 41 of 49 games, raising its median from 48% to 106%. But what does the update optimize before β\beta reaches 1? Fujimoto, Meger and Precup (2020) answered with a change of variables.

DerivationThe uniformly sampled loss that prioritized replay follows
  1. Ei∼P[wi ℓτ′(δi)∇Qi]=∑i∣δi∣α(1−β)S1−βNβ sign⁡(δi)∣δi∣τ−1∇Qi\E_{i\sim P}\big[w_i\,\ell_\tau'(\delta_i)\nabla Q_i\big]=\sum_i\frac{\abs{\delta_i}^{\alpha(1-\beta)}}{S^{1-\beta}N^{\beta}}\,\sign(\delta_i)\abs{\delta_i}^{\tau-1}\nabla Q_i

    Write δi=Qθ(si,ai)−yi\delta_i=Q_{\boldsymbol\theta}(s_i,a_i)-y_i, use the loss ℓτ(δ)=∣δ∣τ/τ\ell_\tau(\delta)=\abs\delta^\tau/\tau (so ℓτ′(δ)=sign⁡(δ)∣δ∣τ−1\ell_\tau'(\delta)=\sign(\delta)\abs\delta^{\tau-1}), priorities ∣δi∣α\abs{\delta_i}^\alpha, and let S=∑k∣δk∣αS=\sum_k\abs{\delta_k}^\alpha. The expected weighted gradient is

  2. =(NS)1−β 1N∑isign⁡(δi)∣δi∣κ−1∇Qi=(NS)1−β Ei∼U[ℓκ′(δi)∇Qi],κ=τ+α−αβ=\Big(\frac NS\Big)^{1-\beta}\,\frac1N\sum_i\sign(\delta_i)\abs{\delta_i}^{\kappa-1}\nabla Q_i=\Big(\frac NS\Big)^{1-\beta}\,\E_{i\sim U}\big[\ell_\kappa'(\delta_i)\nabla Q_i\big],\qquad\kappa=\tau+\alpha-\alpha\beta

    Collect the powers of ∣δi∣\abs{\delta_i}. The remaining factor is the same for every transition:

  3. τ=2:κ=2+α(1−β) ≥ 2\tau=2:\qquad\kappa=2+\alpha(1-\beta)\ \ge\ 2

    So prioritized replay follows, in expectation, the gradient of the uniformly sampled loss ∣δ∣κ/κ\abs\delta^\kappa/\kappa, scaled by a positive factor common to all transitions. With the squared loss (τ=2\tau=2), κ=2\kappa=2 exactly when β=1\beta=1; for any β<1\beta<1, κ>2\kappa>2. (This is Fujimoto et al.'s equivalence, specialized to power losses; the small constant ϵ\epsilon in the priorities is ignored.)

Predict before you look

Proportional prioritization starts with α=0.6\alpha=0.6 and β0=0.4\beta_0=0.4, with the squared loss. Early in training, prioritized replay follows the expected gradient of which power ∣δ∣κ\abs\delta^\kappa?

Show the answer

2.36

κ=2+0.6×(1−0.4)=2.36\kappa=2+0.6\times(1-0.4)=2.36. Why it matters: if one state–action pair has several stored targets yjy_j (random rewards or next states), minimizing ∑j∣q−yj∣κ\sum_j\abs{q-y_j}^\kappa gives their mean for κ=2\kappa=2, their median for κ=1\kappa=1, and drifts toward the extreme targets as κ\kappa 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 L1L_1 loss sampled with priorities ∣δi∣\abs{\delta_i} 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 max⁡(∣δ∣α,1)\max(\abs\delta^\alpha,1), 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, nn-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).
  • nn-step returns were the reason. Of the four components added to DQN one at a time, only nn-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 nn-step returns helped only by shrinking the bootstrap's weight to γn\gamma^n, a one-step update with discount γn\gamma^n 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.
Agent1M → 10M at a fixed replay ratio1M → 10M at a fixed oldest-policy age
DQN+0.1%−0.4%
Rainbow (Dopamine)+28.7%+18.3%
Median relative improvement over the same agent with a 1M buffer (Fedus et al., 2020, Table 1). The DQN result also contradicts, for this setting, Zhang and Sutton's conclusion that larger buffers hurt.

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 14\tfrac14. 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(λ\lambda) is equivalent to one pass of LSTD(λ\lambda) (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, n=20n=20, 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 ii acting ε\varepsilon-greedily with εi=0.41+7i/(N−1)\varepsilon_i=0.4^{1+7i/(N-1)}, 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 gg 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 ρB\rho B times (8 for DQN), the oldest data are NρN\rho updates old, and while a buffer grows, the transition from step tt is drawn about ρBln⁡(T/t)\rho B\ln(T/t) times, overweighting early experience.
  • Importance weights with β=1\beta=1 make prioritized sampling unbiased; in general, prioritized replay with priorities ∣δ∣α\abs\delta^\alpha follows the expected gradient of the uniformly sampled loss ∣δ∣τ+α−αβ\abs\delta^{\tau+\alpha-\alpha\beta}, so with the squared loss and β<1\beta<1 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 nn-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.

Question 1

Why does prioritized replay anneal its importance exponent β\beta to 1 by the end of training, instead of using β=1\beta=1 throughout?

  1. β=1\beta=1 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
  2. β=1\beta=1 gives the strongest prioritization
  3. β\beta controls how often new transitions are replayed
  4. With β=1\beta=1 the sum-tree is no longer needed
Show the answer

A. β=1\beta=1 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 β=1\beta=1 cancels the sampling distribution exactly. Before that the update follows a different loss (∣δ∣2+α(1−β)\abs\delta^{2+\alpha(1-\beta)} with the squared loss), a bias Schaul et al. accepted while the policy, the state distribution and the targets were all changing anyway.

Question 2

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?

  1. Equally often: uniform sampling treats all transitions alike
  2. Less often, because newer transitions crowd it out
  3. Much more often: it is drawn with probability 1/u1/u at every step uu since it was stored, about ρBln⁡(T/t)\rho B\ln(T/t) times in all
  4. It depends only on the size of its TD error
Show the answer

C. Much more often: it is drawn with probability 1/u1/u at every step uu since it was stored, about ρBln⁡(T/t)\rho B\ln(T/t) 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.

Question 3

Fedus et al. grew the buffer from 1 million to 10 million transitions at a fixed replay ratio. What happened?

  1. Both DQN and Rainbow improved about equally: more data always helps
  2. Rainbow improved (+28.7%) and DQN did not (+0.1%), and nn-step returns made the difference: adding them let DQN profit, removing them stopped Rainbow from profiting
  3. DQN improved because it lacks prioritization, which wastes large buffers
  4. 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 nn-step returns made the difference: adding them let DQN profit, removing them stopped Rainbow from profiting

The additive and ablative studies isolate nn-step returns. Prioritization made no significant difference with large buffers, and a one-step update with the smaller weight γn\gamma^n on the bootstrap did not reproduce the effect.

Question 4

When is uniform replay of stored transitions indistinguishable from planning with a perfect model?

  1. Always: a buffer and a model are two names for the same thing
  2. Never, since replay involves no model
  3. Whenever the model is linear
  4. 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).