PrioritizedReplayBuffer¶
- class torchrl.data.PrioritizedReplayBuffer(*, alpha: float, beta: float, eps: float = 1e-08, dtype: torch.dtype = torch.float32, storage: Storage | 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)[source]¶
优先经验回放缓冲区。
所有参数均为仅关键字参数。
- 在以下论文中提出:
“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, optional) – 要使用的存储。如果未提供,则将创建一个默认的
ListStorage
,其max_size
为1_000
。collate_fn (callable, optional) – 合并样本列表以形成 Tensor(s)/输出的 mini-batch。当使用来自 map-style 数据集的批量加载时使用。默认值将根据存储类型决定。
pin_memory (bool) – 是否应在 rb 样本上调用 pin_memory()。
prefetch (int, optional) – 使用多线程预取的下一个批次的数量。默认为 None(不预取)。
transform (Transform, optional) – 当调用 sample() 时要执行的 Transform。要链接 transforms,请使用
Compose
类。Transforms 应该与tensordict.TensorDict
内容一起使用。如果与其他结构一起使用,则 transforms 应该使用"data"
前导键进行编码,该键将用于从非 tensordict 内容构建 tensordict。batch_size (int, optional) –
当调用 sample() 时要使用的批次大小。 .. note
The batch-size can be specified at construction time via the ``batch_size`` argument, or at sampling time. The former should be preferred whenever the batch-size is consistent across the experiment. If the batch-size is likely to change, it can be passed to the :meth:`~.sample` method. This option is incompatible with prefetching (since this requires to know the batch-size in advance) as well as with samplers that have a ``drop_last`` argument.
dim_extend (int, optional) –
指示调用
extend()
时要考虑的扩展维度。默认为storage.ndim-1
。当使用dim_extend > 0
时,我们建议在存储实例化中使用ndim
参数(如果该参数可用),以便让存储知道数据是多维的,并在采样期间保持存储容量和批次大小的概念一致。
注意
通用优先经验回放缓冲区(即非 tensordict 支持的)需要使用设置为
True
的return_info
参数调用sample()
以访问索引,并因此更新优先级。使用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 ¶
在末尾追加 transform。
当调用 sample 时,transforms 按顺序应用。
- 参数:
transform (Transform) – 要追加的 transform
- 关键词参数:
invert (bool, optional) – 如果为
True
,则 transform 将被反转(前向调用将在写入期间调用,反向调用将在读取期间调用)。默认为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()
- 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()¶
清空回放缓冲区并将游标重置为 0。
- extend(data: Sequence) Tensor ¶
使用可迭代对象中包含的一个或多个元素扩展回放缓冲区。
如果存在,将调用反向 transforms。
- 参数:
data (iterable) – 要添加到回放缓冲区的数据集合。
- 返回:
添加到回放缓冲区的数据的索引。
警告
当处理值列表时,
extend()
可能具有不明确的签名,这些列表应被解释为 PyTree(在这种情况下,列表中的所有元素都将放入存储中存储的 PyTree 中的切片中)或一次添加一个值的列表。为了解决这个问题,TorchRL 明确区分了列表和元组:元组将被视为 PyTree,列表(在根级别)将被解释为一次添加到缓冲区的值堆栈。对于ListStorage
实例,只能提供未绑定的元素(没有 PyTrees)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入 transform。
当调用 sample 时,Transforms 按顺序执行。
- 参数:
index (int) – 插入 transform 的位置。
transform (Transform) – 要追加的 transform
- 关键词参数:
invert (bool, optional) – 如果为
True
,则 transform 将被反转(前向调用将在写入期间调用,反向调用将在读取期间调用)。默认为False
。
- loads(path)¶
加载给定路径的回放缓冲区状态。
缓冲区应具有匹配的组件,并使用
dumps()
保存。- 参数:
path (Path 或 str) – 回放缓冲区保存的路径。
有关更多信息,请参阅
dumps()
。
- register_load_hook(hook: Callable[[Any], Any])¶
为存储注册加载 hook。
注意
Hook 目前在保存回放缓冲区时不会序列化:每次创建缓冲区时都必须手动重新初始化它们。
- register_save_hook(hook: Callable[[Any], Any])¶
为存储注册保存 hook。
注意
Hook 目前在保存回放缓冲区时不会序列化:每次创建缓冲区时都必须手动重新初始化它们。
- sample(batch_size: Optional[int] = None, return_info: bool = False) Any ¶
从回放缓冲区中采样一批数据。
使用 Sampler 采样索引,并从 Storage 中检索它们。
- 参数:
batch_size (int, optional) – 要收集的数据大小。如果未提供,此方法将采样一个由 sampler 指示的批次大小。
return_info (bool) – 是否返回信息。如果为 True,则结果为元组 (data, info)。如果为 False,则结果为数据。
- 返回:
在回放缓冲区中选择的一批数据。如果 return_info 标志设置为 True,则返回包含此批次和信息的元组。
- set_storage(storage: Storage, collate_fn: Optional[Callable] = None)¶
在回放缓冲区中设置新的 storage 并返回之前的 storage。
- 参数:
storage (Storage) – 缓冲区的新 storage。
collate_fn (callable, optional) – 如果提供,则 collate_fn 设置为此值。否则,它将重置为默认值。
- property write_count¶
到目前为止通过 add 和 extend 写入缓冲区中的项目总数。