AI Wiki中文/EN

Experience replay: what is actually sampled from memory?

经验回放

Follow a ring buffer through overwrites; calculate duplicate batches and explain the distribution it preserves.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Why keep an old transition?

A robot takes a costly step and records what happened. Throwing that record away after one update means paying for another interaction whenever the learner needs another example. Experience replay keeps previous transitions so that several updates can reuse them. The record still contains the reward that actually occurred; sampling it again does not ask the world for a new outcome.

The distinction matters even in a tiny example. Store records numbered 0,1,2 in a buffer with three slots, then insert 3 and 4. Which records can the next update use? Only 2,3,4 remain. Uniform sampling from this buffer is uniform over the retained records, not over the entire five-record history.

Replay predates DQN. Lin’s1992 paper explicitly studies experience replay among extensions to reinforcement learning; we checked its publisher abstract, not its full algorithm. The 2013 and 2015 DQN methods describe retaining recent transitions and sampling them uniformly for updates. Early historical evidence 2013 replay method 2015 replay method

The DQN article explains how a batch becomes a gradient. Here the independent problem is what data enters that batch: which rows exist, how they are selected, and what distribution that selection represents. Review independence before equating shuffled data with independent observations.

The same retained rows have different physical and chronological orders. With replacement, three draws from three rows repeat an index with probability7/9.
The same retained rows have different physical and chronological orders. With replacement, three draws from three rows repeat an index with probability7/9.

A distribution over a finite memory

Write a stored transition as e=(s,a,r,s′,d,t), where d means task termination and t means a collector truncation. They remain separate fields. Let n be the number of valid rows currently in a capacity-N buffer. Uniform sampling with replacement draws an index I from 0 through n−1:

μ^D=1n∑j=0n−1δej,Pr⁡(I=j∣D)=1n,1≤n≤N.\widehat\mu_D=\frac1n\sum_{j=0}^{n-1}\delta_{e_j},\qquad \Pr(I=j\mid D)=\frac1n,\qquad 1\leq n\leq N.

Here δ at a record denotes a unit point mass, not a temporal-difference error. This empirical distribution is conditional on the actual buffer contents. Two distinct rows can even contain identical transition values. The sampling algorithm treats them as two stored observations; deleting duplicates would change the weighting.

A ring buffer holds a next-write pointer p. Insert into slot p, advance the pointer modulo capacity, and increase the valid size until full:

slot⁡[p]←enew,p←(p+1) mod N,n←min⁡(n+1,N).\operatorname{slot}[p]\leftarrow e_{\mathrm{new}},\qquad p\leftarrow(p+1)\bmod N,\qquad n\leftarrow\min(n+1,N).

Before the buffer fills, valid slots are 0 through n−1 and chronological order starts at 0. After it fills, every slot is valid; p points to the oldest row, which the next insertion will replace. Physical slot order and time order now differ. A chronological view is useful for inspection, but uniformly choosing a valid physical slot does not require sorting.

With replacement, each of B draws can select the same row. The probability of at least one repeated index is one minus the probability that all draws differ:

Pr⁡(repeat)=1−n(n−1)⋯(n−B+1)nB(1≤B≤n);Pr⁡(repeat)=1(B>n).\Pr(\text{repeat})=1-\frac{n(n-1)\cdots(n-B+1)}{n^B}\quad(1\leq B\leq n);\qquad \Pr(\text{repeat})=1\quad(B>n).

For n=B=3, only six of the 27 ordered index triples contain three distinct indices. The repeat probability is 7/9. A batch size equal to buffer size therefore does not mean “one pass through memory.” Sampling without replacement does have distinct indices, requires B≤n, and gives dependent draws within the batch. Both schemes can yield an unbiased batch mean of a fixed per-record quantity under uniform sampling.

To make that last claim precise, freeze both the buffer and the current parameters, and let g(e) be the update contribution associated with a row. Linearity of expectation gives:

