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)[source]¶
围绕
PrioritizedReplayBuffer
类的 TensorDict 特定包装器。此类返回带有新键
"index"
的 tensordict,该键表示经验回放缓冲区中每个元素的索引。它还提供了update_tensordict_priority()
方法,该方法只需将 tensordict 及其新优先级值传递给它即可。- 关键字参数:
alpha (
float
) – 指数 α 决定了优先级的程度,当 α = 0 时对应于均匀分布的情况。beta (
float
) – 重要性采样负指数。eps (
float
) – 添加到优先级中的 delta 值,用于确保缓冲区不包含零优先级。storage (Storage, optional) – 要使用的存储。如果未提供,将创建一个默认的
ListStorage
,其max_size
为1_000
。collate_fn (callable, optional) – 将样本列表合并以形成 Tensor(s)/输出的小批量。在从 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() 时要使用的批量大小。
注意
批量大小可以在构造时通过
batch_size
参数指定,也可以在采样时指定。如果实验中的批量大小一致,应优先使用前者。如果批量大小可能改变,可以将其传递给sample()
方法。此选项与预取不兼容(因为它需要提前知道批量大小),也与带有drop_last
参数的采样器不兼容。priority_key (str, optional) – 优先级被假定存储在此 ReplayBuffer 中添加的 TensorDicts 的键。当采样器类型为
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
(全局默认生成器)。警告
截至目前,该生成器对 transforms 没有影响。
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 ¶
将 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 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)
- empty()¶
清空经验回放缓冲区并将游标重置为 0。
- extend(tensordicts: TensorDictBase) Tensor ¶
使用包含在可迭代对象中的一个或多个元素扩展经验回放缓冲区。
如果存在,将调用反向 transforms。
- 参数:
data (iterable) – 要添加到经验回放缓冲区的数据集合。
- 返回值:
添加到经验回放缓冲区的数据的索引。
警告
extend()
在处理值列表时可能具有模糊的签名,这些列表应被解释为 PyTree(此时列表中的所有元素将放入存储中的 PyTree 的一个切片中)或要逐个添加的值列表。为了解决这个问题,TorchRL 对 list 和 tuple 进行了明确区分:tuple 将被视为 PyTree,而 list(在根级别)将被解释为要逐个添加到缓冲区的值堆栈。对于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 or str) – 经验回放缓冲区保存的路径。
有关详细信息,请参阅
dumps()
。
- 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) TensorDictBase ¶
从经验回放缓冲区采样一个批量的数据。
使用 Sampler 采样索引,并从 Storage 中检索它们。
- 参数:
batch_size (int, optional) – 要收集的数据大小。如果未提供,此方法将按照采样器指示的批量大小进行采样。
return_info (bool) – 是否返回信息。如果为 True,结果是 tuple (data, info)。如果为 False,结果是 data。
- 返回值:
一个 tensordict,包含在经验回放缓冲区中选定的批量数据。如果 return_info 标志设置为 True,则是一个包含此 tensordict 和 info 的 tuple。
- set_storage(storage: Storage, collate_fn: Callable | None = None)¶
在回放缓冲区中设置新的存储器,并返回先前的存储器。
- 参数:
storage (Storage) – 缓冲区的新的存储器。
collate_fn (可调用对象, 可选) – 如果提供,collate_fn 将设置为此值。否则,它将被重置为默认值。
- property write_count¶
通过 add 和 extend 方法至今写入缓冲区项目的总数。