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, compilable: bool = False)[源代码]¶
TensorDict 的特定包装器,围绕
PrioritizedReplayBuffer
类。此类返回带有新键
"index"
的 tensordict,该键表示重放缓冲区中每个元素的索引。它还提供update_tensordict_priority()
方法,该方法只需要将 tensordict 及其新的优先级值传递给它。- 关键字参数:
alpha (
float
) – 指数 α 决定了优先级的应用程度,其中 α = 0 对应于均匀情况。beta (
float
) – 重要性采样负指数。eps (
float
) – 添加到优先级的 delta,以确保缓冲区不包含空优先级。storage (Storage, Callable[], Storage], optional) – 要使用的存储。如果传递了可调用对象,则将其用作存储的构造函数。如果未提供,则会创建一个默认的
ListStorage
,其max_size
为1_000
。collate_fn (callable, optional) – 将样本列表合并以形成 Tensor/输出的 mini-batch。在使用 map 风格数据集进行批处理加载时使用。默认值将根据存储类型确定。
pin_memory (bool) – 是否应对 rb 样本调用 pin_memory()。
prefetch (int, optional) – 要通过多线程预取的下一个批次数。默认为 None(无预取)。
transform (Transform 或 Callable[Any], Any], optional) – 在调用
sample()
时要执行的转换。要链接转换,请使用Compose
类。转换应与tensordict.TensorDict
内容一起使用。如果重放缓冲区与 PyTree 结构一起使用(请参阅下面的示例),也可以传递通用的可调用对象。与存储、写入器和采样器不同,转换构造函数必须作为单独的关键字参数transform_factory
传递,因为无法区分构造函数和转换。transform_factory (Callable[], Callable], optional) – 转换的工厂。与
transform
互斥。batch_size (int, optional) –
调用 sample() 时要使用的批次大小。
注意
批次大小可以在构造时通过
batch_size
参数指定,也可以在采样时指定。前者在整个实验中批次大小一致的情况下应优先考虑。如果批次大小可能发生变化,可以将其传递给sample()
方法。此选项与预取(因为这需要提前知道批次大小)以及具有drop_last
参数的采样器不兼容。priority_key (str, optional) – 在添加到此重放缓冲区的 TensorDict 中假定存储优先级的键。这应在采样器类型为
PrioritizedSampler
时使用。默认为"td_error"
。reduction (str, optional) – 多维 tensordicts(即存储的轨迹)的归约方法。可以是 "max"、"min"、"median" 或 "mean" 之一。
dim_extend (int, optional) –
指示在调用
extend()
时要考虑扩展的维度。默认为storage.ndim-1
。当使用dim_extend > 0
时,我们建议在存储实例化时使用ndim
参数(如果该参数可用),以告知存储数据是多维的,并在采样期间保持存储容量和批次大小的一致概念。generator (torch.Generator, optional) –
用于采样的生成器。为重放缓冲区使用专用生成器可以实现对种子进行精细控制,例如在分布式作业中保持全局种子不同但 RB 种子相同。默认为
None
(全局默认生成器)。警告
目前,生成器对变换没有影响。
shared (bool, optional) – 缓冲区是否将使用多进程共享。默认为
False
。compilable (bool, optional) – 写入器是否可编译。如果为
True
,则写入器不能在多个进程之间共享。默认为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()
- 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(tensordicts: TensorDictBase, *, update_priority: bool | None = None) torch.Tensor ¶
使用数据批次扩展重放缓冲区。
- 参数:
tensordicts (TensorDictBase) – 用于扩展重放缓冲区的数据。
- 关键字参数:
update_priority (bool, optional) – 是否更新数据的优先级。默认为 True。
- 返回:
已添加到重放缓冲区的数据的索引。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入变换。
调用 sample 时按顺序执行变换。
- 参数:
index (int) – 插入变换的位置。
transform (Transform) – 要附加的变换
- 关键字参数:
invert (bool, optional) – 如果为
True
,则在写入时调用正向转换,在读取时调用反向转换。默认为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, include_info: bool | None = None) TensorDictBase ¶
从重放缓冲区中采样数据批次。
使用 Sampler 采样索引,并从 Storage 中检索它们。
- 参数:
batch_size (int, optional) – 要收集的数据的大小。如果未提供,此方法将采样由采样器指示的批次大小。
return_info (bool) – 是否返回信息。如果为 True,则结果为元组 (data, info)。如果为 False,则结果为数据。
- 返回:
一个包含在重放缓冲区中选择的数据批次的 tensordict。如果 return_info 标志设置为 True,则包含此 tensordict 和信息的元组。
- set_storage(storage: Storage, collate_fn: Callable | None = None)¶
在重放缓冲区中设置新的存储并返回之前的存储。
- 参数:
storage (Storage) – 缓冲区的新的存储。
collate_fn (callable, optional) – 如果提供,collate_fn 将设置为此值。否则,它将被重置为默认值。
- property write_count¶
通过 add 和 extend 写入缓冲区的总项数。