NonTensorData¶
- class tensordict.NonTensorData(data: 'Any', _metadata: 'dict | None' = None, _is_non_tensor: 'bool' = True, *, batch_size, device=None, names=None)¶
-
- dumps(prefix: Optional[str] = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False) T ¶
将tensordict保存到磁盘。
此函数是
memmap()
的代理。
- classmethod fields()¶
返回一个描述此数据类的字段的元组。字段类型为 Field。
接受一个数据类或其实例。元组元素为 Field 类型。
- classmethod from_tensordict(tensordict, non_tensordict=None, safe=True)¶
用于实例化新张量类对象的张量类包装器。
- 参数:
tensordict (TensorDict) – 张量类型的字典
non_tensordict (dict) – 包含非张量和嵌套张量类对象的字典
- get(key: NestedKey, *args, **kwargs)¶
获取输入键对应的存储值。
- 参数:
key (str, tuple of str) – 要查询的键。如果为字符串元组,则等同于链式调用 getattr。
default – 如果在张量类中找不到键,则返回默认值。
- 返回:
存储在输入键下的值
- classmethod load(prefix: str | pathlib.Path, *args, **kwargs) T ¶
从磁盘加载 tensordict。
此类方法是
load_memmap()
的代理。
- load_(prefix: str | pathlib.Path, *args, **kwargs)¶
在当前 tensordict 中从磁盘加载 tensordict。
此类方法是
load_memmap_()
的代理。
- classmethod load_memmap(prefix: str | pathlib.Path, device: Optional[device] = None, non_blocking: bool = False, *, out: Optional[TensorDictBase] = None) T ¶
从磁盘加载内存映射的 tensordict。
- 参数:
prefix (str 或 文件夹路径) – 保存 tensordict 的文件夹路径。
device (torch.device 或 等效项, 可选) – 如果提供,数据将异步转换为该设备。支持 “meta” 设备,在这种情况下,数据不会被加载,而是会创建一组空的“meta”张量。这有助于在不实际打开任何文件的情况下了解模型总大小和结构。
non_blocking (bool, 可选) – 如果为
True
,则加载设备上的张量后不会调用同步。默认为False
。out (TensorDictBase, 可选) – 数据应写入的可选 tensordict。
示例
>>> from tensordict import TensorDict >>> td = TensorDict.fromkeys(["a", "b", "c", ("nested", "e")], 0) >>> td.memmap("./saved_td") >>> td_load = TensorDict.load_memmap("./saved_td") >>> assert (td == td_load).all()
此方法还允许加载嵌套的 tensordicts。
示例
>>> nested = TensorDict.load_memmap("./saved_td/nested") >>> assert nested["e"] == 0
tensordict 也可以在“meta”设备上加载,或者作为假张量加载。
示例
>>> import tempfile >>> td = TensorDict({"a": torch.zeros(()), "b": {"c": torch.zeros(())}}) >>> with tempfile.TemporaryDirectory() as path: ... td.save(path) ... td_load = TensorDict.load_memmap(path, device="meta") ... print("meta:", td_load) ... from torch._subclasses import FakeTensorMode ... with FakeTensorMode(): ... td_load = TensorDict.load_memmap(path) ... print("fake:", td_load) meta: TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=meta, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=meta, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=meta, is_shared=False)}, batch_size=torch.Size([]), device=meta, is_shared=False) fake: TensorDict( fields={ a: FakeTensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: FakeTensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False)
- load_state_dict(state_dict: dict[str, Any], strict=True, assign=False, from_flatten=False)¶
尝试将 state_dict 加载到目标张量类中(原地)。
- maybe_to_stack()¶
如果 batch_size 非空,则将 NonTensorDataBase 对象转换为 NonTensorStack 对象。
- memmap(prefix: Optional[str] = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, existsok: bool = True) T ¶
将所有张量写入内存映射的 Tensor 中,并放入新的 tensordict。
- 参数:
- 关键字参数:
num_threads (int, 可选) – 用于写入 memmap 张量的线程数。默认为 0。
return_early (bool, 可选) – 如果为
True
且num_threads>0
,则该方法将返回一个 tensordict 的 future。share_non_tensor (bool, 可选) – 如果为
True
,则非张量数据将在进程之间共享,并且在单个节点内的任何工作进程上执行写入操作(例如原地更新或设置)将更新所有其他工作进程上的值。如果非张量叶子节点的数量很高(例如,共享大量非张量数据),这可能会导致 OOM 或类似错误。默认为False
。existsok (bool, 可选) – 如果为
False
,则如果同一路径中已存在张量,将引发异常。默认为True
。
然后 TensorDict 被锁定,这意味着任何非原地操作的写入操作都将引发异常(例如,重命名、设置或删除条目)。一旦 tensordict 被解锁,内存映射属性将变为
False
,因为不能保证跨进程标识。- 返回:
如果
return_early=False
,则返回一个将张量存储在磁盘上的新 tensordict,否则返回一个TensorDictFuture
实例。
注意
以这种方式序列化对于深度嵌套的 tensordicts 来说可能很慢,因此不建议在训练循环中调用此方法。
- memmap_(prefix: Optional[str] = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False, existsok: bool = True) T ¶
将所有张量原地写入相应的内存映射张量。
- 参数:
- 关键字参数:
num_threads (int, 可选) – 用于写入 memmap 张量的线程数。默认为 0。
return_early (bool, 可选) – 如果为
True
且num_threads>0
,则该方法将返回一个 tensordict 的 future。可以通过 future.result() 查询生成的 tensordict。share_non_tensor (bool, 可选) – 如果为
True
,则非张量数据将在进程之间共享,并且在单个节点内的任何工作进程上执行写入操作(例如原地更新或设置)将更新所有其他工作进程上的值。如果非张量叶子节点的数量很高(例如,共享大量非张量数据),这可能会导致 OOM 或类似错误。默认为False
。existsok (bool, 可选) – 如果为
False
,则如果同一路径中已存在张量,将引发异常。默认为True
。
然后 TensorDict 被锁定,这意味着任何非原地操作的写入操作都将引发异常(例如,重命名、设置或删除条目)。一旦 tensordict 被解锁,内存映射属性将变为
False
,因为不能保证跨进程标识。- 返回:
如果
return_early=False
,则返回 self,否则返回TensorDictFuture
实例。
注意
以这种方式序列化对于深度嵌套的 tensordicts 来说可能很慢,因此不建议在训练循环中调用此方法。
- memmap_like(prefix: Optional[str] = None, copy_existing: bool = False, *, existsok: bool = True, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False) T ¶
创建一个无内容的内存映射 tensordict,其形状与原始 tensordict 相同。
- 参数:
- 关键字参数:
num_threads (int, 可选) – 用于写入 memmap 张量的线程数。默认为 0。
return_early (bool, 可选) – 如果为
True
且num_threads>0
,则该方法将返回一个 tensordict 的 future。share_non_tensor (bool, 可选) – 如果为
True
,则非张量数据将在进程之间共享,并且在单个节点内的任何工作进程上执行写入操作(例如原地更新或设置)将更新所有其他工作进程上的值。如果非张量叶子节点的数量很高(例如,共享大量非张量数据),这可能会导致 OOM 或类似错误。默认为False
。existsok (bool, 可选) – 如果为
False
,则如果同一路径中已存在张量,将引发异常。默认为True
。
然后 TensorDict 被锁定,这意味着任何非原地操作的写入操作都将引发异常(例如,重命名、设置或删除条目)。一旦 tensordict 被解锁,内存映射属性将变为
False
,因为不能保证跨进程标识。- 返回:
一个新
TensorDict
实例,数据存储为内存映射张量,如果return_early=False
,否则为TensorDictFuture
实例。
注意
这是将一组大型缓冲区写入磁盘的推荐方法,因为
memmap_()
会复制信息,对于大量内容来说这可能会很慢。示例
>>> td = TensorDict({ ... "a": torch.zeros((3, 64, 64), dtype=torch.uint8), ... "b": torch.zeros(1, dtype=torch.int64), ... }, batch_size=[]).expand(1_000_000) # expand does not allocate new memory >>> buffer = td.memmap_like("/path/to/dataset")
- memmap_refresh_()¶
如果内存映射的 tensordict 具有
saved_path
,则刷新其内容。如果没有任何路径与之关联,此方法将引发异常。
- save(prefix: Optional[str] = None, copy_existing: bool = False, *, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False) T ¶
将tensordict保存到磁盘。
此函数是
memmap()
的代理。
- state_dict(destination=None, prefix='', keep_vars=False, flatten=False) dict[str, Any] ¶
返回一个 state_dict 字典,可用于保存和加载张量类的数据。