TensorDictParams¶
- class tensordict.TensorDictParams(parameters: Optional[Union[TensorDictBase, dict]] = None, *, no_convert=False, lock: bool = False, **kwargs)¶
TensorDictBase 的包裝器,具有引數暴露功能。
此類旨在儲存一個包含引數的 TensorDictBase 例項,使其可供父
Module訪問。這允許將 tensordict 引數無縫整合到 PyTorch 模組中,從而實現引數迭代和最佳化等操作。主要特點
引數暴露:tensordict 中的引數會暴露給父模組,使其可以包含在 named_parameters() 等操作中。
索引:索引的工作方式與包裝的 tensordict 類似。但是,引數名稱(在
named_parameters()中)使用 TensorDict.flatten_keys(“_”) 註冊,這可能會導致與 tensordict 內容不同的鍵名。自動轉換:除非透過
no_convert關鍵字引數另有指定,否則 tensordict 中設定的任何張量都會自動轉換為torch.nn.Parameter。
- 引數
- parameters (TensorDictBase 或 dict):要表示為引數的 tensordict。值被轉換為
引數,除非 no_convert=True。如果提供了 dict,它將被包裝在 TensorDict 例項中。也可以使用關鍵字引數。
- 關鍵字引數:
no_convert (bool) – 如果 True,則不會進行到 nn.Parameter 的轉換,並且所有非引數、非緩衝區張量都將轉換為
Buffer例項。如果False,則所有具有非整數 dtype 的張量都將轉換為Parameter,而整數 dtype 將轉換為Buffer例項。預設為 False。lock (bool) –
如果 True,則 TensorDictParams 託管的 tensordict 將被鎖定,從而阻止修改,並且在需要 unlock_() 時可能會影響效能。預設為 False。
警告
由於預設情況下內部 tensordict 未被複制或鎖定,因此在
TensorDictParams中註冊 tensordict 並在之後修改其內容將__不會__更新TensorDictParamsparameters()和buffers()序列中的值。**kwargs – 用於填充 TensorDictParams 的鍵值對。與 parameters 輸入互斥。
- 示例
>>> from torch import nn >>> from tensordict import TensorDict >>> module = nn.Sequential(nn.Linear(3, 4), nn.Linear(4, 4)) >>> params = TensorDict.from_module(module) >>> params.lock_() >>> p = TensorDictParams(params) >>> print(p) TensorDictParams(params=TensorDict( fields={ 0: TensorDict( fields={ bias: Parameter(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Parameter(shape=torch.Size([4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False), 1: TensorDict( fields={ bias: Parameter(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Parameter(shape=torch.Size([4, 4]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)) >>> class CustomModule(nn.Module): ... def __init__(self, params): ... super().__init__() ... self.params = params >>> m = CustomModule(p) >>> # The wrapper supports assignment, and values are converted to Parameters >>> m.params['other'] = torch.randn(3) >>> assert isinstance(m.params['other'], nn.Parameter)
- abs() T¶
計算 TensorDict 中每個元素的絕對值。
- abs_() T¶
就地計算 TensorDict 中每個元素的絕對值。
- acos() T¶
計算 TensorDict 中每個元素的
acos()值。
- acos_() T¶
就地計算 TensorDict 中每個元素的
acos()值。
- add(other: tensordict.base.TensorDictBase | torch.Tensor, *, alpha: float | None = None, default: str | torch.Tensor | None = None) TensorDictBase¶
將由
alpha縮放的other新增到self。\[\text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i\]- 引數:
other (TensorDictBase 或 torch.Tensor) – 要新增到
self的張量或 TensorDict。- 關鍵字引數:
alpha (Number, optional) –
other的乘數。default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- add_(other: tensordict.base.TensorDictBase | torch.Tensor | float, *, alpha: Optional[float] = None)¶
add()的原地(in-place)版本。注意
原地
add不支援default關鍵字引數。
- add_module(name: str, module: Optional[Module]) None¶
向當前模組新增子模組。
可以使用給定的名稱作為屬性訪問該模組。
- 引數:
name (str) – 子模組的名稱。可以使用給定的名稱從該模組訪問子模組
module (Module) – 要新增到模組的子模組。
- addcdiv(other1: tensordict.base.TensorDictBase | torch.Tensor, other2: tensordict.base.TensorDictBase | torch.Tensor, value: float | None = 1)¶
執行
other1除以other2的逐元素除法,將結果乘以標量value並將其加到self。\[\text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i}\]self、other1和other2的元素的形狀必須是可廣播的。對於 FloatTensor 或 DoubleTensor 型別的輸入,
value必須是實數,否則為整數。- 引數:
other1 (TensorDict 或 Tensor) – 分子 tensordict (或 tensor)
tensor2 (TensorDict 或 Tensor) – 分母 tensordict (或 tensor)
- 關鍵字引數:
value (Number, 可選) – \(\text{tensor1} / \text{tensor2}\) 的乘數
- addcmul(other1: tensordict.base.TensorDictBase | torch.Tensor, other2: tensordict.base.TensorDictBase | torch.Tensor, *, value: float | None = 1)¶
執行
other1乘以other2的逐元素乘法,將結果乘以標量value並將其加到self。\[\text{out}_i = \text{input}_i + \text{value} \times \text{other1}_i \times \text{other2}_i\]self、other1和other2的形狀必須是可廣播的。對於 FloatTensor 或 DoubleTensor 型別的輸入,
value必須是實數,否則為整數。- 引數:
other1 (TensorDict 或 Tensor) – 要相乘的 tensordict 或 tensor
other2 (TensorDict 或 Tensor) – 要相乘的 tensordict 或 tensor
- 關鍵字引數:
value (Number, 可選) – \(other1 .* other2\) 的乘數
- all(dim: int = None) bool | tensordict.base.TensorDictBase¶
檢查 tensordict 中是否所有值均為 True/非空。
- 引數:
dim (int, optional) – 如果為
None,則返回一個布林值,指示是否所有 tensor 都返回 tensor.all() == True。 如果是整數,則僅當此維度與 tensordict 的形狀相容時,才會對指定的維度呼叫 all。
- amax(dim: int | NO_DEFAULT = _NoDefault.ZERO, keepdim: bool = False, *, reduce: bool | None = None) TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的最大值。
與
max()相同,只是return_indices=False。
- amin(dim: int | NO_DEFAULT = _NoDefault.ZERO, keepdim: bool = False, *, reduce: bool | None = None) TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的最小值。
與
min()相同,只是return_indices=False。
- any(dim: int = None) bool | tensordict.base.TensorDictBase¶
檢查 tensordict 中是否存在任何 True/非空值。
- 引數:
dim (int, optional) – 如果為
None,則返回一個布林值,指示是否所有 tensor 都返回 tensor.any() == True。如果是整數,則僅當此維度與 tensordict 的形狀相容時,才會對指定的維度呼叫 all。
- apply(fn: Callable, *others: TensorDictBase, batch_size: Optional[Sequence[int]] = None, device: torch.device | None = _NoDefault.ZERO, names: Optional[Sequence[str]] = _NoDefault.ZERO, inplace: bool = False, default: Any = _NoDefault.ZERO, filter_empty: bool | None = None, call_on_nested: bool = False, **constructor_kwargs) tensordict.base.TensorDictBase | None¶
將可呼叫物件應用於 tensordict 中儲存的所有值,並將它們設定在一個新的 tensordict 中。
可呼叫物件的簽名必須為
Callable[Tuple[Tensor, ...], Optional[Union[Tensor, TensorDictBase]]]。- 引數:
fn (Callable) – 要應用於 tensordict 中 tensor 的函式。
*others (TensorDictBase 例項, optional) – 如果提供,這些 tensordict 例項應具有與 self 匹配的結構。
fn引數應接收與 tensordict 數量一樣多的未命名輸入,包括 self。 如果其他 tensordict 缺少條目,則可以透過default關鍵字引數傳遞預設值。
- 關鍵字引數:
batch_size (int 序列, 可選) – 如果提供,生成的 TensorDict 將具有所需的 batch_size。
batch_size引數應與轉換後的 batch_size 匹配。 這是一個僅關鍵字引數。device (torch.device, 可選) – 生成的裝置(如果有)。
names (str 列表, 可選) – 新的維度名稱,以防修改了 batch_size。
inplace (bool, 可選) – 如果為 True,則進行原地更改。 預設為 False。 這是一個僅關鍵字引數。
default (Any, 可選) – 其他 tensordict 中缺失條目的預設值。 如果未提供,缺失的條目將引發 KeyError。
filter_empty (bool, 可選) – 如果
True,則將濾除空 tensordict。 這也降低了計算成本,因為不會建立和銷燬空資料結構。 非張量資料被視為葉子,因此即使該函式未觸及,也會保留在 tensordict 中。 出於向後相容性的目的,預設為False。propagate_lock (bool, 可選) – 如果
True,則鎖定的 tensordict 將生成另一個鎖定的 tensordict。 預設為False。call_on_nested (bool, 可選) –
如果
True,則將在第一級張量和容器(TensorDict 或 tensorclass)上呼叫該函式。 在這種情況下,func負責將其呼叫傳播到巢狀級別。 這允許在將呼叫傳播到巢狀 tensordict 時進行細粒度控制。 如果False,則僅在葉子上呼叫該函式,並且apply將負責將該函式分派到所有葉子上。>>> td = TensorDict({"a": {"b": [0.0, 1.0]}, "c": [1.0, 2.0]}) >>> def mean_tensor_only(val): ... if is_tensor_collection(val): ... raise RuntimeError("Unexpected!") ... return val.mean() >>> td_mean = td.apply(mean_tensor_only) >>> def mean_any(val): ... if is_tensor_collection(val): ... # Recurse ... return val.apply(mean_any, call_on_nested=True) ... return val.mean() >>> td_mean = td.apply(mean_any, call_on_nested=True)
out (TensorDictBase, 可選) –
一個用於寫入結果的 tensordict。 這可以用於避免建立新的 tensordict
>>> td = TensorDict({"a": 0}) >>> td.apply(lambda x: x+1, out=td) >>> assert (td==1).all()
警告
如果在 tensordict 上執行的操作需要訪問多個鍵才能進行單個計算,則提供等於
self的out引數可能會導致操作靜默地提供錯誤的結果。 例如>>> td = TensorDict({"a": 1, "b": 1}) >>> td.apply(lambda x: x+td["a"])["b"] # Right! tensor(2) >>> td.apply(lambda x: x+td["a"], out=td)["b"] # Wrong! tensor(3)
**constructor_kwargs – 要傳遞給 TensorDict 建構函式的其他關鍵字引數。
- 返回值:
一個具有 transformed_in 張量的新 tensordict。
示例
>>> td = TensorDict({ ... "a": -torch.ones(3), ... "b": {"c": torch.ones(3)}}, ... batch_size=[3]) >>> td_1 = td.apply(lambda x: x+1) >>> assert (td_1["a"] == 0).all() >>> assert (td_1["b", "c"] == 2).all() >>> td_2 = td.apply(lambda x, y: x+y, td) >>> assert (td_2["a"] == -2).all() >>> assert (td_2["b", "c"] == 2).all()
注意
如果該函式返回
None,則忽略該條目。 這可用於過濾 tensordict 中的資料>>> td = TensorDict({"1": 1, "2": 2, "b": {"2": 2, "1": 1}}, []) >>> def filter(tensor): ... if tensor == 1: ... return tensor >>> td.apply(filter) TensorDict( fields={ 1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ 1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
注意
apply 方法將返回一個
TensorDict例項,無論輸入型別如何。 要保持相同的型別,可以執行>>> out = td.clone(False).update(td.apply(...))
- apply_(fn: Callable, *others, **kwargs) T¶
將可呼叫物件應用於 tensordict 中儲存的所有值,並將其重寫到原地。
- 引數:
fn (Callable) – 要應用於 tensordict 中 tensor 的函式。
*others (TensorDictBase 序列, 可選) – 要使用的其他 tensordict。
關鍵字引數:參見
apply()。- 返回值:
應用該函式的 self 或 self 的副本
- asin() T¶
計算 TensorDict 的每個元素的
asin()值。
- asin_() T¶
計算 TensorDict 的每個元素的
asin()值(原地計算)。
- atan() T¶
計算 TensorDict 的每個元素的
atan()值。
- atan_() T¶
計算 TensorDict 的每個元素的
atan()值(原地計算)。
- auto_batch_size_(batch_dims: Optional[int] = None) T¶
設定 tensordict 的最大批次大小,最多可達可選的 batch_dims。
- 引數:
batch_dims (int, 可選) – 如果提供,則批次大小最多為
batch_dims長。- 返回值:
self
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict({"a": torch.randn(3, 4, 5), "b": {"c": torch.randn(3, 4, 6)}}, batch_size=[]) >>> td.auto_batch_size_() >>> print(td.batch_size) torch.Size([3, 4]) >>> td.auto_batch_size_(batch_dims=1) >>> print(td.batch_size) torch.Size([3])
- auto_device_() T¶
如果裝置是唯一的,則自動設定裝置。
返回值:具有已編輯的
device屬性的 self。
- property batch_size: Size¶
TensorDict 的形狀(或批次大小)。
tensordict 的形狀對應於其包含的張量的公共第一個
N維度,其中N是任意數字。 批次大小與“特徵大小”形成對比,後者表示張量的語義相關形狀。 例如,一批影片的形狀可能為[B, T, C, W, H],其中[B, T]是批次大小(批次和時間維度),[C, W, H]是特徵維度(通道和空間維度)。TensorDict形狀由使用者在初始化時控制(即,它不是從張量形狀推斷出來的)。如果新大小與 TensorDict 內容相容,則可以動態編輯
batch_size。 例如,始終允許將批次大小設定為空值。- 返回值:
一個
Size物件,描述 TensorDict 的批次大小。
示例
>>> data = TensorDict({ ... "key 0": torch.randn(3, 4), ... "key 1": torch.randn(3, 5), ... "nested": TensorDict({"key 0": torch.randn(3, 4)}, batch_size=[3, 4])}, ... batch_size=[3]) >>> data.batch_size = () # resets the batch-size to an empty value
- bfloat16()¶
將所有張量轉換為
torch.bfloat16。
- bitwise_and(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) TensorDictBase¶
執行
self和other之間的按位與操作。\[\text{{out}}_i = \text{{input}}_i \land \text{{other}}_i\]- 引數:
other (TensorDictBase 或 torch.Tensor) – 用於執行按位與操作的張量或 TensorDict。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- bool()¶
將所有張量轉換為
torch.bool型別。
- buffers(recurse: bool = True) Iterator[Tensor]¶
返回模組緩衝區的迭代器。
- 引數:
recurse (bool) – 如果為 True,則產生此模組和所有子模組的緩衝區。 否則,僅產生作為此模組直接成員的緩衝區。
- Yields:
torch.Tensor – 模組緩衝區
示例
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- bytes(*, count_duplicates: bool = True) int¶
計算包含的張量的位元組數。
- 關鍵字引數:
count_duplicates (bool) – 是否將重複的張量視為獨立的。 如果為
False,則只會丟棄完全相同的張量(來自公共基礎張量的相同檢視但不同的 ID 將被計算兩次)。 預設為 True(假設每個張量都是單個副本)。
- classmethod cat(input, dim=0, *, out=None)¶
沿給定維度將 tensordict 連線成一個 tensordict。
此呼叫等效於呼叫
torch.cat(),但與 torch.compile 相容。
- cat_from_tensordict(dim: int = 0, *, sorted: Optional[Union[bool, List[NestedKey]]] = None, out: Tensor = None) Tensor¶
將 tensordict 的所有條目連線成一個張量。
- 引數:
dim (int, optional) – 條目應連線的維度。
- 關鍵字引數:
sorted (bool or list of NestedKeys) – 如果為
True,條目將按字母順序連線。 如果為False(預設),將使用字典順序。 或者,可以提供金鑰名稱列表,並且將相應地連線張量。 這會產生一些開銷,因為將根據 tensordict 中的葉名稱列表檢查金鑰列表。out (torch.Tensor, optional) – 用於 cat 操作的可選目標張量。
- cat_tensors(*keys: NestedKey, out_key: NestedKey, dim: int = 0, keep_entries: bool = False) T¶
將條目連線到新條目中,並可能刪除原始值。
- 引數:
keys (NestedKey 序列) – 要連線的條目。
- 關鍵字引數
out_key (NestedKey): 連線的輸入的新金鑰名稱。 keep_entries (bool, optional): 如果為
False,則將刪除keys中的條目。預設為
False。- dim (int, optional): 必須進行連線的維度。
預設為
0。
返回: self
示例
>>> td = TensorDict(a=torch.zeros(1), b=torch.ones(1)) >>> td.cat_tensors("a", "b", out_key="c") >>> assert "a" not in td >>> assert (td["c"] == torch.tensor([0, 1])).all()
- ceil() T¶
計算 TensorDict 中每個元素的
ceil()值。
- ceil_() T¶
就地計算 TensorDict 中每個元素的
ceil()值。
- chunk(chunks: int, dim: int = 0) tuple[tensordict.base.TensorDictBase, ...]¶
如果可能,將 tensordict 分割成指定數量的塊。
每個塊都是輸入 tensordict 的一個檢視。
示例
>>> td = TensorDict({ ... 'x': torch.arange(24).reshape(3, 4, 2), ... }, batch_size=[3, 4]) >>> td0, td1 = td.chunk(dim=-1, chunks=2) >>> td0['x'] tensor([[[ 0, 1], [ 2, 3]], [[ 8, 9], [10, 11]], [[16, 17], [18, 19]]])
- clamp(min: tensordict.base.TensorDictBase | torch.Tensor = None, max: tensordict.base.TensorDictBase | torch.Tensor = None, *, out=None)¶
將
self中的所有元素限制在範圍 [min,max] 內。令 min_value 和 max_value 分別為
min和max,則返回注意
如果
min大於max,則torch.clamp(..., min, max)將input中的所有元素設定為max的值。
- clamp_max(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) T¶
如果
self的元素大於other,則將其限制為other的值。- 引數:
other (TensorDict or Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- clamp_max_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
clamp_max()的原地版本。注意
原地
clamp_max不支援default關鍵字引數。
- clamp_min(other: tensordict.base.TensorDictBase | torch.Tensor, default: str | torch.Tensor | None = None) T¶
如果
self的元素小於other,則將其限制為other的值。- 引數:
other (TensorDict or Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- clamp_min_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
clamp_min()的原地版本。注意
原地
clamp_min不支援default關鍵字引數。
- clear() T¶
清除 tensordict 的內容。
- clear_device_() T¶
清除 tensordict 的裝置。
返回: self
- clear_refs_for_compile_() T¶
清除 weakrefs,以便 tensordict 安全地退出編譯區域。
在返回 TensorDict 之前,如果遇到 torch._dynamo.exc.Unsupported: reconstruct: WeakRefVariable() 錯誤,請使用此方法。
返回: self
- clone(recurse: bool = True, **kwargs) T¶
將 TensorDictBase 子類的例項克隆到相同型別的新 TensorDictBase 子類例項上。
要從任何其他 TensorDictBase 子型別建立 TensorDict 例項,請改為呼叫
to_tensordict()方法。- 引數:
recurse (bool, 可選) – 如果為
True,則 TensorDict 中包含的每個張量也會被複制。 否則,只會複製 TensorDict 樹結構。 預設為True。
注意
與其他許多操作(逐點算術、形狀操作等)不同,
clone不會繼承原始的鎖屬性。 這種設計選擇是為了可以建立克隆並對其進行修改,這是最常見的用法。
- compile(*args, **kwargs)¶
使用
torch.compile()編譯此模組的 forward 函式。編譯此模組的 __call__ 方法,並將所有引數原封不動地傳遞給
torch.compile()。有關此函式的引數的詳細資訊,請參閱
torch.compile()。
- complex128()¶
將所有張量轉換為
torch.complex128。
- complex32()¶
將所有張量轉換為
torch.complex32。
- complex64()¶
將所有張量轉換為
torch.complex64。
- consolidate(filename: Optional[Union[Path, str]] = None, *, num_threads=0, device: Optional[device] = None, non_blocking: bool = False, inplace: bool = False, return_early: bool = False, use_buffer: bool = False, share_memory: bool = False, pin_memory: bool = False, metadata: bool = False) None¶
將 tensordict 內容整合到單個儲存中,以便快速序列化。
- 引數:
filename (Path, 可選) – 用於記憶體對映張量的可選檔案路徑,用作 tensordict 的儲存。
- 關鍵字引數:
num_threads (integer, 可選) – 用於填充儲存的執行緒數。
device (torch.device, 可選) – 可選的裝置,用於例項化儲存。
inplace (bool, 可選) – 如果為
True,則生成的 tensordict 與具有更新值的self相同。 預設為False。return_early (bool, 可選) – 如果為
True且num_threads>0,則該方法將返回 tensordict 的 future 物件。 可以使用 future.result() 查詢生成的 tensordict。use_buffer (bool, 可選) – 如果為
True並且傳遞了檔名,則將在共享記憶體中建立一箇中間本地緩衝區,並且資料將在最後一步複製到儲存位置。 這可能比直接寫入遠端物理記憶體(例如,NFS)更快。 預設為False。share_memory (bool, 可選) – 如果為
True,則儲存將放置在共享記憶體中。 預設為False。pin_memory (bool, 可選) – 是否應將整合的資料放置在 pinned 記憶體中。 預設為
False。metadata (bool, 可選) – 如果為
True,則元資料將與公共儲存一起儲存。 如果提供了檔名,則無效。 當需要控制序列化的實現方式時,儲存元資料可能很有用,因為如果元資料可用或不可用,TensorDict 以不同的方式處理整合的 TD 的 pickle/unpickle。
注意
如果 tensordict 已經整合,則所有引數都將被忽略並返回
self。 呼叫contiguous()重新整合。示例
>>> import pickle >>> import tempfile >>> import torch >>> import tqdm >>> from torch.utils.benchmark import Timer >>> from tensordict import TensorDict >>> data = TensorDict({"a": torch.zeros(()), "b": {"c": torch.zeros(())}}) >>> data_consolidated = data.consolidate() >>> # check that the data has a single data_ptr() >>> assert torch.tensor([ ... v.untyped_storage().data_ptr() for v in data_c.values(True, True) ... ]).unique().numel() == 1 >>> # Serializing the tensordict will be faster with data_consolidated >>> with open("data.pickle", "wb") as f: ... print("regular", Timer("pickle.dump(data, f)", globals=globals()).adaptive_autorange()) >>> with open("data_c.pickle", "wb") as f: ... print("consolidated", Timer("pickle.dump(data_consolidated, f)", globals=globals()).adaptive_autorange())
- contiguous(*args, **kwargs)¶
返回具有連續值的相同型別的新 tensordict(如果值已連續,則返回 self)。
- copy()¶
返回 tensordict 的淺複製(即,複製結構但不復制資料)。
等效於 TensorDictBase.clone(recurse=False)
- copy_(tensordict: T, non_blocking: bool = None) T¶
-
non-blocking 引數將被忽略,僅為了與
torch.Tensor.copy_()相容而存在。
- copy_at_(tensordict: T, idx: Union[None, int, slice, str, Tensor, List[Any], Tuple[Any, ...]], non_blocking: bool = False) T¶
- cos() T¶
計算 TensorDict 中每個元素的
cos()值。
- cos_() T¶
就地計算 TensorDict 中每個元素的
cos()值。
- cosh() T¶
計算 TensorDict 中每個元素的
cosh()值。
- cosh_() T¶
就地計算 TensorDict 中每個元素的
cosh()值。
- create_nested(key)¶
建立與當前 tensordict 具有相同形狀、裝置和維度名稱的巢狀 tensordict。
如果該值已存在,此操作會將其覆蓋。此操作在鎖定的 tensordict 中被阻止。
示例
>>> data = TensorDict({}, [3, 4, 5]) >>> data.create_nested("root") >>> data.create_nested(("some", "nested", "value")) >>> print(data) TensorDict( fields={ root: TensorDict( fields={ }, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False), some: TensorDict( fields={ nested: TensorDict( fields={ value: TensorDict( fields={ }, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)
- cuda(device=None)¶
將 tensordict 轉換為 cuda 裝置(如果尚未在其上)。
- 引數:
device (int, 可選) – 如果提供,則為應該轉換 tensor 的 cuda 裝置。
此函式還支援
to()的所有關鍵字引數。
- cummax(dim: int, *, reduce: Optional[bool] = None, return_indices: bool = True) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的累積最大值。
- 引數:
dim (int) – 表示執行 cummax 操作的維度的整數。
- 關鍵字引數:
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.cummax(dim=0) cummax( indices=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.int64, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), vals=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), batch_size=torch.Size([4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.cummax(reduce=True, dim=0) torch.return_types.cummax(...)
- cummin(dim: int, *, reduce: Optional[bool] = None, return_indices: bool = True) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的累積最小值。
- 引數:
dim (int) – 表示執行 cummin 操作的維度的整數。
- 關鍵字引數:
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.cummin(dim=0) cummin( indices=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.int64, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), vals=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), batch_size=torch.Size([4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.cummin(reduce=True, dim=0) torch.return_types.cummin(...)
- property data¶
返回一個 tensordict,其中包含葉張量的 .data 屬性。
- data_ptr(*, storage: bool = False)¶
返回 tensordict 葉子的 data_ptr。
這可以用於檢查兩個 tensordict 是否共享相同的
data_ptr()。- 關鍵字引數:
storage (bool, 可選) – 如果
True,將呼叫 tensor.untyped_storage().data_ptr()。預設為False。
示例
>>> from tensordict import TensorDict >>> td = TensorDict(a=torch.randn(2), b=torch.randn(2), batch_size=[2]) >>> assert (td0.data_ptr() == td.data_ptr()).all()
注意
LazyStackedTensorDict例項將顯示為巢狀的 tensordict,以反映其葉節點的真實data_ptr()>>> td0 = TensorDict(a=torch.randn(2), b=torch.randn(2), batch_size=[2]) >>> td1 = TensorDict(a=torch.randn(2), b=torch.randn(2), batch_size=[2]) >>> td = TensorDict.lazy_stack([td0, td1]) >>> td.data_ptr() TensorDict( fields={ 0: TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False), 1: TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False)}, batch_size=torch.Size([]), device=cpu, is_shared=False)
- del_(*args, **kwargs)¶
刪除 tensordict 的鍵。
- 引數:
key (NestedKey) – 要刪除的鍵
- 返回值:
self
- densify(layout: layout = torch.strided)¶
嘗試使用連續張量(普通張量或巢狀張量)表示延遲堆疊。
- 關鍵字引數:
layout (torch.layout) – 巢狀張量的佈局(如果有)。預設為
strided。
- detach() T¶
分離 tensordict 中的張量。
- 返回值:
一個新的 tensordict,其中沒有需要梯度的張量。
- detach_(*args, **kwargs)¶
就地分離 tensordict 中的張量。
- 返回值:
self.
- property device¶
TensorDict 的裝置。
如果 TensorDict 具有指定的裝置,則其所有張量(包括巢狀張量)必須位於同一裝置上。 如果 TensorDict 裝置為
None,則不同的值可以位於不同的裝置上。- 返回值:
torch.device 物件,指示張量所在的裝置,如果 TensorDict 沒有裝置,則為 None。
示例
>>> td = TensorDict({ ... "cpu": torch.randn(3, device='cpu'), ... "cuda": torch.randn(3, device='cuda'), ... }, batch_size=[], device=None) >>> td['cpu'].device device(type='cpu') >>> td['cuda'].device device(type='cuda') >>> td = TensorDict({ ... "x": torch.randn(3, device='cpu'), ... "y": torch.randn(3, device='cuda'), ... }, batch_size=[], device='cuda') >>> td['x'].device device(type='cuda') >>> td['y'].device device(type='cuda') >>> td = TensorDict({ ... "x": torch.randn(3, device='cpu'), ... "y": TensorDict({'z': torch.randn(3, device='cpu')}, batch_size=[], device=None), ... }, batch_size=[], device='cuda') >>> td['x'].device device(type='cuda') >>> td['y'].device # nested tensordicts are also mapped onto the appropriate device. device(type='cuda') >>> td['y', 'x'].device device(type='cuda')
- dim() int¶
參見
batch_dims()。
- div(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) T¶
將輸入
self的每個元素除以other的相應元素。\[\text{out}_i = \frac{\text{input}_i}{\text{other}_i}\]支援廣播、型別提升以及整數、浮點數、tensordict 或張量輸入。 始終將整數型別提升為預設標量型別。
- 引數:
other (TensorDict, Tensor 或 Number) – 除數。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- div_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
div()的就地版本。注意
就地
div不支援default關鍵字引數。
- double()¶
將所有張量轉換為
torch.bool型別。
- property dtype¶
返回 tensordict 中值的 dtype(如果它是唯一的)。
- 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()的代理。
- empty(recurse=False, *, batch_size=None, device=_NoDefault.ZERO, names=None) T¶
返回一個新的,空的 tensordict,具有相同的裝置和批次大小。
- 引數:
recurse (bool, optional) – 如果
True,則會複製TensorDict的整個結構,但不包含內容。 否則,只會複製根節點。 預設為False。- 關鍵字引數:
batch_size (torch.Size, optional) – tensordict 的新批次大小。
device (torch.device, optional) – 新裝置。
names (字串列表, optional) – 維度名稱。
- entry_class(*args, **kwargs)¶
返回條目的類,可能避免呼叫 isinstance(td.get(key), type)。
只要
get()的執行成本很高,就應優先使用此方法,而不是tensordict.get(key).shape。
- erf() T¶
計算 TensorDict 中每個元素的
erf()值。
- erf_() T¶
就地計算 TensorDict 中每個元素的
erf()值。
- erfc() T¶
計算 TensorDict 中每個元素的
erfc()值。
- erfc_() T¶
就地計算 TensorDict 中每個元素的
erfc()值。
- eval() T¶
將模組設定為評估模式。
這僅對某些模組有效。 有關其在訓練/評估模式下的行為的詳細資訊(即,它們是否受到影響),請參閱特定模組的文件,例如
Dropout、BatchNorm等。這等效於
self.train(False)。有關 .eval() 與可能與其混淆的幾種類似機制的比較,請參閱 本地停用梯度計算。
- 返回值:
self
- 返回型別:
模組
- exclude(*keys: NestedKey, inplace: bool = False) T¶
排除 tensordict 的鍵,並返回一個不包含這些條目的新 tensordict。
這些值不會被複制:就地修改原始或新 tensordict 的張量會導致兩個 tensordict 都發生更改。
- 引數:
- 返回值:
一個新的 tensordict(如果
inplace=True則為同一個)不包含排除的條目。
示例
>>> from tensordict import TensorDict >>> td = TensorDict({"a": 0, "b": {"c": 1, "d": 2}}, []) >>> td.exclude("a", ("b", "c")) TensorDict( fields={ b: TensorDict( fields={ d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.exclude("a", "b") TensorDict( fields={ }, batch_size=torch.Size([]), device=None, is_shared=False)
- exp() T¶
計算 TensorDict 中每個元素的
exp()值。
- exp_() T¶
就地計算 TensorDict 中每個元素的
exp()值。
- expand(*args, **kwargs) T¶
根據
expand()函式展開 tensordict 的每個張量,忽略特徵維度。支援使用可迭代物件來指定形狀。
示例
>>> td = TensorDict({ ... 'a': torch.zeros(3, 4, 5), ... 'b': torch.zeros(3, 4, 10)}, batch_size=[3, 4]) >>> td_expand = td.expand(10, 3, 4) >>> assert td_expand.shape == torch.Size([10, 3, 4]) >>> assert td_expand.get("a").shape == torch.Size([10, 3, 4, 5])
- expand_as(other: tensordict.base.TensorDictBase | torch.Tensor) TensorDictBase¶
將 tensordict 的形狀廣播到 other 的形狀,並相應地展開它。
如果輸入是張量集合(tensordict 或 tensorclass),則葉子將以一對一的基礎進行擴充套件。
示例
>>> from tensordict import TensorDict >>> import torch >>> td0 = TensorDict({ ... "a": torch.ones(3, 1, 4), ... "b": {"c": torch.ones(3, 2, 1, 4)}}, ... batch_size=[3], ... ) >>> td1 = TensorDict({ ... "a": torch.zeros(2, 3, 5, 4), ... "b": {"c": torch.zeros(2, 3, 2, 6, 4)}}, ... batch_size=[2, 3], ... ) >>> expanded = td0.expand_as(td1) >>> assert (expanded==1).all() >>> print(expanded) TensorDict( fields={ a: Tensor(shape=torch.Size([2, 3, 5, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([2, 3, 2, 6, 4]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([2, 3]), device=None, is_shared=False)}, batch_size=torch.Size([2, 3]), device=None, is_shared=False)
- expm1() T¶
計算 TensorDict 中每個元素的
expm1()值。
- expm1_() T¶
就地計算 TensorDict 中每個元素的
expm1()值。
- fill_(key: NestedKey, value: float | bool) T¶
用給定的標量值填充鍵指向的張量。
- 引數:
key (str 或 巢狀鍵) – 要填充的條目。
value (數字 或 bool) – 用於填充的值。
- 返回值:
self
- filter_empty_()¶
就地過濾掉所有空的 tensordict。
- filter_non_tensor_data() T¶
過濾掉所有非張量資料。
- flatten(start_dim=0, end_dim=- 1)¶
扁平化 tensordict 的所有張量。
示例
>>> td = TensorDict({ ... "a": torch.arange(60).view(3, 4, 5), ... "b": torch.arange(12).view(3, 4)}, batch_size=[3, 4]) >>> td_flat = td.flatten(0, 1) >>> td_flat.batch_size torch.Size([12]) >>> td_flat["a"] tensor([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34], [35, 36, 37, 38, 39], [40, 41, 42, 43, 44], [45, 46, 47, 48, 49], [50, 51, 52, 53, 54], [55, 56, 57, 58, 59]]) >>> td_flat["b"] tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
- flatten_keys(separator: str = '.', inplace: bool = False) TensorDictBase¶
遞迴地將巢狀的 tensordict 轉換為扁平的 tensordict。
TensorDict 型別將會丟失,結果將會是一個簡單的 TensorDict 例項。
- 引數:
separator (str, optional) – 巢狀項之間的分隔符。預設為
'.'。inplace (bool, optional) – 如果
True,則結果 tensordict 將與呼叫它的 tensordict 具有相同的標識。預設為False。is_leaf (callable, optional) –
一個可呼叫物件,接受一個類型別作為引數,返回一個布林值,指示該類是否應被視為葉節點。
注意
is_leaf 的目的不是阻止對巢狀 tensordict 的遞迴呼叫,而是將某些型別標記為“葉節點”,以便在 leaves_only=True 時進行過濾。 即使 is_leaf(cls) 返回 True,如果 include_nested=True,tensordict 的巢狀結構仍將被遍歷。 換句話說,is_leaf 不控制遞迴深度,而是提供了一種在 leaves_only=True 時從結果中過濾掉某些型別的方法。 這意味著樹中的一個節點可以既是葉節點,又是帶有子節點的節點。 實際上,
is_leaf的預設值會將 tensordict 和 tensorclass 例項從葉節點集中排除。另請參閱
示例
>>> data = TensorDict({"a": 1, ("b", "c"): 2, ("e", "f", "g"): 3}, batch_size=[]) >>> data.flatten_keys(separator=" - ") TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b - c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), e - f - g: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
此方法和
unflatten_keys()在處理 state-dicts 時特別有用,因為它們可以無縫地將扁平字典轉換為模仿模型結構的資料結構。示例
>>> model = torch.nn.Sequential(torch.nn.Linear(3 ,4)) >>> ddp_model = torch.ao.quantization.QuantWrapper(model) >>> state_dict = TensorDict(ddp_model.state_dict(), batch_size=[]).unflatten_keys(".") >>> print(state_dict) TensorDict( fields={ module: TensorDict( fields={ 0: TensorDict( fields={ bias: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Tensor(shape=torch.Size([4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> model_state_dict = state_dict.get("module") >>> print(model_state_dict) TensorDict( fields={ 0: TensorDict( fields={ bias: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Tensor(shape=torch.Size([4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> model.load_state_dict(dict(model_state_dict.flatten_keys(".")))
- float()¶
將所有張量轉換為
torch.float。
- float16()¶
將所有張量轉換為
torch.float16。
- float32()¶
將所有張量轉換為
torch.float32。
- float64()¶
將所有張量轉換為
torch.float64。
- floor() T¶
計算 TensorDict 中每個元素的
floor()值。
- floor_() T¶
原地計算 TensorDict 中每個元素的
floor()值。
- forward(*input: Any) None¶
定義每次呼叫時執行的計算。
應由所有子類重寫。
注意
儘管需要在該函式中定義前向傳遞的配方,但之後應呼叫
Module例項而不是此函式,因為前者負責執行註冊的鉤子,而後者會默默地忽略它們。
- frac() T¶
計算 TensorDict 中每個元素的
frac()值。
- frac_() T¶
原地計算 TensorDict 中每個元素的
frac()值。
- classmethod from_any(obj, *, auto_batch_size: bool = False, batch_dims: Optional[int] = None, device: Optional[device] = None, batch_size: Optional[Size] = None)¶
遞迴地將任何物件轉換為 TensorDict。
注意
from_any比常規 TensorDict 建構函式的限制更少。 它可以利用自定義啟發式方法將 dataclasses 或 tuples 等資料結構轉換為 tensordict。 這種方法可能會產生一些額外的開銷,並且在對映策略方面涉及更多主觀選擇。注意
此方法遞迴地將輸入物件轉換為 TensorDict。 如果物件已經是 TensorDict(或任何類似的張量集合物件),它將按原樣返回。
- 引數:
obj – 要轉換的物件。
- 關鍵字引數:
auto_batch_size (bool, optional) – 如果
True,將自動計算批次大小。 預設為False。batch_dims (int, optional) – 如果 auto_batch_size 為
True,則定義輸出 tensordict 應具有的維度數。 預設為None(每個級別的完整批次大小)。device (torch.device, optional) – TensorDict 將被建立在其上的裝置。 (可選)
batch_size (torch.Size, optional) – TensorDict 的批次大小。與
auto_batch_size互斥。(可選)
- 返回值:
輸入物件的 TensorDict 表示。
支援的物件
透過
from_dataclass()的 Dataclasses (dataclasses 將被轉換為 TensorDict 例項,而不是 tensorclasses)。透過
from_namedtuple()的 Namedtuples。透過
from_dict()的字典。透過
from_tuple()的元組。透過
from_struct_array()的 NumPy 結構化陣列。透過
from_h5()的 HDF5 物件。
- classmethod from_dataclass(dataclass, *, auto_batch_size: bool = False, batch_dims: Optional[int] = None, as_tensorclass: bool = False, device: Optional[device] = None, batch_size: Optional[Size] = None)¶
將 dataclass 轉換為 TensorDict 例項。
- 引數:
dataclass – 要轉換的 dataclass 例項。
- 關鍵字引數:
auto_batch_size (bool, optional) – 如果為
True,自動確定並將批次大小應用於生成的 TensorDict。預設為False。(可選)batch_dims (int, optional) – 如果
auto_batch_size為True,則定義輸出 tensordict 應具有的維度數。預設為None(每一級的完整批次大小)。 (可選)as_tensorclass (bool, optional) – 如果為
True,則將轉換委託給自由函式from_dataclass()並返回一個 tensor 相容的類 (tensorclass()) 或例項,而不是 TensorDict。預設為False。(可選)device (torch.device, optional) – TensorDict 將被建立在其上的裝置。預設為
None。(可選)batch_size (torch.Size, optional) – TensorDict 的批次大小。預設為
None。(可選)
- 返回值:
從提供的 dataclass 派生的 TensorDict 例項,除非 as_tensorclass 為 True,在這種情況下,將返回 tensor 相容的類或例項。
- 引發:
TypeError – 如果提供的輸入不是 dataclass 例項。
警告
此方法與自由函式 from_dataclass 不同,並且用途不同。雖然自由函式返回一個 tensor 相容的類或例項,但此方法返回一個 TensorDict 例項。
- classmethod from_dict(*args, **kwargs)¶
返回從字典或另一個
TensorDict建立的 TensorDict。如果未指定
batch_size,則返回可能的最大批次大小。此函式也適用於巢狀字典,或者可用於確定巢狀 tensordict 的批次大小。
- 引數:
input_dict (dictionary, optional) – 要用作資料來源的字典(相容巢狀鍵)。(可選)
- 關鍵字引數:
auto_batch_size (bool, optional) – 如果
True,將自動計算批次大小。 預設為False。batch_size (iterable of int, optional) – tensordict 的批次大小。(可選)
device (torch.device or compatible type, optional) – TensorDict 的裝置。(可選)
batch_dims (int, optional) –
batch_dims(即要考慮為batch_size的前導維度數)。與batch_size互斥。請注意,這是 tensordict 的 __最大__ 批次維度數,允許更小的數字。(可選)names (list of str, optional) – tensordict 的維度名稱列表。(可選)
示例
>>> input_dict = {"a": torch.randn(3, 4), "b": torch.randn(3)} >>> print(TensorDict.from_dict(input_dict)) TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False) >>> # nested dict: the nested TensorDict can have a different batch-size >>> # as long as its leading dims match. >>> input_dict = {"a": torch.randn(3), "b": {"c": torch.randn(3, 4)}} >>> print(TensorDict.from_dict(input_dict)) TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False) >>> # we can also use this to work out the batch sie of a tensordict >>> input_td = TensorDict({"a": torch.randn(3), "b": {"c": torch.randn(3, 4)}}, []) >>> print(TensorDict.from_dict(input_td)) TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- from_dict_instance(input_dict, *, auto_batch_size: bool = False, batch_size=None, device=None, batch_dims=None)¶
from_dict()的例項方法版本。與
from_dict()不同,此方法將嘗試保持現有樹中的 tensordict 型別(對於任何現有葉)。示例
>>> from tensordict import TensorDict, tensorclass >>> import torch >>> >>> @tensorclass >>> class MyClass: ... x: torch.Tensor ... y: int >>> >>> td = TensorDict({"a": torch.randn(()), "b": MyClass(x=torch.zeros(()), y=1)}) >>> print(td.from_dict_instance(td.to_dict())) TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: MyClass( x=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), y=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> print(td.from_dict(td.to_dict())) TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ x: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), y: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- classmethod from_h5(filename, *, mode: str = 'r', auto_batch_size: bool = False, batch_dims: Optional[int] = None, batch_size: Optional[Size] = None)¶
從 h5 檔案建立 PersistentTensorDict。
- 引數:
filename (str) – h5 檔案的路徑。
- 關鍵字引數
mode (str, 可選): 讀取模式。預設為
"r"。auto_batch_size (bool, 可選): 如果為True,則自動計算批次大小。預設為
False。- batch_dims (int, 可選): 如果 auto_batch_size 為
True,則定義輸出 tensordict 應該具有的維度數量。預設為
None(每個級別的完整批次大小)。
batch_size (torch.Size, 可選): TensorDict 的批次大小。預設為
None。- batch_dims (int, 可選): 如果 auto_batch_size 為
- 返回值:
輸入 h5 檔案的 PersistentTensorDict 表示。
示例
>>> td = TensorDict.from_h5("path/to/file.h5") >>> print(td) PersistentTensorDict( fields={ key1: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), key2: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- classmethod from_module(module, as_module: bool = False, lock: bool = True, use_state_dict: bool = False)¶
將模組的引數和緩衝區複製到 tensordict 中。
- 引數:
module (nn.Module) – 要從中獲取引數的模組。
as_module (bool, optional) – 如果為
True,將返回一個TensorDictParams例項,該例項可用於在torch.nn.Module中儲存引數。預設為False。lock (bool, optional) – 如果為
True,則生成的 tensordict 將被鎖定。預設為True。use_state_dict (bool, optional) –
如果為
True,將使用模組的狀態字典,並將其展開為具有模型樹結構的 TensorDict。預設為False。注意
當必須使用 state-dict 鉤子時,這特別有用。
示例
>>> from torch import nn >>> module = nn.TransformerDecoder( ... decoder_layer=nn.TransformerDecoderLayer(nhead=4, d_model=4), ... num_layers=1 ... ) >>> params = TensorDict.from_module(module) >>> print(params["layers", "0", "linear1"]) TensorDict( fields={ bias: Parameter(shape=torch.Size([2048]), device=cpu, dtype=torch.float32, is_shared=False), weight: Parameter(shape=torch.Size([2048, 4]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- classmethod from_modules(*modules, as_module: bool = False, lock: bool = True, use_state_dict: bool = False, lazy_stack: bool = False, expand_identical: bool = False)¶
檢索多個模組的引數,用於 ensebmle 學習/期望透過 vmap 的應用功能。
- 引數:
modules (nn.Module 的序列) – 要從中獲取引數的模組。如果模組的結構不同,則需要一個延遲堆疊(請參閱下面的
lazy_stack引數)。- 關鍵字引數:
as_module (bool, optional) – 如果為
True,將返回一個TensorDictParams例項,該例項可用於在torch.nn.Module中儲存引數。預設為False。lock (bool, optional) – 如果為
True,則生成的 tensordict 將被鎖定。預設為True。use_state_dict (bool, optional) –
如果為
True,將使用模組的狀態字典,並將其展開為具有模型樹結構的 TensorDict。預設為False。注意
當必須使用 state-dict 鉤子時,這特別有用。
lazy_stack (bool, optional) –
引數應該密集堆疊還是延遲堆疊。預設為
False(密集堆疊)。注意
lazy_stack和as_module是互斥的功能。警告
延遲輸出和非延遲輸出之間存在一個關鍵區別,即非延遲輸出將使用所需的批次大小重新例項化引數,而
lazy_stack將僅將引數表示為延遲堆疊。這意味著雖然原始引數可以在lazy_stack=True時安全地傳遞給最佳化器,但當設定為True時,需要傳遞新引數。警告
雖然使用延遲堆疊來保持原始引數引用可能很誘人,但請記住,每次呼叫
get()時,延遲堆疊都會執行堆疊。這將需要記憶體(引數大小的 N 倍,如果構建圖形則更多)和時間來計算。這也意味著最佳化器將包含更多引數,並且像step()或zero_grad()這樣的操作將需要更長時間才能執行。一般來說,lazy_stack應該保留給極少數用例。expand_identical (bool, optional) – 如果
True並且相同的引數(相同的標識)正在堆疊到自身,則將返回此引數的擴充套件版本。當lazy_stack=True時,將忽略此引數。
示例
>>> from torch import nn >>> from tensordict import TensorDict >>> torch.manual_seed(0) >>> empty_module = nn.Linear(3, 4, device="meta") >>> n_models = 2 >>> modules = [nn.Linear(3, 4) for _ in range(n_models)] >>> params = TensorDict.from_modules(*modules) >>> print(params) TensorDict( fields={ bias: Parameter(shape=torch.Size([2, 4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Parameter(shape=torch.Size([2, 4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([2]), device=None, is_shared=False) >>> # example of batch execution >>> def exec_module(params, x): ... with params.to_module(empty_module): ... return empty_module(x) >>> x = torch.randn(3) >>> y = torch.vmap(exec_module, (0, None))(params, x) >>> assert y.shape == (n_models, 4) >>> # since lazy_stack = False, backprop leaves the original params untouched >>> y.sum().backward() >>> assert params["weight"].grad.norm() > 0 >>> assert modules[0].weight.grad is None
使用
lazy_stack=True時,情況略有不同>>> params = TensorDict.from_modules(*modules, lazy_stack=True) >>> print(params) LazyStackedTensorDict( fields={ bias: Tensor(shape=torch.Size([2, 4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Tensor(shape=torch.Size([2, 4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, exclusive_fields={ }, batch_size=torch.Size([2]), device=None, is_shared=False, stack_dim=0) >>> # example of batch execution >>> y = torch.vmap(exec_module, (0, None))(params, x) >>> assert y.shape == (n_models, 4) >>> y.sum().backward() >>> assert modules[0].weight.grad is not None
- classmethod from_namedtuple(named_tuple, *, auto_batch_size: bool = False, batch_dims: Optional[int] = None, device: Optional[device] = None, batch_size: Optional[Size] = None)¶
遞迴地將一個 namedtuple 轉換為 TensorDict。
- 引數:
named_tuple – 要轉換的 namedtuple 例項。
- 關鍵字引數:
auto_batch_size (bool, optional) – 如果
True,將自動計算批次大小。 預設為False。batch_dims (int, optional) – 如果
auto_batch_size為True,則定義輸出 tensordict 應具有的維度數。預設為None(每一級的完整批次大小)。 (可選)device (torch.device, optional) – TensorDict 將被建立在其上的裝置。預設為
None。(可選)batch_size (torch.Size, optional) – TensorDict 的批次大小。預設為
None。(可選)
- 返回值:
輸入 namedtuple 的 TensorDict 表示。
示例
>>> from tensordict import TensorDict >>> import torch >>> data = TensorDict({ ... "a_tensor": torch.zeros((3)), ... "nested": {"a_tensor": torch.zeros((3)), "a_string": "zero!"}}, [3]) >>> nt = data.to_namedtuple() >>> print(nt) GenericDict(a_tensor=tensor([0., 0., 0.]), nested=GenericDict(a_tensor=tensor([0., 0., 0.]), a_string='zero!')) >>> TensorDict.from_namedtuple(nt, auto_batch_size=True) TensorDict( fields={ a_tensor: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), nested: TensorDict( fields={ a_string: NonTensorData(data=zero!, batch_size=torch.Size([3]), device=None), a_tensor: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)
- classmethod from_pytree(pytree, *, batch_size: Optional[Size] = None, auto_batch_size: bool = False, batch_dims: Optional[int] = None)¶
將一個 pytree 轉換為 TensorDict 例項。
該方法旨在儘可能保留 pytree 的巢狀結構。
新增額外的非 tensor 鍵來跟蹤每個級別的標識,提供了一個內建的 pytree 到 tensordict 的雙射變換 API。
當前接受的類包括列表、元組、命名元組和字典。
注意
對於字典,非 NestedKey 鍵會單獨註冊為
NonTensorData例項。注意
可轉換為 Tensor 的型別(例如 int、float 或 np.ndarray)將被轉換為 torch.Tensor 例項。 請注意,此轉換是滿射的:將 tensordict 轉換回 pytree 將無法恢復原始型別。
示例
>>> # Create a pytree with tensor leaves, and one "weird"-looking dict key >>> class WeirdLookingClass: ... pass ... >>> weird_key = WeirdLookingClass() >>> # Make a pytree with tuple, lists, dict and namedtuple >>> pytree = ( ... [torch.randint(10, (3,)), torch.zeros(2)], ... { ... "tensor": torch.randn( ... 2, ... ), ... "td": TensorDict({"one": 1}), ... weird_key: torch.randint(10, (2,)), ... "list": [1, 2, 3], ... }, ... {"named_tuple": TensorDict({"two": torch.ones(1) * 2}).to_namedtuple()}, ... ) >>> # Build a TensorDict from that pytree >>> td = TensorDict.from_pytree(pytree) >>> # Recover the pytree >>> pytree_recon = td.to_pytree() >>> # Check that the leaves match >>> def check(v1, v2): >>> assert (v1 == v2).all() >>> >>> torch.utils._pytree.tree_map(check, pytree, pytree_recon) >>> assert weird_key in pytree_recon[1]
- classmethod from_struct_array(struct_array: ndarray, *, auto_batch_size: bool = False, batch_dims: Optional[int] = None, device: Optional[device] = None, batch_size: Optional[Size] = None) T¶
將結構化的 numpy 陣列轉換為 TensorDict。
生成的 TensorDict 將與 numpy 陣列共享相同的記憶體內容(這是一個零複製操作)。就地更改結構化的 numpy 陣列的值將影響 TensorDict 的內容。
注意
此方法執行零複製操作,這意味著生成的 TensorDict 將與輸入 numpy 陣列共享相同的記憶體內容。因此,就地更改 numpy 陣列的值將影響 TensorDict 的內容。
- 引數:
struct_array (np.ndarray) – 要轉換的結構化的 numpy 陣列。
- 關鍵字引數:
auto_batch_size (bool, 可選) – 如果為
True,則會自動計算批次大小。預設為False。batch_dims (int, optional) – 如果
auto_batch_size為True,則定義輸出 tensordict 應具有的維度數。預設為None(每一級的完整批次大小)。 (可選)device (torch.device, 可選) –
TensorDict 將在其上建立的裝置。預設為
None。注意
更改裝置(即,指定任何非
None或"cpu"的裝置)將傳輸資料,從而導致返回的資料的記憶體位置發生更改。batch_size (torch.Size, 可選) – TensorDict 的批次大小。預設為 None。
- 返回值:
輸入結構化的 numpy 陣列的 TensorDict 表示。
示例
>>> x = np.array( ... [("Rex", 9, 81.0), ("Fido", 3, 27.0)], ... dtype=[("name", "U10"), ("age", "i4"), ("weight", "f4")], ... ) >>> td = TensorDict.from_struct_array(x) >>> x_recon = td.to_struct_array() >>> assert (x_recon == x).all() >>> assert x_recon.shape == x.shape >>> # Try modifying x age field and check effect on td >>> x["age"] += 1 >>> assert (td["age"] == np.array([10, 4])).all()
- classmethod from_tuple(obj, *, auto_batch_size: bool = False, batch_dims: Optional[int] = None, device: Optional[device] = None, batch_size: Optional[Size] = None)¶
將一個元組轉換為 TensorDict。
- 引數:
obj – 要轉換的元組例項。
- 關鍵字引數:
auto_batch_size (bool, 可選) – 如果為
True,則會自動計算批次大小。預設為False。batch_dims (int, optional) – 如果 auto_batch_size 為
True,則定義輸出 tensordict 應具有的維度數。 預設為None(每個級別的完整批次大小)。device (torch.device, optional) – TensorDict 將被建立在其上的裝置。預設為
None。(可選)batch_size (torch.Size, optional) – TensorDict 的批次大小。預設為
None。(可選)
- 返回值:
輸入元組的 TensorDict 表示。
示例
>>> my_tuple = (1, 2, 3) >>> td = TensorDict.from_tuple(my_tuple) >>> print(td) TensorDict( fields={ 0: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), 1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), 2: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- classmethod fromkeys(keys: List[NestedKey], value: Any = 0)¶
從一個鍵列表和一個單獨的值建立一個 tensordict。
- 引數:
keys (NestedKey 的列表) – 一個可迭代物件,指定新字典的鍵。
value (相容的型別, 可選) – 所有鍵的值。預設為
0。
- gather(dim: int, index: Tensor, out: Optional[T] = None) T¶
沿著 dim 指定的軸收集值。
- 引數:
dim (int) – 收集元素的維度。
index (torch.Tensor) – 一個長整型張量,其維度數與 tensordict 的維度數匹配,且只有收集維度不同。它的元素是指沿所需維度收集的索引。
out (TensorDictBase, optional) – 一個目標 tensordict。它必須與索引具有相同的形狀。
示例
>>> td = TensorDict( ... {"a": torch.randn(3, 4, 5), ... "b": TensorDict({"c": torch.zeros(3, 4, 5)}, [3, 4, 5])}, ... [3, 4]) >>> index = torch.randint(4, (3, 2)) >>> td_gather = td.gather(dim=1, index=index) >>> print(td_gather) TensorDict( fields={ a: Tensor(shape=torch.Size([3, 2, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 2, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 2, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 2]), device=None, is_shared=False)
Gather 保留維度名稱。
示例
>>> td.names = ["a", "b"] >>> td_gather = td.gather(dim=1, index=index) >>> td_gather.names ["a", "b"]
- gather_and_stack(dst: int, group: 'torch.distributed.ProcessGroup' | None = None) T | None¶
從不同的工作程序收集 tensordict,並將它們堆疊到目標工作程序的 self 上。
- 引數:
dst (int) – 將呼叫
gather_and_stack()的目標工作程序的秩。group (torch.distributed.ProcessGroup, 可選) – 如果設定,將使用指定的程序組進行通訊。否則,將使用預設程序組。預設為
None。
示例
>>> from torch import multiprocessing as mp >>> from tensordict import TensorDict >>> import torch >>> >>> def client(): ... torch.distributed.init_process_group( ... "gloo", ... rank=1, ... world_size=2, ... init_method=f"tcp://:10003", ... ) ... # Create a single tensordict to be sent to server ... td = TensorDict( ... {("a", "b"): torch.randn(2), ... "c": torch.randn(2)}, [2] ... ) ... td.gather_and_stack(0) ... >>> def server(): ... torch.distributed.init_process_group( ... "gloo", ... rank=0, ... world_size=2, ... init_method=f"tcp://:10003", ... ) ... # Creates the destination tensordict on server. ... # The first dim must be equal to world_size-1 ... td = TensorDict( ... {("a", "b"): torch.zeros(2), ... "c": torch.zeros(2)}, [2] ... ).expand(1, 2).contiguous() ... td.gather_and_stack(0) ... assert td["a", "b"] != 0 ... print("yuppie") ... >>> if __name__ == "__main__": ... mp.set_start_method("spawn") ... ... main_worker = mp.Process(target=server) ... secondary_worker = mp.Process(target=client) ... ... main_worker.start() ... secondary_worker.start() ... ... main_worker.join() ... secondary_worker.join()
- get(key: NestedKey, default: Any = None) Tensor¶
獲取與輸入鍵儲存的值。
- 引數:
key (str, str 的元組) – 要查詢的鍵。如果是 str 的元組,則等效於鏈式呼叫 getattr。
default –
如果在 tensordict 中未找到鍵,則返回預設值。預設為
None。警告
以前,如果在 tensordict 中不存在某個鍵且沒有傳遞預設值,則會引發 KeyError。從 v0.7 開始,此行為已更改,而是返回 None 值(與 dict.get 行為一致)。要採用舊的行為,請設定環境變數 export TD_GET_DEFAULTS_TO_NONE=’0’ 或呼叫 :func`~tensordict.set_get_defaults_to_none(False)`。
示例
>>> td = TensorDict({"x": 1}, batch_size=[]) >>> td.get("x") tensor(1) >>> td.get("y") None
- get_at(key: NestedKey, *args, **kwargs) Tensor¶
從鍵 key 在索引 idx 處獲取 tensordict 的值。
- 引數:
key (str, str 的元組) – 要檢索的鍵。
index (int, slice, torch.Tensor, iterable) – 張量的索引。
default (torch.Tensor) – 如果在 tensordict 中不存在該鍵,則返回預設值。
- 返回值:
索引張量。
示例
>>> td = TensorDict({"x": torch.arange(3)}, batch_size=[]) >>> td.get_at("x", index=1) tensor(1)
- get_buffer(target: str) Tensor¶
如果存在,則返回由
target給出的緩衝區,否則丟擲錯誤。有關此方法的功能以及如何正確指定
target的更詳細說明,請參閱get_submodule的文件字串。- 引數:
target – 要查詢的緩衝區的完全限定字串名稱。(有關如何指定完全限定字串,請參閱
get_submodule。)- 返回值:
由
target引用的緩衝區- 返回型別:
- 引發:
AttributeError – 如果目標字串引用了無效路徑或解析為非緩衝區的內容
- get_extra_state() Any¶
返回要包含在模組的 state_dict 中的任何額外狀態。
如果您需要儲存額外的狀態,請為此模組實現此方法和相應的
set_extra_state()。在構建模組的 state_dict() 時呼叫此函式。請注意,額外狀態應該是可 pickle 化的,以確保 state_dict 的工作序列化。我們僅提供序列化張量的向後相容性保證;如果其序列化的 pickle 形式發生更改,其他物件可能會破壞向後相容性。
- 返回值:
要儲存在模組的 state_dict 中的任何額外狀態
- 返回型別:
- get_non_tensor(key: NestedKey, default=_NoDefault.ZERO)¶
獲取非張量值(如果存在),或者在找不到非張量值時獲取 default。
此方法對於張量/TensorDict 值是穩健的,這意味著如果收集的值是常規張量,它也將被返回(儘管此方法帶有一些開銷,不應超出其自然範圍使用)。
有關如何在 tensordict 中設定非張量值的更多資訊,請參閱
set_non_tensor()。- 引數:
key (NestedKey) – NonTensorData 物件的位置。
default (Any, 可選) – 如果找不到鍵,則返回的值。
- 返回:
tensordict.tensorclass.NonTensorData的內容, 如果該條目不是
tensordict.tensorclass.NonTensorData型別,則返回與key對應的條目(如果找不到該條目,則返回default)。
示例
>>> data = TensorDict({}, batch_size=[]) >>> data.set_non_tensor(("nested", "the string"), "a string!") >>> assert data.get_non_tensor(("nested", "the string")) == "a string!" >>> # regular `get` works but returns a NonTensorData object >>> data.get(("nested", "the string")) NonTensorData( data='a string!', batch_size=torch.Size([]), device=None, is_shared=False)
- get_parameter(target: str) Parameter¶
如果存在
target指定的 parameter,則返回該 parameter,否則丟擲錯誤。有關此方法的功能以及如何正確指定
target的更詳細說明,請參閱get_submodule的文件字串。- 引數:
target – 要查詢的 Parameter 的完整字串名稱。(有關如何指定完整字串,請參閱
get_submodule。)- 返回值:
由
target引用的 Parameter- 返回型別:
torch.nn.Parameter
- 引發:
AttributeError – 如果目標字串引用了無效路徑或解析為非
nn.Parameter的物件,則引發此異常
- get_submodule(target: str) Module¶
如果存在
target指定的 submodule,則返回該 submodule,否則丟擲錯誤。例如,假設你有一個
nn.ModuleA,其結構如下:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(該圖顯示了一個
nn.ModuleA。A具有一個巢狀的 submodulenet_b,它本身又有兩個 submodulenet_c和linear。net_c又有一個 submoduleconv。)要檢查是否具有
linearsubmodule,我們將呼叫get_submodule("net_b.linear")。 要檢查是否具有convsubmodule,我們將呼叫get_submodule("net_b.net_c.conv")。get_submodule的執行時受target中 module 巢狀程度的限制。 對named_modules的查詢可以實現相同的結果,但它在傳遞 module 的數量上是 O(N) 的。 因此,對於檢查某些 submodule 是否存在的簡單檢查,應始終使用get_submodule。- 引數:
target – 要查詢的 submodule 的完整字串名稱。(有關如何指定完整字串,請參閱上面的示例。)
- 返回值:
由
target引用的 submodule- 返回型別:
- 引發:
AttributeError – 如果目標字串產生的路徑中的任何一點上的(子)路徑解析為不存在的屬性名稱或不是
nn.Module例項的物件,則會引發此異常。
- property grad¶
返回一個 tensordict,其中包含葉 tensor 的 .grad 屬性。
- half()¶
將所有 tensor 轉換為
torch.half。
- int()¶
將所有 tensor 轉換為
torch.int。
- int16()¶
將所有 tensor 轉換為
torch.int16。
- int32()¶
將所有 tensor 轉換為
torch.int32。
- int64()¶
將所有 tensor 轉換為
torch.int64。
- int8()¶
將所有 tensor 轉換為
torch.int8。
- ipu(device: Optional[Union[int, device]] = None) T¶
將所有模型引數和緩衝區移動到 IPU。
這也會使關聯的引數和緩衝區成為不同的物件。 因此,如果模組將在 IPU 上進行最佳化,則應在構建最佳化器之前呼叫此方法。
注意
此方法會就地修改模組。
- 引數:
device (int, optional) – 如果指定,所有引數都將複製到該裝置
- 返回值:
self
- 返回型別:
模組
- irecv(src: int, *, group: 'torch.distributed.ProcessGroup' | None = None, return_premature: bool = False, init_tag: int = 0, pseudo_rand: bool = False) tuple[int, list[torch.Future]] | list[torch.Future] | None¶
非同步接收 tensordict 的內容並使用它更新內容。
有關上下文,請檢視
isend()方法中的示例。- 引數:
src (int) – 源 worker 的排名。
- 關鍵字引數:
group (torch.distributed.ProcessGroup, 可選) – 如果設定,將使用指定的程序組進行通訊。否則,將使用預設程序組。預設為
None。return_premature (bool) – 如果為
True,則返回一個 futures 列表,用於等待直到 tensordict 被更新。預設為False,即在呼叫中等待直到更新完成。init_tag (int) – 源 worker 使用的
init_tag。pseudo_rand (bool) – 如果為 True,則標籤序列將是偽隨機的,允許從不同節點發送多個數據而不會重疊。 請注意,生成這些偽隨機數非常耗時(1e-5 秒/數字),這意味著它可能會降低演算法的執行時。 該值必須與傳遞給
isend()的值匹配。 預設為False。
- 返回值:
- 如果
return_premature=True,則為要等待的 futures 列表 直到 tensordict 被更新。
- 如果
- is_consolidated()¶
檢查 TensorDict 是否具有 consolidated 儲存。
- is_contiguous(*args, **kwargs)¶
返回一個布林值,指示所有張量是否都是連續的。
- property is_memmap: bool¶
檢查 tensordict 是否為記憶體對映。
如果 TensorDict 例項是記憶體對映的,則它被鎖定(條目無法重新命名、刪除或新增)。 如果使用都是記憶體對映的張量建立
TensorDict,這 __並不__ 意味著is_memmap將返回True(因為新的張量可能是也可能不是記憶體對映的)。 只有當呼叫 tensordict.memmap_() 時,tensordict 才會被認為是記憶體對映的。對於 CUDA 裝置上的 tensordict,這始終為
True。
檢查 tensordict 是否在共享記憶體中。
如果 TensorDict 例項在共享記憶體中,則它被鎖定(條目無法重新命名、刪除或新增)。 如果使用都在共享記憶體中的張量建立
TensorDict,這 __並不__ 意味著is_shared將返回True(因為新的張量可能是也可能不是在共享記憶體中)。 只有當呼叫 tensordict.share_memory_() 或將 tensordict 放置在預設情況下內容共享的裝置上(例如,"cuda")時,tensordict 才會被認為是在共享記憶體中。對於 CUDA 裝置上的 tensordict,這始終為
True。
- isend(dst: int, *, group: 'torch.distributed.ProcessGroup' | None = None, init_tag: int = 0, pseudo_rand: bool = False) int¶
非同步傳送 tensordict 的內容。
- 引數:
dst (int) – 目標 worker 的 rank,內容應傳送到該 worker。
- 關鍵字引數:
示例
>>> import torch >>> from tensordict import TensorDict >>> from torch import multiprocessing as mp >>> def client(): ... torch.distributed.init_process_group( ... "gloo", ... rank=1, ... world_size=2, ... init_method=f"tcp://:10003", ... ) ... ... td = TensorDict( ... { ... ("a", "b"): torch.randn(2), ... "c": torch.randn(2, 3), ... "_": torch.ones(2, 1, 5), ... }, ... [2], ... ) ... td.isend(0) ... >>> >>> def server(queue, return_premature=True): ... torch.distributed.init_process_group( ... "gloo", ... rank=0, ... world_size=2, ... init_method=f"tcp://:10003", ... ) ... td = TensorDict( ... { ... ("a", "b"): torch.zeros(2), ... "c": torch.zeros(2, 3), ... "_": torch.zeros(2, 1, 5), ... }, ... [2], ... ) ... out = td.irecv(1, return_premature=return_premature) ... if return_premature: ... for fut in out: ... fut.wait() ... assert (td != 0).all() ... queue.put("yuppie") ... >>> >>> if __name__ == "__main__": ... queue = mp.Queue(1) ... main_worker = mp.Process( ... target=server, ... args=(queue, ) ... ) ... secondary_worker = mp.Process(target=client) ... ... main_worker.start() ... secondary_worker.start() ... out = queue.get(timeout=10) ... assert out == "yuppie" ... main_worker.join() ... secondary_worker.join()
- isfinite() T¶
返回一個新的 tensordict,其中包含布林元素,表示每個元素是否有限。
當實數值不是 NaN、負無窮或正無窮時,它們是有限的。 當複數的實部和虛部都有限時,它們是有限的。
- isnan() T¶
返回一個新的 tensordict,其中包含布林元素,表示輸入的每個元素是否為 NaN。
當複數的實部和/或虛部為 NaN 時,該複數被認為是 NaN。
- isneginf() T¶
測試輸入的每個元素是否為負無窮。
- isposinf() T¶
測試輸入的每個元素是否為負無窮。
- isreal() T¶
返回一個新的 tensordict,其中包含布林元素,表示輸入的每個元素是否為實數值。
- items(include_nested: bool = False, leaves_only: bool = False, is_leaf: Optional[Callable[[Type], bool]] = None, *, sort: bool = False) Iterator[Tensor]¶
返回 tensordict 的鍵值對生成器。
- 引數:
include_nested (bool, optional) – 如果
True, 將返回巢狀的值。預設為False。leaves_only (bool, optional) – 如果
False,則僅返回葉子節點。預設為False。is_leaf (callable, optional) –
一個可呼叫物件,接受一個類型別作為引數,返回一個布林值,指示該類是否應被視為葉節點。
注意
is_leaf 的目的不是阻止對巢狀 tensordict 的遞迴呼叫,而是將某些型別標記為“葉節點”,以便在 leaves_only=True 時進行過濾。 即使 is_leaf(cls) 返回 True,如果 include_nested=True,tensordict 的巢狀結構仍將被遍歷。 換句話說,is_leaf 不控制遞迴深度,而是提供了一種在 leaves_only=True 時從結果中過濾掉某些型別的方法。 這意味著樹中的一個節點可以既是葉節點,又是帶有子節點的節點。 實際上,
is_leaf的預設值會將 tensordict 和 tensorclass 例項從葉節點集中排除。另請參閱
- 關鍵字引數:
sort (bool, optional) – 是否應該對鍵進行排序。對於巢狀鍵,鍵將根據它們的連線名稱進行排序(即,
("a", "key")將被視為"a.key"進行排序)。請注意,處理大型 tensordict 時,排序可能會產生顯著的開銷。預設為False。
- keys(*args, **kwargs)¶
返回 tensordict 鍵的生成器。
警告
TensorDict 的
keys()方法返回鍵的惰性檢視。如果查詢了keys但未對其進行迭代,然後修改了 tensordict,則稍後迭代鍵將返回鍵的新配置。- 引數:
include_nested (bool, optional) – 如果
True, 將返回巢狀的值。預設為False。leaves_only (bool, optional) – 如果
False,則僅返回葉子節點。預設為False。is_leaf (callable, optional) –
一個可呼叫物件,接受一個類型別作為引數,返回一個布林值,指示該類是否應被視為葉節點。
注意
is_leaf 的目的不是阻止對巢狀 tensordict 的遞迴呼叫,而是將某些型別標記為“葉節點”,以便在 leaves_only=True 時進行過濾。 即使 is_leaf(cls) 返回 True,如果 include_nested=True,tensordict 的巢狀結構仍將被遍歷。 換句話說,is_leaf 不控制遞迴深度,而是提供了一種在 leaves_only=True 時從結果中過濾掉某些型別的方法。 這意味著樹中的一個節點可以既是葉節點,又是帶有子節點的節點。 實際上,
is_leaf的預設值會將 tensordict 和 tensorclass 例項從葉節點集中排除。另請參閱
- 關鍵字引數:
sort (bool, optional) – 是否應對鍵進行排序。對於巢狀鍵,鍵將根據它們的連線名稱進行排序(即,
("a", "key")將被視為"a.key"進行排序)。請注意,處理大型 tensordict 時,排序可能會產生顯著的開銷。預設為False。
示例
>>> from tensordict import TensorDict >>> data = TensorDict({"0": 0, "1": {"2": 2}}, batch_size=[]) >>> data.keys() ['0', '1'] >>> list(data.keys(leaves_only=True)) ['0'] >>> list(data.keys(include_nested=True, leaves_only=True)) ['0', '1', ('1', '2')]
- classmethod lazy_stack(input, dim=0, *, out=None, **kwargs)¶
建立 tensordict 的惰性堆疊。
有關詳細資訊,請參見
lazy_stack()。
- lerp(end: tensordict.base.TensorDictBase | torch.Tensor, weight: tensordict.base.TensorDictBase | torch.Tensor | float)¶
根據標量或張量
weight對兩個張量start(由self給出)和end進行線性插值。\[\text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i)\]start和end的形狀必須是可廣播的。如果weight是一個張量,那麼weight、start和end的形狀必須是可廣播的。- 引數:
end (TensorDict) – 包含結束點的 tensordict。
weight (TensorDict, tensor 或 float) – 插值公式的權重。
- lerp_(end: tensordict.base.TensorDictBase | torch.Tensor | float, weight: tensordict.base.TensorDictBase | torch.Tensor | float)¶
lerp()的原地版本。
- lgamma() T¶
計算 TensorDict 中每個元素的
lgamma()值。
- lgamma_() T¶
就地計算 TensorDict 中每個元素的
lgamma()值。
- 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 或 Path to folder) – 儲存的 tensordict 所在的資料夾路徑。
device (torch.device 或 等價物, 可選) – 如果提供,資料將被非同步地轉換到該裝置。支援 “meta” 裝置,在這種情況下,資料不會被載入,而是建立一組空的 “meta” 張量。這對於瞭解總模型大小和結構而不實際開啟任何檔案很有用。
non_blocking (bool, 可選) – 如果
True,則在裝置上載入張量後不會呼叫 synchronize。預設為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_memmap_(prefix: str | pathlib.Path)¶
在呼叫
load_memmap_的 tensordict 中載入一個記憶體對映的 tensordict 的內容。有關更多資訊,請參閱
load_memmap()。
- load_state_dict(state_dict: OrderedDict[str, Any], strict=True, assign=False)¶
載入一個 state_dict (狀態字典), 格式如
state_dict(),到 tensordict 中。- 引數:
state_dict (OrderedDict) – 要複製的 state_dict。
strict (bool, 可選) – 是否嚴格強制
state_dict中的鍵與此 tensordict 的torch.nn.Module.state_dict()函式返回的鍵匹配。預設值:Trueassign (bool, 可選) – 是否將狀態字典中的專案分配給 tensordict 中對應的鍵,而不是將它們就地複製到 tensordict 的當前張量中。當
False時,當前模組中張量的屬性將被保留,而當True時,狀態字典中張量的屬性將被保留。預設值:Falsefrom_flatten (bool, 可選) – 如果
True,則假定輸入的 state_dict 已被扁平化。預設為False。
示例
>>> data = TensorDict({"1": 1, "2": 2, "3": {"3": 3}}, []) >>> data_zeroed = TensorDict({"1": 0, "2": 0, "3": {"3": 0}}, []) >>> sd = data.state_dict() >>> data_zeroed.load_state_dict(sd) >>> print(data_zeroed["3", "3"]) tensor(3) >>> # with flattening >>> data_zeroed = TensorDict({"1": 0, "2": 0, "3": {"3": 0}}, []) >>> data_zeroed.load_state_dict(data.state_dict(flatten=True), from_flatten=True) >>> print(data_zeroed["3", "3"]) tensor(3)
- lock_() T¶
鎖定一個 tensordict,以防止非就地操作。
諸如
set(),__setitem__(),update(),rename_key_()或其他新增或刪除條目的操作將被阻止。此方法可以用作裝飾器。
示例
>>> from tensordict import TensorDict >>> td = TensorDict({"a": 1, "b": 2, "c": 3}, batch_size=[]) >>> with td.lock_(): ... assert td.is_locked ... try: ... td.set("d", 0) # error! ... except RuntimeError: ... print("td is locked!") ... try: ... del td["d"] ... except RuntimeError: ... print("td is locked!") ... try: ... td.rename_key_("a", "d") ... except RuntimeError: ... print("td is locked!") ... td.set("a", 0, inplace=True) # No storage is added, moved or removed ... td.set_("a", 0) # No storage is added, moved or removed ... td.update({"a": 0}, inplace=True) # No storage is added, moved or removed ... td.update_({"a": 0}) # No storage is added, moved or removed >>> assert not td.is_locked
- log() T¶
計算 TensorDict 中每個元素的
log()值。
- log10() T¶
計算 TensorDict 中每個元素的
log10()值。
- log10_() T¶
就地計算 TensorDict 中每個元素的
log10()值。
- log1p() T¶
計算 TensorDict 中每個元素的
log1p()值。
- log1p_() T¶
就地計算 TensorDict 中每個元素的
log1p()值。
- log2() T¶
計算 TensorDict 中每個元素的
log2()值。
- log2_() T¶
原地計算 TensorDict 中每個元素的
log2()值。
- log_() T¶
原地計算 TensorDict 中每個元素的
log()值。
- logical_and(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) TensorDictBase¶
執行
self和other之間的邏輯與運算。\[\text{{out}}_i = \text{{input}}_i \land \text{{other}}_i\]- 引數:
other (TensorDictBase 或 torch.Tensor) – 用於執行邏輯與運算的 tensor 或 TensorDict。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- logsumexp(dim=None, keepdim=False, *, out=None)¶
返回給定維度
dim中輸入 tensordict 每行的指數和的對數。該計算經過數值穩定處理。如果 keepdim 為
True,則輸出張量的大小與輸入張量相同,只是在維度dim中大小為1。 否則,dim被壓縮(參見squeeze()),導致輸出張量的維度減少 1(或 len(dim))。- 引數:
- 關鍵字引數:
out (TensorDictBase, 可選) – 輸出 tensordict。
- make_memmap(key: NestedKey, shape: torch.Size | torch.Tensor, *, dtype: Optional[dtype] = None) MemoryMappedTensor¶
根據形狀(shape)和可能的 dtype 建立一個空的記憶體對映張量。
警告
此方法在設計上不是鎖安全的。 存在於多個節點上的記憶體對映 TensorDict 例項需要使用方法
memmap_refresh_()進行更新。寫入現有條目將導致錯誤。
- 引數:
key (NestedKey) – 要寫入的新條目的鍵。 如果該鍵已存在於 tensordict 中,則會引發異常。
shape (torch.Size 或 等效項, 巢狀張量的 torch.Tensor) – 要寫入的張量的形狀。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 新張量的 dtype。
- 返回值:
一個新的記憶體對映張量。
- make_memmap_from_storage(key: NestedKey, storage: UntypedStorage, shape: torch.Size | torch.Tensor, *, dtype: Optional[dtype] = None) MemoryMappedTensor¶
根據儲存(storage)、形狀(shape)和可能的 dtype 建立一個空的記憶體對映張量。
警告
此方法在設計上不是鎖安全的。 存在於多個節點上的記憶體對映 TensorDict 例項需要使用方法
memmap_refresh_()進行更新。注意
如果儲存具有關聯的檔名,則它必須與該檔案的新檔名匹配。 如果它沒有關聯的檔名,但 tensordict 具有關聯的路徑,則會導致異常。
- 引數:
key (NestedKey) – 要寫入的新條目的鍵。 如果該鍵已存在於 tensordict 中,則會引發異常。
storage (torch.UntypedStorage) – 用於新 MemoryMappedTensor 的儲存。 必須是物理記憶體儲存。
shape (torch.Size 或 等效項, 巢狀張量的 torch.Tensor) – 要寫入的張量的形狀。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 新張量的 dtype。
- 返回值:
具有給定儲存的新記憶體對映張量。
- make_memmap_from_tensor(key: NestedKey, tensor: Tensor, *, copy_data: bool = True) MemoryMappedTensor¶
根據張量建立一個空的記憶體對映張量。
警告
此方法在設計上不是鎖安全的。 存在於多個節點上的記憶體對映 TensorDict 例項需要使用方法
memmap_refresh_()進行更新。如果
copy_data為True(即儲存未共享),則此方法始終複製儲存內容。- 引數:
key (NestedKey) – 要寫入的新條目的鍵。 如果該鍵已存在於 tensordict 中,則會引發異常。
tensor (torch.Tensor) – 要在物理記憶體上覆制的張量。
- 關鍵字引數:
copy_data (bool, optional) – 如果
False,則新張量將共享輸入的元資料,例如形狀和資料型別,但內容將為空。 預設為True。- 返回值:
具有給定儲存的新記憶體對映張量。
- map(fn: Callable, dim: int = 0, num_workers: Optional[int] = None, chunksize: Optional[int] = None, num_chunks: Optional[int] = None, pool: Optional[Pool] = None, generator: Optional[Generator] = None, max_tasks_per_child: Optional[int] = None, worker_threads: int = 1, mp_start_method: Optional[str] = None)¶
將函式對映到 tensordict 沿一個維度的拆分。
此方法將透過將 tensordict 例項分成大小相等的 tensordict 並將操作分派到所需數量的工作程式,從而將函式應用於 tensordict 例項。
函式簽名應為
Callabe[[TensorDict], Union[TensorDict, Tensor]]。 輸出必須支援torch.cat()操作。 函式必須是可序列化的。注意
當處理儲存在磁碟上的大型資料集(例如,記憶體對映的 tensordict)時,此方法特別有用,其中塊將是原始資料的零複製切片,可以幾乎零成本地傳遞到程序。 這允許以很小的代價處理非常大的資料集(例如,超過 Tb)。
- 引數:
- 關鍵字引數:
out (TensorDictBase, optional) – 輸出的可選容器。 其沿提供的
dim的批處理大小必須與self.ndim匹配。 如果它是共享的或 memmap (is_shared()或is_memmap()返回True) ,它將在遠端程序中填充,從而避免資料向內傳輸。 否則,來自self切片的資料將被髮送到程序,在當前程序上收集並就地寫入out。chunksize (int, optional) – 每個資料塊的大小。
chunksize為 0 將沿所需的維度解繫結 tensordict 並在應用函式後重新堆疊它,而chunksize>0將拆分 tensordict 並在生成的 tensordict 列表上呼叫torch.cat()。 如果未提供,塊的數量將等於工作程式的數量。 對於非常大的 tensordict,如此大的塊可能不適合在記憶體中進行操作,並且可能需要更多塊才能使操作在實踐中可行。 此引數與num_chunks互斥。num_chunks (int, optional) – 將 tensordict 分成塊的數量。 如果未提供,塊的數量將等於工作程式的數量。 對於非常大的 tensordict,如此大的塊可能不適合在記憶體中進行操作,並且可能需要更多塊才能使操作在實踐中可行。 此引數與
chunksize互斥。pool (mp.Pool, optional) – 用於執行作業的多程序池例項。 如果未提供,則將在
map方法中建立一個池。generator (torch.Generator, optional) –
用於播種的生成器。 將從中生成一個基本種子,並且池的每個工作程式都將使用提供的種子遞增一個從
0到num_workers的唯一整數來播種。 如果未提供生成器,則將使用一個隨機整數作為種子。 要使用未播種的工作程式,應單獨建立一個池並直接傳遞給map()。注意
提供一個低值的種子時應謹慎,因為這可能會導致實驗之間的自相關,例如:如果請求了 8 個工作程式,並且種子為 4,則工作程式種子將從 4 到 11。如果種子為 5,則工作程式種子將從 5 到 12。這兩個實驗將有 7 個種子的重疊,這可能會對結果產生意想不到的影響。
注意
worker 初始化的目標是讓每個 worker 擁有獨立的種子,而**不是**讓 map 方法的每次呼叫都產生可復現的結果。 換句話說,由於無法知道哪個 worker 將選擇哪個任務,因此兩個實驗可能並且很可能會返回不同的結果。但是,我們可以確保每個 worker 都有不同的種子,並且每個 worker 上的偽隨機操作是不相關的。
max_tasks_per_child (int, optional) – 每個子程序選擇的最大任務數。預設為
None,即對任務數量沒有限制。worker_threads (int, optional) – worker 使用的執行緒數。預設為
1。index_with_generator (bool, optional) – 如果為
True,則將在查詢期間完成 tensordict 的拆分/分塊,從而節省初始化時間。請注意,chunk()和split()比索引(在生成器中使用)效率高得多,因此在初始化時節省處理時間可能會對總執行時間產生負面影響。預設為False。pbar (bool, optional) – 如果為
True,將顯示進度條。需要安裝 tqdm。預設為False。mp_start_method (str, optional) – 多程序的啟動方法。如果未提供,將使用預設啟動方法。接受的字串為
"fork"和"spawn"。請記住,使用"fork"啟動方法時,"cuda"張量不能在程序之間共享。如果pool傳遞給map方法,則此設定無效。
示例
>>> import torch >>> from tensordict import TensorDict >>> >>> def process_data(data): ... data.set("y", data.get("x") + 1) ... return data >>> if __name__ == "__main__": ... data = TensorDict({"x": torch.zeros(1, 1_000_000)}, [1, 1_000_000]).memmap_() ... data = data.map(process_data, dim=1) ... print(data["y"][:, :10]) ... tensor([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
- map_iter(fn: Callable[[TensorDictBase], TensorDictBase | None], dim: int = 0, num_workers: int | None = None, *, shuffle: bool = False, 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 = True, pbar: bool = False, mp_start_method: str | None = None)¶
迭代地將函式對映到 tensordict 沿一個維度的拆分。
這是
map()的可迭代版本。此方法將透過將 tensordict 例項分塊為大小相等的 tensordict,並將操作分派到所需數量的 worker 上來將函式應用於 tensordict 例項。它將一次產生一個結果。
函式簽名應為
Callabe[[TensorDict], Union[TensorDict, Tensor]]。該函式必須是可序列化的。注意
當處理儲存在磁碟上的大型資料集(例如,記憶體對映的 tensordict)時,此方法特別有用,其中塊將是原始資料的零複製切片,可以幾乎零成本地傳遞到程序。 這允許以很小的代價處理非常大的資料集(例如,超過 Tb)。
注意
此函式可用於表示資料集並從中載入資料,類似於 dataloader 的方式。
- 引數:
- 關鍵字引數:
shuffle (bool, optional) – 是否應全域性打亂索引。如果為
True,則每個批次將包含非連續樣本。如果index_with_generator=False並且 shuffle=True`,則會引發錯誤。預設為False。chunksize (int, optional) – 每個資料塊的大小。
chunksize為 0 將沿所需的維度解繫結 tensordict 並在應用函式後重新堆疊它,而chunksize>0將拆分 tensordict 並在生成的 tensordict 列表上呼叫torch.cat()。 如果未提供,塊的數量將等於工作程式的數量。 對於非常大的 tensordict,如此大的塊可能不適合在記憶體中進行操作,並且可能需要更多塊才能使操作在實踐中可行。 此引數與num_chunks互斥。num_chunks (int, optional) – 將 tensordict 分成塊的數量。 如果未提供,塊的數量將等於工作程式的數量。 對於非常大的 tensordict,如此大的塊可能不適合在記憶體中進行操作,並且可能需要更多塊才能使操作在實踐中可行。 此引數與
chunksize互斥。pool (mp.Pool, optional) – 用於執行作業的多程序池例項。 如果未提供,則將在
map方法中建立一個池。generator (torch.Generator, optional) –
用於播種的生成器。 將從中生成一個基本種子,並且池的每個工作程式都將使用提供的種子遞增一個從
0到num_workers的唯一整數來播種。 如果未提供生成器,則將使用一個隨機整數作為種子。 要使用未播種的工作程式,應單獨建立一個池並直接傳遞給map()。注意
提供一個低值的種子時應謹慎,因為這可能會導致實驗之間的自相關,例如:如果請求了 8 個工作程式,並且種子為 4,則工作程式種子將從 4 到 11。如果種子為 5,則工作程式種子將從 5 到 12。這兩個實驗將有 7 個種子的重疊,這可能會對結果產生意想不到的影響。
注意
worker 初始化的目標是讓每個 worker 擁有獨立的種子,而**不是**讓 map 方法的每次呼叫都產生可復現的結果。 換句話說,由於無法知道哪個 worker 將選擇哪個任務,因此兩個實驗可能並且很可能會返回不同的結果。但是,我們可以確保每個 worker 都有不同的種子,並且每個 worker 上的偽隨機操作是不相關的。
max_tasks_per_child (int, optional) – 每個子程序選擇的最大任務數。預設為
None,即對任務數量沒有限制。worker_threads (int, optional) – worker 使用的執行緒數。預設為
1。index_with_generator (bool, optional) –
如果為
True,則將在查詢期間完成 tensordict 的拆分/分塊,從而節省初始化時間。請注意,chunk()和split()比索引(在生成器中使用)效率高得多,因此在初始化時節省處理時間可能會對總執行時間產生負面影響。預設為True。注意
對於
map_iter和map,index_with_generator的預設值不同,前者假定將 TensorDict 的拆分版本儲存在記憶體中成本過高。pbar (bool, optional) – 如果為
True,將顯示進度條。需要安裝 tqdm。預設為False。mp_start_method (str, optional) – 多程序的啟動方法。如果未提供,將使用預設啟動方法。接受的字串為
"fork"和"spawn"。請記住,使用"fork"啟動方法時,"cuda"張量不能在程序之間共享。如果pool傳遞給map方法,則此設定無效。
示例
>>> import torch >>> from tensordict import TensorDict >>> >>> def process_data(data): ... data.unlock_() ... data.set("y", data.get("x") + 1) ... return data >>> if __name__ == "__main__": ... data = TensorDict({"x": torch.zeros(1, 1_000_000)}, [1, 1_000_000]).memmap_() ... for sample in data.map_iter(process_data, dim=1, chunksize=5): ... print(sample["y"]) ... break ... tensor([[1., 1., 1., 1., 1.]])
- masked_fill(*args, **kwargs)¶
masked_fill 的非原地版本。
- 引數:
mask (boolean torch.Tensor) – 要填充的值的掩碼。形狀必須與 tensordict 的批大小匹配。
value – 用於填充張量的值。
- 返回值:
self
示例
>>> td = TensorDict(source={'a': torch.zeros(3, 4)}, ... batch_size=[3]) >>> mask = torch.tensor([True, False, False]) >>> td1 = td.masked_fill(mask, 1.0) >>> td1.get("a") tensor([[1., 1., 1., 1.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
- masked_fill_(*args, **kwargs)¶
用所需的值填充對應於掩碼的值。
- 引數:
mask (boolean torch.Tensor) – 要填充的值的掩碼。形狀必須與 tensordict 的批大小匹配。
value – 用於填充張量的值。
- 返回值:
self
示例
>>> td = TensorDict(source={'a': torch.zeros(3, 4)}, ... batch_size=[3]) >>> mask = torch.tensor([True, False, False]) >>> td.masked_fill_(mask, 1.0) >>> td.get("a") tensor([[1., 1., 1., 1.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
- masked_select(mask: Tensor) T¶
遮蔽 TensorDict 的所有張量,並返回一個新的 TensorDict 例項,該例項具有指向遮蔽值的相似鍵。
- 引數:
mask (torch.Tensor) – 用於張量的布林掩碼。形狀必須與 TensorDict 的
batch_size匹配。
示例
>>> td = TensorDict(source={'a': torch.zeros(3, 4)}, ... batch_size=[3]) >>> mask = torch.tensor([True, False, False]) >>> td_mask = td.masked_select(mask) >>> td_mask.get("a") tensor([[0., 0., 0., 0.]])
- max(dim: int | NO_DEFAULT = _NoDefault.ZERO, keepdim: bool = False, *, reduce: bool | None = None, return_indices: bool = True) TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的最大值。
- 引數:
- 關鍵字引數:
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.max(dim=0) max( indices=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.int64, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), vals=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.max() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.max(reduce=True) tensor(3.2942)
- maximum(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) T¶
計算
self和other的逐元素最大值。- 引數:
other (TensorDict or Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- maximum_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
maximum()的原地版本。注意
原地
maximum不支援default關鍵字引數。
- classmethod maybe_dense_stack(input, dim=0, *, out=None, **kwargs)¶
嘗試製作 tensordict 的密集堆疊,並在需要時回退到惰性堆疊。
有關詳細資訊,請參見
maybe_dense_stack()。
- mean(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的平均值。
- 引數:
dim (int, int 元組, str, 可選) – 如果為
None,則返回包含所有葉子節點平均值的無維度 tensordict(如果可以計算)。如果為整數或整數元組,則僅當此維度與 tensordict 形狀相容時,才對指定的維度呼叫 mean。目前只允許使用 “feature” 字串。使用 dim=”feature” 將實現對所有特徵維度的縮減。如果 reduce=True,則返回一個形狀與 TensorDict 的 batch-size 相同的張量。否則,將返回一個新的 tensordict,其結構與self相同,但特徵維度已縮減。keepdim (bool) – 輸出張量是否保留 dim。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回張量的所需資料型別。如果指定,輸入張量在執行操作之前會被強制轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:
None。reduce (bool, 可選) – 如果為
True,則將在所有 TensorDict 值上進行規約,並返回單個規約後的 tensor。預設為False。
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.mean(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.mean() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.mean(reduce=True) tensor(-0.0547) >>> td.mean(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.mean(reduce=True, dim="feature") tensor([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]) >>> td.mean(reduce=True, dim=0) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]])
- 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¶
將所有張量寫入新 tensordict 中對應的記憶體對映張量。
- 引數:
prefix (str) – 記憶體對映張量將儲存的目錄字首。目錄樹結構將模仿 tensordict 的結構。
copy_existing (bool) – 如果為 False(預設值),如果 tensordict 中的條目已經是儲存在磁碟上的張量,並且有相關聯的檔案,但沒有根據字首儲存在正確的位置,則會引發異常。如果為
True,任何現有張量都將被複制到新位置。
- 關鍵字引數:
num_threads (int, 可選) – 用於寫入 memmap 張量的執行緒數。預設為 0。
return_early (bool, 可選) – 如果
True且num_threads>0,該方法將返回 tensordict 的 future。share_non_tensor (bool, 可選) – 如果為
True,非張量資料將在程序之間共享,並且在單個節點內的任何 worker 上執行的寫入操作(例如,就地更新或設定)將更新所有其他 worker 上的值。 如果非張量葉子的數量很高(例如,共享大量的非張量資料堆疊),這可能會導致 OOM 或類似的錯誤。預設為False。existsok (bool, 可選) – 如果為
False,如果張量已存在於同一路徑中,則會引發異常。預設為True。
然後,TensorDict 被鎖定,這意味著任何非就地寫入操作都會引發異常(例如,重新命名、設定或刪除條目)。一旦 tensordict 被解鎖,memory-mapped 屬性將變為
False,因為無法再保證跨程序標識。- 返回值:
如果
return_early=False,則返回一個新的 tensordict,其中張量儲存在磁碟上,否則返回一個TensorDictFuture例項。
注意
以這種方式序列化對於深度巢狀的 tensordict 可能會很慢,因此不建議在訓練迴圈中呼叫此方法。
- memmap_(prefix: Optional[str] = None, copy_existing: bool = False, num_threads: int = 0) TensorDictBase¶
將所有張量就地寫入對應的記憶體對映張量。
- 引數:
prefix (str) – 記憶體對映張量將儲存的目錄字首。目錄樹結構將模仿 tensordict 的結構。
copy_existing (bool) – 如果為 False(預設值),如果 tensordict 中的條目已經是儲存在磁碟上的張量,並且有相關聯的檔案,但沒有根據字首儲存在正確的位置,則會引發異常。如果為
True,任何現有張量都將被複制到新位置。
- 關鍵字引數:
num_threads (int, 可選) – 用於寫入 memmap 張量的執行緒數。預設為 0。
return_early (bool, 可選) – 如果為
True且num_threads>0,則該方法將返回 tensordict 的 future 物件。 可以使用 future.result() 查詢生成的 tensordict。share_non_tensor (bool, 可選) – 如果為
True,非張量資料將在程序之間共享,並且在單個節點內的任何 worker 上執行的寫入操作(例如,就地更新或設定)將更新所有其他 worker 上的值。 如果非張量葉子的數量很高(例如,共享大量的非張量資料堆疊),這可能會導致 OOM 或類似的錯誤。預設為False。existsok (bool, 可選) – 如果為
False,如果張量已存在於同一路徑中,則會引發異常。預設為True。
然後,TensorDict 被鎖定,這意味著任何非就地寫入操作都會引發異常(例如,重新命名、設定或刪除條目)。一旦 tensordict 被解鎖,memory-mapped 屬性將變為
False,因為無法再保證跨程序標識。- 返回值:
如果
return_early=False,則返回 self,否則返回一個TensorDictFuture例項。
注意
以這種方式序列化對於深度巢狀的 tensordict 可能會很慢,因此不建議在訓練迴圈中呼叫此方法。
- memmap_like(prefix: str | None = None, copy_existing: bool = False, num_threads: int = 0) T¶
建立一個與原始 tensordict 具有相同形狀的無內容記憶體對映 tensordict。
- 引數:
prefix (str) – 記憶體對映張量將儲存的目錄字首。目錄樹結構將模仿 tensordict 的結構。
copy_existing (bool) – 如果為 False(預設值),如果 tensordict 中的條目已經是儲存在磁碟上的張量,並且有相關聯的檔案,但沒有根據字首儲存在正確的位置,則會引發異常。如果為
True,任何現有張量都將被複制到新位置。
- 關鍵字引數:
num_threads (int, 可選) – 用於寫入 memmap 張量的執行緒數。預設為 0。
return_early (bool, 可選) – 如果
True且num_threads>0,該方法將返回 tensordict 的 future。share_non_tensor (bool, 可選) – 如果為
True,非張量資料將在程序之間共享,並且在單個節點內的任何 worker 上執行的寫入操作(例如,就地更新或設定)將更新所有其他 worker 上的值。 如果非張量葉子的數量很高(例如,共享大量的非張量資料堆疊),這可能會導致 OOM 或類似的錯誤。預設為False。existsok (bool, 可選) – 如果為
False,如果張量已存在於同一路徑中,則會引發異常。預設為True。
然後,TensorDict 被鎖定,這意味著任何非就地寫入操作都會引發異常(例如,重新命名、設定或刪除條目)。一旦 tensordict 被解鎖,memory-mapped 屬性將變為
False,因為無法再保證跨程序標識。- 返回值:
如果
return_early=False,則返回一個新的TensorDict例項,其中資料儲存為記憶體對映張量,否則返回一個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,則重新整理其內容。如果沒有與它關聯的路徑,此方法將引發異常。
- min(dim: int | NO_DEFAULT = _NoDefault.ZERO, keepdim: bool = False, *, reduce: bool | None = None, return_indices: bool = True) TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的最小值。
- 引數:
- 關鍵字引數:
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.min(dim=0) min( indices=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.int64, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), vals=TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False), batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.min() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.min(reduce=True) tensor(-2.9953)
- minimum(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) T¶
計算
self和other的逐元素最小值。- 引數:
other (TensorDict or Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- minimum_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
minimum()的原地版本。注意
原地
minimum不支援default關鍵字引數。
- modules() Iterator[Module]¶
返回網路中所有模組的迭代器。
- Yields:
Module – 網路中的一個模組
注意
重複的模組只返回一次。在下面的例子中,
l只會被返回一次。示例
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- mtia(device: Optional[Union[int, device]] = None) T¶
將所有模型引數和緩衝區移動到 MTIA。
這也使得相關的引數和緩衝區成為不同的物件。因此,如果模組在最佳化時將駐留在 MTIA 上,則應在構建最佳化器之前呼叫此方法。
注意
此方法會就地修改模組。
- 引數:
device (int, optional) – 如果指定,所有引數都將複製到該裝置
- 返回值:
self
- 返回型別:
模組
- mul(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) T¶
將
other乘以self。\[\text{{out}}_i = \text{{input}}_i \times \text{{other}}_i\]支援廣播、型別提升以及整數、浮點數和複數輸入。
- 引數:
other (TensorDict, Tensor 或 Number) – 要從
self中減去的 tensor 或數字。- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- mul_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
mul()的原地版本。注意
原地
mul不支援default關鍵字引數。
- named_apply(fn: Callable, *others: TensorDictBase, batch_size: Optional[Sequence[int]] = None, device: torch.device | None = _NoDefault.ZERO, names: Optional[Sequence[str]] = _NoDefault.ZERO, inplace: bool = False, default: Any = _NoDefault.ZERO, filter_empty: bool | None = None, call_on_nested: bool = False, **constructor_kwargs) tensordict.base.TensorDictBase | None¶
將一個鍵條件可呼叫物件應用於 tensordict 中儲存的所有值,並將它們設定在一個新的 tensordict 中。
可呼叫物件的簽名必須是
Callable[Tuple[str, Tensor, ...], Optional[Union[Tensor, TensorDictBase]]]。- 引數:
fn (Callable) – 要應用於 tensordict 中的 (name, tensor) 對的函式。對於每個葉子節點,僅使用其葉子名稱(而不是完整的 NestedKey)。
*others (TensorDictBase 例項, optional) – 如果提供,這些 tensordict 例項應具有與 self 匹配的結構。
fn引數應接收與 tensordict 數量一樣多的未命名輸入,包括 self。 如果其他 tensordict 缺少條目,則可以透過default關鍵字引數傳遞預設值。nested_keys (bool, 可選) – 如果
True,將使用到葉子節點的完整路徑。預設為False,即僅將最後一個字串傳遞給函式。batch_size (int 序列, 可選) – 如果提供,生成的 TensorDict 將具有所需的 batch_size。
batch_size引數應與轉換後的 batch_size 匹配。 這是一個僅關鍵字引數。device (torch.device, 可選) – 生成的裝置(如果有)。
names (str 列表, 可選) – 新的維度名稱,以防修改了 batch_size。
inplace (bool, 可選) – 如果為 True,則進行原地修改。預設為 False。這是一個僅關鍵字引數。
default (Any, 可選) – 其他 tensordict 中缺失條目的預設值。 如果未提供,缺失的條目將引發 KeyError。
filter_empty (bool, 可選) – 如果
True,將過濾掉空的 tensordict。這也可以降低計算成本,因為不會建立和銷燬空的資料結構。為了向後相容,預設為False。propagate_lock (bool, 可選) – 如果
True,鎖定的 tensordict 將生成另一個鎖定的 tensordict。預設為False。call_on_nested (bool, 可選) –
如果
True,則將在第一級張量和容器(TensorDict 或 tensorclass)上呼叫該函式。 在這種情況下,func負責將其呼叫傳播到巢狀級別。 這允許在將呼叫傳播到巢狀 tensordict 時進行細粒度控制。 如果False,則僅在葉子上呼叫該函式,並且apply將負責將該函式分派到所有葉子上。>>> td = TensorDict({"a": {"b": [0.0, 1.0]}, "c": [1.0, 2.0]}) >>> def mean_tensor_only(val): ... if is_tensor_collection(val): ... raise RuntimeError("Unexpected!") ... return val.mean() >>> td_mean = td.apply(mean_tensor_only) >>> def mean_any(val): ... if is_tensor_collection(val): ... # Recurse ... return val.apply(mean_any, call_on_nested=True) ... return val.mean() >>> td_mean = td.apply(mean_any, call_on_nested=True)
out (TensorDictBase, 可選) –
一個用於寫入結果的 tensordict。 這可以用於避免建立新的 tensordict
>>> td = TensorDict({"a": 0}) >>> td.apply(lambda x: x+1, out=td) >>> assert (td==1).all()
警告
如果在 tensordict 上執行的操作需要訪問多個鍵才能進行單個計算,則提供等於
self的out引數可能會導致操作靜默地提供錯誤的結果。 例如>>> td = TensorDict({"a": 1, "b": 1}) >>> td.apply(lambda x: x+td["a"])["b"] # Right! tensor(2) >>> td.apply(lambda x: x+td["a"], out=td)["b"] # Wrong! tensor(3)
**constructor_kwargs – 要傳遞給 TensorDict 建構函式的其他關鍵字引數。
- 返回值:
一個具有 transformed_in 張量的新 tensordict。
示例
>>> td = TensorDict({ ... "a": -torch.ones(3), ... "nested": {"a": torch.ones(3), "b": torch.zeros(3)}}, ... batch_size=[3]) >>> def name_filter(name, tensor): ... if name == "a": ... return tensor >>> td.named_apply(name_filter) TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), nested: TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False) >>> def name_filter(name, *tensors): ... if name == "a": ... r = 0 ... for tensor in tensors: ... r = r + tensor ... return tensor >>> out = td.named_apply(name_filter, td) >>> print(out) TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False), nested: TensorDict( fields={ a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False)}, batch_size=torch.Size([3]), device=None, is_shared=False) >>> print(out["a"]) tensor([-1., -1., -1.])
注意
如果該函式返回
None,則忽略該條目。 這可用於過濾 tensordict 中的資料>>> td = TensorDict({"1": 1, "2": 2, "b": {"2": 2, "1": 1}}, []) >>> def name_filter(name, tensor): ... if name == "1": ... return tensor >>> td.named_apply(name_filter) TensorDict( fields={ 1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ 1: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[tuple[str, torch.Tensor]]¶
返回一個模組緩衝區上的迭代器,產生緩衝區的名稱和緩衝區本身。
- 引數:
- Yields:
(str, torch.Tensor) – 包含名稱和緩衝區的元組
示例
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[tuple[str, 'Module']]¶
返回一個直接子模組上的迭代器,產生模組的名稱和模組本身。
- Yields:
(str, Module) – 包含名稱和子模組的元組
示例
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Optional[set['Module']] = None, prefix: str = '', remove_duplicate: bool = True)¶
返回網路中所有模組上的迭代器,產生模組的名稱以及模組本身。
- 引數:
memo – 一個備忘錄,用於儲存已新增到結果中的模組集
prefix – 將被新增到模組名稱的字首
remove_duplicate – 是否移除結果中重複的模組例項
- Yields:
(str, Module) – 名稱和模組的元組
注意
重複的模組只返回一次。在下面的例子中,
l只會被返回一次。示例
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[tuple[str, torch.nn.parameter.Parameter]]¶
返回一個模組引數的迭代器,產生引數的名稱和引數本身。
- 引數:
- Yields:
(str, Parameter) – 包含名稱和引數的元組
示例
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- property names¶
tensordict的維度名稱。
可以使用
names引數在構造時設定名稱。另請參閱
refine_names(),瞭解有關如何在構造後設置名稱的詳細資訊。
- nanmean(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有非 NaN 元素的平均值。
- 引數:
dim (int, tuple of int, optional) – 如果
None,則返回一個包含所有葉子的平均值的無維度 tensordict(如果可以計算)。 如果是整數或整數元組,則僅當此維度與 tensordict 形狀相容時,才對指定維度呼叫 mean。 目前只允許使用 “feature” 字串。 使用 dim=”feature” 將實現對所有特徵維度的縮減。 如果 reduce=True,將返回一個與 TensorDict 的批大小形狀相同的張量。 否則,將返回一個與self具有相同結構,但特徵維度縮減的 tensordict。keepdim (bool) – 輸出張量是否保留 dim。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回張量的所需資料型別。如果指定,輸入張量在執行操作之前會被強制轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:
None。reduce (bool, 可選) – 如果為
True,則將在所有 TensorDict 值上進行規約,並返回單個規約後的 tensor。預設為False。
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.nanmean(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.nanmean() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.nanmean(reduce=True) tensor(-0.0547) >>> td.nanmean(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.nanmean(reduce=True, dim="feature") tensor([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]) >>> td.nanmean(reduce=True, dim=0) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]])
- nansum(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有非 NaN 元素的總和。
- 引數:
dim (int, tuple of int, optional) – 如果
None,則返回一個包含所有葉子的總和值的無維度 tensordict(如果可以計算)。 如果是整數或整數元組,則僅當此維度與 tensordict 形狀相容時,才對指定維度呼叫 sum。 目前只允許使用 “feature” 字串。 使用 dim=”feature” 將實現對所有特徵維度的縮減。 如果 reduce=True,將返回一個與 TensorDict 的批大小形狀相同的張量。 否則,將返回一個與self具有相同結構,但特徵維度縮減的 tensordict。keepdim (bool) – 輸出張量是否保留 dim。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回張量的所需資料型別。如果指定,輸入張量在執行操作之前會被強制轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:
None。reduce (bool, 可選) – 如果為
True,則將在所有 TensorDict 值上進行規約,並返回單個規約後的 tensor。預設為False。
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.nansum(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.nansum() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.nansum(reduce=True) tensor(-0.) >>> td.nansum(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.nansum(reduce=True, dim="feature") tensor([[15., 15., 15., 15.], [15., 15., 15., 15.], [15., 15., 15., 15.]]) >>> td.nansum(reduce=True, dim=0) tensor([[9., 9., 9., 9., 9.], [9., 9., 9., 9., 9.], [9., 9., 9., 9., 9.], [9., 9., 9., 9., 9.]])
- property ndim: int¶
參見
batch_dims()。
- ndimension() int¶
參見
batch_dims()。
- neg() T¶
計算 TensorDict 中每個元素的
neg()值。
- neg_() T¶
就地計算 TensorDict 中每個元素的
neg()值。
- new_empty(*size: Size, dtype: Optional[dtype] = None, device: Union[device, str, int] = _NoDefault.ZERO, requires_grad: bool = False, layout: layout = torch.strided, pin_memory: Optional[bool] = None)¶
返回一個大小為
size且包含空 tensors 的 TensorDict。預設情況下,返回的 TensorDict 具有與此 tensordict 相同的
torch.dtype和torch.device。- 引數:
size (int...) – 定義輸出 tensor 形狀的整數列表、元組或 torch.Size。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回的 tensordict 的期望型別。預設值:如果
None,則 torch.dtype 將保持不變。device (torch.device, 可選) – 返回的 tensordict 的期望裝置。預設值:如果
None,則torch.device將保持不變。requires_grad (bool, 可選) – 如果 autograd 應該記錄返回 tensors 的操作。預設值:
False。layout (torch.layout, 可選) – 返回的 TensorDict 值的期望佈局。預設值:
torch.strided。pin_memory (bool, 可選) – 如果設定,返回的 tensor 將分配在鎖頁記憶體中。僅適用於 CPU tensors。預設值:
False。
- new_full(size: Size, fill_value, *, dtype: Optional[dtype] = None, device: Union[device, str, int] = _NoDefault.ZERO, requires_grad: bool = False, layout: layout = torch.strided, pin_memory: Optional[bool] = None)¶
返回一個大小為
size並填充了 1 的 TensorDict。預設情況下,返回的 TensorDict 具有與此 tensordict 相同的
torch.dtype和torch.device。- 引數:
size (整數序列) – 定義輸出 tensor 形狀的整數列表、元組或 torch.Size。
fill_value (標量) – 用於填充輸出 tensor 的數字。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回的 tensordict 的期望型別。預設值:如果
None,則 torch.dtype 將保持不變。device (torch.device, 可選) – 返回的 tensordict 的期望裝置。預設值:如果
None,則torch.device將保持不變。requires_grad (bool, 可選) – 如果 autograd 應該記錄返回 tensors 的操作。預設值:
False。layout (torch.layout, 可選) – 返回的 TensorDict 值的期望佈局。預設值:
torch.strided。pin_memory (bool, 可選) – 如果設定,返回的 tensor 將分配在鎖頁記憶體中。僅適用於 CPU tensors。預設值:
False。
- new_ones(*size: Size, dtype: Optional[dtype] = None, device: Union[device, str, int] = _NoDefault.ZERO, requires_grad: bool = False, layout: layout = torch.strided, pin_memory: Optional[bool] = None)¶
返回一個大小為
size並填充了 1 的 TensorDict。預設情況下,返回的 TensorDict 具有與此 tensordict 相同的
torch.dtype和torch.device。- 引數:
size (int...) – 定義輸出 tensor 形狀的整數列表、元組或 torch.Size。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回的 tensordict 的期望型別。預設值:如果
None,則 torch.dtype 將保持不變。device (torch.device, 可選) – 返回的 tensordict 的期望裝置。預設值:如果
None,則torch.device將保持不變。requires_grad (bool, 可選) – 如果 autograd 應該記錄返回 tensors 的操作。預設值:
False。layout (torch.layout, 可選) – 返回的 TensorDict 值的期望佈局。預設值:
torch.strided。pin_memory (bool, 可選) – 如果設定,返回的 tensor 將分配在鎖頁記憶體中。僅適用於 CPU tensors。預設值:
False。
- new_tensor(data: torch.Tensor | tensordict.base.TensorDictBase, *, dtype: Optional[dtype] = None, device: Union[device, str, int] = _NoDefault.ZERO, requires_grad: bool = False, pin_memory: Optional[bool] = None)¶
返回一個以
data張量為資料的新 TensorDict。預設情況下,返回的 TensorDict 值與此張量具有相同的
torch.dtype和torch.device。data也可以是一個張量集合(TensorDict或tensorclass),在這種情況下,new_tensor方法會迭代self和data的張量對。- 引數:
data (torch.Tensor 或 TensorDictBase) – 要複製的資料。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回的 tensordict 的期望型別。預設值:如果
None,則 torch.dtype 將保持不變。device (torch.device, 可選) – 返回的 tensordict 的期望裝置。預設值:如果
None,則torch.device將保持不變。requires_grad (bool, 可選) – 如果 autograd 應該記錄返回 tensors 的操作。預設值:
False。pin_memory (bool, 可選) – 如果設定,返回的 tensor 將分配在鎖頁記憶體中。僅適用於 CPU tensors。預設值:
False。
- new_zeros(*size: Size, dtype: Optional[dtype] = None, device: Union[device, str, int] = _NoDefault.ZERO, requires_grad: bool = False, layout: layout = torch.strided, pin_memory: Optional[bool] = None)¶
返回一個大小為
size且填充 0 的 TensorDict。預設情況下,返回的 TensorDict 具有與此 tensordict 相同的
torch.dtype和torch.device。- 引數:
size (int...) – 定義輸出 tensor 形狀的整數列表、元組或 torch.Size。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回的 tensordict 的期望型別。預設值:如果
None,則 torch.dtype 將保持不變。device (torch.device, 可選) – 返回的 tensordict 的期望裝置。預設值:如果
None,則torch.device將保持不變。requires_grad (bool, 可選) – 如果 autograd 應該記錄返回 tensors 的操作。預設值:
False。layout (torch.layout, 可選) – 返回的 TensorDict 值的期望佈局。預設值:
torch.strided。pin_memory (bool, 可選) – 如果設定,返回的 tensor 將分配在鎖頁記憶體中。僅適用於 CPU tensors。預設值:
False。
- norm(*, out=None, dtype: torch.dtype | None = None)¶
計算 tensordict 中每個張量的範數。
- 關鍵字引數:
out (TensorDict, 可選) – 輸出的 tensordict。
dtype (torch.dtype, 可選) – 輸出的資料型別 (torch>=2.4)。
- numpy()¶
將 tensordict 轉換為 (可能是巢狀的) numpy 陣列字典。
非張量資料按原樣公開。
示例
>>> from tensordict import TensorDict >>> import torch >>> data = TensorDict({"a": {"b": torch.zeros(()), "c": "a string!"}}) >>> print(data) TensorDict( fields={ a: TensorDict( fields={ b: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), c: NonTensorData(data=a string!, batch_size=torch.Size([]), device=None)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> print(data.numpy()) {'a': {'b': array(0., dtype=float32), 'c': 'a string!'}}
- param_count(*, count_duplicates: bool = True) int¶
計算引數的數量 (可索引專案的總數),僅考慮張量。
- 關鍵字引數:
count_duplicates (bool) – 是否將重複的張量視為獨立的。 如果為
False,則只會丟棄完全相同的張量(來自公共基礎張量的相同檢視但不同的 ID 將被計算兩次)。 預設為 True(假設每個張量都是單個副本)。
- parameters(recurse: bool = True) Iterator[Parameter]¶
返回模組引數的迭代器。
這通常傳遞給最佳化器。
- 引數:
recurse (bool) – 如果為 True,則產生此模組和所有子模組的引數。 否則,僅產生作為此模組直接成員的引數。
- Yields:
Parameter – 模組引數
示例
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- permute(*args, **kwargs)¶
返回一個 tensordict 的檢視,其中批次維度根據 dims 排列。
- 引數:
*dims_list (int) – tensordict 批次維度的新順序。 或者,可以提供一個整數的可迭代物件。
dims (int 列表) – 呼叫 permute(…) 的另一種方式。
- 返回值:
一個新的 tensordict,其批次維度按照所需的順序排列。
示例
>>> tensordict = TensorDict({"a": torch.randn(3, 4, 5)}, [3, 4]) >>> print(tensordict.permute([1, 0])) PermutedTensorDict( source=TensorDict( fields={ a: Tensor(torch.Size([3, 4, 5]), dtype=torch.float32)}, batch_size=torch.Size([3, 4]), device=cpu, is_shared=False), op=permute(dims=[1, 0])) >>> print(tensordict.permute(1, 0)) PermutedTensorDict( source=TensorDict( fields={ a: Tensor(torch.Size([3, 4, 5]), dtype=torch.float32)}, batch_size=torch.Size([3, 4]), device=cpu, is_shared=False), op=permute(dims=[1, 0])) >>> print(tensordict.permute(dims=[1, 0])) PermutedTensorDict( source=TensorDict( fields={ a: Tensor(torch.Size([3, 4, 5]), dtype=torch.float32)}, batch_size=torch.Size([3, 4]), device=cpu, is_shared=False), op=permute(dims=[1, 0]))
- pin_memory(*args, **kwargs)¶
在儲存的張量上呼叫
pin_memory()。- 引數:
num_threads (int 或 str) – 如果提供,則用於在葉子上呼叫
pin_memory的執行緒數。 預設為None,這會在ThreadPoolExecutor(max_workers=None)中設定大量的執行緒。 要在主執行緒上執行對pin_memory()的所有呼叫,請傳遞num_threads=0。inplace (bool, 可選) – 如果
True,則 tensordict 會被就地修改。 預設為False。
- pin_memory_(num_threads: int | str = 0) T¶
在儲存的張量上呼叫
pin_memory()並返回就地修改的 TensorDict。
- pop(key: NestedKey, default: Any = _NoDefault.ZERO) Tensor¶
從 tensordict 中移除並返回一個值。
如果該值不存在且未提供預設值,則會丟擲 KeyError。
- 引數:
key (str 或 巢狀鍵) – 要查詢的條目。
default (Any, 可選) – 如果找不到鍵,則返回的值。
示例
>>> td = TensorDict({"1": 1}, []) >>> one = td.pop("1") >>> assert one == 1 >>> none = td.pop("1", default=None) >>> assert none is None
- popitem()¶
移除最後插入 TensorDict 的項。
popitem將僅返回非巢狀值。
- pow(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: str | torch.Tensor | None = None) T¶
計算
self中每個元素的other次冪,並返回一個包含結果的張量。other可以是單個float數字,Tensor 或TensorDict。當
other是一個張量時,input和other的形狀必須是可廣播的。- 引數:
other (float, tensor 或 tensordict) – 指數值
- 關鍵字引數:
default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- pow_(other: tensordict.base.TensorDictBase | torch.Tensor) T¶
是
pow()的原地 (in-place) 版本。注意
原地 (Inplace)
pow不支援default關鍵字引數。
- prod(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的乘積。
- 引數:
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回張量的所需資料型別。如果指定,輸入張量在執行操作之前會被強制轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:
None。reduce (bool, 可選) – 如果為
True,則將在所有 TensorDict 值上進行規約,並返回單個規約後的 tensor。預設為False。
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.prod(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.prod() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.prod(reduce=True) tensor(-0.) >>> td.prod(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.prod(reduce=True, dim="feature") tensor([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]) >>> td.prod(reduce=True, dim=0) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]])
- qint32()¶
將所有張量轉換為
torch.qint32。
- qint8()¶
將所有張量轉換為
torch.qint8。
- quint4x2()¶
將所有張量轉換為
torch.quint4x2。
- quint8()¶
將所有張量轉換為
torch.quint8。
- reciprocal() T¶
計算 TensorDict 中每個元素的
reciprocal()值。
- reciprocal_() T¶
原地 (in-place) 計算 TensorDict 中每個元素的
reciprocal()值。
- record_stream(stream: Stream) T¶
將 tensordict 標記為已被該流使用。
當 tensordict 被釋放時,確保張量記憶體不會被其他張量重用,直到在釋放時流上排隊的所有工作完成為止。
有關更多資訊,請參見
record_stream()。
- recv(src: int, *, group: 'torch.distributed.ProcessGroup' | None = None, init_tag: int = 0, pseudo_rand: bool = False) int¶
接收 tensordict 的內容並使用它更新內容。
請檢視 send 方法中的示例以瞭解上下文。
- 引數:
src (int) – 源 worker 的排名。
- 關鍵字引數:
- reduce(dst, op=None, async_op=False, return_premature=False, group=None) None¶
在所有機器上縮減 tensordict。
只有具有
rankdst 的程序才會收到最終結果。
- refine_names(*names) T¶
根據名稱細化 self 的維度名稱。
細化是重新命名的一種特殊情況,它“提升”了未命名的維度。 可以將 None 維度細化為具有任何名稱; 命名的維度只能細化為具有相同的名稱。
由於命名張量可以與未命名張量共存,因此細化名稱提供了一種編寫命名張量感知程式碼的好方法,該程式碼可以與命名張量和未命名張量一起使用。
名稱最多可以包含一個省略號 (…)。 省略號被貪婪地擴充套件; 它被就地擴充套件以使用 self.names 中相應索引的名稱,將名稱填充到與 self.dim() 相同的長度。
返回:與輸入相同,但維度根據輸入命名的 tensordict。
示例
>>> td = TensorDict({}, batch_size=[3, 4, 5, 6]) >>> tdr = td.refine_names(None, None, None, "d") >>> assert tdr.names == [None, None, None, "d"] >>> tdr = td.refine_names("a", None, None, "d") >>> assert tdr.names == ["a", None, None, "d"]
- register_backward_hook(hook: Callable[[Module, Union[tuple[torch.Tensor, ...], Tensor], Union[tuple[torch.Tensor, ...], Tensor]], Union[None, tuple[torch.Tensor, ...], Tensor]]) RemovableHandle¶
在模組上註冊一個反向鉤子。
此函式已被棄用,推薦使用
register_full_backward_hook(),並且此函式的行為將在未來版本中更改。- 返回值:
一個控制代碼,可用於透過呼叫
handle.remove()來刪除新增的鉤子。- 返回型別:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Optional[Tensor], persistent: bool = True) None¶
向模組新增一個緩衝區。
這通常用於註冊一個不應被視為模型引數的緩衝區。 例如,BatchNorm 的
running_mean不是一個引數,但它是模組狀態的一部分。 預設情況下,緩衝區是持久的,並將與引數一起儲存。 可以透過將persistent設定為False來更改此行為。 持久緩衝區和非持久緩衝區之間的唯一區別是後者不會是此模組的state_dict的一部分。可以使用給定的名稱作為屬性訪問緩衝區。
- 引數:
name (str) – 緩衝區的名稱。 可以使用給定的名稱從此模組訪問緩衝區
tensor (Tensor 或 None) – 要註冊的緩衝區。 如果
None,則忽略在緩衝區上執行的操作,例如cuda。 如果None,則緩衝區不包含在模組的state_dict中。persistent (bool) – 緩衝區是否是此模組的
state_dict的一部分。
示例
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Union[Callable[[T, tuple[Any, ...], Any], Optional[Any]], Callable[[T, tuple[Any, ...], dict[str, Any], Any], Optional[Any]]], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle¶
在模組上註冊一個前向鉤子。
每次
forward()計算出一個輸出後,都會呼叫該鉤子。如果
with_kwargs為False或未指定,則輸入僅包含傳遞給模組的位置引數。 關鍵字引數不會傳遞給鉤子,僅傳遞給forward。 鉤子可以修改輸出。 它可以就地修改輸入,但由於在呼叫forward()之後呼叫它,因此它不會對前向產生影響。 鉤子應具有以下簽名hook(module, args, output) -> None or modified output
如果
with_kwargs為True,則前向 hook 將會接收傳遞給前向函式的kwargs,並應返回可能被修改的輸出。該 hook 應具有以下簽名:hook(module, args, kwargs, output) -> None or modified output
- 引數:
hook (Callable) – 要註冊的使用者定義的 hook。
prepend (bool) – 如果
True,則提供的hook將在此torch.nn.modules.Module上所有現有forwardhook 之前觸發。否則,提供的hook將在此torch.nn.modules.Module上所有現有forwardhook 之後觸發。請注意,使用register_module_forward_hook()註冊的全域性forwardhook 將在透過此方法註冊的所有 hook 之前觸發。 預設值:Falsewith_kwargs (bool) – 如果
True,則hook將接收傳遞給前向函式的 kwargs。 預設值:Falsealways_call (bool) – 如果
True,則無論在呼叫 Module 時是否引發異常,都會執行hook。 預設值:False
- 返回值:
一個控制代碼,可用於透過呼叫
handle.remove()來刪除新增的鉤子。- 返回型別:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Union[Callable[[T, tuple[Any, ...]], Optional[Any]], Callable[[T, tuple[Any, ...], dict[str, Any]], Optional[tuple[Any, dict[str, Any]]]]], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle¶
在模組上註冊一個前向預處理 hook。
每次呼叫
forward()之前,都會呼叫該 hook。如果
with_kwargs為 false 或未指定,則輸入僅包含傳遞給模組的位置引數。關鍵字引數不會傳遞給 hook,而只會傳遞給forward。該 hook 可以修改輸入。使用者可以在 hook 中返回一個元組或一個單獨的修改值。如果返回單個值(除非該值已經是元組),我們將把該值包裝到一個元組中。該 hook 應具有以下簽名:hook(module, args) -> None or modified input
如果
with_kwargs為 true,則前向預處理 hook 將會接收傳遞給前向函式的 kwargs。如果 hook 修改了輸入,則應同時返回 args 和 kwargs。該 hook 應具有以下簽名:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- 引數:
hook (Callable) – 要註冊的使用者定義的 hook。
prepend (bool) – 如果為 true,則提供的
hook將在此torch.nn.modules.Module上所有現有forward_prehook 之前觸發。 否則,提供的hook將在此torch.nn.modules.Module上所有現有forward_prehook 之後觸發。 請注意,使用register_module_forward_pre_hook()註冊的全域性forward_prehook 將在透過此方法註冊的所有 hook 之前觸發。 預設值:Falsewith_kwargs (bool) – 如果為 true,則
hook將接收傳遞給前向函式的 kwargs。 預設值:False
- 返回值:
一個控制代碼,可用於透過呼叫
handle.remove()來刪除新增的鉤子。- 返回型別:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Union[tuple[torch.Tensor, ...], Tensor], Union[tuple[torch.Tensor, ...], Tensor]], Union[None, tuple[torch.Tensor, ...], Tensor]], prepend: bool = False) RemovableHandle¶
在模組上註冊一個反向鉤子。
每次計算模組的梯度時,都會呼叫該 hook,即,當且僅當計算模組輸出的梯度時,才會執行該 hook。該 hook 應具有以下簽名:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
grad_input和grad_output是元組,分別包含相對於輸入和輸出的梯度。Hook 不應該修改其引數,但可以選擇性地返回相對於輸入的新梯度,該梯度將代替grad_input用於後續計算。grad_input只對應於作為位置引數給出的輸入,所有 kwarg 引數都會被忽略。對於所有非 Tensor 引數,grad_input和grad_output中的條目都將為None。由於技術原因,當此 hook 應用於 Module 時,其 forward 函式將接收傳遞給 Module 的每個 Tensor 的檢視。同樣,呼叫者將接收由 Module 的 forward 函式返回的每個 Tensor 的檢視。
警告
在使用 backward hooks 時,不允許就地修改輸入或輸出,否則會引發錯誤。
- 引數:
hook (Callable) – 要註冊的,使用者定義的 hook。
prepend (bool) – 如果為 true,則提供的
hook將在該torch.nn.modules.Module上的所有現有backwardhooks 之前觸發。否則,提供的hook將在該torch.nn.modules.Module上的所有現有backwardhooks 之後觸發。請注意,使用register_module_full_backward_hook()註冊的全域性backwardhooks 將在透過此方法註冊的所有 hooks 之前觸發。
- 返回值:
一個控制代碼,可用於透過呼叫
handle.remove()來刪除新增的鉤子。- 返回型別:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Union[tuple[torch.Tensor, ...], Tensor]], Union[None, tuple[torch.Tensor, ...], Tensor]], prepend: bool = False) RemovableHandle¶
在模組上註冊一個 backward pre-hook。
每次計算模組的梯度時,都會呼叫該 hook。該 hook 應具有以下簽名
hook(module, grad_output) -> tuple[Tensor] or None
grad_output是一個元組。 Hook 不應該修改其引數,但可以選擇性地返回相對於輸出的新梯度,該梯度將代替grad_output用於後續計算。對於所有非 Tensor 引數,grad_output中的條目都將為None。由於技術原因,當此 hook 應用於 Module 時,其 forward 函式將接收傳遞給 Module 的每個 Tensor 的檢視。同樣,呼叫者將接收由 Module 的 forward 函式返回的每個 Tensor 的檢視。
警告
在使用 backward hooks 時,不允許就地修改輸入,否則會引發錯誤。
- 引數:
hook (Callable) – 要註冊的,使用者定義的 hook。
prepend (bool) – 如果為 true,則提供的
hook將在該torch.nn.modules.Module上的所有現有backward_prehooks 之前觸發。否則,提供的hook將在該torch.nn.modules.Module上的所有現有backward_prehooks 之後觸發。請注意,使用register_module_full_backward_pre_hook()註冊的全域性backward_prehooks 將在透過此方法註冊的所有 hooks 之前觸發。
- 返回值:
一個控制代碼,可用於透過呼叫
handle.remove()來刪除新增的鉤子。- 返回型別:
torch.utils.hooks.RemovableHandle
- register_get_post_hook(hook)¶
註冊一個 hook,以便在對葉張量執行任何 get 操作後呼叫它。
- register_load_state_dict_post_hook(hook)¶
註冊一個 post-hook,以便在呼叫模組的
load_state_dict()後執行。- 它應該具有以下簽名:
hook(module, incompatible_keys) -> None
module引數是註冊此 hook 的當前模組,incompatible_keys引數是一個NamedTuple,由屬性missing_keys和unexpected_keys組成。missing_keys是一個list的str,包含缺失的鍵,而unexpected_keys是一個list的str,包含意外的鍵。如果需要,可以就地修改給定的 incompatible_keys。
請注意,當使用
strict=True呼叫load_state_dict()時執行的檢查會受到 hook 對missing_keys或unexpected_keys所做修改的影響,正如預期的那樣。 向任一鍵集新增內容將導致在strict=True時丟擲錯誤,而清除缺失和意外的鍵將避免錯誤。- 返回值:
一個控制代碼,可用於透過呼叫
handle.remove()來刪除新增的鉤子。- 返回型別:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_pre_hook(hook)¶
註冊一個 pre-hook,以便在呼叫模組的
load_state_dict()之前執行。- 它應該具有以下簽名:
hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950
- 引數:
hook (Callable) – 將在載入 state dict 之前呼叫的可呼叫 hook。
- register_parameter(name: str, param: Optional[Parameter]) None¶
向模組新增引數。
可以使用給定的名稱作為屬性訪問該引數。
- 引數:
name (str) – 引數的名稱。可以使用給定的名稱從該模組訪問該引數
param (Parameter 或 None) – 要新增到模組的引數。如果
None,則忽略在引數上執行的操作,例如cuda。如果None,則該引數不包含在模組的state_dict中。
- register_state_dict_post_hook(hook)¶
為
state_dict()方法註冊一個後置鉤子 (post-hook)。- 它應該具有以下簽名:
hook(module, state_dict, prefix, local_metadata) -> None
註冊的鉤子可以就地修改
state_dict。
- register_state_dict_pre_hook(hook)¶
為
state_dict()方法註冊一個前置鉤子 (pre-hook)。- 它應該具有以下簽名:
hook(module, prefix, keep_vars) -> None
註冊的鉤子可用於在進行
state_dict呼叫之前執行預處理。
- rename(*names, **rename_map)¶
返回一個張量字典的克隆,其中維度已重新命名。
示例
>>> td = TensorDict({}, batch_size=[1, 2, 3 ,4]) >>> td.names = list("abcd") >>> td_rename = td.rename(c="g") >>> assert td_rename.names == list("abgd")
- rename_(*names, **rename_map)¶
與
rename()相同,但執行就地重新命名。示例
>>> td = TensorDict({}, batch_size=[1, 2, 3 ,4]) >>> td.names = list("abcd") >>> assert td.rename_(c="g") >>> assert td.names == list("abgd")
- rename_key_(old_key: NestedKey, new_key: NestedKey, safe: bool = False) TensorDictBase¶
使用新的字串重新命名鍵,並返回具有更新後的鍵名的相同張量字典。
- repeat(*repeats: int) TensorDictBase¶
沿指定維度重複此張量。
與
expand()不同,此函式會複製張量的資料。警告
repeat()的行為與repeat()不同,但更類似於numpy.tile()。對於類似於numpy.repeat()的運算子,請參閱repeat_interleave()。- 引數:
repeat (torch.Size, int..., int 的元組 或 int 的列表) – 沿每個維度重複此張量的次數。
示例
>>> import torch >>> >>> from tensordict import TensorDict >>> >>> td = TensorDict( ... { ... "a": torch.randn(3, 4, 5), ... "b": TensorDict({ ... "c": torch.randn(3, 4, 10, 1), ... "a string": "a string!", ... }, batch_size=[3, 4, 10]) ... }, batch_size=[3, 4], ... ) >>> print(td.repeat(1, 2)) TensorDict( fields={ a: Tensor(shape=torch.Size([3, 8, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ a string: NonTensorData(data=a string!, batch_size=torch.Size([3, 8, 10]), device=None), c: Tensor(shape=torch.Size([3, 8, 10, 1]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 8, 10]), device=None, is_shared=False)}, batch_size=torch.Size([3, 8]), device=None, is_shared=False)
- repeat_interleave(*shape: int)¶
重複 TensorDict 的元素。
警告
這與
repeat()不同,但類似於numpy.repeat()。- 引數:
repeats (torch.Tensor 或 int) – 每個元素的重複次數。repeats 被廣播以適合給定軸的形狀。
dim (int, 可選) – 沿其重複值的維度。預設情況下,使用展平的輸入陣列,並返回一個扁平的輸出陣列。
- 關鍵字引數:
output_size (int, 可選) – 給定軸的總輸出大小(例如,重複的總和)。如果給定,它將避免計算張量字典的輸出形狀所需的流同步。
- 返回值:
重複的 TensorDict,其形狀與輸入相同,但沿給定軸除外。
示例
>>> import torch >>> >>> from tensordict import TensorDict >>> >>> td = TensorDict( ... { ... "a": torch.randn(3, 4, 5), ... "b": TensorDict({ ... "c": torch.randn(3, 4, 10, 1), ... "a string": "a string!", ... }, batch_size=[3, 4, 10]) ... }, batch_size=[3, 4], ... ) >>> print(td.repeat_interleave(2, dim=0)) TensorDict( fields={ a: Tensor(shape=torch.Size([6, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ a string: NonTensorData(data=a string!, batch_size=torch.Size([6, 4, 10]), device=None), c: Tensor(shape=torch.Size([6, 4, 10, 1]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([6, 4, 10]), device=None, is_shared=False)}, batch_size=torch.Size([6, 4]), device=None, is_shared=False)
- replace(*args, **kwargs)¶
建立一個 tensordict 的淺複製,其中的條目已被替換。
接受一個未命名的引數,該引數必須是
TensorDictBase子類的字典。 此外,可以使用命名的關鍵字引數更新第一級條目。- 返回值:
如果輸入不為空,則返回
self的副本,其中的條目已更新。如果提供的是空字典或未提供字典,且 kwargs 為空,則返回self。
- requires_grad_(requires_grad=True) T¶
更改是否應記錄此張量的自動求導操作:就地設定此張量的 requires_grad 屬性。
返回此 tensordict。
- 引數:
requires_grad (bool, optional) – 是否應記錄此 tensordict 的自動求導操作。 預設為
True。
- reshape(*shape: int)¶
返回具有所需形狀的連續的、重塑的張量。
- 引數:
*shape (int) – 生成的 tensordict 的新形狀。
- 返回值:
一個帶有重塑鍵的 TensorDict
示例
>>> td = TensorDict({ ... 'x': torch.arange(12).reshape(3, 4), ... }, batch_size=[3, 4]) >>> td = td.reshape(12) >>> print(td['x']) torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
- round() T¶
計算 TensorDict 中每個元素的
round()值。
- round_() T¶
就地計算 TensorDict 中每個元素的
round()值。
- 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()的代理。
- property saved_path¶
返回儲存 memmap 儲存的 TensorDict 的路徑。
只要 is_memmap() 返回
False(例如,當 tensordict 被解鎖時),此引數就會消失。
- select(*keys: NestedKey, inplace: bool = False, strict: bool = True) T¶
選擇 tensordict 的鍵,並返回一個新的僅包含所選鍵的 tensordict。
這些值不會被複制:就地修改原始或新 tensordict 的張量會導致兩個 tensordict 都發生更改。
- 引數:
- 返回值:
一個新的 tensordict(如果
inplace=True則為同一個),僅包含所選鍵。
注意
要在 tensordict 中選擇鍵並返回一個刪除了這些鍵的 tensordict 版本,請參閱
split_keys()方法。示例
>>> from tensordict import TensorDict >>> td = TensorDict({"a": 0, "b": {"c": 1, "d": 2}}, []) >>> td.select("a", ("b", "c")) TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.select("a", "b") TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.select("this key does not exist", strict=False) TensorDict( fields={ }, batch_size=torch.Size([]), device=None, is_shared=False)
- send(dst: int, *, group: 'torch.distributed.ProcessGroup' | None = None, init_tag: int = 0, pseudo_rand: bool = False) None¶
將 tensordict 的內容傳送給遠端工作程序。
- 引數:
dst (int) – 目標 worker 的 rank,內容應傳送到該 worker。
- 關鍵字引數:
示例
>>> from torch import multiprocessing as mp >>> from tensordict import TensorDict >>> import torch >>> >>> >>> def client(): ... torch.distributed.init_process_group( ... "gloo", ... rank=1, ... world_size=2, ... init_method=f"tcp://:10003", ... ) ... ... td = TensorDict( ... { ... ("a", "b"): torch.randn(2), ... "c": torch.randn(2, 3), ... "_": torch.ones(2, 1, 5), ... }, ... [2], ... ) ... td.send(0) ... >>> >>> def server(queue): ... torch.distributed.init_process_group( ... "gloo", ... rank=0, ... world_size=2, ... init_method=f"tcp://:10003", ... ) ... td = TensorDict( ... { ... ("a", "b"): torch.zeros(2), ... "c": torch.zeros(2, 3), ... "_": torch.zeros(2, 1, 5), ... }, ... [2], ... ) ... td.recv(1) ... assert (td != 0).all() ... queue.put("yuppie") ... >>> >>> if __name__=="__main__": ... queue = mp.Queue(1) ... main_worker = mp.Process(target=server, args=(queue,)) ... secondary_worker = mp.Process(target=client) ... ... main_worker.start() ... secondary_worker.start() ... out = queue.get(timeout=10) ... assert out == "yuppie" ... main_worker.join() ... secondary_worker.join()
- separates(*keys: NestedKey, default: Any = _NoDefault.ZERO, strict: bool = True, filter_empty: bool = True) T¶
就地從 tensordict 中分離指定的鍵。
另請參閱
該方法等效於呼叫
split_keys(),並設定inplace=True,用於單個拆分。另請參閱
該方法等效於呼叫
exclude(),不同之處在於它返回資料的另一個拆分。- 引數:
- 返回值:
分離的 tensordict。
- 返回型別:
T
示例
>>> td = TensorDict( ... a=0, ... b=0, ... c=0, ... d=0, ... ) >>> td_a_c = td.separates("a", "c") >>> print(td_a_c) TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> print(td) TensorDict( fields={ b: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
- set(key: NestedKey, item: Tensor, inplace: bool = False, **kwargs: Any) TensorDictBase¶
設定一個新的鍵值對。
- 引數:
key (str, tuple of str) – 要設定的鍵的名稱。
item (torch.Tensor or equivalent, TensorDictBase instance) – 要儲存在 tensordict 中的值。
inplace (bool, optional) – 如果
True且某個鍵與 tensordict 中的現有鍵匹配,則將對該鍵值對進行就地更新。 如果 inplace 為True且找不到條目,則會新增該條目。 對於更嚴格的就地操作,請改用set_()。 預設為False。
- 關鍵字引數:
non_blocking (bool, optional) – 如果
True並且此複製發生在不同裝置之間,則複製可能相對於主機非同步發生。- 返回值:
self
示例
>>> td = TensorDict({}, batch_size[3, 4]) >>> td.set("x", torch.randn(3, 4)) >>> y = torch.randn(3, 4, 5) >>> td.set("y", y, inplace=True) # works, even if 'y' is not present yet >>> td.set("y", torch.zeros_like(y), inplace=True) >>> assert (y==0).all() # y values are overwritten >>> td.set("y", torch.ones(5), inplace=True) # raises an exception as shapes mismatch
- set_(key: NestedKey, item: Tensor) T¶
設定現有鍵的值,同時保留原始儲存。
- 引數:
key (str) – 值的名稱
item (torch.Tensor or compatible type, TensorDictBase) – 要儲存在 tensordict 中的值
- 關鍵字引數:
non_blocking (bool, optional) – 如果
True並且此複製發生在不同裝置之間,則複製可能相對於主機非同步發生。- 返回值:
self
示例
>>> td = TensorDict({}, batch_size[3, 4]) >>> x = torch.randn(3, 4) >>> td.set("x", x) >>> td.set_("x", torch.zeros_like(x)) >>> assert (x == 0).all()
- set_at_(key: NestedKey, value: Tensor, index: Union[None, int, slice, str, Tensor, List[Any], Tuple[Any, ...]]) T¶
在
index指示的索引處就地設定值。- 引數:
key (str, tuple of str) – 要修改的鍵。
value (torch.Tensor) – 要在索引 index 處設定的值
- 關鍵字引數:
non_blocking (bool, optional) – 如果
True並且此複製發生在不同裝置之間,則複製可能相對於主機非同步發生。- 返回值:
self
示例
>>> td = TensorDict({}, batch_size[3, 4]) >>> x = torch.randn(3, 4) >>> td.set("x", x) >>> td.set_at_("x", value=torch.ones(1, 4), index=slice(1)) >>> assert (x[0] == 1).all()
- set_extra_state(state: Any) None¶
設定載入的 state_dict 中包含的額外狀態。
從
load_state_dict()呼叫此函式,以處理 state_dict 中找到的任何額外狀態。如果需要在模組的 state_dict 中儲存額外狀態,請為你的模組實現此函式以及相應的get_extra_state()。- 引數:
state (dict) – 來自 state_dict 的額外狀態
- set_non_tensor(key: NestedKey, value: Any)¶
使用
tensordict.tensorclass.NonTensorData在 tensordict 中註冊一個非張量值。可以使用
TensorDictBase.get_non_tensor()或直接使用 get 檢索該值,這將返回tensordict.tensorclass.NonTensorData物件。return: self
示例
>>> data = TensorDict({}, batch_size=[]) >>> data.set_non_tensor(("nested", "the string"), "a string!") >>> assert data.get_non_tensor(("nested", "the string")) == "a string!" >>> # regular `get` works but returns a NonTensorData object >>> data.get(("nested", "the string")) NonTensorData( data='a string!', batch_size=torch.Size([]), device=None, is_shared=False)
- set_submodule(target: str, module: Module, strict: bool = False) None¶
設定由
target指定的子模組,如果該子模組存在;否則,丟擲錯誤。注意
如果
strict設定為False(預設值),該方法將替換現有的子模組,或者如果父模組存在,則建立一個新的子模組。 如果strict設定為True,該方法將僅嘗試替換現有的子模組,如果該子模組不存在,則丟擲錯誤。例如,假設你有一個
nn.ModuleA,其結構如下:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(該圖展示了一個
nn.ModuleA。A具有一個巢狀的子模組net_b,它本身有兩個子模組net_c和linear。然後,net_c具有一個子模組conv。)要使用新的子模組
Linear覆蓋Conv2d,您可以呼叫set_submodule("net_b.net_c.conv", nn.Linear(1, 1)),其中strict可以是True或False。要將新的子模組
Conv2d新增到現有的net_b模組,您可以呼叫set_submodule("net_b.conv", nn.Conv2d(1, 1, 1))。在以上示例中,如果您設定
strict=True並呼叫set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True),則會引發 AttributeError,因為net_b沒有名為conv的子模組。- 引數:
target – 要查詢的 submodule 的完整字串名稱。(有關如何指定完整字串,請參閱上面的示例。)
module – 要將子模組設定到的模組。
strict – 如果
False,該方法將替換現有的子模組,或者如果父模組存在,則建立一個新的子模組。 如果True,該方法將僅嘗試替換現有的子模組,如果該子模組不存在,則丟擲錯誤。
- 引發:
ValueError – 如果
target字串為空,或者如果module不是nn.Module的例項。AttributeError – 如果沿著
target字串產生的路徑上的任何點,(子)路徑解析為不存在的屬性名稱或不是nn.Module例項的物件。
- setdefault(key: NestedKey, default: Tensor, inplace: bool = False) Tensor¶
如果 tensordict 中不存在
key,則插入key條目,其值為default。如果 tensordict 中存在
key,則返回key的值;否則返回default。- 引數:
key (str 或 nested key) – 值的名稱。
default (torch.Tensor 或 compatible type, TensorDictBase) – 如果 tensordict 中尚不存在該鍵,則將該值儲存在 tensordict 中。
- 返回值:
tensordict 中鍵的值。如果先前未設定該鍵,則將為 default。
示例
>>> td = TensorDict({}, batch_size=[3, 4]) >>> val = td.setdefault("a", torch.zeros(3, 4)) >>> assert (val == 0).all() >>> val = td.setdefault("a", torch.ones(3, 4)) >>> assert (val == 0).all() # output is still 0
- property shape: Size¶
請參閱
batch_size。
將所有張量放置在共享記憶體中。
然後鎖定 TensorDict,這意味著任何非就地寫入操作都將引發異常(例如,重新命名、設定或刪除條目)。 相反,一旦 tensordict 被解鎖,share_memory 屬性將變為
False,因為不再保證跨程序標識。- 返回值:
self
- sigmoid() T¶
計算 TensorDict 中每個元素的
sigmoid()值。
- sigmoid_() T¶
就地計算 TensorDict 中每個元素的
sigmoid()值。
- sign() T¶
計算 TensorDict 中每個元素的
sign()值。
- sign_() T¶
就地計算 TensorDict 中每個元素的
sign()值。
- sin() T¶
計算 TensorDict 中每個元素的
sin()值。
- sin_() T¶
就地計算 TensorDict 中每個元素的
sin()值。
- sinh() T¶
計算 TensorDict 中每個元素的
sinh()值。
- sinh_() T¶
對 TensorDict 的每個元素執行原位
sinh()值計算。
- size(dim: Optional[int] = None) torch.Size | int¶
返回由
dim指示的維度的大小。如果未指定
dim,則返回 TensorDict 的batch_size屬性。
- softmax(dim: int, dtype: Optional[dtype] = None)¶
將 softmax 函式應用於 tensordict 元素。
- 引數:
dim (int 或 ints 元組) – 將計算 softmax 的 tensordict 維度。
dtype (torch.dtype, 可選) – 返回張量的期望資料型別。 如果指定,則在執行操作之前將輸入張量轉換為 dtype。 這對於防止資料型別溢位很有用。
- property sorted_keys: list[tensordict._nestedkey.NestedKey]¶
返回按字母順序排序的鍵。
不支援額外的引數。
如果 TensorDict 被鎖定,則鍵將被快取,直到 tensordict 被解鎖以加快執行速度。
- split(split_size: int | list[int], dim: int = 0) list[tensordict.base.TensorDictBase]¶
使用給定維度中的指定大小分割 TensorDict 中的每個張量,如 torch.split。
返回一個
TensorDict例項列表,其中包含分割塊的檢視。- 引數:
split_size (int 或 List(int)) – 單個塊的大小或每個塊的大小列表。
dim (int) – 用於分割張量的維度。
- 返回值:
具有給定維度中指定大小的 TensorDict 列表。
示例
>>> td = TensorDict({ ... 'x': torch.arange(12).reshape(3, 4), ... }, batch_size=[3, 4]) >>> td0, td1 = td.split([1, 2], dim=0) >>> print(td0['x']) torch.Tensor([[0, 1, 2, 3]])
- split_keys(*key_sets, inplace=False, default: Any = _NoDefault.ZERO, strict: bool = True, reproduce_struct: bool = False) Tuple[T, ...]¶
將 tensordict 分割為給定一個或多個鍵集的子集。
該方法將返回
N+1個 tensordict,其中N是提供的引數數量。- 引數:
key_sets (Dict[in_key, out_key] 序列或 鍵列表) – 各種拆分。
inplace (bool, 可選) – 如果為
True,則鍵將從self中原位刪除。 預設為False。default (Any, 可選) – 缺少鍵時要返回的值。 如果未指定且
strict=True,則會引發異常。strict (bool, optional) – 如果
True,則在鍵缺失時會引發異常。預設為True。reproduce_struct (bool, 可選) – 如果為
True,則所有返回的 tensordict 都具有與self相同的樹結構,即使某些子 tensordict 不包含任何葉子。
注意
None非張量值將被忽略且不會返回。注意
該方法不檢查提供的列表中是否存在重複項。
示例
>>> td = TensorDict( ... a=0, ... b=0, ... c=0, ... d=0, ... ) >>> td_a, td_bc, td_d = td.split_keys(["a"], ["b", "c"]) >>> print(td_bc)
- sqrt()¶
計算
self的逐元素平方根。
- squeeze(*args, **kwargs)¶
壓縮 -self.batch_dims+1 和 self.batch_dims-1 之間的維度的所有張量,並在新的 tensordict 中返回它們。
- 引數:
dim (Optional[int]) – 要沿其壓縮的維度。 如果 dim 是
None,則將壓縮所有單例維度。 預設為None。
示例
>>> td = TensorDict({ ... 'x': torch.arange(24).reshape(3, 1, 4, 2), ... }, batch_size=[3, 1, 4]) >>> td = td.squeeze() >>> td.shape torch.Size([3, 4]) >>> td.get("x").shape torch.Size([3, 4, 2])
此操作也可以用作上下文管理器。 對原始 tensordict 的更改將發生在外部,即不會更改原始張量的內容。 這也假設 tensordict 未被鎖定(否則,需要解鎖 tensordict)。 此功能與隱式壓縮不相容。
>>> td = TensorDict({ ... 'x': torch.arange(24).reshape(3, 1, 4, 2), ... }, batch_size=[3, 1, 4]) >>> with td.squeeze(1) as tds: ... tds.set("y", torch.zeros(3, 4)) >>> assert td.get("y").shape == [3, 1, 4]
- classmethod stack(input, dim=0, *, out=None)¶
將 tensordict 沿給定維度堆疊到單個 tensordict 中。
此呼叫等效於呼叫
torch.stack()但與 torch.compile 相容。
- stack_from_tensordict(dim: int = 0, *, sorted: Optional[Union[bool, List[NestedKey]]] = None, out: Optional[Tensor] = None) Tensor¶
將tensordict中的所有條目堆疊成單個張量。
- 引數:
dim (int, 可選) – 條目應沿其堆疊的維度。
- 關鍵字引數:
sorted (bool 或 NestedKey 的列表) – 如果
True,條目將按字母順序堆疊。 如果False(預設),將使用字典順序。 或者,可以提供鍵名稱的列表,並且張量將相應地堆疊。 這會產生一些開銷,因為將根據 tensordict 中的葉名稱列表檢查鍵列表。out (torch.Tensor, 可選) – 用於堆疊操作的可選目標張量。
- stack_tensors(*keys: NestedKey, out_key: NestedKey, dim: int = 0, keep_entries: bool = False) T¶
將條目堆疊到新條目中,並可能刪除原始值。
- 引數:
keys (NestedKey 的序列) – 要堆疊的條目。
- 關鍵字引數
out_key (NestedKey): 堆疊輸入的新鍵名。 keep_entries (bool, optional): 如果
False,keys中的條目將被刪除。預設為
False。- dim (int, optional): 堆疊必須發生的維度。
預設為
0。
返回: self
示例
>>> td = TensorDict(a=torch.zeros(()), b=torch.ones(())) >>> td.stack_tensors("a", "b", out_key="c") >>> assert "a" not in td >>> assert (td["c"] == torch.tensor([0, 1])).all()
- state_dict(*args, destination=None, prefix='', keep_vars=False, flatten=True)¶
從 tensordict 生成 state_dict。
state-dict 的結構仍然是巢狀的,除非
flatten設定為True。tensordict state-dict 包含重建 tensordict 所需的所有張量和元資料(當前不支援名稱)。
- 引數:
destination (dict, 可選) – 如果提供,tensordict 的狀態將更新到 dict 中,並返回相同的物件。 否則,將建立並返回一個
OrderedDict。 預設值:None。prefix (str, 可選) – 新增到張量名稱的字首,用於組成 state_dict 中的鍵。 預設值:
''。keep_vars (bool, 可選) – 預設情況下,在狀態字典中返回的
torch.Tensor項與 autograd 分離。 如果設定為True,則不會執行分離。 預設值:False。flatten (bool, 可選) – 是否應使用
"."字元來展平結構。 預設為False。
示例
>>> data = TensorDict({"1": 1, "2": 2, "3": {"3": 3}}, []) >>> sd = data.state_dict() >>> print(sd) OrderedDict([('1', tensor(1)), ('2', tensor(2)), ('3', OrderedDict([('3', tensor(3)), ('__batch_size', torch.Size([])), ('__device', None)])), ('__batch_size', torch.Size([])), ('__device', None)]) >>> sd = data.state_dict(flatten=True) OrderedDict([('1', tensor(1)), ('2', tensor(2)), ('3.3', tensor(3)), ('__batch_size', torch.Size([])), ('__device', None)])
- std(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, correction: int = 1, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的標準偏差值。
- 引數:
dim (int, int 元組, 可選) – 如果為
None,則返回一個無維度 tensordict,其中包含所有葉子的總和值(如果可以計算)。 如果是整數或整數元組,則僅當此維度與 tensordict 形狀相容時,才會在指定的維度上呼叫 std。 目前僅允許使用 “feature” 字串。 使用 dim=”feature” 將實現對所有特徵維度的縮減。 如果 reduce=True,則將返回一個形狀為 TensorDict 批大小的張量。 否則,將返回一個與self具有相同結構但縮減了特徵維度的新 tensordict。keepdim (bool) – 輸出張量是否保留 dim。
- 關鍵字引數:
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.std(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.std() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.std(reduce=True) tensor(1.0006) >>> td.std(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.std(reduce=True, dim="feature") tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) >>> td.std(reduce=True, dim=0) tensor([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]])
- sub(other: tensordict.base.TensorDictBase | torch.Tensor | float, *, alpha: float | None = None, default: str | torch.Tensor | None = None)¶
從
self中減去other,並按alpha縮放。\[\text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i\]支援廣播、型別提升以及整數、浮點數和複數輸入。
- 引數:
other (TensorDict, Tensor 或 Number) – 要從
self中減去的 tensor 或數字。- 關鍵字引數:
alpha (數字) –
other的乘數。default (torch.Tensor 或 str, 可選) – 用於互斥條目的預設值。如果沒有提供,則兩個 tensordict 的鍵列表必須完全匹配。如果傳遞
default="intersection",則只會考慮相交的鍵集合,其他鍵將被忽略。在所有其他情況下,default將用於操作兩側所有缺失的條目。
- sub_(other: tensordict.base.TensorDictBase | torch.Tensor | float, alpha: Optional[float] = None)¶
sub()的原地版本。注意
原地
sub不支援default關鍵字引數。
- sum(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的總和值。
- 引數:
dim (int, tuple of int, optional) – 如果
None,則返回一個包含所有葉子的總和值的無維度 tensordict(如果可以計算)。 如果是整數或整數元組,則僅當此維度與 tensordict 形狀相容時,才對指定維度呼叫 sum。 目前只允許使用 “feature” 字串。 使用 dim=”feature” 將實現對所有特徵維度的縮減。 如果 reduce=True,將返回一個與 TensorDict 的批大小形狀相同的張量。 否則,將返回一個與self具有相同結構,但特徵維度縮減的 tensordict。keepdim (bool) – 輸出張量是否保留 dim。
- 關鍵字引數:
dtype (torch.dtype, 可選) – 返回張量的所需資料型別。如果指定,輸入張量在執行操作之前會被強制轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:
None。reduce (bool, 可選) – 如果為
True,則將在所有 TensorDict 值上進行規約,並返回單個規約後的 tensor。預設為False。
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.sum(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.sum() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.sum(reduce=True) tensor(-0.) >>> td.sum(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.sum(reduce=True, dim="feature") tensor([[15., 15., 15., 15.], [15., 15., 15., 15.], [15., 15., 15., 15.]]) >>> td.sum(reduce=True, dim=0) tensor([[9., 9., 9., 9., 9.], [9., 9., 9., 9., 9.], [9., 9., 9., 9., 9.], [9., 9., 9., 9., 9.]])
- tan() T¶
計算 TensorDict 中每個元素的
tan()值。
- tan_() T¶
原地計算 TensorDict 中每個元素的
tan()值。
- tanh() T¶
計算 TensorDict 中每個元素的
tanh()值。
- tanh_() T¶
原地計算 TensorDict 中每個元素的
tanh()值。
- to(*args, **kwargs) TensorDictBase¶
將 TensorDictBase 子類對映到另一個裝置、dtype 或另一個 TensorDictBase 子類(如果允許)。
不允許將張量轉換為新的 dtype,因為 tensordict 不一定包含單一的張量 dtype。
- 引數:
device (torch.device, 可選) – tensordict 的所需裝置。
dtype (torch.dtype, 可選) – tensordict 的所需浮點或複數 dtype。
tensor (torch.Tensor, 可選) – 張量,其 dtype 和裝置是此 TensorDict 中所有張量的所需 dtype 和裝置。
- 關鍵字引數:
non_blocking (bool, 可選) – 操作是否應為阻塞。
memory_format (torch.memory_format, 可選) – 此 tensordict 中 4D 引數和緩衝區的所需記憶體格式。
batch_size (torch.Size, 可選) – 輸出的 tensordict 的結果批大小。
other (TensorDictBase, 可選) –
TensorDict 例項,其 dtype 和 device 是此 TensorDict 中所有張量所需的 dtype 和 device。
注意
由於
TensorDictBase例項沒有 dtype,因此 dtype 從示例葉子節點收集。 如果有多個 dtype,則不進行 dtype 轉換。non_blocking_pin (bool, 可選) –
如果
True, 張量在傳送到裝置之前會被 pinned。 這將非同步完成,但可以透過num_threads引數來控制。注意
呼叫
tensordict.pin_memory().to("cuda")通常比tensordict.to("cuda", non_blocking_pin=True)慢得多,因為在第二種情況下 pin_memory 是非同步呼叫的。 如果張量很大且數量眾多,則多執行緒pin_memory通常是有益的:當要傳送的張量太少時,生成執行緒和收集資料的開銷會超過多執行緒的優勢;如果張量很小,則迭代長列表的開銷也大得驚人。num_threads (int 或 None, 可選) – 如果
non_blocking_pin=True, 用於pin_memory的執行緒數。 預設情況下,將生成max(1, torch.get_num_threads())個執行緒。num_threads=0將取消 pin_memory() 呼叫的任何多執行緒處理。inplace (bool, 可選) – 如果
True, 資料將被直接寫入同一個 tensordict 中。當構建 tensordict 的 CPU 開銷受到限制時,這可能會顯著加快速度。 預設為False。
- 返回值:
如果裝置與 tensordict 裝置不同和/或傳遞了 dtype,則返回一個新的 tensordict 例項。 否則,返回相同的 tensordict。 只有
batch_size的修改才會就地進行。
注意
如果 TensorDict 已整合,則結果 TensorDict 也將整合。 每個新張量都將是投射到所需裝置的整合儲存上的一個檢視。
示例
>>> data = TensorDict({"a": 1.0}, [], device=None) >>> data_cuda = data.to("cuda:0") # casts to cuda >>> data_int = data.to(torch.int) # casts to int >>> data_cuda_int = data.to("cuda:0", torch.int) # multiple casting >>> data_cuda = data.to(torch.randn(3, device="cuda:0")) # using an example tensor >>> data_cuda = data.to(other=TensorDict({}, [], device="cuda:0")) # using a tensordict example
- to_dict(*, retain_none: bool = True) dict[str, Any]¶
返回一個字典,其中的鍵值對與 tensordict 的鍵值對匹配。
- 引數:
retain_none (bool) – 如果
True,則 tensorclass 例項中的None值將被寫入字典中。 否則,它們將被丟棄。 預設值:True。
- to_empty(*, device: Optional[Union[int, str, device]], recurse: bool = True) T¶
將引數和緩衝區移動到指定的裝置,而不復制儲存。
- 引數:
device (
torch.device) – 此模組中引數和所需的裝置。recurse (bool) – 子模組的引數和緩衝區是否應遞迴移動到指定的裝置。
- 返回值:
self
- 返回型別:
模組
- to_h5(filename, **kwargs)¶
將 tensordict 轉換為具有 h5 後端的 PersistentTensorDict。
- 引數:
filename (str 或 path) – h5 檔案的路徑。
**kwargs – 要傳遞給
h5py.File.create_dataset()的 kwargs。
- 返回值:
一個連結到新建立的檔案的
PersitentTensorDict例項。
示例
>>> import tempfile >>> import timeit >>> >>> from tensordict import TensorDict, MemoryMappedTensor >>> td = TensorDict({ ... "a": MemoryMappedTensor.from_tensor(torch.zeros(()).expand(1_000_000)), ... "b": {"c": MemoryMappedTensor.from_tensor(torch.zeros(()).expand(1_000_000, 3))}, ... }, [1_000_000]) >>> >>> file = tempfile.NamedTemporaryFile() >>> td_h5 = td.to_h5(file.name, compression="gzip", compression_opts=9) >>> print(td_h5) PersistentTensorDict( fields={ a: Tensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float32, is_shared=False), b: PersistentTensorDict( fields={ c: Tensor(shape=torch.Size([1000000, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([1000000]), device=None, is_shared=False)}, batch_size=torch.Size([1000000]), device=None, is_shared=False)
- to_module(module: Module, *, inplace: bool | None = None, return_swap: bool = True, swap_dest=None, use_state_dict: bool = False, non_blocking: bool = False, memo=None)¶
遞迴地將 TensorDictBase 例項的內容寫入給定的 nn.Module 屬性。
to_module也可以用作上下文管理器,以臨時使用一系列引數/緩衝區填充模組(請參見下面的示例)。- 引數:
module (nn.Module) – 一個要將引數寫入的模組。
- 關鍵字引數:
inplace (bool, 可選) – 如果
True,則模組中的引數或張量將就地更新。 預設為False。return_swap (bool, 可選) – 如果
True,則返回舊的引數配置。 預設為False。swap_dest (TensorDictBase, 可選) – 如果
return_swap為True,則應寫入交換的 tensordict。use_state_dict (bool, 可選) – 如果
True,則將使用 state-dict API 載入引數(包括 state-dict 鉤子)。 預設為False。non_blocking (bool, optional) – 如果
True並且此複製發生在不同裝置之間,則複製可能相對於主機非同步發生。
示例
>>> from torch import nn >>> module = nn.TransformerDecoder( ... decoder_layer=nn.TransformerDecoderLayer(nhead=4, d_model=4), ... num_layers=1) >>> params = TensorDict.from_module(module) >>> params.data.zero_() >>> params.to_module(module) >>> assert (module.layers[0].linear1.weight == 0).all()
將 tensordict 用作上下文管理器對於進行函式式呼叫很有用: .. rubric:: 示例
>>> from tensordict import from_module >>> module = nn.TransformerDecoder( ... decoder_layer=nn.TransformerDecoderLayer(nhead=4, d_model=4), ... num_layers=1) >>> params = TensorDict.from_module(module) >>> params = params.data * 0 # Use TensorDictParams to remake these tensors regular nn.Parameter instances >>> with params.to_module(module): ... # Call the module with zeroed params ... y = module(*inputs) >>> # The module is repopulated with its original params >>> assert (TensorDict.from_module(module) != 0).any()
- 返回值:
如果
return_swap為True,則包含模組中值的 tensordict;否則,為None。
- to_namedtuple(dest_cls: Optional[type] = None)¶
將 tensordict 轉換為 namedtuple。
- 引數:
dest_cls (Type, 可選) – 要使用的可選的 namedtuple 類。
示例
>>> from tensordict import TensorDict >>> import torch >>> data = TensorDict({ ... "a_tensor": torch.zeros((3)), ... "nested": {"a_tensor": torch.zeros((3)), "a_string": "zero!"}}, [3]) >>> data.to_namedtuple() GenericDict(a_tensor=tensor([0., 0., 0.]), nested=GenericDict(a_tensor=tensor([0., 0., 0.]), a_string='zero!'))
- to_padded_tensor(padding=0.0, mask_key: Optional[NestedKey] = None) T¶
將所有巢狀張量轉換為填充版本,並相應地調整批次大小。
- 引數:
padding (float) – tensordict 中張量的填充值。預設為
0.0。mask_key (NestedKey, optional) – 如果提供,則寫入有效值的掩碼的鍵。如果異構維度不是 tensordict 批次大小的一部分,則會導致錯誤。預設為
None
- to_pytree()¶
將 tensordict 轉換為 PyTree。
如果 tensordict 不是從 pytree 建立的,此方法僅返回
self而不做修改。有關更多資訊和示例,請參閱
from_pytree()。
- to_struct_array()¶
將 tensordict 轉換為 numpy 結構化陣列。
在
from_struct_array()-to_struct_array()迴圈中,輸入和輸出陣列的內容應匹配。但是,to_struct_array 不會保留原始陣列的記憶體內容。另請參閱
有關更多資訊,請參閱
from_struct_array()。- 返回值:
輸入 TensorDict 的 numpy 結構化陣列表示。
示例
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict({'a': torch.tensor([1, 2, 3]), 'b': torch.tensor([4.0, 5.0, 6.0])}, batch_size=[3]) >>> arr = td.to_struct_array() >>> print(arr) [(1, 4.) (2, 5.) (3, 6.)]
- to_tensordict(*, retain_none: bool | None = None)¶
從 TensorDictBase 返回一個常規的 TensorDict 例項。
- 引數:
retain_none (bool) –
如果
True,tensorclass 例項中的None值將被寫入 tensordict。否則,它們將被丟棄。預設值:True。注意
從 v0.8 開始,預設值將切換為
False。- 返回值:
包含相同值的新的 TensorDict 物件。
- train(mode: bool = True) T¶
將模組設定為訓練模式。
這僅對某些模組有效。有關訓練/評估模式下特定模組的行為的詳細資訊,請參閱特定模組的文件,例如,它們是否受到影響,例如
Dropout,BatchNorm, 等等。- 引數:
mode (bool) – 是否設定訓練模式 (
True) 或評估模式 (False)。預設值:True。- 返回值:
self
- 返回型別:
模組
- transpose(dim0, dim1)¶
返回一個轉置版本的輸入 tensordict。給定的維度
dim0和dim1被交換。轉置 tensordict 的就地或異地修改也會影響原始 tensordict,因為記憶體是共享的,並且操作會映射回原始 tensordict。
示例
>>> tensordict = TensorDict({"a": torch.randn(3, 4, 5)}, [3, 4]) >>> tensordict_transpose = tensordict.transpose(0, 1) >>> print(tensordict_transpose.shape) torch.Size([4, 3]) >>> tensordict_transpose.set("b",, torch.randn(4, 3)) >>> print(tensordict.get("b").shape) torch.Size([3, 4])
- trunc() T¶
計算 TensorDict 中每個元素的
trunc()值。
- trunc_() T¶
就地計算 TensorDict 中每個元素的
trunc()值。
- uint16()¶
將所有張量強制轉換為
torch.uint16。
- uint32()¶
將所有張量強制轉換為
torch.uint32。
- uint64()¶
將所有張量強制轉換為
torch.uint64。
- uint8()¶
將所有張量強制轉換為
torch.uint8。
- unbind(dim: int) tuple[T, ...]¶
返回一個索引 tensordict 的元組,沿指示的維度解綁。
示例
>>> td = TensorDict({ ... 'x': torch.arange(12).reshape(3, 4), ... }, batch_size=[3, 4]) >>> td0, td1, td2 = td.unbind(0) >>> td0['x'] tensor([0, 1, 2, 3]) >>> td1['x'] tensor([4, 5, 6, 7])
- unflatten(dim, unflattened_size)¶
展開一個 tensordict 維度,將其擴充套件為所需的形狀。
- 引數:
dim (int) – 指定要展開的輸入張量的維度。
unflattened_size (shape) – 是 tensordict 的展開維度的新形狀。
示例
>>> td = TensorDict({ ... "a": torch.arange(60).view(3, 4, 5), ... "b": torch.arange(12).view(3, 4)}, ... batch_size=[3, 4]) >>> td_flat = td.flatten(0, 1) >>> td_unflat = td_flat.unflatten(0, [3, 4]) >>> assert (td == td_unflat).all()
- unflatten_keys(separator: str = '.', inplace: bool = False) TensorDictBase¶
遞迴地將扁平的 tensordict 轉換為巢狀的 tensordict。
TensorDict 型別將丟失,結果將是一個簡單的 TensorDict 例項。巢狀 tensordict 的元資料將從根推斷:資料樹中的所有例項將共享相同的批次大小、維度名稱和裝置。
- 引數:
示例
>>> data = TensorDict({"a": 1, "b - c": 2, "e - f - g": 3}, batch_size=[]) >>> data.unflatten_keys(separator=" - ") TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False), e: TensorDict( fields={ f: TensorDict( fields={ g: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int64, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
此方法和
unflatten_keys()在處理 state-dicts 時特別有用,因為它們可以無縫地將扁平字典轉換為模仿模型結構的資料結構。示例
>>> model = torch.nn.Sequential(torch.nn.Linear(3 ,4)) >>> ddp_model = torch.ao.quantization.QuantWrapper(model) >>> state_dict = TensorDict(ddp_model.state_dict(), batch_size=[]).unflatten_keys(".") >>> print(state_dict) TensorDict( fields={ module: TensorDict( fields={ 0: TensorDict( fields={ bias: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Tensor(shape=torch.Size([4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> model_state_dict = state_dict.get("module") >>> print(model_state_dict) TensorDict( fields={ 0: TensorDict( fields={ bias: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.float32, is_shared=False), weight: Tensor(shape=torch.Size([4, 3]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> model.load_state_dict(dict(model_state_dict.flatten_keys(".")))
- unsqueeze(*args, **kwargs)¶
對所有張量沿 -td.batch_dims 和 td.batch_dims 之間的維度進行 unsqueeze 操作,並將它們返回到新的 tensordict 中。
- 引數:
dim (int) – 進行 unsqueeze 操作的維度
示例
>>> td = TensorDict({ ... 'x': torch.arange(24).reshape(3, 4, 2), ... }, batch_size=[3, 4]) >>> td = td.unsqueeze(-2) >>> td.shape torch.Size([3, 1, 4]) >>> td.get("x").shape torch.Size([3, 1, 4, 2])
此操作也可以用作上下文管理器。對原始 tensordict 的更改將在外部進行,即原始張量的內容不會被改變。這還假設 tensordict 沒有被鎖定(否則,需要解鎖 tensordict)。
>>> td = TensorDict({ ... 'x': torch.arange(24).reshape(3, 4, 2), ... }, batch_size=[3, 4]) >>> with td.unsqueeze(-2) as tds: ... tds.set("y", torch.zeros(3, 1, 4)) >>> assert td.get("y").shape == [3, 4]
- update(input_dict_or_td: dict[str, torch.Tensor] | tensordict.base.TensorDictBase, clone: bool = False, inplace: bool = False, *, non_blocking: bool = False, keys_to_update: Optional[Sequence[NestedKey]] = None, is_leaf: Optional[Callable[[Type], bool]] = None) TensorDictBase¶
使用字典或另一個 TensorDict 中的值更新 TensorDict。
- 引數:
input_dict_or_td (TensorDictBase 或 dict) – 要寫入 self 的輸入資料。
clone (bool, optional) – 是否應在設定之前克隆輸入(張量)字典中的張量。預設為
False。inplace (bool, optional) – 如果為
True並且鍵與 tensordict 中的現有鍵匹配,則該鍵值對的更新將就地進行。 如果找不到該條目,則會將其新增。預設為False。
- 關鍵字引數:
- 返回值:
self
示例
>>> td = TensorDict({}, batch_size=[3]) >>> a = torch.randn(3) >>> b = torch.randn(3, 4) >>> other_td = TensorDict({"a": a, "b": b}, batch_size=[]) >>> td.update(other_td, inplace=True) # writes "a" and "b" even though they can't be found >>> assert td['a'] is other_td['a'] >>> other_td = other_td.clone().zero_() >>> td.update(other_td) >>> assert td['a'] is not other_td['a']
- update_(input_dict_or_td: Union[dict[str, torch.Tensor], T], clone: bool = False, *, non_blocking: bool = False, keys_to_update: Optional[Sequence[NestedKey]] = None) T¶
使用字典或另一個 TensorDict 中的值就地更新 TensorDict。
與
update()不同,如果self未知該鍵,此函式將丟擲錯誤。- 引數:
input_dict_or_td (TensorDictBase 或 dict) – 要寫入 self 的輸入資料。
clone (bool, optional) – 是否應在設定之前克隆輸入(張量)字典中的張量。預設為
False。
- 關鍵字引數:
keys_to_update (NestedKeys 序列, 可選) – 如果提供,則僅更新
key_to_update中的鍵列表。 旨在避免呼叫data_dest.update_(data_src.select(*keys_to_update))。non_blocking (bool, optional) – 如果
True並且此複製發生在不同裝置之間,則複製可能相對於主機非同步發生。
- 返回值:
self
示例
>>> a = torch.randn(3) >>> b = torch.randn(3, 4) >>> td = TensorDict({"a": a, "b": b}, batch_size=[3]) >>> other_td = TensorDict({"a": a*0, "b": b*0}, batch_size=[]) >>> td.update_(other_td) >>> assert td['a'] is not other_td['a'] >>> assert (td['a'] == other_td['a']).all() >>> assert (td['a'] == 0).all()
- update_at_(input_dict_or_td: Union[dict[str, torch.Tensor], T], idx: Union[None, int, slice, str, Tensor, List[Any], Tuple[Any, ...]], clone: bool = False, *, non_blocking: bool = False, keys_to_update: Optional[Sequence[NestedKey]] = None) T¶
在指定的索引處,使用來自字典或另一個 TensorDict 的值,就地更新 TensorDict。
與 TensorDict.update 不同,如果 TensorDict 不知道該鍵,此函式將丟擲錯誤。
- 引數:
input_dict_or_td (TensorDictBase 或 dict) – 要寫入 self 的輸入資料。
idx (int, torch.Tensor, iterable, slice) – 應該發生更新的 tensordict 的索引。
clone (bool, optional) – 是否應在設定之前克隆輸入(tensor)字典中的張量。 預設為 False。
- 關鍵字引數:
keys_to_update (NestedKeys 的序列, optional) – 如果提供,則只會更新
key_to_update中的鍵列表。non_blocking (bool, optional) – 如果
True並且此複製發生在不同裝置之間,則複製可能相對於主機非同步發生。
- 返回值:
self
示例
>>> td = TensorDict({ ... 'a': torch.zeros(3, 4, 5), ... 'b': torch.zeros(3, 4, 10)}, batch_size=[3, 4]) >>> td.update_at_( ... TensorDict({ ... 'a': torch.ones(1, 4, 5), ... 'b': torch.ones(1, 4, 10)}, batch_size=[1, 4]), ... slice(1, 2)) TensorDict( fields={ a: Tensor(torch.Size([3, 4, 5]), dtype=torch.float32), b: Tensor(torch.Size([3, 4, 10]), dtype=torch.float32)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> assert (td[1] == 1).all()
- values(include_nested: bool = False, leaves_only: bool = False, is_leaf: Optional[Callable[[Type], bool]] = None, *, sort: bool = False) Iterator[Tensor]¶
返回一個生成器,表示 tensordict 的值。
- 引數:
include_nested (bool, optional) – 如果
True, 將返回巢狀的值。預設為False。leaves_only (bool, optional) – 如果
False,則僅返回葉子節點。預設為False。is_leaf (callable, optional) –
一個可呼叫物件,接受一個類型別作為引數,返回一個布林值,指示該類是否應被視為葉節點。
注意
is_leaf 的目的不是阻止對巢狀 tensordict 的遞迴呼叫,而是將某些型別標記為“葉節點”,以便在 leaves_only=True 時進行過濾。 即使 is_leaf(cls) 返回 True,如果 include_nested=True,tensordict 的巢狀結構仍將被遍歷。 換句話說,is_leaf 不控制遞迴深度,而是提供了一種在 leaves_only=True 時從結果中過濾掉某些型別的方法。 這意味著樹中的一個節點可以既是葉節點,又是帶有子節點的節點。 實際上,
is_leaf的預設值會將 tensordict 和 tensorclass 例項從葉節點集中排除。另請參閱
- 關鍵字引數:
sort (bool, optional) – 是否應該對鍵進行排序。對於巢狀鍵,鍵將根據它們的連線名稱進行排序(即,
("a", "key")將被視為"a.key"進行排序)。請注意,處理大型 tensordict 時,排序可能會產生顯著的開銷。預設為False。
- var(dim: Union[int, Tuple[int], Literal['feature']] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, correction: int = 1, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor¶
返回輸入 tensordict 中所有元素的方差值。
- 引數:
dim (int, int 元組, optional) – 如果
None,則返回一個無量綱的 tensordict,其中包含所有葉節點的總和值(如果可以計算)。 如果是整數或整數元組,則僅當此維度與 tensordict 形狀相容時才對指定的維度呼叫 var。 目前只允許使用 “feature” 字串。 使用 dim="feature" 將實現所有特徵維度上的縮減。 如果 reduce=True,則將返回一個 TensorDict 批大小形狀的張量。 否則,將返回一個與self具有相同結構的新 tensordict,其中包含縮減的特徵維度。keepdim (bool) – 輸出張量是否保留 dim。
- 關鍵字引數:
示例
>>> from tensordict import TensorDict >>> import torch >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict( ... c=torch.randn(3, 4, 5, 6), ... d=torch.randn(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.var(dim=0) TensorDict( fields={ a: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([4, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([4]), device=None, is_shared=False) >>> td.var() TensorDict( fields={ a: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False) >>> td.var(reduce=True) tensor(1.0006) >>> td.var(dim="feature") TensorDict( fields={ a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False), b: TensorDict( fields={ c: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False), d: Tensor(shape=torch.Size([3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([3, 4, 5]), device=None, is_shared=False)}, batch_size=torch.Size([3, 4]), device=None, is_shared=False) >>> td = TensorDict( ... a=torch.ones(3, 4, 5), ... b=TensorDict( ... c=torch.ones(3, 4, 5), ... d=torch.ones(3, 4, 5), ... batch_size=(3, 4, 5), ... ), ... batch_size=(3, 4) ... ) >>> td.var(reduce=True, dim="feature") tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) >>> td.var(reduce=True, dim=0) tensor([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]])
- view(*shape: int, size: list | tuple | torch.Size | None = None, batch_size: torch.Size | None = None)¶
返回一個 tensordict,其中包含根據與 tensordict batch_size 相容的新形狀檢視的張量。
或者,可以提供 dtype 作為第一個未命名引數。在這種情況下,所有張量都將使用相應的 dtype 檢視。請注意,這假設新形狀將與提供的 dtype 相容。有關 dtype 檢視的更多資訊,請參見
view()。- 引數:
*shape (int) – 生成的 tensordict 的新形狀。
dtype (torch.dtype) – 或者,用於表示張量內容的 dtype。
size – 可迭代物件
- 關鍵字引數:
batch_size (torch.Size, optional) – 如果提供了 dtype,則可以使用此關鍵字引數重置 batch_size。 如果呼叫帶有 shape 的
view,則此操作無效。- 返回值:
具有所需 batch_size 的新 tensordict。
示例
>>> td = TensorDict(source={'a': torch.zeros(3,4,5), ... 'b': torch.zeros(3,4,10,1)}, batch_size=torch.Size([3, 4])) >>> td_view = td.view(12) >>> print(td_view.get("a").shape) # torch.Size([12, 5]) >>> print(td_view.get("b").shape) # torch.Size([12, 10, 1]) >>> td_view = td.view(-1, 4, 3) >>> print(td_view.get("a").shape) # torch.Size([1, 4, 3, 5]) >>> print(td_view.get("b").shape) # torch.Size([1, 4, 3, 10, 1])
- where(condition, other, *, out=None, pad=None)¶
返回一個
TensorDict,其中包含從 self 或 other 中選擇的元素,具體取決於 condition。- 引數:
condition (BoolTensor) – 當
True(非零) 時,產生self,否則產生other。other (TensorDictBase 或 Scalar) – 值 (如果
other是標量) 或在 condition 為False的索引處選擇的值。
- 關鍵字引數:
out (TensorDictBase, optional) – 輸出
TensorDictBase例項。pad (scalar, optional) – 如果提供,則源或目標 tensordict 中缺少的鍵將寫為 torch.where(mask, self, pad) 或 torch.where(mask, pad, other)。 預設為
None,即不允許缺少鍵。
- xpu(device: Optional[Union[int, device]] = None) T¶
將所有模型引數和緩衝區移動到 XPU。
這也會使關聯的引數和緩衝區成為不同的物件。因此,如果模組將在 XPU 上進行最佳化,則應在構造最佳化器之前呼叫它。
注意
此方法會就地修改模組。
- 引數:
device (int, optional) – 如果指定,所有引數都將複製到該裝置
- 返回值:
self
- 返回型別:
模組
- zero_() T¶
就地將 tensordict 中的所有張量置零。