快捷方式

TensorDictPrioritizedReplayBuffer

class torchrl.data.TensorDictPrioritizedReplayBuffer(*, alpha: float, beta: float, priority_key: str = 'td_error', eps: float = 1e-08, storage: Storage | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: 'Transform' | None = None, reduction: str = 'max', batch_size: int | None = None, dim_extend: int | None = None, generator: torch.Generator | None = None, shared: bool = False)[source]

围绕 PrioritizedReplayBuffer 类的特定于 TensorDict 的包装器。

此类返回带有新键 "index" 的 tensordict,该键表示回放缓冲区中每个元素的索引。它还提供了 update_tensordict_priority() 方法,该方法仅需要将带有新优先级值的 tensordict 传递给它。

关键字参数:
  • alpha (float) – 指数 α 决定了优先化的程度,其中 α = 0 对应于均匀情况。

  • beta (float) – 重要性采样的负指数。

  • eps (float) – 添加到优先级中的 delta,以确保缓冲区不包含空优先级。

  • storage (Storage, 可选) – 要使用的存储。如果未提供,则将创建一个默认的 ListStorage,其 max_size1_000

  • collate_fn (callable, 可选) – 合并样本列表以形成 Tensor(s)/输出 的小批量。当使用来自 map-style 数据集的批量加载时使用。默认值将根据存储类型决定。

  • pin_memory (bool) – 是否应在 rb 样本上调用 pin_memory()。

  • prefetch (int, 可选) – 使用多线程预取的下一个批次的数量。默认为 None(不预取)。

  • transform (Transform, 可选) – 调用 sample() 时要执行的变换。要链接变换,请使用 Compose 类。变换应与 tensordict.TensorDict 内容一起使用。如果与其他结构一起使用,则变换应使用 "data" 前导键进行编码,该键将用于从非 tensordict 内容构建 tensordict。

  • batch_size (int, 可选) –

    调用 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.
    

  • priority_key (str, 可选) – 优先级假定存储在此 ReplayBuffer 中添加的 TensorDict 中的键。这用于当采样器类型为 PrioritizedSampler 时。默认为 "td_error"

  • reduction (str, 可选) – 多维 tensordict(即存储的轨迹)的归约方法。可以是 “max”、“min”、“median” 或 “mean” 之一。

  • dim_extend (int, 可选) –

    指示调用 extend() 时要考虑的扩展维度。默认为 storage.ndim-1。当使用 dim_extend > 0 时,我们建议在存储实例化中使用 ndim 参数(如果该参数可用),以便让存储知道数据是多维的,并在采样期间保持存储容量和批次大小的概念一致。

    注意

    此参数对 add() 没有影响,因此当在代码库中同时使用 add()extend() 时应谨慎使用。例如

    >>> data = torch.zeros(3, 4)
    >>> rb = ReplayBuffer(
    ...     storage=LazyTensorStorage(10, ndim=2),
    ...     dim_extend=1)
    >>> # these two approaches are equivalent:
    >>> for d in data.unbind(1):
    ...     rb.add(d)
    >>> rb.extend(data)
    

  • generator (torch.Generator, 可选) –

    用于采样的生成器。为回放缓冲区使用专用生成器可以对播种进行细粒度控制,例如,保持全局种子不同,但 RB 种子对于分布式作业保持相同。默认为 None(全局默认生成器)。

    警告

    目前,生成器对变换没有影响。

  • shared (bool, 可选) – 缓冲区是否将使用多处理共享。默认为 False

示例

