AI Wiki中文/EN

Prioritized replay: sample unevenly, account for the change

优先经验回放

Build a sum tree, calculate sampling and importance weights, and distinguish exact correction from rescaling.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Which memory should get another turn?

A replay buffer holds three transitions. Their current TD errors have magnitudes 0.9, 1.9 and 3.9. Uniform replay treats all three equally. Prioritized replay asks whether the third, whose target and prediction disagree most, should be revisited more often. That can allocate updates toward a useful learning signal, but it also changes the distribution of training examples. The sampling rule and its correction belong in the same explanation. Prioritization and bias

TD error is a proxy for learning opportunity, not an oracle for usefulness. A large error may reflect a learnable mistake, stochastic rewards or an outlier. Before this chapter, read experience replay for buffer mechanics and importance sampling for changing a sampling distribution without silently changing the intended expectation.

We will calculate an exact three-record example and implement a small sum tree. The goal is to inspect what is sampled and how a weighted mean behaves, rather than to claim a complete prioritized DQN benchmark.

Raw beta-one weights recover the fixed-buffer uniform gradient expectation; global max normalization rescales it. Probability rows track the last repeated update and the next overwrite.
Raw beta-one weights recover the fixed-buffer uniform gradient expectation; global max normalization rescales it. Probability rows track the last repeated update and the next overwrite.

Separate priority, probability and weight

For n retained transitions, let delta_i be a TD error, such as target minus the current selected-action prediction. Proportional prioritization uses a positive raw priority and then converts it to a probability:

pi=∣δi∣+ε,P(i)=piα∑j=1npjα,ε>0,0≤α≤1.p_i=|\delta_i|+\varepsilon,\qquad P(i)=\frac{p_i^\alpha}{\sum_{j=1}^{n}p_j^\alpha}, \qquad \varepsilon>0,\quad 0\leq\alpha\leq1.

The interval for alpha is the one supported by our teaching implementation. Alpha zero recovers uniform sampling; alpha one uses the raw priorities directly. The positive epsilon gives even a zero-error retained record a nonzero chance in exact arithmetic. The paper also discusses rank-based prioritization, using inverse rank rather than raw error magnitude. That is a different priority rule and is not implemented below. Proportional and rank variants

To sample, give record i an interval whose width is its transformed priority. Let c_i be the cumulative sum through i and c_0=0. Draw a uniform u in the half-open total interval and find its leaf:

u∼Uniform⁡[0,cn),ci−1≤u<ci,ci=∑j=1ipjα.u\sim\operatorname{Uniform}[0,c_n),\qquad c_{i-1}\leq u<c_i,\qquad c_i=\sum_{j=1}^{i}p_j^\alpha.

Our code uses zero-based indices, while this equation numbers records from 1. A sum tree stores interval widths at its leaves and subtree totals above them. At each branch, go left if u is below the left total; otherwise subtract that total and go right. Equality goes right. Zero-width leaves and capacity-padding leaves must never be returned.

Now freeze the current buffer, model parameters and probabilities. Write g_i for the loss gradient of record i. The target for this calculation is the uniform average over those n records, not the distribution of every transition the agent has ever seen. Raw importance weights with beta one give:

wi=1nP(i),Ei∼P[wigi]=∑iP(i)ginP(i)=1n∑igi.w_i=\frac{1}{nP(i)},\qquad \mathbb E_{i\sim P}[w_i g_i] =\sum_iP(i)\frac{g_i}{nP(i)} =\frac1n\sum_i g_i.

This is a conditional expectation for a fixed buffer and fixed current parameters. It does not undo eviction, observation bias or absent exploration. With partial correction, beta between zero and one yields:

wi(β)=(nP(i))−β,EP[wi(β)gi]=n−β∑iP(i)1−βgi.w_i^{(\beta)}=(nP(i))^{-\beta},\qquad \mathbb E_P[w_i^{(\beta)}g_i] =n^{-\beta}\sum_iP(i)^{1-\beta}g_i.

