PrioritizedReplayBuffer¶
- class torchrl.data.PrioritizedReplayBuffer(*, alpha: float, beta: float, eps: float = 1e-08, dtype: torch.dtype = torch.float32, storage: Storage | None = None, sampler: Sampler | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: Transform | None = None, batch_size: int | None = None, dim_extend: int | None = None)[源代码]¶
优先回放缓冲区。
所有参数均为关键字参数。
在“Schaul, T.; Quan, J.; Antonoglou, I.; and Silver, D. 2015. Prioritized experience replay.”( https://arxiv.org/abs/1511.05952)中介绍
- 参数:
alpha (
float
) – 指数 α 决定了优先级的多少,其中 α = 0 对应于均匀情况。beta (
float
) – 重要性采样负指数。eps (
float
) – 添加到优先级的 delta,以确保缓冲区不包含空优先级。storage (Storage, 可选) – 要使用的存储。如果未提供,将创建一个默认的
ListStorage
,其max_size
为1_000
。sampler (Sampler, 可选) – 要使用的采样器。如果未提供,将创建一个默认的
PrioritizedSampler
,其参数为alpha
、beta
和eps
。collate_fn (callable, 可选) – 将样本列表合并以形成一个 Tensor/输出的 mini-batch。当从 map 风格的数据集使用批处理加载时使用。默认值将根据存储类型确定。
pin_memory (bool) – 是否应对 rb 样本调用 pin_memory()。
prefetch (int, optional) – 要通过多线程预取的下一个批次数。默认为 None(无预取)。
transform (Transform, 可选) – 调用 sample() 时要执行的转换。要链接转换,请使用
Compose
类。转换应与tensordict.TensorDict
内容一起使用。如果与其他结构一起使用,转换应使用一个以"data"
开头的键进行编码,该键将用于从非 tensordict 内容构建 tensordict。batch_size (int, 可选) –
调用 sample() 时要使用的批次大小。
注意
批处理大小可以在构造时通过
batch_size
参数指定,也可以在采样时指定。前者应优先于后者,只要批处理大小在整个实验中保持一致。如果批处理大小可能会发生变化,则可以将其传递给sample()
方法。此选项与预取(因为这需要提前知道批处理大小)以及具有drop_last
参数的采样器不兼容。dim_extend (int, 可选) –
指示调用
extend()
时要考虑的扩展维度。默认为storage.ndim-1
。当使用dim_extend > 0
时,建议在实例化存储时使用ndim
参数(如果该参数可用),以便存储知道数据是多维的,并在采样过程中保持存储容量和批处理大小的一致性。
注意
通用的优先回放缓冲区(即非 tensordict 支持的)需要将
sample()
与return_info
参数设置为True
才能访问索引,从而更新优先级。使用tensordict.TensorDict
和相关的TensorDictPrioritizedReplayBuffer
可以简化此过程。示例
>>> import torch >>> >>> from torchrl.data import ListStorage, PrioritizedReplayBuffer >>> >>> torch.manual_seed(0) >>> >>> rb = PrioritizedReplayBuffer(alpha=0.7, beta=0.9, storage=ListStorage(10)) >>> data = range(10) >>> rb.extend(data) >>> sample = rb.sample(3) >>> print(sample) tensor([1, 0, 1]) >>> # get the info to find what the indices are >>> sample, info = rb.sample(5, return_info=True) >>> print(sample, info) tensor([2, 7, 4, 3, 5]) {'_weight': array([1., 1., 1., 1., 1.], dtype=float32), 'index': array([2, 7, 4, 3, 5])} >>> # update priority >>> priority = torch.ones(5) * 5 >>> rb.update_priority(info["index"], priority) >>> # and now a new sample, the weights should be updated >>> sample, info = rb.sample(5, return_info=True) >>> print(sample, info) tensor([2, 5, 2, 2, 5]) {'_weight': array([0.36278465, 0.36278465, 0.36278465, 0.36278465, 0.36278465], dtype=float32), 'index': array([2, 5, 2, 2, 5])}
- add(data: Any) int ¶
将单个元素添加到重放缓冲区。
- 参数:
data (Any) – 要添加到重放缓冲区的数据
- 返回:
数据在重放缓冲区中的索引。
- append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer ¶
将变换附加到末尾。
调用 sample 时按顺序应用变换。
- 参数:
transform (Transform) – 要附加的变换
- 关键字参数:
invert (bool, 可选) – 如果
True
,转换将在写入时调用(forward),在读取时调用(inverse)。默认为False
。
示例
>>> rb = ReplayBuffer(storage=LazyMemmapStorage(10), batch_size=4) >>> data = TensorDict({"a": torch.zeros(10)}, [10]) >>> def t(data): ... data += 1 ... return data >>> rb.append_transform(t, invert=True) >>> rb.extend(data) >>> assert (data == 1).all()
- classmethod as_remote(remote_config=None)¶
创建一个远程 ray 类的实例。
- 参数:
cls (Python Class) – 要远程实例化的类。
remote_config (dict) – 为该类保留的 CPU 核心数量。默认为 torchrl.collectors.distributed.ray.DEFAULT_REMOTE_CLASS_CONFIG。
- 返回:
一个创建 ray 远程类实例的函数。
- property batch_size¶
重放缓冲区的批次大小。
批处理大小可以通过在
sample()
方法中设置 batch_size 参数来覆盖。它定义了
sample()
返回的样本数量以及ReplayBuffer
迭代器产生的样本数量。
- dumps(path)¶
将重放缓冲区保存到指定路径的磁盘上。
- 参数:
path (Path 或 str) – 保存重放缓冲区的路径。
示例
>>> import tempfile >>> import tqdm >>> from torchrl.data import LazyMemmapStorage, TensorDictReplayBuffer >>> from torchrl.data.replay_buffers.samplers import PrioritizedSampler, RandomSampler >>> import torch >>> from tensordict import TensorDict >>> # Build and populate the replay buffer >>> S = 1_000_000 >>> sampler = PrioritizedSampler(S, 1.1, 1.0) >>> # sampler = RandomSampler() >>> storage = LazyMemmapStorage(S) >>> rb = TensorDictReplayBuffer(storage=storage, sampler=sampler) >>> >>> for _ in tqdm.tqdm(range(100)): ... td = TensorDict({"obs": torch.randn(100, 3, 4), "next": {"obs": torch.randn(100, 3, 4)}, "td_error": torch.rand(100)}, [100]) ... rb.extend(td) ... sample = rb.sample(32) ... rb.update_tensordict_priority(sample) >>> # save and load the buffer >>> with tempfile.TemporaryDirectory() as tmpdir: ... rb.dumps(tmpdir) ... ... sampler = PrioritizedSampler(S, 1.1, 1.0) ... # sampler = RandomSampler() ... storage = LazyMemmapStorage(S) ... rb_load = TensorDictReplayBuffer(storage=storage, sampler=sampler) ... rb_load.loads(tmpdir) ... assert len(rb) == len(rb_load)
- empty(empty_write_count: bool = True)¶
清空重放缓冲区并将游标重置为 0。
- 参数:
empty_write_count (bool, optional) – 是否清空 write_count 属性。默认为 True。
- extend(data: Sequence, *, update_priority: bool | None = None) torch.Tensor ¶
使用包含在可迭代对象中的一个或多个元素扩展经验回放缓冲区。
如果存在,将调用逆向转换。
- 参数:
data (iterable) – 要添加到经验回放缓冲区的元素集合。
- 关键字参数:
update_priority (bool, 可选) – 是否更新数据的优先级。默认为 True。在此类中无效。有关更多详细信息,请参阅
extend()
。- 返回:
添加到经验回放缓冲区的数据的索引。
警告
extend()
在处理值列表时可能具有歧义的签名,应将其解释为 PyTree(在这种情况下,列表中的所有元素都将被放入存储中的 PyTree 切片)或要逐个添加到缓冲区的 值列表。为解决此问题,TorchRL 会在列表和元组之间做出明确区分:元组将被视为 PyTree,列表(在根级别)将被解释为要逐个添加到缓冲区的值堆栈。对于ListStorage
实例,只能提供未绑定的元素(无 PyTrees)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入变换。
调用 sample 时按顺序执行变换。
- 参数:
index (int) – 插入变换的位置。
transform (Transform) – 要附加的变换
- 关键字参数:
invert (bool, 可选) – 如果
True
,转换将在写入时调用(forward),在读取时调用(inverse)。默认为False
。
- loads(path)¶
在给定路径加载重放缓冲区状态。
缓冲区应具有匹配的组件,并使用
dumps()
保存。- 参数:
path (Path 或 str) – 重放缓冲区保存的路径。
有关更多信息,请参阅
dumps()
。
- next()¶
返回重放缓冲区的下一个项。
此方法用于在 __iter__ 不可用的情况下迭代重放缓冲区,例如
RayReplayBuffer
。
- register_load_hook(hook: Callable[[Any], Any])¶
为存储注册加载钩子。
注意
钩子目前不会在保存重放缓冲区时序列化:每次创建缓冲区时都必须手动重新初始化它们。
- register_save_hook(hook: Callable[[Any], Any])¶
为存储注册保存钩子。
注意
钩子目前不会在保存重放缓冲区时序列化:每次创建缓冲区时都必须手动重新初始化它们。
- sample(batch_size: int | None = None, return_info: bool = False) Any ¶
从重放缓冲区中采样数据批次。
使用 Sampler 采样索引,并从 Storage 中检索它们。
- 参数:
batch_size (int, optional) – 要收集的数据的大小。如果未提供,此方法将采样由采样器指示的批次大小。
return_info (bool) – 是否返回信息。如果为 True,则结果为元组 (data, info)。如果为 False,则结果为数据。
- 返回:
从经验回放缓冲区中选择的数据批次。如果 return_info 标志设置为 True,则返回包含此批次和信息的元组。
- set_storage(storage: Storage, collate_fn: Callable | None = None)¶
在重放缓冲区中设置新的存储并返回之前的存储。
- 参数:
storage (Storage) – 缓冲区的新的存储。
collate_fn (callable, optional) – 如果提供,collate_fn 将设置为此值。否则,它将被重置为默认值。
- property write_count¶
通过 add 和 extend 写入缓冲区的总项数。