OpenXExperienceReplay¶
- class torchrl.data.datasets.OpenXExperienceReplay(dataset_id, batch_size: int | None = None, *, shuffle: bool = True, num_slices: int | None = None, slice_len: int | None = None, pad: float | bool | None = None, replacement: bool = None, streaming: bool | None = None, root: str | Path | None = None, download: bool | None = None, sampler: Sampler | None = None, writer: Writer | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: 'torchrl.envs.Transform' | None = None, split_trajs: bool = False, strict_length: bool = True)[源代码]¶
Open X-Embodiment 数据集经验回放。
Open X-Embodiment 数据集包含 100 多万条真实的机器人轨迹,涵盖 22 种机器人实体,这些轨迹是通过 21 家机构之间的合作收集的,展示了 527 种技能(160266 个任务)。
网站:https://robotics-transformer-x.github.io/
GitHub:https://github.com/google-deepmind/open_x_embodiment
论文:https://arxiv.org/abs/2310.08864
数据格式遵循 TED 约定。
注意
非张量数据将使用
NonTensorData
原语写入 tensordict 数据中。例如,数据中的 language_instruction 字段将存储在 data.get_non_tensor(“language_instruction”) 中(或等效地 data.get(“language_instruction”).data)。有关如何在TensorDict
中与存储的非张量数据交互的更多信息,请参阅此类的文档。- 参数:
dataset_id (str) – 要下载的数据集。必须是
OpenXExperienceReplay.available_datasets
的一部分。batch_size (int) – 采样期间使用的批大小。如有必要,可以通过 data.sample(batch_size) 覆盖。有关改进的采样策略,请参阅
num_slices
和slice_len
关键字参数。如果batch_size
为None
(默认值),则迭代数据集将一次交付一条轨迹,而调用sample()
仍然需要提供批大小。
- 关键字参数:
shuffle (bool, optional) –
如果
True
,则迭代数据集时,轨迹将以随机顺序交付。如果False
,则按预定义顺序迭代数据集。警告
shuffle=False 也会影响采样。我们建议用户创建数据集的副本,其中采样器的
shuffle
属性设置为False
,如果他们希望在同一个代码库中享受两种不同的行为(随机和非随机)。num_slices (int, optional) – 批中的切片数量。这对应于批中存在的轨迹数量。收集后,批次将显示为可以按 batch.reshape(num_slices, -1) 恢复的子轨迹的连接。如果提供,则 batch_size 必须能被 num_slices 整除。此参数与
slice_len
互斥。如果num_slices
参数等于batch_size
,则每个样本将属于不同的轨迹。如果既没有提供slice_len
也没有提供num_slice
:每当轨迹的长度短于批大小时,将对其采样长度为 batch_size 的连续切片。如果轨迹长度不足,则会引发异常,除非 pad 不是 None。slice_len (int, optional) –
批中切片的长度。这对应于批中存在的轨迹的长度。收集后,批次将显示为可以按 batch.reshape(-1, slice_len) 恢复的子轨迹的连接。如果提供,则 batch_size 必须能被 slice_len 整除。此参数与
num_slice
互斥。如果slice_len
参数等于1
,则每个样本将属于不同的轨迹。如果既没有提供slice_len
也没有提供num_slice
:每当轨迹的长度短于批大小时,将对其采样长度为 batch_size 的连续切片。如果轨迹长度不足,则会引发异常,除非 pad 不是 None。注意
在不向构造函数传递批大小的情况下迭代数据集时,可以使用
slice_len
(但不能使用num_slices
)。在这种情况下,将选择轨迹的随机子序列。replacement (bool, optional) – 如果
False
,则将无替换地进行采样。对于下载的数据集,默认为True
,对于流式数据集,默认为False
。pad (bool, float 或 None) – 如果
True
,则根据 slice_len 或 num_slices 参数长度不足的轨迹将用 0 填充。如果提供了其他值,则将用于填充。如果False
或None
(默认值),则任何遇到长度不足的轨迹都会引发异常。root (Path 或 str, optional) – OpenX 数据集根目录。实际的数据集内存映射文件将保存在 <root>/<dataset_id> 下。如果未提供,则默认为 ``~/.cache/torchrl/openx`。
streaming (bool, optional) –
如果
True
,则不会下载数据,而是从流中读取。注意
当 download=True 与 streaming=True 相比时,数据的格式__将更改__。如果数据已下载并且采样器保持不变(即,num_slices=None、slice_len=None 和 sampler=None),则将从数据集中随机采样转换。这在 streaming=True 的情况下以合理的成本是不可能的:在这种情况下,将一次采样一条轨迹并按此方式交付(通过裁剪以符合批大小等)。当指定 num_slices 和 slice_len 时,两种模式的行为更加相似,因为在这种情况下,两种情况下都将返回子情节的视图。
download (bool 或 str, optional) – 如果未找到,是否应下载数据集。默认为
True
。下载也可以作为“force”传递,在这种情况下,下载的数据将被覆盖。sampler (Sampler, optional) – 要使用的采样器。如果未提供,将使用默认的 RandomSampler()。
writer (Writer, optional) – 要使用的写入器。如果未提供,将使用默认的
ImmutableDatasetWriter
。collate_fn (callable, optional) – 将样本列表合并以形成 Tensor/输出的小批量。在使用来自映射风格数据集的批量加载时使用。
pin_memory (bool) – 是否应在 rb 样本上调用 pin_memory()。
prefetch (int, optional) – 使用多线程预取的下一个批次的数目。
transform (Transform, optional) – 调用 sample() 时要执行的转换。要链接转换,请使用
Compose
类。split_trajs (bool, optional) – 如果
True
,则轨迹将在第一个维度上分割并填充以具有匹配的形状。要分割轨迹,将使用"done"
信号,该信号通过done = truncated | terminated
恢复。换句话说,假设任何truncated
或terminated
信号等效于轨迹的结束。默认为False
。strict_length (bool, optional) – 如果
False
,则允许长度短于 slice_len(或 batch_size // num_slices)的轨迹出现在批次中。请注意,这可能导致有效 batch_size 短于请求的!可以使用torchrl.collectors.split_trajectories()
拆分轨迹。默认为True
。
示例
>>> from torchrl.data.datasets import OpenXExperienceReplay >>> import tempfile >>> # Download the data, and sample 128 elements in each batch out of two trajectories >>> num_slices = 2 >>> with tempfile.TemporaryDirectory() as root: ... dataset = OpenXExperienceReplay("cmu_stretch", batch_size=128, ... num_slices=num_slices, download=True, streaming=False, ... root=root, ... ) ... for batch in dataset: ... print(batch.reshape(num_slices, -1)) ... break TensorDict( fields={ action: Tensor(shape=torch.Size([2, 64, 8]), device=cpu, dtype=torch.float64, is_shared=False), discount: Tensor(shape=torch.Size([2, 64]), device=cpu, dtype=torch.float32, is_shared=False), done: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.bool, is_shared=False), episode: Tensor(shape=torch.Size([2, 64]), device=cpu, dtype=torch.int32, is_shared=False), index: Tensor(shape=torch.Size([2, 64]), device=cpu, dtype=torch.int64, is_shared=False), is_init: Tensor(shape=torch.Size([2, 64]), device=cpu, dtype=torch.bool, is_shared=False), language_embedding: Tensor(shape=torch.Size([2, 64, 512]), device=cpu, dtype=torch.float64, is_shared=False), language_instruction: NonTensorData( data='lift open green garbage can lid', batch_size=torch.Size([2, 64]), device=cpu, is_shared=False), next: TensorDict( fields={ done: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.bool, is_shared=False), observation: TensorDict( fields={ image: Tensor(shape=torch.Size([2, 64, 3, 128, 128]), device=cpu, dtype=torch.uint8, is_shared=False), state: Tensor(shape=torch.Size([2, 64, 4]), device=cpu, dtype=torch.float64, is_shared=False)}, batch_size=torch.Size([2, 64]), device=cpu, is_shared=False), reward: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.float32, is_shared=False), terminated: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.bool, is_shared=False), truncated: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.bool, is_shared=False)}, batch_size=torch.Size([2, 64]), device=cpu, is_shared=False), observation: TensorDict( fields={ image: Tensor(shape=torch.Size([2, 64, 3, 128, 128]), device=cpu, dtype=torch.uint8, is_shared=False), state: Tensor(shape=torch.Size([2, 64, 4]), device=cpu, dtype=torch.float64, is_shared=False)}, batch_size=torch.Size([2, 64]), device=cpu, is_shared=False), terminated: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.bool, is_shared=False), truncated: Tensor(shape=torch.Size([2, 64, 1]), device=cpu, dtype=torch.bool, is_shared=False)}, batch_size=torch.Size([2, 64]), device=cpu, is_shared=False) >>> # Read data from a stream. Deliver entire trajectories when iterating >>> dataset = OpenXExperienceReplay("cmu_stretch", ... num_slices=num_slices, download=False, streaming=True) >>> for data in dataset: # data does not have a consistent shape ... break >>> # Define batch-size dynamically >>> data = dataset.sample(128) # delivers 2 sub-trajectories of length 64
- 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()
- property data_path¶
数据集的路径,包括分割。
- 属性 data_path_root¶
数据集根目录的路径。
- delete()¶
从磁盘删除数据集存储。
- dumps(path)¶
将回放缓冲区保存到指定路径的磁盘上。
- 参数:
path (路径 或 字符串) – 保存回放缓冲区的路径。
示例
>>> 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) 张量 ¶
使用可迭代对象中包含的一个或多个元素扩展回放缓冲区。
如果存在,则将调用逆变换。
- 参数:
data (可迭代对象) – 要添加到回放缓冲区的数据集合。
- 返回值:
添加到回放缓冲区的数据的索引。
警告
extend()
在处理值列表时可能具有模棱两可的签名,这些值应解释为 PyTree(在这种情况下,列表中的所有元素都将放在存储中存储的 PyTree 中的一个切片中)或要逐个添加的值列表。为了解决这个问题,TorchRL 在列表和元组之间做出了明确的区分:元组将被视为 PyTree,列表(在根级别)将被解释为要逐个添加到缓冲区的值的堆栈。对于ListStorage
实例,只能提供未绑定的元素(没有 PyTree)。
- insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer ¶
插入变换。
调用 sample 时,将按顺序执行变换。
- 参数:
index (int) – 插入变换的位置。
transform (Transform) – 要追加的转换
- 关键字参数:
invert (bool, optional) – 如果
True
,则转换将被反转(前向调用将在写入期间调用,反向调用将在读取期间调用)。默认为False
。
- loads(path)¶
加载给定路径处的回放缓冲区状态。
缓冲区应具有匹配的组件,并使用
dumps()
保存。- 参数:
path (路径 或 字符串) – 保存回放缓冲区的路径。
有关更多信息,请参阅
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 (路径 或 等效项) – 新数据集所在位置的路径。
num_frames (int, 可选) – 如果提供,则只转换前 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) – 是否返回信息。如果为 True,则结果为一个元组 (data, info)。如果为 False,则结果为数据。
- 返回值:
包含在重放缓冲区中选择的一批数据的张量字典。如果 return_info 标志设置为 True,则包含此张量字典和信息的元组。