Except in special cases, that is not the uniform mean when beta is below one. The PER paper discusses increasing beta toward one during learning. Our example exposes beta in weights; its sample method deliberately returns raw beta-one weights, so the correction demonstrated by the program is unambiguous. Importance weights

Implementations often divide weights by their maximum. If that maximum is taken over the entire fixed buffer, it is a fixed scalar for the conditional calculation:

wmax⁡=max⁡j1nP(j),w~i=wiwmax⁡,EP[w~igi]=1wmax⁡1n∑igi.w_{\max}=\max_j\frac1{nP(j)},\qquad \widetilde w_i=\frac{w_i}{w_{\max}},\qquad \mathbb E_P[\widetilde w_i g_i] =\frac1{w_{\max}}\frac1n\sum_i g_i.

The expected direction is rescaled, not numerically equal to the original mean. A maximum computed only within a randomly sampled batch is itself random, so the same fixed-scalar proof does not apply. Nor should a rescaling automatically be described as equivalent under every optimizer or clipping rule.

Return to the three errors. With epsilon 0.1 and alpha one, raw priorities are [1,2,4]. For a scalar gradient example g=[−2,1,4]:

P=(1/7,2/7,4/7),w=(7/3,7/6,7/12),w~=(1,1/2,1/4),gˉ=1,EP[g]=16/7,EP[wg]=1,EP[w~g]=3/7.P=(1/7,2/7,4/7),\quad w=(7/3,7/6,7/12),\quad\widetilde w=(1,1/2,1/4), \qquad \bar g=1,\quad \mathbb E_P[g]=16/7,\quad \mathbb E_P[wg]=1,\quad\mathbb E_P[\widetilde w g]=3/7.

These are exact weighted sums. A finite sampled batch fluctuates around its expectation; importance weighting does not promise that each batch equals the uniform mean.

A tree with explicit boundary and overwrite rules

Run the following complete standard-library Python program. SumTree pads capacity to a power of two. set_many validates all affected final subtree totals before committing changes, so invalid updates do not partly modify the tree. If an index appears repeatedly, the last supplied value wins. This is a chosen protocol, not a requirement of the PER equations.

The replay wrapper keeps a ring buffer. A new record without an explicit error receives the largest raw priority currently in the buffer, measured before overwriting; the first record receives priority 1. This differs from tracking the historical maximum over all previous priorities. On error updates, it recomputes the positive raw priority and transformed leaf weight. Extreme floating-point ranges that produce nonrepresentable probabilities or weights are rejected rather than silently treated as valid sampling distributions.

"""Original scalar sum tree and finite prioritized replay with explicit IS conventions."""
import math
import random
from collections import Counter


def integer(x, minimum=0):
    if isinstance(x, bool) or not isinstance(x, int) or x < minimum:
        raise ValueError('Integer in range required')
    return x


