ReplayBuffer¶
- class torchrl.data.ReplayBuffer(*, storage: Storage | None = None, sampler: Sampler | None = None, writer: Writer | 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, checkpointer: 'StorageCheckpointerBase' | None = None, generator: torch.Generator | None = None, shared: bool = False)[source]¶
一个通用的、可组合的回放缓冲区类。
- 关键字参数:
storage (Storage, optional) – 要使用的存储。如果未提供,则将创建一个默认的
ListStorage
,其max_size
为1_000
。sampler (Sampler, optional) – 要使用的采样器。如果未提供,则将使用默认的
RandomSampler
。writer (Writer, optional) – 要使用的写入器。如果未提供,则将使用默认的
RoundRobinWriter
。collate_fn (callable, optional) – 将样本列表合并以形成 Tensor(s)/输出的 mini-batch。当从 map-style 数据集使用批量加载时使用。默认值将根据存储类型决定。
pin_memory (bool) – 是否应该在 rb 样本上调用 pin_memory()。
prefetch (int, optional) – 使用多线程预取的下一个批次的数量。默认为 None (不预取)。
transform (Transform, optional) – 当调用
sample()
时要执行的转换。要链式转换,请使用Compose
类。转换应与tensordict.TensorDict
内容一起使用。如果回放缓冲区与 PyTree 结构一起使用,也可以传递通用可调用对象(见下面的示例)。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
参数(如果该参数可用),以使存储知道数据是多维的,并在采样期间保持存储容量和批次大小的概念一致。generator (torch.Generator, optional) –
用于采样的生成器。为回放缓冲区使用专用生成器可以对种子进行细粒度控制,例如,对于分布式作业,保持全局种子不同但 RB 种子相同。默认为
None
(全局默认生成器)。警告
到目前为止,生成器对转换没有影响。
shared (bool, optional) – 缓冲区是否将使用多进程共享。默认为
False
。
示例
>>> import torch >>> >>> from torchrl.data import ReplayBuffer, ListStorage >>> >>> torch.manual_seed(0) >>> rb = ReplayBuffer( ... storage=ListStorage(max_size=1000), ... batch_size=5, ... ) >>> # populate the replay buffer and get the item indices >>> data = range(10) >>> indices = rb.extend(data) >>> # sample will return as many elements as specified in the constructor >>> sample = rb.sample() >>> print(sample) tensor([4, 9, 3, 0, 3]) >>> # Passing the batch-size to the sample method overrides the one in the constructor >>> sample = rb.sample(batch_size=3) >>> print(sample) tensor([9, 7, 3]) >>> # one cans sample using the ``sample`` method or iterate over the buffer >>> for i, batch in enumerate(rb): ... print(i, batch) ... if i == 3: ... break 0 tensor([7, 3, 1, 6, 6]) 1 tensor([9, 8, 6, 6, 8]) 2 tensor([4, 3, 6, 9, 1]) 3 tensor([4, 4, 1, 9, 9])
回放缓冲区接受任何类型的数据。并非所有存储类型都适用,因为有些存储类型仅期望数值数据,但默认的
ListStorage
可以。示例
>>> torch.manual_seed(0) >>> buffer = ReplayBuffer(storage=ListStorage(100), collate_fn=lambda x: x) >>> indices = buffer.extend(["a", 1, None]) >>> buffer.sample(3) [None, 'a', None]
TensorStorage
、LazyMemmapStorage
和LazyTensorStorage
也适用于任何 PyTree 结构(PyTree 是由字典、列表或元组组成的任意深度的嵌套结构,其中叶子是张量),前提是它仅包含张量数据。示例
>>> from torch.utils._pytree import tree_map >>> def transform(x): ... # Zeros all the data in the pytree ... return tree_map(lambda y: y * 0, x) >>> rb = ReplayBuffer(storage=LazyMemmapStorage(100), transform=transform) >>> data = { ... "a": torch.randn(3), ... "b": {"c": (torch.zeros(2), [torch.ones(1)])}, ... 30: -torch.ones(()), ... } >>> rb.add(data) >>> # The sample has a similar structure to the data (with a leading dimension of 10 for each tensor) >>> s = rb.sample(10) >>> # let's check that our transform did its job: >>> def assert0(x): >>> assert (x == 0).all() >>> tree_map(assert0, s)
- append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer [source]¶
在末尾追加转换。
当调用 sample 时,转换按顺序应用。
- 参数:
transform (Transform) – 要追加的转换
- 关键字参数:
invert (bool, optional) – 如果
True
,则转换将被反转(前向调用将在写入期间调用,反向调用将在读取期间调用)。默认为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)[source]¶
将回放缓冲区保存在磁盘上的指定路径。
- 参数:
path (Path or 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)
- extend(data: Sequence) Tensor [source]¶
使用可迭代对象中包含的一个或多个元素扩展回放缓冲区。
如果存在,将调用反向转换。`
- 参数:
data (iterable) – 要添加到回放缓冲区的数据集合。
- 返回:
添加到回放缓冲区的数据的索引。
警告
extend()
在处理值列表时可能具有歧义的签名,这应解释为 PyTree(在这种情况下,列表中的所有元素都将放入存储中存储的 PyTree 中的切片中)或一次添加一个值的列表。为了解决这个问题,TorchRL 清晰地区分了列表和元组:元组将被视为 PyTree,列表(在根级别)将被解释为一次添加一个值到缓冲区的堆栈。对于ListStorage
实例,只能提供未绑定的元素(没有 PyTree)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer [source]¶
插入转换。
当调用 sample 时,转换按顺序执行。
- 参数:
index (int) – 插入转换的位置。
transform (Transform) – 要追加的转换
- 关键字参数:
invert (bool, optional) – 如果
True
,则转换将被反转(前向调用将在写入期间调用,反向调用将在读取期间调用)。默认为False
。
- loads(path)[source]¶
加载给定路径的回放缓冲区状态。
缓冲区应具有匹配的组件,并使用
dumps()
保存。- 参数:
path (Path or str) – 回放缓冲区保存的路径。
有关更多信息,请参阅
dumps()
。
- register_load_hook(hook: Callable[[Any], Any])[source]¶
为存储注册加载钩子。
注意
钩子当前在保存回放缓冲区时不会序列化:每次创建缓冲区时都必须手动重新初始化它们。
- register_save_hook(hook: Callable[[Any], Any])[source]¶
为存储注册保存钩子。
注意
钩子当前在保存回放缓冲区时不会序列化:每次创建缓冲区时都必须手动重新初始化它们。
- sample(batch_size: Optional[int] = None, return_info: bool = False) Any [source]¶
从回放缓冲区中采样一批数据。
使用 Sampler 采样索引,并从 Storage 中检索它们。
- 参数:
batch_size (int, optional) – 要收集的数据大小。如果未提供,则此方法将采样一个批次大小,如采样器所示。
return_info (bool) – 是否返回信息。如果为 True,则结果为元组 (data, info)。如果为 False,则结果为数据。
- 返回:
在回放缓冲区中选择的一批数据。如果 return_info 标志设置为 True,则返回包含此批次和信息的元组。
- set_storage(storage: Storage, collate_fn: Optional[Callable] = None)[source]¶
在回放缓冲区中设置新的存储并返回之前的存储。
- 参数:
storage (Storage) – 缓冲区的新的存储。
collate_fn (callable, optional) – 如果提供,则 collate_fn 将设置为此值。否则,它将重置为默认值。
- property write_count¶
到目前为止通过添加和扩展写入缓冲区中的项目总数。