经验回放:从记忆里抽到的究竟是什么?
Experience replay
跟踪环形覆盖、计算批内重复概率,解释缓存保留的数据分布及其局限。
experience-replay为什么留着旧转移?
机器人花费代价执行一步,并记下发生了什么。如果更新一次就扔掉记录,每次需要新例子都得再付出交互成本。经验回放保留过去的转移,让多次更新重复使用它们。记录里的奖励仍是当时实际发生的结果;再抽一次,并不等于再向世界询问一个新结果。
即使极小的例子,也要分清这点。容量只有三个槽位,先存编号0、1、2的记录,再插入3、4。下一次更新还能使用哪些记录?只剩2、3、4。从这个缓存均匀抽样,是对保留记录均匀,不是对全部五条历史记录均匀。
经验回放早于DQN。Lin在1992年的论文中明确研究了包括经验回放在内的强化学习扩展;这里核读的是出版方摘要,不是全文算法。2013年与2015年的DQN方法描述了保留近期转移、均匀抽样更新的做法。早期历史证据 2013年回放方法 2015年回放方法
DQN篇解释一个批次如何变成梯度;本篇的独立问题是,哪些数据进入了这个批次:行是否存在、怎样选择、选择代表什么分布。把打乱后的数据视为独立观测之前,先读独立性。
有限记忆上的分布
把一条转移写成e=(s,a,r,s′,d,t),其中d表示任务终止,t表示采集器截断,两者分别存储。容量为N,当前有效记录数为n。有放回均匀抽样从0到n−1选择索引I:
这里记录处的δ表示单位点质量,不是时序差分误差。经验分布以实际缓存内容为条件。两条不同的记录也可能恰好有相同转移值;抽样算法仍把它们视为两次存入的观测,主动去重会改变权重。
环形缓存保存下次写入指针p。将新记录放入槽位p,指针对容量取模前进,有效大小增长到容量后保持不变:
缓存未满时,有效槽位为0到n−1,时间顺序从0开始。填满后,每个槽位都有效,p指向最老的一行,也就是下次将被替换的行。此时物理槽位顺序与时间顺序不同。按时间查看有助于检查,但均匀选择有效物理槽位并不需要排序。
有放回意味着B次抽取可以选中同一行。至少一个索引重复的概率,等于1减去全部不同的概率:
n=B=3时,27种有序索引三元组只有6种各不相同,重复概率为7/9。因此,“批大小等于缓存大小”并不意味着“把缓存各遍历一次”。无放回抽样才保证索引各不相同,要求B≤n,且批内抽取相互依赖。在均匀抽样下,两种方案的批均值都可以无偏估计固定的逐记录量的缓存均值。
准确地说,先固定缓存与当前参数,让g(e)表示一行带来的更新贡献。由期望的线性性:
这句话只针对经验缓存均值,不保证对当前策略的状态分布、全部训练历史或新环境总体无偏。回放里常有旧行为策略产生的动作。Q-learning能够离策略使用这些转移,但有限覆盖与函数近似的问题依旧存在。如果像优先回放那样改变抽样概率,除非使用恰当校正,否则目标的权重也会改变。离策略回放讨论
教学记录让奖励等于编号,覆盖操作造成的分布变化无需随机实验就能看见:
从保留的三行均匀抽多少次,也找不回丢失的0、1记录。增加回放步数能减少围绕保留均值的抽样噪声,不能修复已经遗忘的覆盖。
看写指针绕回来
这个独立的Python3.12例子只用标准库。每条记录是包含标量字段的不可变dataclass,调用者不能修改原始行后意外改掉旧奖励。缓存拒绝零容量、从空缓存抽样以及不可能的无放回批次。实际系统若存数组,还必须决定何时复制观测;仅把外层对象设为frozen,并不能让内部可变数组也不可变。
固定版本的Spinning Up提供了一个源码对照:它用数组存转移,维护写指针和有效大小,并有放回抽整数索引。本程序为原创,用两个显式结束标记,未沿用旧API的单一done字段;没有执行或复制上游代码。固定版本实现
"""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))
五次插入后的时间顺序依次为[0]、[0,1]、[0,1,2]、[1,2,3]、[2,3,4]。最后的下次写指针为2,物理槽位为3、4、2;从指针2开始读取,才能恢复正确时间顺序。
种子17的12000次有放回抽样中,编号2、3、4分别出现4027、3998、3975次。随后另抽6000组三条批次,含重复的比例为0.775,接近7/9。这些频数用于展示理论,不能证明均匀性。另一个检查枚举全部27种索引三元组,核对映射以及21种重复组合。重新使用种子17无放回抽样,结果为[2,4,3],每条记录各出现一次。
预分配占O(N)槽位;对这些固定大小的标量记录,一次插入为O(1),有放回批次需要O(B)时间及结果空间。无放回使用Python标准库采样算法,要求B≤n;产生时间顺序列表需O(n)。演示还保存了全部12000次抽样和6000个批次用于报告,这些诊断数据不是缓存必需状态。
打乱不产生新经历
给定固定缓存,独立生成的有放回索引会从其经验分布中得到独立抽样。但不作条件化时,这些抽样共享生成缓存的那段随机历史;原始转移之间也可能存在时间相关。因此,“已经打乱”不足以把回放当成无限供应的新鲜独立环境观测。
容量在近期覆盖与旧数据之间作取舍。重要的稀有转移可能被覆盖;很大的缓存则可能长期保留已经不再有代表性的行为经历。如果转移规律或奖励改变,旧记录甚至可能属于另一个问题。DQN论文把有限记忆与均匀权重作为局限讨论,并没有让缓存记住一切有用经历的能力。2015年讨论
存错下一观测、合并终止与截断,或抽到尚未初始化的槽位,都会在优化器运行之前改变学习问题。本例的标量模型没有处理帧堆叠、循环网络序列边界或并发写入;这些需要额外数据约定,环形指针本身并不能解决。诊断时,先记录有效大小、抽样协议与实际保留内容,再考虑是否应归咎于网络架构。
想清楚留下了哪些数据
- 容量3的环形缓存依次收到0到4号记录。最终时间顺序、物理槽位和下次写入指针分别是什么?
答案:时间顺序为[2,3,4],物理槽位为[3,4,2],指针2将覆盖记录2。若把槽位顺序当成时间顺序,就会误把记录2放在最后。
- 从这三行有放回抽三次。有多少种有序批次没有重复索引?重复概率是多少?
答案:3³=27种可能中,3×2×1=6种索引全不同;至少一次重复的概率为21/27=7/9。这里数的是记录身份,即使两行的数值恰好相同,也仍是两条记录。
- 容量100的缓存只有一条有效记录。可以有放回抽32条吗?可以无放回抽32条吗?
答案:前者可以,同一条会重复32次;后者不可能。若按容量而非有效大小抽样,暴露的是未初始化槽位,不是额外经历。
- 奖励0到4依次到达,却只保留最近三行。没有额外信息时,一百万次均匀回放能估计全部历史的均值2吗?
答案:不能,样本均值会趋近保留均值3,而非2。要回答那个统计问题,需要另存恰当的汇总量或保留必要记录。加大批次或删除重复,都不能重建被覆盖的观测。
把历史证据与实现方案分开
Lin1992只在摘要范围内提供早期历史证据,本篇不会把具体采样协议归于未读的全文。2013年与2015年方法支持近期记忆、均匀回放的描述。固定Spinning Up文件使有效大小和有放回选择可以逐项检查;本项目读了相关段落与MIT许可证,没有运行或复用源码。这些阅读都不能证明某个容量对所有任务最好。
先判断,再看解释
三条记录的缓存有放回抽三次,至少一条重复的概率是多少?
学习目标
- 跟踪有效条目、容量和有/无放回均匀抽样。
- 解释回放为何不能恢复被覆盖数据,也不能产生新的独立环境观测。
先修与延伸
查看知识关联图 →参考文献
- Playing Atari with Deep Reinforcement Learning — arXiv v1
Volodymyr Mnih; Koray Kavukcuoglu; David Silver; Alex Graves; Ioannis Antonoglou; Daan Wierstra; Martin Riedmiller · 2013 - 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 - Spinning Up: replay and target-network mechanisms at fixed commit
OpenAI; Joshua Achiam and contributors · 2020 - Self-improving reactive agents based on reinforcement learning, planning and teaching — metadata and abstract
Long-Ji Lin · 1992
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 核环形容量、有效大小、覆盖与时间顺序、不可变标量行、有/无放回、穷举27三元组及缓存均值期望。条件经验抽样不当新独立环境数据;Lin1992只在摘要范围支持历史归属。
- 每题四张计算SVG,11数值/几何与18响应式组合通过;六张选定当前截图均直接实看;浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- Playing Atari with Deep Reinforcement Learning — arXiv v1 · 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.
- Human-level control through deep reinforcement learning — scoped Methods reading · 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.
- Spinning Up: replay and target-network mechanisms at fixed commit · 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.
- Self-improving reactive agents based on reinforcement learning, planning and teaching — metadata and abstract · 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.
相关主题