class SumTree:
    def __init__(self, capacity):
        self.capacity = integer(capacity, 1)
        self.base = 1 << (self.capacity - 1).bit_length()
        self.nodes = [0.] * (2 * self.base)

    def set_many(self, indices, values):
        indices, values = list(indices), list(values)
        if len(indices) != len(values):
            raise ValueError('Equal lengths required')
        replacements = {}
        for i, v in zip(indices, values):
            i = integer(i)
            if i >= self.capacity or not math.isfinite(v) or v < 0:
                raise ValueError('Valid index and nonnegative finite mass required')
            replacements[i] = float(v)  # Last occurrence wins, explicitly.
        # Validate the final affected paths before committing any mutation.
        pending = {self.base + i: v for i, v in replacements.items()}
        frontier = set(pending)
        while frontier and frontier != {1}:
            parents = {j // 2 for j in frontier if j > 1}
            for j in parents:
                value = pending.get(2 * j, self.nodes[2 * j]) + pending.get(2 * j + 1, self.nodes[2 * j + 1])
                if not math.isfinite(value):
                    raise ValueError('Finite tree sums required')
                pending[j] = value
            frontier = parents
        for j, value in pending.items():
            self.nodes[j] = value

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

    def find(self, value):
        if not math.isfinite(value) or not 0 <= value < self.total:
            raise ValueError('Query must lie in [0,total)')
        j = 1
        while j < self.base:
            left = 2 * j
            if value < self.nodes[left]:
                j = left
            else:
                value -= self.nodes[left]
                j = left + 1
        return j - self.base


class PrioritizedReplay:
    def __init__(self, capacity, alpha=1., epsilon=.1):
        if not math.isfinite(alpha) or not 0 <= alpha <= 1 or not math.isfinite(epsilon) or epsilon <= 0:
            raise ValueError('alpha in [0,1] and positive epsilon required')
        self.tree = SumTree(capacity)
        self.capacity, self.alpha, self.epsilon = capacity, alpha, epsilon
        self.rows, self.raw = [None] * capacity, [0.] * capacity
        self.size, self.cursor = 0, 0

    def add(self, record, error=None):
        priority = max(self.raw) if self.size else 1.
        if error is not None:
            if not math.isfinite(error):
                raise ValueError('Finite TD error required')
            priority = abs(error) + self.epsilon
        if not math.isfinite(priority):
            raise ValueError('Finite raw priority required')
        i = self.cursor
        self.tree.set_many([i], [priority ** self.alpha])
        self.rows[i], self.raw[i] = record, priority
        self.size = min(self.size + 1, self.capacity)
        self.cursor = (i + 1) % self.capacity

    def probabilities(self):
        if not self.size:
            raise ValueError('Empty replay')
        ps = [self.tree.nodes[self.tree.base + i] / self.tree.total for i in range(self.size)]
        if any(p <= 0 or not math.isfinite(p) for p in ps):
            raise ValueError('Probability dynamic range is not representable')
        return ps

    def weights(self, beta=1., normalize=False):
        if not math.isfinite(beta) or not 0 <= beta <= 1 or type(normalize) is not bool:
            raise ValueError('Invalid beta or normalization flag')
        ps = self.probabilities()
        try:
            raw = [(self.size * p) ** (-beta) for p in ps]
        except OverflowError as error:
            raise ValueError('Importance weights are not representable') from error
        if not all(math.isfinite(w) for w in raw):
            raise ValueError('Importance weights are not representable')
        scale = max(raw) if normalize else 1.
        return [w / scale for w in raw]

    def sample(self, batch_size, rng):
        integer(batch_size, 1)
        ps, weights = self.probabilities(), self.weights()
        ids = [self.tree.find(rng.random() * self.tree.total) for _ in range(batch_size)]
        return [(i, self.rows[i], ps[i], weights[i]) for i in ids]

    def update_errors(self, indices, errors):
        indices, errors = list(indices), list(errors)
        if len(indices) != len(errors):
            raise ValueError('Equal lengths required')
        updates = {}
        for i, error in zip(indices, errors):
            i = integer(i)
            if i >= self.size or not math.isfinite(error):
                raise ValueError('Invalid retained index or TD error')
            priority = abs(error) + self.epsilon
            if not math.isfinite(priority):
                raise ValueError('Finite raw priority required')
            updates[i] = priority
        self.tree.set_many(updates.keys(), [v ** self.alpha for v in updates.values()])
        for i, value in updates.items():
            self.raw[i] = value


def demo():
    replay = PrioritizedReplay(3)
    for i, error in enumerate([.9, 1.9, 3.9]):
        replay.add(i, error)
    p, w, normalized = replay.probabilities(), replay.weights(), replay.weights(normalize=True)
    gradient = [-2., 1., 4.]
    counts = Counter(row[0] for row in replay.sample(14000, random.Random(7)))
    old = dict(probabilities=p, raw_weights=w, normalized_weights=normalized,
               uniform_gradient=sum(gradient) / 3,
               prioritized_gradient=sum(a * b for a, b in zip(p, gradient)),
               corrected_gradient=sum(a * b * c for a, b, c in zip(p, w, gradient)),
               max_normalized_gradient=sum(a * b * c for a, b, c in zip(p, normalized, gradient)))
    replay.update_errors([1, 1], [2.9, 6.9])
    updated = replay.probabilities()
    replay.add(3)
    return dict(initial=old, counts=dict(sorted(counts.items())), after_duplicate_update=updated,
                after_overwrite_rows=replay.rows, after_overwrite_probabilities=replay.probabilities(),
                duplicate_protocol='last error wins', scope='Fixed-buffer gradient arithmetic; raw beta1 weights recover its uniform mean, global max normalization rescales it.')


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

With seed 7, 14,000 draws give counts [2012,4077,7911] for the three records. They are near, not identical to, counts proportional to [1,2,4]. Updating index 1 twice with errors 2.9 then 6.9 leaves raw priorities [1,7,4], so probabilities become [1/12,7/12,4/12]. Adding a new record without an error takes current maximum 7 and overwrites slot 0. The retained records are [3,1,2], with probabilities [7/18,7/18,4/18].

A tree lookup costs O(log N) for capacity N; K replacements cost at most O(K log N), and the tree uses O(N) space. This deliberately readable wrapper also materializes all n valid probabilities and weights on each sampling call, so drawing a batch of B costs O(N+B log N) as an upper bound, not just O(B log N). Finding the current maximum for an insertion scans O(N) entries. A production implementation can maintain additional statistics, but that changes the code and needs its own checks.

Tests compare tree lookups with a flat prefix-sum oracle, including equality boundaries, zero leaves and non-power-of-two capacities. They also check duplicate updates, atomic rejection, uniform sampling at alpha zero, exact expectation arithmetic, overwrite behavior and reproducible draws. This is a sampler and gradient-arithmetic example; it does not integrate weighted neural-network optimization.

A large error can be repeatedly unhelpful

Priorities become stale as the network changes. A stored error says what the model found surprising when it was measured, not necessarily now. Large stochastic errors can absorb sampling effort even when repeated updates cannot remove the underlying randomness. Positive epsilon preserves mathematical support but does not ensure balanced use within a finite budget.

Giving a new record maximum priority is a way to encourage early use. It cannot guarantee a draw before the record is overwritten: sampling remains random and storage finite. Importance weights correct the stated fixed-buffer objective, not this coverage problem.

Combined agents can also change the priority signal. Rainbow’s distributional combination uses a KL-based priority; calling every such implementation “absolute TD error plus epsilon” would conflate distinct choices. State the actual loss, priority, sampling distribution and weight normalization when describing a system. Distributional combination

Follow one probability through the update

  1. Keep positive raw priorities [1,2,4] but set alpha to zero. What probabilities and raw beta-one weights result?

Answer: Every transformed priority is 1, so probabilities are [1/3,1/3,1/3] and weights are [1,1,1]. Equal probabilities follow from alpha zero, not from equal TD errors.

  1. For the scalar gradients in the worked example, does dividing the raw weights by their global maximum still produce expected gradient 1?

Answer: No. The maximum is 7/3, so the expectation is multiplied by 3/7 and becomes 3/7. Its direction is preserved in this fixed-buffer scalar example; its magnitude is changed.

  1. The same retained index is updated twice in one call, with errors 2.9 and 6.9 and epsilon 0.1. What raw priority remains in this implementation?

Answer: It is 7, because the last occurrence wins. Accumulating both updates as unrelated tree deltas would use a different protocol and can corrupt totals if the old leaf value is handled inconsistently.

  1. A newly inserted record has the highest priority. Can an implementation promise that it will be sampled before its ring-buffer slot is overwritten?

Answer: No, not from this random priority rule alone. Even a positive large probability leaves a chance of no draw during a finite lifetime. A guaranteed first visit would require an additional explicit scheduling rule.

Read the sampling law and correction together

This chapter uses the February 25, 2016 arXiv v4 of Prioritized Experience Replay, following its November 18, 2015 first preprint and ICLR 2016 publication. The scoped reading covers PDF pages 3–5: prioritization variants, stochastic sampling and importance weights. The positive epsilon follows the body text; it is not discarded merely because an algorithm line abbreviates the priority update. We do not reproduce the paper’s Cliffwalk or Atari experiments. PER source

Rainbow’s October 6, 2017 v1, PDF pages 2–3, provides the methods context for combining replay with other DQN changes. The original scalar tree here was checked against explicit probability laws and boundary tests; it is not copied upstream code. Continue with return distributions to see why a richer prediction can lead to a different loss and priority. Rainbow methods

Make a prediction, then check

A three-entry buffer has P=[1/7,2/7,4/7]. Which raw beta1 importance weights restore its uniform mean?

Choose one answer

Learning objectives

  • Compute positive priorities, inverse-CDF draws and duplicate-index updates in a finite replay buffer.
  • Derive raw beta1 correction for a fixed-buffer uniform mean and explain global max normalization.

Prerequisites & connections

Explore related knowledge →

References

  1. Prioritized Experience Replay — arXiv v4
    Tom Schaul; John Quan; Ioannis Antonoglou; David Silver · 2016
  2. Rainbow: Combining Improvements in Deep Reinforcement Learning — arXiv v1 methods
    Matteo Hessel; Joseph Modayil; Hado van Hasselt; Tom Schaul; Georg Ostrovski; Will Dabney; Dan Horgan; Bilal Piot; Mohammad Azar; David Silver · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF3–5; viewed5. First preprint2015-11-18, selected v4 dated2016-02-25, ICLR2016. Positive priorities, proportional/rank variants and IS weights. Distinguish raw correction from max normalization; no guaranteed visit before eviction. No full appendix or Atari replication. Selected2017-10-06v1, then under review for AAAI2018; not verified final2018 bytes. Read PDF2–3 methods: Double Q, PER, dueling mean, categorical softmax and integrated targets. Distributional Rainbow uses KL priority. No later full architecture, benchmark or ablation audit. 6 paired equations and four explained exercises. Checked positive raw priority versus sampling probability, half-open sum-tree boundaries, last repeated update, atomic numeric rejection, ring overwrites and finite counts. Raw beta1 IS restores the fixed-buffer uniform gradient expectation; global-max normalization rescales it and random batch normalization needs a different argument. Explicit O(N+B log N) teaching sampler and current rather than historical maximum; no guaranteed first visit.

  • Checked positive raw priority versus sampling probability, half-open sum-tree boundaries, last repeated update, atomic numeric rejection, ring overwrites and finite counts. Raw beta1 IS restores the fixed-buffer uniform gradient expectation; global-max normalization rescales it and random batch normalization needs a different argument. Explicit O(N+B log N) teaching sampler and current rather than historical maximum; no guaranteed first visit.
  • Four computed SVG variants per topic;14 numeric/geometry tests and24 current responsive cases passed. All eight selected current captures directly viewed. Two unchanged groups retain initial captures, two revised groups use new captures; actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.

Source locations checked:

  • Prioritized Experience Replay — arXiv v4 · Read PDF3–5; viewed5. First preprint2015-11-18, selected v4 dated2016-02-25, ICLR2016. Positive priorities, proportional/rank variants and IS weights. Distinguish raw correction from max normalization; no guaranteed visit before eviction. No full appendix or Atari replication.
  • Rainbow: Combining Improvements in Deep Reinforcement Learning — arXiv v1 methods · Selected2017-10-06v1, then under review for AAAI2018; not verified final2018 bytes. Read PDF2–3 methods: Double Q, PER, dueling mean, categorical softmax and integrated targets. Distributional Rainbow uses KL priority. No later full architecture, benchmark or ablation audit.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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