>>> import torch
>>>
>>> from torchrl.data import LazyTensorStorage, TensorDictPrioritizedReplayBuffer
>>> from tensordict import TensorDict
>>>
>>> torch.manual_seed(0)
>>>
>>> rb = TensorDictPrioritizedReplayBuffer(alpha=0.7, beta=1.1, storage=LazyTensorStorage(10), batch_size=5)
>>> data = TensorDict({"a": torch.ones(10, 3), ("b", "c"): torch.zeros(10, 3, 1)}, [10])
>>> rb.extend(data)
>>> print("len of rb", len(rb))
len of rb 10
>>> sample = rb.sample(5)
>>> print(sample)
TensorDict(
    fields={
        _weight: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.float32, is_shared=False),
        a: Tensor(shape=torch.Size([5, 3]), device=cpu, dtype=torch.float32, is_shared=False),
        b: TensorDict(
            fields={
                c: Tensor(shape=torch.Size([5, 3, 1]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([5]),
            device=cpu,
            is_shared=False),
        index: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False)},
    batch_size=torch.Size([5]),
    device=cpu,
    is_shared=False)
>>> print("index", sample["index"])
index tensor([9, 5, 2, 2, 7])
>>> # give a high priority to these samples...
>>> sample.set("td_error", 100*torch.ones(sample.shape))
>>> # and update priority
>>> rb.update_tensordict_priority(sample)
>>> # the new sample should have a high overlap with the previous one
>>> sample = rb.sample(5)
>>> print(sample)
TensorDict(
    fields={
        _weight: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.float32, is_shared=False),
        a: Tensor(shape=torch.Size([5, 3]), device=cpu, dtype=torch.float32, is_shared=False),
        b: TensorDict(
            fields={
                c: Tensor(shape=torch.Size([5, 3, 1]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([5]),
            device=cpu,
            is_shared=False),
        index: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False)},
    batch_size=torch.Size([5]),
    device=cpu,
    is_shared=False)
>>> print("index", sample["index"])
index tensor([2, 5, 5, 9, 7])
add(data: TensorDictBase) int

向回放缓冲区添加单个元素。

参数:

data (Any) – 要添加到回放缓冲区的数据

返回:

数据在回放缓冲区中的索引。

append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer

在末尾追加变换。

当调用 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()
dump(*args, **kwargs)

dumps() 的别名。

dumps(path)

将回放缓冲区保存到磁盘上的指定路径。

参数:

path (Pathstr) – 保存回放缓冲区的路径。

示例

>>> 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(tensordicts: TensorDictBase) Tensor

使用一个或多个可迭代对象中包含的元素扩展回放缓冲区。

如果存在,将调用反向变换。`

参数:

data (iterable) – 要添加到回放缓冲区的数据集合。

返回:

添加到回放缓冲区的数据的索引。

警告

extend() 在处理值列表时可能具有不明确的签名,这应该被解释为 PyTree(在这种情况下,列表中的所有元素都将放入存储中存储的 PyTree 中的切片)或一次添加一个值的列表。为了解决这个问题,TorchRL 明确区分了列表和元组:元组将被视为 PyTree,列表(在根级别)将被解释为一次添加一个值到缓冲区的堆栈。对于 ListStorage 实例,只能提供未绑定元素(没有 PyTrees)。

insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer

插入变换。

当调用 sample 时,变换会按顺序执行。

参数:
  • index (int) – 插入变换的位置。

  • transform (Transform) – 要追加的变换

关键字参数:

invert (bool, optional) – 如果 True,变换将被反转(前向调用将在写入期间调用,反向调用将在读取期间调用)。默认为 False

load(*args, **kwargs)

loads() 的别名。

loads(path)

加载给定路径的回放缓冲区状态。

缓冲区应具有匹配的组件,并使用 dumps() 保存。

参数:

path (Pathstr) – 回放缓冲区保存的路径。

有关更多信息,请参阅 dumps()

register_load_hook(hook: Callable[[Any], Any])

为存储注册加载钩子。

注意

钩子当前在保存回放缓冲区时不会被序列化:每次创建缓冲区时都必须手动重新初始化它们。

register_save_hook(hook: Callable[[Any], Any])

为存储注册保存钩子。

注意

钩子当前在保存回放缓冲区时不会被序列化:每次创建缓冲区时都必须手动重新初始化它们。

sample(batch_size: Optional[int] = None, return_info: bool = False, include_info: Optional[bool] = None) TensorDictBase

从回放缓冲区中采样一批数据。

使用 Sampler 采样索引,并从 Storage 中检索它们。

参数:
  • batch_size (int, optional) – 要收集的数据大小。如果未提供,此方法将按照采样器指示的方式采样批次大小。

  • return_info (bool) – 是否返回 info。如果为 True,则结果为元组 (data, info)。如果为 False,则结果为数据。

返回:

一个 tensordict,其中包含在回放缓冲区中选择的一批数据。如果 return_info 标志设置为 True,则为一个包含此 tensordict 和 info 的元组。

property sampler

回放缓冲区的采样器。

采样器必须是 Sampler 的一个实例。

save(*args, **kwargs)

dumps() 的别名。

set_sampler(sampler: Sampler)

在回放缓冲区中设置一个新的采样器,并返回之前的采样器。

set_storage(storage: Storage, collate_fn: Optional[Callable] = None)

在回放缓冲区中设置新的存储,并返回之前的存储。

参数:
  • storage (Storage) – 缓冲区的新的存储。

  • collate_fn (callable, optional) – 如果提供,则 collate_fn 将设置为此值。否则,它将重置为默认值。

set_writer(writer: Writer)

在回放缓冲区中设置新的写入器,并返回之前的写入器。

property storage

回放缓冲区的存储。

存储必须是 Storage 的一个实例。

property write_count

通过 add 和 extend 写入缓冲区至今的项目总数。

property writer

回放缓冲区的写入器。

写入器必须是 Writer 的一个实例。

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得您的问题解答

查看资源