E ⁣[1B∑b=1Bg(eIb) | D]=1n∑j=0n−1g(ej).\mathbb E\!\left[\frac1B\sum_{b=1}^{B}g(e_{I_b})\,\middle|\,D\right]=\frac1n\sum_{j=0}^{n-1}g(e_j).

This is a statement about the empirical buffer average. It is not an unbiasedness claim for the current policy’s state distribution, the entire training history, or a new environment population. Replay commonly contains actions from older behavior policies. Q-learning can use such transitions off-policy, but finite coverage and function approximation still matter. Changing sampling probabilities, as in prioritized replay, changes the objective weighting unless an appropriate correction is included. Off-policy replay discussion

For the teaching records whose rewards equal their IDs, overwriting illustrates the distribution change without randomness:

r‾retained=2+3+43=3,r‾all=0+1+2+3+45=2.\overline r_{\mathrm{retained}}=\frac{2+3+4}{3}=3,\qquad \overline r_{\mathrm{all}}=\frac{0+1+2+3+4}{5}=2.

No number of uniform draws from the three retained rows can recover the missing 0 and 1 records. More replay steps reduce sampling noise around the retained mean; they do not repair forgotten coverage.

Watch the write pointer wrap around

This standalone Python 3.12 example uses only the standard library. Each record is an immutable dataclass of scalar fields, so the caller cannot accidentally change an old reward by editing the original row. The buffer rejects zero capacity, empty sampling and impossible without-replacement batches. A production implementation storing arrays must also decide when to copy observation data; a frozen wrapper alone would not make mutable array contents immutable.

The fixed Spinning Up implementation provides a useful code-reading comparison: it stores transitions in arrays, tracks a write pointer and valid size, and samples integer indices with replacement. Our program is original and uses an explicit two-flag record rather than that old API’s single done field. No upstream code was executed or copied. Fixed implementation

"""Original finite replay buffer: scalar teaching transitions, standard library."""
from dataclasses import dataclass
from collections import Counter
import random
import math


def integer(value, minimum=0):
    if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
        raise ValueError('Expected an integer within the documented range')
    return value


@dataclass(frozen=True)
class Transition:
    identity: int
    state: int
    action: int
    reward: float
    next_state: int
    terminated: bool
    truncated: bool = False

    def __post_init__(self):
        for v in [self.identity, self.state, self.action, self.next_state]:
            integer(v)
        if not math.isfinite(self.reward) or type(self.terminated) is not bool or type(self.truncated) is not bool:
            raise ValueError('Finite reward and explicit boolean flags required')


class Replay:
    def __init__(self, capacity):
        self.capacity = integer(capacity, 1)
        self.rows = [None] * self.capacity
        self.cursor, self.size = 0, 0

    def add(self, row):
        if not isinstance(row, Transition):
            raise ValueError('Use an immutable Transition')
        self.rows[self.cursor] = row
        self.cursor = (self.cursor + 1) % self.capacity
        self.size = min(self.capacity, self.size + 1)

    def chronological(self):
        start = self.cursor if self.size == self.capacity else 0
        return [self.rows[(start + i) % self.capacity] for i in range(self.size)]

    def sample(self, batch_size, rng, replace=True):
        b = integer(batch_size, 1)
        if not self.size or type(replace) is not bool or (not replace and b > self.size):
            raise ValueError('Cannot sample the requested batch from valid entries')
        indices = [rng.randrange(self.size) for _ in range(b)] if replace else rng.sample(range(self.size), b)
        return [self.rows[i] for i in indices]


