GenDGRLExperienceReplay¶
- class torchrl.data.datasets.GenDGRLExperienceReplay(dataset_id: str, batch_size: int = None, *, download: bool = True, root: str | None = None, **kwargs)[源代码]¶
Gen-DGRL 经验回放数据集。
此数据集配套论文“离线强化学习中的泛化差距”提供。
Arxiv: https://arxiv.org/abs/2312.05742
GitHub: https://github.com/facebookresearch/gen_dgrl
数据格式遵循 TED 规范。
此类提供对 ProcGen 数据集的访问。在 GenDGRLExperienceReplay.available_datasets 中注册的每个 dataset_id 包含一个特定任务(“bigfish”、“bossfight” 等),该任务通过逗号(“bigfish-1M_E” 等)与一个类别(“1M_E”、“1M_S” 等)分开。
在下载和准备过程中,数据以下载为 .tar 文件,其中每个轨迹都独立存储在一个 .npy 文件中。这些文件会被提取,写入连续的 mmap 张量,然后清除。此过程每个数据集可能需要几分钟。在集群上,建议首先在不同的 worker 或进程上单独对不同数据集运行下载和预处理,然后再启动训练脚本。
- 参数:
dataset_id (str) – 要下载的数据集。必须是
GenDGRLExperienceReplay.available_datasets
的一部分。batch_size (int, optional) – 采样期间使用的批量大小。如果需要,可以通过 data.sample(batch_size) 覆盖此值。
- 关键字参数:
root (Path or str, optional) –
GenDGRLExperienceReplay
数据集的根目录。实际的数据集内存映射文件将保存在 <root>/<dataset_id> 下。如果未提供,则默认为 ~/.cache/torchrl/atari.gen_dgrl`。download (bool or str, optional) – 如果数据集未找到,是否应该下载。默认为
True
。也可以将 download 设置为"force"
,在这种情况下将覆盖已下载的数据。sampler (Sampler, optional) – 要使用的采样器。如果未提供,将使用默认的 RandomSampler()。
writer (Writer, optional) – 要使用的写入器。如果未提供,将使用默认的 RoundRobinWriter()。
collate_fn (callable, optional) – 合并样本列表以形成 Tensor(s)/输出的小批量。在从映射式数据集批量加载时使用。
pin_memory (bool) – 是否应在 rb 样本上调用 pin_memory()。
prefetch (int, optional) – 使用多线程预取下一个批次的数量。
transform (Transform, optional) – 在调用 sample() 时执行的转换。要链式应用转换,请使用
Compose
类。
- 变量:
available_datasets – 可接受的待下载条目列表。这些名称对应于 huggingface 数据集仓库中的目录路径。如果可能,该列表将从 huggingface 动态检索。如果没有互联网连接,则将使用缓存的版本。
示例
>>> import torch >>> torch.manual_seed(0) >>> from torchrl.data.datasets import GenDGRLExperienceReplay >>> d = GenDGRLExperienceReplay("bigfish-1M_E", batch_size=32) >>> for batch in d: ... break >>> print(batch)
- add(data: TensorDictBase) int ¶
向经验回放缓冲区添加单个元素。
- 参数:
data (Any) – 要添加到经验回放缓冲区的数据
- 返回:
数据在经验回放缓冲区中的索引。
- append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer ¶
在末尾追加转换。
调用 sample 时,转换会按顺序应用。
- 参数:
transform (Transform) – 要追加的转换
- 关键字参数:
invert (bool, optional) – 如果为
True
,则转换将被反转(forward 调用将在写入时调用,inverse 调用将在读取时调用)。默认为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()
- property data_path¶
数据集的路径,包括拆分。
- property data_path_root¶
数据集根目录的路径。
- delete()¶
从磁盘删除数据集存储。
- 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 ¶
使用可迭代对象中包含的一个或多个元素扩展经验回放缓冲区。
如果存在,将调用 inverse 转换。`
- 参数:
data (iterable) – 要添加到经验回放缓冲区的数据集合。
- 返回:
添加到经验回放缓冲区的数据的索引。
警告
extend()
在处理值列表时可能具有模糊的签名,可以将其解释为 PyTree(在这种情况下,列表中的所有元素都将放入存储中 PyTree 的切片中)或要一次添加一个的值列表。为了解决这个问题,TorchRL 明确区分了 list 和 tuple:tuple 将被视为 PyTree,list(在根级别)将被解释为堆栈中的值,用于一次向缓冲区添加一个。对于ListStorage
实例,只能提供未绑定的元素(不能是 PyTrees)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入转换。
调用 sample 时,转换会按顺序执行。
- 参数:
index (int) – 插入转换的位置。
transform (Transform) – 要追加的转换
- 关键字参数:
invert (bool, optional) – 如果为
True
,则转换将被反转(forward 调用将在写入时调用,inverse 调用将在读取时调用)。默认为False
。
- loads(path)¶
从给定路径加载经验回放缓冲区状态。
缓冲区应具有匹配的组件,并且是使用
dumps()
保存的。- 参数:
path (Path or str) – 经验回放缓冲区保存的路径。
有关更多信息,请参阅
dumps()
。
- preprocess(fn: Callable[[TensorDictBase], TensorDictBase], dim: int = 0, num_workers: int | None = None, *, chunksize: int | None = None, num_chunks: int | None = None, pool: mp.Pool | None = None, generator: torch.Generator | None =None, max_tasks_per_child: int | None =None, worker_threads: int =1, index_with_generator: bool =False, pbar: bool =False, mp_start_method: str | None =None, num_frames: int | None =None, dest: str | Path) TensorStorage ¶
预处理数据集并返回一个包含格式化数据的新存储。
数据转换必须是单元的(作用于数据集的单个样本)。
参数和关键字参数会被转发到
map()
。随后可以使用
delete()
删除数据集。- 关键字参数:
dest (path or equivalent) – 新数据集位置的路径。
num_frames (int, optional) – 如果提供,则仅转换前 num_frames 帧。这对于初步调试转换很有用。
返回: 一个新的存储,可在
ReplayBuffer
实例中使用。示例
>>> from torchrl.data.datasets import MinariExperienceReplay >>> >>> data = MinariExperienceReplay( ... list(MinariExperienceReplay.available_datasets)[0], ... batch_size=32 ... ) >>> print(data) MinariExperienceReplay( storages=TensorStorage(TensorDict( fields={ action: MemoryMappedTensor(shape=torch.Size([1000000, 8]), device=cpu, dtype=torch.float32, is_shared=True), episode: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.int64, is_shared=True), info: TensorDict( fields={ distance_from_origin: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), forward_reward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), qpos: MemoryMappedTensor(shape=torch.Size([1000000, 15]), device=cpu, dtype=torch.float64, is_shared=True), qvel: MemoryMappedTensor(shape=torch.Size([1000000, 14]), device=cpu, dtype=torch.float64, is_shared=True), reward_ctrl: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_forward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_survive: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), success: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.bool, is_shared=True), x_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), x_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), next: TensorDict( fields={ done: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), info: TensorDict( fields={ distance_from_origin: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), forward_reward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), qpos: MemoryMappedTensor(shape=torch.Size([1000000, 15]), device=cpu, dtype=torch.float64, is_shared=True), qvel: MemoryMappedTensor(shape=torch.Size([1000000, 14]), device=cpu, dtype=torch.float64, is_shared=True), reward_ctrl: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_forward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), reward_survive: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), success: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.bool, is_shared=True), x_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), x_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True), y_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), observation: TensorDict( fields={ achieved_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), desired_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), observation: MemoryMappedTensor(shape=torch.Size([1000000, 27]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), reward: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.float64, is_shared=True), terminated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), truncated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), observation: TensorDict( fields={ achieved_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), desired_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True), observation: MemoryMappedTensor(shape=torch.Size([1000000, 27]), device=cpu, dtype=torch.float64, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False)), samplers=RandomSampler, writers=ImmutableDatasetWriter(), batch_size=32, transform=Compose( ), collate_fn=<function _collate_id at 0x120e21dc0>) >>> from torchrl.envs import CatTensors, Compose >>> from tempfile import TemporaryDirectory >>> >>> cat_tensors = CatTensors( ... in_keys=[("observation", "observation"), ("observation", "achieved_goal"), ... ("observation", "desired_goal")], ... out_key="obs" ... ) >>> cat_next_tensors = CatTensors( ... in_keys=[("next", "observation", "observation"), ... ("next", "observation", "achieved_goal"), ... ("next", "observation", "desired_goal")], ... out_key=("next", "obs") ... ) >>> t = Compose(cat_tensors, cat_next_tensors) >>> >>> def func(td): ... td = td.select( ... "action", ... "episode", ... ("next", "done"), ... ("next", "observation"), ... ("next", "reward"), ... ("next", "terminated"), ... ("next", "truncated"), ... "observation" ... ) ... td = t(td) ... return td >>> with TemporaryDirectory() as tmpdir: ... new_storage = data.preprocess(func, num_workers=4, pbar=True, mp_start_method="fork", dest=tmpdir) ... rb = ReplayBuffer(storage=new_storage) ... print(rb) ReplayBuffer( storage=TensorStorage( data=TensorDict( fields={ action: MemoryMappedTensor(shape=torch.Size([1000000, 8]), device=cpu, dtype=torch.float32, is_shared=True), episode: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.int64, is_shared=True), next: TensorDict( fields={ done: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), obs: MemoryMappedTensor(shape=torch.Size([1000000, 31]), device=cpu, dtype=torch.float64, is_shared=True), observation: TensorDict( fields={ }, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), reward: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.float64, is_shared=True), terminated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True), truncated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), obs: MemoryMappedTensor(shape=torch.Size([1000000, 31]), device=cpu, dtype=torch.float64, is_shared=True), observation: TensorDict( fields={ }, batch_size=torch.Size([1000000]), device=cpu, is_shared=False)}, batch_size=torch.Size([1000000]), device=cpu, is_shared=False), shape=torch.Size([1000000]), len=1000000, max_size=1000000), sampler=RandomSampler(), writer=RoundRobinWriter(cursor=0, full_storage=True), batch_size=None, collate_fn=<function _collate_id at 0x168406fc0>)
- 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) – 是否返回 info。如果为 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 (callable, optional) – 如果提供,则 collate_fn 将设置为此值。否则它将被重置为默认值。
- property write_count¶
通过 add 和 extend 操作写入缓冲区中的项目总数。