def demo():
    replay = Replay(3)
    trace = []
    for i in range(5):
        replay.add(Transition(i, i, i % 2, float(i), i + 1, False, i == 4))
        trace.append(dict(inserted=i, next_write=replay.cursor, size=replay.size,
                          chronological=[r.identity for r in replay.chronological()]))
    rng = random.Random(17)
    draws = [r.identity for r in replay.sample(12000, rng)]
    counts = Counter(draws)
    batches = [[r.identity for r in replay.sample(3, rng)] for _ in range(6000)]
    duplicate_fraction = sum(len(set(b)) < len(b) for b in batches) / len(batches)
    unique = [r.identity for r in replay.sample(3, random.Random(17), replace=False)]
    return dict(capacity=3, trace=trace, counts=dict(sorted(counts.items())),
                uniform_probability=1 / 3, duplicate_probability=1 - 6 / 27,
                measured_duplicate_fraction=duplicate_fraction, without_replacement=unique,
                kept_reward_mean=sum(r.reward for r in replay.chronological()) / 3,
                all_five_reward_mean=2., last_row_truncated=replay.chronological()[-1].truncated)


if __name__ == '__main__':
    import json
    print(json.dumps(demo(), indent=2, allow_nan=False))

The chronological views after the five insertions are[0], [0,1], [0,1,2], [1,2,3], [2,3,4]. The next-write pointer is 2 at the end. The physical slots then contain 3,4,2: starting the chronological view at pointer 2 reconstructs the correct order.

With seed 17,12000 with-replacement draws produce record counts 4027,3998,3975 for IDs 2,3,4. Among 6000 additional three-draw batches, the observed fraction containing a duplicate is 0.775, near 7/9. These sampled frequencies illustrate the theory; they do not prove uniformity. A separate check enumerates all 27 index triples to verify the mapping and the 21 repeated triples. The without-replacement sample with a fresh seed 17 is[2,4,3], containing all three IDs once.

Preallocation uses O(N) slots. An insertion costs O(1) for these fixed-size scalar rows; a with-replacement batch costs O(B) time and result space. Without-replacement sampling uses Python’s standard sampling algorithm with B≤n. Producing the chronological list costs O(n). The demonstration additionally holds all 12000 draws and 6000 batches for reporting; those diagnostics are not necessary buffer state.

Shuffling does not create new experience

Conditional on a fixed buffer, independently generated with-replacement indices give independent draws from its empirical distribution. Unconditionally, however, all those draws share the same random history that produced the buffer. The original transitions can also be temporally correlated. This is why “we shuffled it” is not enough to justify treating replay as an unlimited supply of fresh independent environment observations.

Capacity trades recent coverage against older data. An important rare transition can be overwritten; a huge buffer can preserve experience from behavior that is no longer representative. If dynamics or rewards have changed, old transitions may belong to a different problem. The DQN papers discuss finite memory and uniform weighting as limitations, rather than an ability to remember every useful experience. 2015 discussion

Storing the wrong next observation, merging termination with truncation, or sampling uninitialized slots changes the learning problem before the optimizer runs. Our scalar model avoids frame stacking, recurrent sequence boundaries and concurrent writers. Those need additional data contracts; they are not solved by the ring pointer alone. A diagnostic should log buffer size, sampling protocol and the actual retained contents before blaming a network’s architecture.

Reason about the data you kept

  1. A capacity-three ring receives records 0 through 4. What are its final chronological order, physical slots and next-write pointer?

Answer: Chronological order is[2,3,4], slots are [3,4,2], and pointer 2 will overwrite record 2. Confusing slots with time order would incorrectly place record 2 last.

  1. Sample three times with replacement from those three rows. How many ordered batches have no repeated index, and what is the repeat probability?

Answer: There are 3×2×1=6 distinct-index batches among 3³=27 possibilities. At least one repetition therefore has probability 21/27=7/9. This counts row identities, even if two rows happen to contain the same values.

  1. A capacity 100 buffer currently has one valid row. Is a with-replacement batch of size 32 valid? Is a without-replacement batch of size 32 valid?

Answer: The first is valid and repeats the sole row 32 times. The second is impossible. Sampling from capacity rather than valid size would expose uninitialized entries instead of creating extra experience.

  1. Rewards 0 through 4 arrive in order, but only the latest three rows remain. Can a million uniform replay draws estimate the all-history mean 2 without additional information?

Answer: No. Their empirical mean approaches the retained mean 3, not 2. Keep an appropriate aggregate for that separate statistical question or preserve the necessary records. Neither a larger batch nor duplicate removal reconstructs overwritten observations.

Separate history from an implementation recipe

Lin 1992 supplies early historical evidence at abstract scope only; the detailed sampling protocol here is not attributed to unread full text. The 2013 and 2015 methods support the recent-memory, uniform-replay description. The fixed Spinning Up file makes valid-size and replacement choices inspectable; we read the relevant sections and its MIT license, without running or reusing its code. None of these readings establishes that a particular buffer size is best for every task.

Make a prediction, then check

A three-entry buffer is sampled three times with replacement. What is the probability of at least one repeated entry?

Choose one answer

Learning objectives

  • Trace valid entries, capacity and uniform sampling with and without replacement.
  • Explain why replay neither restores overwritten data nor creates new independent environment observations.

Prerequisites & connections

Explore related knowledge →

References

  1. Playing Atari with Deep Reinforcement Learning — arXiv v1
    Volodymyr Mnih; Koray Kavukcuoglu; David Silver; Alex Graves; Ioannis Antonoglou; Daan Wierstra; Martin Riedmiller · 2013
  2. Human-level control through deep reinforcement learning — scoped Methods reading
    Volodymyr Mnih; Koray Kavukcuoglu; David Silver; Andrei A. Rusu; Joel Veness; Marc G. Bellemare; Alex Graves; Martin Riedmiller; Andreas K. Fidjeland; Georg Ostrovski; Stig Petersen; Charles Beattie; Amir Sadik; Ioannis Antonoglou; Helen King; Dharshan Kumaran; Daan Wierstra; Shane Legg; Demis Hassabis · 2015
  3. Spinning Up: replay and target-network mechanisms at fixed commit
    OpenAI; Joshua Achiam and contributors · 2020
  4. Self-improving reactive agents based on reinforcement learning, planning and teaching — metadata and abstract
    Long-Ji Lin · 1992

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 identity/abstract,3–5,6 opening architecture/training paragraphs; viewed3/5. Explicit2013-12-19v1, not2015 Nature algorithm. No score-table audit or Atari reproduction. Derive loss gradient independently: printed target-minus-Q expression is an update direction, not the stated square-loss gradient. Read PDF1 identity/abstract,6 left-column Methods and right-column evaluation,7; viewed7. Separate target network, uniform replay and stated training conditions only; score/extended tables not audited. Printed variance decomposition and gradient sign require independent correction; no general convergence claim or benchmark replication. Fixed2020-02-07 commit; read code1–52,145–230,255–280, full readme.md/MIT LICENSE, docs Q-learning-side section. Ring storage, replacement sampling, deepcopy, no_grad and Polyak convention. Old length-based done heuristic not copied. No upstream execution, source reuse or DDPG benchmark audit. Publisher identity/abstract only: May1992, Machine Learning8:293–321, comparison including experience replay. Full-text retrieval failed; this supports historical attribution only, not the exact replay protocol or empirical results. 5 paired equations and four explained exercises. Checked ring capacity, valid size, overwrite/time order, immutable scalar records, with/without-replacement protocols, exhaustive27 triples and cache-mean expectation. Conditional empirical sampling is not fresh independent environment data; Lin1992 reading supports historical attribution at abstract scope only.

  • Checked ring capacity, valid size, overwrite/time order, immutable scalar records, with/without-replacement protocols, exhaustive27 triples and cache-mean expectation. Conditional empirical sampling is not fresh independent environment data; Lin1992 reading supports historical attribution at abstract scope only.
  • Four computed SVG variants per topic;11 numeric/geometry tests and18 responsive cases passed. All six selected current captures directly viewed. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.