LazyStackedTensorDict¶
- class tensordict.LazyStackedTensorDict(*tensordicts: T, stack_dim: int = 0, hook_out: callable | None = None, hook_in: callable | None = None, batch_size: Sequence[int] | None = None, device: torch.device | None = None, names: Sequence[str] | None = None, stack_dim_name: str | None = None, strict_shape: bool = False)¶
TensorDict 的延遲堆疊。
將 TensorDict 堆疊在一起時,預設行為是將它們放入一個未實例化的堆疊中。這允許無縫地處理 tensordicts 的堆疊,並進行會影響原始 tensordicts 的操作。
- 參數:
範例
>>> from tensordict import TensorDict >>> import torch >>> tds = [TensorDict({'a': torch.randn(3, 4)}, batch_size=[3]) ... for _ in range(10)] >>> td_stack = torch.stack(tds, -1) >>> print(td_stack.shape) torch.Size([3, 10]) >>> print(td_stack.get("a").shape) torch.Size([3, 10, 4]) >>> print(td_stack[:, 0] is tds[0]) True
- abs() T ¶
計算 TensorDict 中每個元素的絕對值。
- abs_() T ¶
就地 (in-place) 計算 TensorDict 中每個元素的絕對值。
- acos() T ¶
計算 TensorDict 中每個元素的
acos()
值。
- acos_() T ¶
就地 (in-place) 計算 TensorDict 中每個元素的
acos()
值。
- add(other: tensordict.base.TensorDictBase | torch.Tensor, *, alpha: Optional[float] = None, default: Optional[Union[str, Tensor]] = None) TensorDictBase ¶
將
other
乘以alpha
後,加到self
。\[\text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i\]- 參數:
other (TensorDictBase 或 torch.Tensor) – 要加到
self
的 tensor 或 TensorDict。- 關鍵字參數:
alpha (Number, optional) –
other
的乘數。default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- add_(other: tensordict.base.TensorDictBase | float, *, alpha: Optional[float] = None)¶
add()
的就地 (in-place) 版本。注意
就地 (in-place)
add
不支援default
關鍵字參數。
- 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, optional) – \(\text{tensor1} / \text{tensor2}\) 的乘數
- addcmul(other1, other2, *, 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, optional) – \(other1 .* other2\) 的乘數
- all(dim: Optional[int] = None) bool | tensordict.base.TensorDictBase ¶
檢查 tensordict 中是否所有值都為 True/非空值 (non-null)。
- 參數:
dim (int, optional) – 如果
None
,則傳回一個布林值,指示是否所有 tensors 都傳回 tensor.all() == True。如果是整數,則僅當此維度與 tensordict 形狀相容時,才會對指定的維度呼叫 all。
- any(dim: Optional[int] = None) bool | tensordict.base.TensorDictBase ¶
檢查 tensordict 中是否有任何值為 True/非空值。
- 參數:
dim (int, optional) – 如果
None
,則返回一個布林值,指示是否所有張量都返回 tensor.any() == True。 如果是整數,則僅當此維度與 tensordict 形狀相容時,才對指定的維度調用 all。
- append(tensordict: T) None ¶
將一個 TensorDict 附加到堆疊上。
類似於 list.append。附加的 TensorDict 必須具有相容的 batch_size 和 device。 附加操作是就地進行的,不會返回任何內容。
- 參數:
tensordict (TensorDictBase) – 要附加到堆疊上的 TensorDict。
- apply(fn: Callable, *others: T, 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: Optional[bool] = None, propagate_lock: bool = False, call_on_nested: bool = False, out: Optional[TensorDictBase] = None, **constructor_kwargs) Optional[T] ¶
將可呼叫物件應用於 tensordict 中儲存的所有值,並將它們設置在新的 tensordict 中。
可呼叫物件的簽章必須是
Callable[Tuple[Tensor, ...], Optional[Union[Tensor, TensorDictBase]]]
。- 參數:
fn (Callable) – 要應用於 tensordict 中張量的函式。
*others (TensorDictBase 的實例, 選填) – 如果提供,這些 tensordict 實例的結構應與 self 的結構相符。
fn
參數應接收與 tensordict 數量一樣多的未命名輸入,包括 self。如果其他 tensordict 缺少條目,可以透過default
關鍵字參數傳遞預設值。
- 關鍵字參數:
batch_size (int 的序列, 選填) – 如果提供,產生的 TensorDict 將具有所需的 batch_size。
batch_size
參數應與轉換後的 batch_size 相符。這是一個僅限關鍵字的參數。device (torch.device, 選填) – 產生的 device (如果有的話)。
names (str 的列表, 選填) – 新的維度名稱,以防 batch_size 被修改。
inplace (bool, 選填) – 如果為 True,則會進行原地變更。預設值為 False。這是一個僅限關鍵字的參數。
default (Any, 選填) – 其他 tensordict 中缺少條目的預設值。如果未提供,則缺少條目將引發 KeyError。
filter_empty (bool, 選填) – 如果
True
,則會過濾掉空的 tensordict。這也降低了計算成本,因為不會建立和銷毀空的資料結構。非 tensor 資料被視為葉節點,因此即使函式沒有觸及,也會保留在 tensordict 中。為了向後相容性,預設值為False
。propagate_lock (bool, 選填) – 如果
True
,則鎖定的 tensordict 將產生另一個鎖定的 tensordict。預設值為False
。call_on_nested (bool, 選填) –
如果
True
,則將在第一層的 tensors 和容器 (TensorDict 或 tensorclass) 上呼叫該函式。 在這種情況下,func
負責將其呼叫傳播到巢狀層級。 這允許在將呼叫傳播到巢狀 tensordicts 時進行細粒度的行為。 如果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 tensors 的新 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)¶
將可呼叫物件套用到 tensordict 中儲存的所有值,並將它們原地重寫。
- 參數:
fn (Callable) – 要應用於 tensordict 中張量的函式。
*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-size),最多到可選的 batch_dims。
- 參數:
batch_dims (int, optional) – 如果提供,批次大小最多為
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 的形狀 (shape) (或批次大小 (batch_size))。
tensordict 的形狀對應於其包含的 tensors 的共同前
N
個維度,其中N
是一個任意數字。批次大小 (batch-size) 與代表 tensor 在語義上相關的形狀的“特徵大小 (feature size)” 形成對比。 例如,一批影片可能具有形狀[B, T, C, W, H]
,其中[B, T]
是批次大小 (batch-size)(批次和時間維度),而[C, W, H]
是特徵維度(通道和空間維度)。TensorDict
的形狀在初始化時由使用者控制(即,它不是從 tensor 形狀推斷出來的)。如果新大小與 TensorDict 內容相容,則可以動態編輯
batch_size
。 例如,始終允許將批次大小設定為空值。- 傳回:
描述 TensorDict 批次大小的
Size
物件。
範例
>>> 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()¶
將所有 tensors 轉換為
torch.bfloat16
。
- bool()¶
將所有 tensors 轉換為
torch.bool
。
- bytes(*, count_duplicates: bool = True) int ¶
計算所包含的 tensors 的位元組數。
- 關鍵字參數:
count_duplicates (bool) – 是否將重複的 tensor 計算為獨立的。 如果
False
,則只會丟棄嚴格相同的 tensors(來自公共基礎 tensor 的相同檢視但不同的 ids 將被計算兩次)。 預設為 True (每個 tensor 都被假定為單一副本)。
- classmethod cat(input, dim=0, *, out=None)¶
沿給定維度將 tensordicts 連接成單個 tensordict。
此呼叫等效於呼叫
torch.cat()
但與 torch.compile 相容。
- cat_from_tensordict(dim: int = 0, *, sorted: Optional[Union[bool, List[NestedKey]]] = None, out: Optional[Tensor] = None) Tensor ¶
將 tensordict 中的所有條目串連成一個單一張量。
- 參數:
dim (int, optional) – 條目應沿其串連的維度。
- 關鍵字參數:
sorted (bool 或 NestedKeys 列表) – 如果
True
,條目將按字母順序串連。 如果False
(預設),將使用 dict 順序。 或者,可以提供金鑰名稱的列表,並且張量將相應地串連。 這會產生一些額外負擔,因為將根據 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 分割成指定數量的區塊。
每個 chunk 都是輸入 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_max(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: Optional[Union[str, Tensor]] = None) T ¶
如果
self
的元素大於other
的值,則將其鉗制為other
。- 參數:
other (TensorDict 或 Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 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: Optional[Union[str, Tensor]] = None) T ¶
如果
self
的元素小於other
的值,則將其鉗制為other
。- 參數:
other (TensorDict 或 Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 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
- clone(recurse: bool = True, **kwargs) T ¶
將 TensorDictBase 子類別實例複製到相同類型的新 TensorDictBase 子類別。
要從任何其他 TensorDictBase 子類型建立 TensorDict 實例,請改為呼叫
to_tensordict()
方法。- 參數:
recurse (bool, optional) – 若為
True
,TensorDict 中包含的每個張量也會被複製。否則,只會複製 TensorDict 的樹狀結構。預設為True
。
注意
與許多其他的操作(逐點算術、形狀操作等)不同,
clone
不會繼承原始的鎖定屬性。 這樣的設計選擇是為了可以建立一個 clone 並進行修改,這是最常見的用法。
- 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, optional) – 一個可選的檔案路徑,用於記憶體映射張量,並將其用作 tensordict 的儲存空間。
- 關鍵字參數:
num_threads (integer, optional) – 用於填充儲存空間的執行緒數。
device (torch.device, optional) – 一個可選的裝置,儲存空間必須在此裝置上實例化。
non_blocking (bool, optional) – 傳遞給
copy_()
的non_blocking
引數。inplace (bool, optional) – 如果為
True
,則產生的 tensordict 與self
相同,但值已更新。預設為False
。return_early (bool, optional) – 如果
True
且num_threads>0
,則該方法將傳回 tensordict 的 future。 可以使用 future.result() 查詢結果 tensordict。use_buffer (bool, optional) – 如果
True
且傳入檔案名稱,則會在共享記憶體中建立一個中間本地緩衝區,並且資料將在最後一個步驟複製到儲存位置。這可能會比直接寫入遠端物理記憶體(例如,NFS)更快。預設值為False
。share_memory (bool, optional) – 如果
True
,儲存空間將放置在共享記憶體中。預設值為False
。pin_memory (bool, optional) – 是否應將合併的資料放置在鎖定記憶體中。預設值為
False
。metadata (bool, optional) – 如果
True
,則元資料將與通用儲存空間一起儲存。如果提供了檔案名稱,則此選項無效。當需要控制序列化的實現方式時,儲存元資料可能很有用,因為如果元資料可用或不可用,TensorDict 會以不同的方式處理合併的 TD 的封裝/解封裝。
注意
如果 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() T ¶
返回一個與原始 TensorDict 相同類型的新 tensordict,其值是連續的(如果值已經是連續的,則返回 self)。
- copy()¶
返回 tensordict 的淺拷貝(即,複製結構但不複製資料)。
等同於 TensorDictBase.clone(recurse=False)
- copy_(tensordict: T, non_blocking: bool = False) 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: Optional[int] = None, **kwargs) T ¶
將 tensordict 轉換為 cuda 設備(如果尚未在其上)。
- 參數:
device (int, optional) – 如果提供,tensor 應轉換到的 cuda 設備。
此函數也支援
to()
的所有關鍵字參數。
- property data¶
返回一個 tensordict,其中包含葉 tensors 的 .data 屬性。
- data_ptr(*, storage: bool = False)¶
返回 tensordict 葉的 data_ptr。
這對於檢查兩個 tensordict 是否共享相同的
data_ptr()
可能很有用。- 關鍵字參數:
storage (bool, optional) – 如果
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)
- densify(*, layout: layout = torch.strided)¶
嘗試使用連續 tensors(普通 tensors 或巢狀)表示延遲堆疊。
- 關鍵字參數:
layout (torch.layout) – 巢狀 tensors 的佈局(如果有的話)。預設為
strided
。
- detach() T ¶
分離 tensordict 中的 tensors。
- 傳回:
一個新的 tensordict,其中沒有 tensor 需要梯度。
- detach_() T ¶
就地分離 tensordict 中的 tensors。
- 傳回:
self.
- property device: torch.device | None¶
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: Optional[Union[str, Tensor]] = None) T ¶
將輸入
self
的每個元素除以other
的對應元素。\[\text{out}_i = \frac{\text{input}_i}{\text{other}_i}\]支援廣播 (broadcasting)、類型提升 (type promotion) 以及整數、浮點數、tensordict 或張量輸入。總是將整數類型提升為預設的純量類型。
- 參數:
other (TensorDict, Tensor 或 Number) – 除數。
- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- div_(other: tensordict.base.TensorDictBase | torch.Tensor) T ¶
div()
的原地 (in-place) 版本。注意
原地
div
不支援default
關鍵字引數。
- double()¶
將所有 tensors 轉換為
torch.bool
。
- property dtype¶
如果 tensordict 中的值的 dtype 是唯一的,則傳回該 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 (str 的清單, optional) – 維度名稱。
- entry_class(key: NestedKey) type ¶
傳回條目的類別,可能避免呼叫 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()
值。
- exclude(*keys: NestedKey, inplace: bool = False) T ¶
排除 tensordict 的鍵,並回傳一個沒有這些條目的新 tensordict。
這些值不會被複製:對原始或新 tensordict 的張量進行就地修改,將會導致兩個 tensordict 都發生變更。
- 參數:
- 傳回:
一個新的 tensordict (如果
inplace=True
,則為相同的 tensordict),不包含排除的條目。
範例
>>> 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: int, inplace: bool = False) 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 的形狀,並據此進行擴展。
如果輸入是一個 tensor 集合(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 所指向的 tensor。
- 參數:
key (str 或 巢狀 key) – 要填寫的項目。
value (Number 或 bool) – 用於填寫的值。
- 傳回:
self
- filter_empty_()¶
就地篩選掉所有空的 tensordict。
- filter_non_tensor_data() T ¶
篩選掉所有非 tensor 的資料。
- flatten(start_dim=0, end_dim=- 1)¶
展平 tensordict 的所有 tensor。
範例
>>> 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, is_leaf: Optional[Callable[[Type], bool]] = None) T ¶
將巢狀 tensordict 遞迴地轉換為扁平的 tensordict。
TensorDict 類型將會遺失,結果將是一個簡單的 TensorDict 實例。
- 參數:
separator (str, optional) – 巢狀項目之間的分隔符號。
inplace (bool, optional) – 如果
True
,則產生的 tensordict 將與進行呼叫的 tensordict 具有相同的標識。預設為False
。is_leaf (callable, optional) – 一個可呼叫物件,針對類別類型返回一個布林值,指示是否應將此類別視為葉節點。
範例
>>> 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-dict 時特別有用,因為它們可以無縫地將扁平字典轉換為模仿模型結構的資料結構。範例
>>> 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()¶
將所有 tensors 轉換為
torch.float
。
- float16()¶
將所有 tensors 轉換為
torch.float16
。
- float32()¶
將所有 tensors 轉換為
torch.float32
。
- float64()¶
將所有 tensors 轉換為
torch.float64
。
- floor() T ¶
計算 TensorDict 中每個元素的
floor()
值。
- floor_() T ¶
就地 (in-place) 計算 TensorDict 中每個元素的
floor()
值。
- frac() T ¶
計算 TensorDict 中每個元素的
frac()
值。
- frac_() T ¶
就地 (in-place) 計算 TensorDict 中每個元素的
frac()
值。
- classmethod from_dict(input_dict, batch_size=None, device=None, batch_dims=None, stack_dim_name=None, stack_dim=0)¶
從字典或另一個
TensorDict
建立並傳回一個 TensorDict。如果未指定
batch_size
,則傳回可能的最大 batch size。此函數也適用於巢狀字典,或者可用於確定巢狀 tensordict 的 batch-size。
- 參數:
input_dict (dictionary, optional) – 用作資料來源的字典(相容於巢狀鍵)。
batch_size (iterable of int, optional) – tensordict 的 batch size。
device (torch.device 或 相容類型, optional) – TensorDict 的裝置。
batch_dims (int, optional) –
batch_dims
(即要考慮用於batch_size
的前導維度的數量)。 與batch_size
互斥。 請注意,這是 tensordict 的 __maximum__ batch dims 數,可以容忍較小的數字。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, batch_size=None, device=None, batch_dims=None, names=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='r')¶
從 h5 檔案建立一個 PersistentTensorDict。
此函數將自動確定每個巢狀 tensordict 的 batch-size。
- 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
,將使用來自模組的 state-dict,並將其解展平為一個具有模型樹狀結構的 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)¶
透過 vmap 檢索用於 ensemble learning/期望特徵應用程式的多個模組的參數。
- 參數:
modules (nn.Module 的序列) – 要從中獲取參數的模組。如果模組的結構不同,則需要 lazy stack(請參閱下面的
lazy_stack
參數)。- 關鍵字參數:
as_module (bool, optional) – 如果
True
,將返回一個TensorDictParams
實例,該實例可用於在torch.nn.Module
中儲存參數。默認為False
。lock (bool, optional) – 如果
True
,則產生的 tensordict 將被鎖定。默認為True
。use_state_dict (bool, optional) –
如果
True
,將使用來自模組的 state-dict,並將其解展平為一個具有模型樹狀結構的 TensorDict。默認為False
。注意
當需要使用 state-dict 鉤子時,這特別有用。
lazy_stack (bool, optional) –
參數應該密集堆疊還是延遲堆疊。默認為
False
(密集堆疊)。注意
lazy_stack
和as_module
是互斥的功能。警告
lazy 和 non-lazy 輸出之間的一個關鍵區別在於,non-lazy 輸出將重新實例化具有所需批次大小的參數,而
lazy_stack
只會將參數表示為延遲堆疊。這意味著,當lazy_stack=True
時,原始參數可以安全地傳遞給優化器,而當其設置為True
時,則需要傳遞新參數。警告
雖然使用 lazy stack 來保留原始參數引用可能很誘人,但請記住,lazy stack 每次調用
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)¶
遞迴地將一個 namedtuple 轉換為 TensorDict。
- 關鍵字參數:
auto_batch_size (bool, optional) – 如果
True
,批次大小將自動計算。預設為False
。
範例
>>> 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-to-tensordict 雙射轉換 API。
目前接受的類別包括 lists、tuples、named tuples 和 dict。
注意
對於字典,非 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, device: Optional[device] = None) T ¶
將一個結構化的 numpy 陣列轉換為 TensorDict。
結果 TensorDict 的內容將與 numpy 陣列共享相同的記憶體內容(這是一個零複製操作)。就地更改結構化的 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 fromkeys(keys: List[NestedKey], value: Any = 0)¶
從鍵的列表和單一值建立一個 tensordict。
- 參數:
keys (list of NestedKey) – 一個可迭代物件,指定新字典的鍵。
value (compatible type, optional) – 所有鍵的值。預設為
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: 'dist.ProcessGroup' | None = None) T | None ¶
從不同的 worker 收集 tensordict,並將它們堆疊到目標 worker 的 self 中。
- 參數:
dst (int) –
gather_and_stack()
將被呼叫的目的地 worker 的排名。group (torch.distributed.ProcessGroup, optional) – 如果設定,將使用指定的進程組進行通訊。否則,將使用預設進程組。預設值為
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://127.0.0.1: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://127.0.0.1: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, *args, **kwargs) Tensor ¶
取得使用輸入鍵儲存的值。
- 參數:
key (str, tuple of str) – 要查詢的鍵。如果是字串的元組,則等同於鏈式呼叫 getattr。
default –
如果在 tensordict 中找不到鍵,則為預設值。
警告
目前,如果在 tensordict 中不存在鍵且未傳遞預設值,則會引發 KeyError。 從 v0.7 開始,此行為將會變更,並會改為傳回 None 值。 若要採用新行為,請設定環境變數 export TD_GET_DEFAULTS_TO_NONE='1' 或呼叫 :func`~tensordict.set_get_defaults_to_none`。
範例
>>> td = TensorDict({"x": 1}, batch_size=[]) >>> td.get("x") tensor(1) >>> set_get_defaults_to_none(False) # Current default behaviour >>> td.get("y") # Raises KeyError >>> set_get_defaults_to_none(True) >>> td.get("y") None
- get_at(key: NestedKey, index: Union[None, int, slice, str, Tensor, List[Any], Tuple[Any, ...]], default: Tensor = _NoDefault.ZERO) Tensor ¶
從 tensordict 中獲取位於索引 idx 的鍵 key 的值。
- 參數:
key (str, str 的 tuple) – 要檢索的鍵。
index (int, slice, torch.Tensor, iterable) – tensor 的索引。
default (torch.Tensor) – 如果鍵不存在於 tensordict 中,則傳回的預設值。
- 傳回:
已索引的 tensor。
範例
>>> td = TensorDict({"x": torch.arange(3)}, batch_size=[]) >>> td.get_at("x", index=1) tensor(1)
- get_item_shape(key)¶
取得 lazy stack 中一個項目的形狀。
異質維度會傳回 -1。
此實作效率不高,因為它會嘗試堆疊項目以計算其形狀,因此僅應用於列印。
- get_nestedtensor(key: NestedKey, default: Any = _NoDefault.ZERO, *, layout: Optional[layout] = None) Tensor ¶
當無法達成堆疊時,傳回巢狀 tensor。
- 參數:
key (NestedKey) – 要巢狀化的項目。
default (Any, optional) –
如果鍵不在所有子 tensordict 中,則傳回的預設值。
注意
如果預設值為 tensor,此方法將嘗試使用它來建構巢狀 tensor。 否則,將傳回預設值。
- 關鍵字參數:
layout (torch.layout, optional) – 巢狀 tensor 的版面配置。
範例
>>> td0 = TensorDict({"a": torch.zeros(4), "b": torch.zeros(4)}, []) >>> td1 = TensorDict({"a": torch.ones(5)}, []) >>> td = torch.stack([td0, td1], 0) >>> a = td.get_nestedtensor("a") >>> # using a tensor as default uses this default to build the nested tensor >>> b = td.get_nestedtensor("b", default=torch.ones(4)) >>> assert (a == b).all() >>> # using anything else as default returns the default >>> b2 = td.get_nestedtensor("b", None) >>> assert b2 is None
- get_non_tensor(key: NestedKey, default=_NoDefault.ZERO)¶
取得非 tensor 值(如果存在),如果找不到非 tensor 值,則取得 default。
此方法對於 tensor/TensorDict 值具有強大的適應性,這表示如果收集的值是一般的 tensor,它也會被傳回(雖然此方法會產生一些額外負擔,不應在其自然範圍之外使用)。
有關如何在 tensordict 中設定非 tensor 值的更多資訊,請參閱
set_non_tensor()
。- 參數:
key (NestedKey) – NonTensorData 物件的位置。
default (Any, optional) – 如果找不到鍵,則傳回的值。
- 傳回:
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)
- property grad¶
傳回包含葉 tensor 的 .grad 屬性的 tensordict。
- half()¶
將所有 tensor 轉換為
torch.half
。
- insert(index: int, tensordict: T) None ¶
在指定的索引位置將 TensorDict 插入堆疊中。
類似於 list.insert。插入的 TensorDict 必須具有相容的 batch_size 和 device。插入是原地 (in-place) 操作,不返回任何值。
- 參數:
index (int) – 新 TensorDict 應該被插入的索引。
tensordict (TensorDictBase) – 要插入到堆疊中的 TensorDict。
- int()¶
將所有 tensors 轉換為
torch.int
。
- int16()¶
將所有 tensors 轉換為
torch.int16
。
- int32()¶
將所有 tensors 轉換為
torch.int32
。
- int64()¶
將所有 tensors 轉換為
torch.int64
。
- int8()¶
將所有 tensors 轉換為
torch.int8
。
- irecv(src: int, *, group: 'dist.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 的 rank。
- 關鍵字參數:
group (torch.distributed.ProcessGroup, optional) – 如果設定,將使用指定的進程組進行通訊。否則,將使用預設進程組。預設值為
None
。return_premature (bool) – 如果
True
,則返回一個 future 列表,等待直到 tensordict 被更新。預設為False
,即在呼叫中等待直到更新完成。init_tag (int) – 來源 worker 使用的
init_tag
。pseudo_rand (bool) – 如果為 True,tag 的序列將是偽隨機的,允許從不同節點發送多個資料而不會重疊。請注意,生成這些偽隨機數的成本很高(1e-5 秒/個數字),這意味著它可能會降低演算法的運行時間。此值必須與傳遞給
isend()
的值相符。預設為False
。
- 傳回:
- 如果
return_premature=True
,則返回一個 futures 列表,等待 直到 tensordict 被更新。
- 如果
- is_consolidated()¶
檢查 TensorDict 是否具有合併的儲存空間。
- is_memmap() bool ¶
檢查 tensordict 是否為記憶體映射。
如果 TensorDict 實例是記憶體映射的,則會被鎖定(條目無法重新命名、移除或新增)。 如果使用所有記憶體映射的 tensors 建立
TensorDict
,這__並不__表示is_memmap
將返回True
(因為新的 tensor 可能或可能不是記憶體映射的)。 只有在呼叫 tensordict.memmap_() 後,tensordict 才被視為記憶體映射。對於 CUDA 裝置上的 tensordict,這始終為
True
。
檢查 tensordict 是否在共享記憶體中。
如果 TensorDict 實例位於共享記憶體中,則會被鎖定(條目無法重新命名、移除或新增)。 如果使用所有位於共享記憶體中的 tensors 建立
TensorDict
,這__並不__表示is_shared
將返回True
(因為新的 tensor 可能或可能不在共享記憶體中)。 只有在呼叫 tensordict.share_memory_() 或將 tensordict 放置在內容預設共享的裝置上(例如,"cuda"
),tensordict 才被視為位於共享記憶體中。對於 CUDA 裝置上的 tensordict,這始終為
True
。
- isend(dst: int, *, group: 'dist.ProcessGroup' | None = None, init_tag: int = 0, pseudo_rand: bool = False) int ¶
非同步傳送 tensordict 的內容。
- 參數:
dst (int) – 應該傳送內容的目的工作人員的等級。
- 關鍵字參數:
範例
>>> 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://127.0.0.1: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://127.0.0.1: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=False, leaves_only=False, is_leaf=None, *, sort: bool = False)¶
返回 tensordict 的鍵值對產生器 (generator)。
- 參數:
- 關鍵字參數:
sort (bool, optional) – 是否應對鍵進行排序。對於巢狀鍵,鍵會根據它們的組合名稱 (joined name) 進行排序(即,
("a", "key")
將被視為"a.key"
進行排序)。請注意,處理大型 tensordict 時,排序可能會產生顯著的效能開銷。預設為False
。
- keys(include_nested: bool = False, leaves_only: bool = False, is_leaf: Optional[Callable[[Type], bool]] = None, *, sort: bool = False) _LazyStackedTensorDictKeysView ¶
返回 tensordict 鍵的產生器 (generator)。
警告
TensorDict 的
keys()
方法返回鍵的延遲視圖 (lazy view)。如果查詢了keys
但沒有迭代它們,然後修改了 tensordict,稍後迭代這些鍵將返回鍵的新配置。- 參數:
- 關鍵字參數:
sort (bool, optional) – 是否應對鍵進行排序。對於巢狀鍵,鍵會根據它們的組合名稱 (joined name) 進行排序(即,
("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(items: Sequence[TensorDictBase], dim: int = 0, *, device: Optional[Union[device, str, int]] = None, out: Optional[T] = None, stack_dim_name: Optional[str] = None, strict_shape: bool = False) T ¶
將 tensordict 物件堆疊成 LazyStackedTensorDict。
- 參數:
items (TensorDictBase 實例的序列) – 要堆疊的 TensorDictBase 實例的序列。
dim (int, optional) – 執行延遲堆疊的維度。預設值為 0。
- 關鍵字參數:
device (torch.device, optional) – 一個裝置,用於在無法從 tensordict 清單中推斷出的情況下,在 LazyStackedTensorDict 中設定(例如,清單為空)。
out (TensorDictBase, optional) – 寫入資料的 LazyStackedTensorDict。
stack_dim_name (str, optional) – 堆疊維度的名稱。
strict_shape (bool, optional) – 如果為
True
,則每個 tensordict 的形狀必須匹配。預設值為False
。
- 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 | float, weight: tensordict.base.TensorDictBase | float)¶
lerp()
的原地 (in-place) 版本。
- lgamma() T ¶
計算 TensorDict 中每個元素的
lgamma()
值。
- lgamma_() T ¶
原地 (in-place) 計算 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 或 等效物件, optional) – 如果提供,資料將被非同步地轉換到該裝置。支援 “meta” 裝置,在這種情況下,資料不會被載入,而是建立一組空的 “meta” 張量。這對於了解總模型大小和結構,而無需實際打開任何檔案非常有用。
non_blocking (bool, optional) – 如果
True
,則在將 tensors 載入裝置後,不會呼叫 synchronize。預設為False
。out (TensorDictBase, optional) – 可選的 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" 裝置上,或者作為一個假的 tensor。
範例
>>> 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)¶
載入記憶體映射 (memory-mapped) 的 tensordict 的內容到呼叫
load_memmap_
的 tensordict 中。參閱
load_memmap()
以取得更多資訊。
- load_state_dict(state_dict: OrderedDict[str, Any], strict=True, assign=False, from_flatten=False) T ¶
載入一個 state-dict,格式如
state_dict()
,到 tensordict 中。- 參數:
state_dict (OrderedDict) – 要複製的 state_dict。
strict (bool, optional) – 是否嚴格要求
state_dict
中的鍵與此 tensordict 的torch.nn.Module.state_dict()
函數傳回的鍵相符。預設值:True
assign (bool, optional) – 是否將 state dictionary 中的項目賦值到 tensordict 中對應的鍵,而不是將它們原地複製到 tensordict 當前的 tensors 中。當
False
時,會保留當前模組中 tensors 的屬性,而當True
時,會保留 state dict 中 tensors 的屬性。預設值:False
from_flatten (bool, optional) – 如果
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,使其無法進行原地 (in-place) 操作。
諸如
set()
,__setitem__()
,update()
,rename_key_()
或其他新增或移除 entries 的操作將被阻止。此方法可以用作裝飾器 (decorator)。
範例
>>> 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()
值,原地 (in-place) 進行。
- log1p() T ¶
計算 TensorDict 中每個元素的
log1p()
值。
- log1p_() T ¶
計算 TensorDict 中每個元素的
log1p()
值,原地 (in-place) 進行。
- log2() T ¶
計算 TensorDict 中每個元素的
log2()
值。
- log2_() T ¶
原地 (in-place) 計算 TensorDict 中每個元素的
log2()
值。
- log_() T ¶
原地 (in-place) 計算 TensorDict 中每個元素的
log()
值。
- make_memmap(key: NestedKey, shape: torch.Size | torch.Tensor, *, dtype: Optional[dtype] = None) MemoryMappedTensor ¶
根據給定的形狀 (shape) 和可能的資料類型 (dtype) 建立一個空的記憶體映射張量 (memory-mapped tensor)。
警告
此方法在設計上不是鎖定安全的 (lock-safe)。存在於多個節點上的記憶體映射 TensorDict 實例需要使用方法
memmap_refresh_()
進行更新。寫入現有的條目會導致錯誤。
- 參數:
key (NestedKey) – 要寫入的新條目的鍵。如果該鍵已存在於 tensordict 中,則會引發例外。
shape (torch.Size 或 等效值, nested tensors 則為 torch.Tensor) – 要寫入的張量的形狀。
- 關鍵字參數:
dtype (torch.dtype, optional) – 新張量的資料類型。
- 傳回:
一個新的記憶體映射張量。
- make_memmap_from_storage(key: NestedKey, storage: UntypedStorage, shape: torch.Size | torch.Tensor, *, dtype: Optional[dtype] = None) MemoryMappedTensor ¶
根據給定的儲存空間 (storage)、形狀 (shape) 和可能的資料類型 (dtype) 建立一個空的記憶體映射張量 (memory-mapped tensor)。
警告
此方法在設計上不是鎖定安全的 (lock-safe)。存在於多個節點上的記憶體映射 TensorDict 實例需要使用方法
memmap_refresh_()
進行更新。注意
如果儲存空間已關聯一個檔案名稱,則它必須與檔案的新檔案名稱匹配。如果它沒有關聯的檔案名稱,但 tensordict 有關聯的路徑,則會導致例外。
- 參數:
key (NestedKey) – 要寫入的新條目的鍵。如果該鍵已存在於 tensordict 中,則會引發例外。
storage (torch.UntypedStorage) – 用於新 MemoryMappedTensor 的儲存空間。必須是實體記憶體儲存空間。
shape (torch.Size 或 等效值, nested tensors 則為 torch.Tensor) – 要寫入的張量的形狀。
- 關鍵字參數:
dtype (torch.dtype, optional) – 新張量的資料類型。
- 傳回:
具有給定儲存空間的新記憶體映射張量。
- make_memmap_from_tensor(key: NestedKey, tensor: Tensor, *, copy_data: bool = True) MemoryMappedTensor ¶
根據給定的張量 (tensor) 建立一個空的記憶體映射張量 (memory-mapped tensor)。
警告
此方法在設計上不是鎖定安全的 (lock-safe)。存在於多個節點上的記憶體映射 TensorDict 實例需要使用方法
memmap_refresh_()
進行更新。如果
copy_data
為True
,此方法始終複製儲存空間的內容 (即,不共享儲存空間)。- 參數:
key (NestedKey) – 要寫入的新條目的鍵。如果該鍵已存在於 tensordict 中,則會引發例外。
tensor (torch.Tensor) – 要在實體記憶體上複製的張量。
- 關鍵字參數:
copy_data (bool, optionaL) – 如果
False
,則新張量將共享輸入的中繼資料,例如形狀和資料類型,但內容將為空。預設為True
。- 傳回:
具有給定儲存空間的新記憶體映射張量。
- map(fn: Callable[[TensorDictBase], TensorDictBase | None], dim: int = 0, num_workers: int | None = None, *, out: TensorDictBase | None = None, chunksize: int | None = None, num_chunks: int | None = None, pool: mp.Pool | None = None, generator: torch.Generator | None = None, max_tasks_per_child: int | None = None, worker_threads: int = 1, index_with_generator: bool = False, pbar: bool = False, mp_start_method: str | None = None)¶
將函式映射到 tensordict 在一個維度上的分割。
這個方法會將函式應用於 tensordict 實例,方法是將它分割成大小相等的 tensordict,並將操作分派到所需數量的 worker 上。
函式的簽名應該是
Callabe[[TensorDict], Union[TensorDict, Tensor]]
。輸出必須支援torch.cat()
操作。該函式必須是可序列化的。注意
當處理儲存在磁碟上的大型資料集(例如,memory-mapped tensordict)時,這個方法特別有用,因為 chunks 將是原始資料的 zero-copied 切片,可以以幾乎零成本的方式傳遞給程序。這允許以很少的成本處理非常大的資料集(例如,超過 Tb 大小)。
- 參數:
- 關鍵字參數:
out (TensorDictBase, optional) – 用於輸出的可選容器。其沿著提供的
dim
維度的批次大小(batch-size)必須與self.ndim
相符。 如果它是共享記憶體或記憶體映射(memmap)(is_shared()
或is_memmap()
回傳True
),它將在遠端程序中被填充,從而避免資料向內傳輸。否則,來自self
切片的資料將被傳送到該程序,在當前程序上收集並就地寫入到out
中。chunksize (int, optional) – 每個資料塊的大小。
chunksize
為 0 將沿著所需的維度解綁(unbind)tensordict,並在應用函數後重新堆疊它,而chunksize>0
將分割 tensordict 並在生成的 tensordict 列表上調用torch.cat()
。 如果未提供,資料塊的數量將等於工作人員的數量。 對於非常大的 tensordict,如此大的資料塊可能不適合記憶體以進行操作,可能需要更多的資料塊才能使操作實際可行。 此參數與num_chunks
互斥。num_chunks (int, optional) – 要將 tensordict 分割成的資料塊的數量。 如果未提供,資料塊的數量將等於工作人員的數量。 對於非常大的 tensordict,如此大的資料塊可能不適合記憶體以進行操作,可能需要更多的資料塊才能使操作實際可行。 此參數與
chunksize
互斥。pool (mp.Pool, optional) – 用於執行工作的多進程 Pool 實例。 如果未提供,將在
map
方法中建立一個 pool。generator (torch.Generator, optional) –
用於設定種子的 generator。 將從它生成一個基本種子,並且 pool 的每個工作人員都將使用提供的種子遞增一個從
0
到num_workers
的唯一整數來設定種子。 如果未提供 generator,將使用一個隨機整數作為種子。 要與未設定種子的工作人員一起使用,應單獨建立一個 pool 並直接傳遞給map()
。注意
當提供一個低值的種子時,應謹慎,因為這可能會導致實驗之間的自相關,例如:如果請求 8 個工作人員並且種子為 4,則工作人員的種子將從 4 到 11。如果種子為 5,則工作人員的種子將從 5 到 12。這兩個實驗將有 7 個種子重疊,這可能會對結果產生意想不到的影響。
注意
為工作人員設定種子的目標是在每個工作人員上都有獨立的種子,而不是在 map 方法的呼叫中獲得可重現的結果。 換句話說,兩個實驗可能並且很可能會返回不同的結果,因為不可能知道哪個工作人員將選擇哪個工作。 但是,我們可以確保每個工作人員都有不同的種子,並且每個工作人員上的偽隨機操作是不相關的。
max_tasks_per_child (int, optional) – 每個子程序選取的最大任務數。 預設為
None
,即對任務數沒有限制。worker_threads (int, optional) – 工作人員的執行緒數。 預設為
1
。index_with_generator (bool, optional) – 如果
True
,tensordict 的分割/分塊將在查詢期間完成,從而節省初始化時間。 請注意,chunk()
和split()
比索引(在 generator 中使用)效率更高,因此在初始化時節省處理時間可能會對總運行時間產生負面影響。 預設為False
。pbar (bool, optional) – 如果
True
,將顯示進度條。 需要 tqdm 可用。 預設為False
。mp_start_method (str, optional) – 多進程的啟動方法。 如果未提供,將使用預設的啟動方法。 接受的字串為
"fork"
和"spawn"
。 請記住,"cuda"
張量不能在使用"fork"
啟動方法的程序之間共享。 如果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]]
。該函數必須可序列化。注意
當處理儲存在磁碟上的大型資料集(例如,memory-mapped tensordict)時,這個方法特別有用,因為 chunks 將是原始資料的 zero-copied 切片,可以以幾乎零成本的方式傳遞給程序。這允許以很少的成本處理非常大的資料集(例如,超過 Tb 大小)。
注意
此函數可用於表示資料集並從中載入資料,類似於資料載入器的方式。
- 參數:
- 關鍵字參數:
shuffle (bool, optional) – 指出是否應全域隨機排序索引。如果
True
,則每個批次將包含非連續樣本。如果index_with_generator=False
且 shuffle=True`,則會引發錯誤。預設為False
。chunksize (int, optional) – 每個資料塊的大小。
chunksize
為 0 將沿著所需的維度解綁(unbind)tensordict,並在應用函數後重新堆疊它,而chunksize>0
將分割 tensordict 並在生成的 tensordict 列表上調用torch.cat()
。 如果未提供,資料塊的數量將等於工作人員的數量。 對於非常大的 tensordict,如此大的資料塊可能不適合記憶體以進行操作,可能需要更多的資料塊才能使操作實際可行。 此參數與num_chunks
互斥。num_chunks (int, optional) – 要將 tensordict 分割成的資料塊的數量。 如果未提供,資料塊的數量將等於工作人員的數量。 對於非常大的 tensordict,如此大的資料塊可能不適合記憶體以進行操作,可能需要更多的資料塊才能使操作實際可行。 此參數與
chunksize
互斥。pool (mp.Pool, optional) – 用於執行工作的多進程 Pool 實例。 如果未提供,將在
map
方法中建立一個 pool。generator (torch.Generator, optional) –
用於設定種子的 generator。 將從它生成一個基本種子,並且 pool 的每個工作人員都將使用提供的種子遞增一個從
0
到num_workers
的唯一整數來設定種子。 如果未提供 generator,將使用一個隨機整數作為種子。 要與未設定種子的工作人員一起使用,應單獨建立一個 pool 並直接傳遞給map()
。注意
當提供一個低值的種子時,應謹慎,因為這可能會導致實驗之間的自相關,例如:如果請求 8 個工作人員並且種子為 4,則工作人員的種子將從 4 到 11。如果種子為 5,則工作人員的種子將從 5 到 12。這兩個實驗將有 7 個種子重疊,這可能會對結果產生意想不到的影響。
注意
為工作人員設定種子的目標是在每個工作人員上都有獨立的種子,而不是在 map 方法的呼叫中獲得可重現的結果。 換句話說,兩個實驗可能並且很可能會返回不同的結果,因為不可能知道哪個工作人員將選擇哪個工作。 但是,我們可以確保每個工作人員都有不同的種子,並且每個工作人員上的偽隨機操作是不相關的。
max_tasks_per_child (int, optional) – 每個子程序選取的最大任務數。 預設為
None
,即對任務數沒有限制。worker_threads (int, optional) – 工作人員的執行緒數。 預設為
1
。index_with_generator (bool, optional) –
如果
True
,則 tensordict 的分割/分塊將在查詢期間完成,從而節省初始化時間。請注意,chunk()
和split()
比索引(在產生器中使用)效率更高,因此在初始化時節省處理時間可能會對總執行時間產生負面影響。預設值為True
。注意
index_with_generator
的預設值對於map_iter
和map
是不同的,前者假設將 TensorDict 的分割版本儲存在記憶體中成本過高。pbar (bool, optional) – 如果
True
,將顯示進度條。 需要 tqdm 可用。 預設為False
。mp_start_method (str, optional) – 多進程的啟動方法。 如果未提供,將使用預設的啟動方法。 接受的字串為
"fork"
和"spawn"
。 請記住,"cuda"
張量不能在使用"fork"
啟動方法的程序之間共享。 如果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(mask: Tensor, value: float | bool) T ¶
masked_fill 的異地 (Out-of-place) 版本。
- 參數:
mask (boolean torch.Tensor) – 要填充的值的遮罩。形狀必須與 tensordict 的批次大小相符。
value – 用於填充 tensors 的值。
- 傳回:
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_(mask: Tensor, value: float | bool) T ¶
用所需的值填充對應於遮罩的值。
- 參數:
mask (boolean torch.Tensor) – 要填充的值的遮罩。形狀必須與 tensordict 的批次大小相符。
value – 用於填充 tensors 的值。
- 傳回:
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 的所有 tensors,並傳回一個新的 TensorDict 實例,其中包含指向遮罩值的相似鍵。
- 參數:
mask (torch.Tensor) – 用於 tensors 的布林遮罩。形狀必須與 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.]])
- maximum(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: Optional[Union[str, Tensor]] = None) T ¶
計算
self
和other
的逐元素最大值。- 參數:
other (TensorDict 或 Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- maximum_(other: tensordict.base.TensorDictBase | torch.Tensor) T ¶
maximum()
的原地 (In-place) 版本。注意
原地
maximum
不支援default
關鍵字引數。
- classmethod maybe_dense_stack(items: Sequence[TensorDictBase], dim: int = 0, out: Optional[T] = None, strict: bool = False) T ¶
如果可能,將 tensors 或 tensordicts 以密集方式堆疊,否則堆疊到 LazyStackedTensorDict 上。
範例
>>> td0 = TensorDict({"a": 0}, []) >>> td1 = TensorDict({"b": 0}, []) >>> LazyStackedTensorDict.maybe_dense_stack([td0, td0]) # returns a TensorDict with shape [2] >>> LazyStackedTensorDict.maybe_dense_stack([td0, td1]) # returns a LazyStackedTensorDict with shape [2] >>> LazyStackedTensorDict.maybe_dense_stack(list(torch.randn(2))) # returns a torch.Tensor with shape [2]
- mean(dim: Union[int, Tuple[int]] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor ¶
傳回輸入 tensordict 中所有元素的平均值。
- 參數:
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回 tensor 的所需資料類型。如果指定,則在執行操作之前,輸入 tensor 會轉換為 dtype。這對於防止資料類型溢位很有用。預設值:
None
。reduce (bool, optional) – 如果
True
,則將在所有 TensorDict 值上進行歸約,並傳回單個歸約 tensor。預設為False
。
- 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 ¶
將所有 tensors 寫入新的 tensordict 中對應的記憶體對應 Tensor。
- 參數:
- 關鍵字參數:
num_threads (執行緒數量) (int, optional (選填)) – 用於寫入記憶體對應 (memmap) 張量的執行緒數量。預設值為 0。
return_early (提早返回) (bool, optional (選填)) – 如果
True
且num_threads>0
,該方法將會返回 tensordict 的 future (期貨)。share_non_tensor (共享非張量) (bool, optional (選填)) – 如果
True
,非張量資料將會在進程和寫入操作之間共享(例如,inplace 更新或設定),並且單一節點中任何 worker 上的操作都會更新所有其他 worker 上的值。如果非張量葉節點的數量很多(例如,共享大量非張量資料堆疊),這可能會導致記憶體不足 (OOM) 或類似的錯誤。預設值為False
。existsok (已存在也沒關係) (bool, optional (選填)) – 如果
False
,如果在相同的路徑中已經存在張量,則會引發例外。預設值為True
。
然後 TensorDict 會被鎖定,這表示任何非 in-place (原地) 的寫入操作都會拋出例外(例如,重新命名、設定或移除項目)。一旦 tensordict 被解鎖,記憶體對應 (memory-mapped) 屬性會變為
False
,因為跨進程 (cross-process) 的一致性已不再保證。- 傳回:
如果
return_early=False
,則會返回一個新的 tensordict,其中的張量儲存在磁碟上;否則會返回一個TensorDictFuture
實例。
注意
以這種方式序列化對於深度巢狀的 tensordict 可能會很慢,因此不建議在訓練迴圈中呼叫此方法。
- 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 ¶
將所有張量 in-place (原地) 寫入對應的記憶體對應張量 (memory-mapped Tensor)。
- 參數:
- 關鍵字參數:
num_threads (執行緒數量) (int, optional (選填)) – 用於寫入記憶體對應 (memmap) 張量的執行緒數量。預設值為 0。
return_early (bool, optional) – 如果
True
且num_threads>0
,則該方法將傳回 tensordict 的 future。 可以使用 future.result() 查詢結果 tensordict。share_non_tensor (共享非張量) (bool, optional (選填)) – 如果
True
,非張量資料將會在進程和寫入操作之間共享(例如,inplace 更新或設定),並且單一節點中任何 worker 上的操作都會更新所有其他 worker 上的值。如果非張量葉節點的數量很多(例如,共享大量非張量資料堆疊),這可能會導致記憶體不足 (OOM) 或類似的錯誤。預設值為False
。existsok (已存在也沒關係) (bool, optional (選填)) – 如果
False
,如果在相同的路徑中已經存在張量,則會引發例外。預設值為True
。
然後 TensorDict 會被鎖定,這表示任何非 in-place (原地) 的寫入操作都會拋出例外(例如,重新命名、設定或移除項目)。一旦 tensordict 被解鎖,記憶體對應 (memory-mapped) 屬性會變為
False
,因為跨進程 (cross-process) 的一致性已不再保證。- 傳回:
如果
return_early=False
,則返回 self (自身);否則返回一個TensorDictFuture
實例。
注意
以這種方式序列化對於深度巢狀的 tensordict 可能會很慢,因此不建議在訓練迴圈中呼叫此方法。
- memmap_like(prefix: Optional[str] = None, copy_existing: bool = False, *, existsok: bool = True, num_threads: int = 0, return_early: bool = False, share_non_tensor: bool = False) T ¶
建立一個無內容 (contentless) 的記憶體對應 tensordict (Memory-mapped tensordict),其形狀與原始 tensordict 相同。
- 參數:
- 關鍵字參數:
num_threads (執行緒數量) (int, optional (選填)) – 用於寫入記憶體對應 (memmap) 張量的執行緒數量。預設值為 0。
return_early (提早返回) (bool, optional (選填)) – 如果
True
且num_threads>0
,該方法將會返回 tensordict 的 future (期貨)。share_non_tensor (共享非張量) (bool, optional (選填)) – 如果
True
,非張量資料將會在進程和寫入操作之間共享(例如,inplace 更新或設定),並且單一節點中任何 worker 上的操作都會更新所有其他 worker 上的值。如果非張量葉節點的數量很多(例如,共享大量非張量資料堆疊),這可能會導致記憶體不足 (OOM) 或類似的錯誤。預設值為False
。existsok (已存在也沒關係) (bool, optional (選填)) – 如果
False
,如果在相同的路徑中已經存在張量,則會引發例外。預設值為True
。
然後 TensorDict 會被鎖定,這表示任何非 in-place (原地) 的寫入操作都會拋出例外(例如,重新命名、設定或移除項目)。一旦 tensordict 被解鎖,記憶體對應 (memory-mapped) 屬性會變為
False
,因為跨進程 (cross-process) 的一致性已不再保證。- 傳回:
如果
return_early=False
,則返回一個新的TensorDict
實例,其中的資料儲存為記憶體對應張量 (memory-mapped tensors);否則返回一個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
,則重新整理其內容。如果沒有路徑與之關聯,此方法將引發例外。
- minimum(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: Optional[Union[str, Tensor]] = None) T ¶
計算
self
和other
的元素最小值。- 參數:
other (TensorDict 或 Tensor) – 另一個輸入 tensordict 或 tensor。
- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- minimum_(other: tensordict.base.TensorDictBase | torch.Tensor) T ¶
minimum()
的原地 (in-place) 版本。注意
Inplace
minimum
不支援default
關鍵字引數。
- mul(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: Optional[Union[str, Tensor]] = None) T ¶
將
other
乘以self
。\[\text{{out}}_i = \text{{input}}_i \times \text{{other}}_i\]支援廣播、類型提升以及整數、浮點數和複數輸入。
- 參數:
other (TensorDict, Tensor 或 Number) – 要從
self
減去的張量或數字。- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- mul_(other: tensordict.base.TensorDictBase | torch.Tensor) T ¶
mul()
的原地 (in-place) 版本。注意
Inplace
mul
不支援default
關鍵字引數。
- named_apply(fn: Callable, *others: T, nested_keys: bool = False, 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: Optional[bool] = None, propagate_lock: bool = False, call_on_nested: bool = False, out: Optional[TensorDictBase] = None, **constructor_kwargs) Optional[T] ¶
將鍵條件的可呼叫物件套用至 tensordict 中儲存的所有值,並將它們設置在新的 atensordict 中。
可呼叫物件的簽章必須是
Callable[Tuple[str, Tensor, ...], Optional[Union[Tensor, TensorDictBase]]]
。- 參數:
fn (Callable) – 要套用至 tensordict 中 (名稱, 張量) 對的函式。對於每個葉節點,只會使用其葉節點名稱(而不是完整的 NestedKey)。
*others (TensorDictBase 的實例, 選填) – 如果提供,這些 tensordict 實例的結構應與 self 的結構相符。
fn
參數應接收與 tensordict 數量一樣多的未命名輸入,包括 self。如果其他 tensordict 缺少條目,可以透過default
關鍵字參數傳遞預設值。nested_keys (bool, optional) – 如果
True
,將使用葉節點的完整路徑。預設為False
,也就是只將最後一個字串傳遞給函式。batch_size (int 的序列, 選填) – 如果提供,產生的 TensorDict 將具有所需的 batch_size。
batch_size
參數應與轉換後的 batch_size 相符。這是一個僅限關鍵字的參數。device (torch.device, 選填) – 產生的 device (如果有的話)。
names (str 的列表, 選填) – 新的維度名稱,以防 batch_size 被修改。
inplace (bool, optional) – 如果為 True,則會就地進行變更。預設值為 False。這是一個僅限關鍵字引數。
default (Any, 選填) – 其他 tensordict 中缺少條目的預設值。如果未提供,則缺少條目將引發 KeyError。
filter_empty (bool, optional) – 若為
True
,則會過濾掉空的 tensordict。這也能降低計算成本,因為不會建立和銷毀空的資料結構。為了向後相容性,預設值為False
。propagate_lock (bool, optional) – 若為
True
,鎖定的 tensordict 將會產生另一個鎖定的 tensordict。預設值為False
。call_on_nested (bool, optional) –
如果
True
,則將在第一層的 tensors 和容器 (TensorDict 或 tensorclass) 上呼叫該函式。 在這種情況下,func
負責將其呼叫傳播到巢狀層級。 這允許在將呼叫傳播到巢狀 tensordicts 時進行細粒度的行為。 如果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 tensors 的新 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)
- property names¶
tensordict 的維度名稱。
名稱可以在建構時使用
names
參數進行設定。另請參閱
refine_names()
以取得有關如何在建構後設定名稱的詳細資訊。
- nanmean(dim: Union[int, Tuple[int]] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor ¶
傳回輸入 tensordict 中所有非 NaN 元素的平均值。
- 參數:
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回 tensor 的所需資料類型。如果指定,則在執行操作之前,輸入 tensor 會轉換為 dtype。這對於防止資料類型溢位很有用。預設值:
None
。reduce (bool, optional) – 如果
True
,則將在所有 TensorDict 值上進行歸約,並傳回單個歸約 tensor。預設為False
。
- nansum(dim: Union[int, Tuple[int]] = _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 。keepdim (bool) – 輸出 tensor 是否保留 dim。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回 tensor 的所需資料類型。如果指定,則在執行操作之前,輸入 tensor 會轉換為 dtype。這對於防止資料類型溢位很有用。預設值:
None
。reduce (bool, optional) – 如果
True
,則將在所有 TensorDict 值上進行歸約,並傳回單個歸約 tensor。預設為False
。
- property ndim: int¶
請參閱
batch_dims()
。
- ndimension() int ¶
請參閱
batch_dims()
。
- neg() T ¶
計算 TensorDict 中每個元素的
neg()
值。
- neg_() T ¶
就地 (in-place) 計算 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...) – 一個整數的列表、元組或 torch.Size,用於定義輸出 tensor 的形狀。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回的 tensordict 的所需型別。預設值:如果
None
,則 torch.dtype 將保持不變。device (torch.device, optional) – 傳回的 tensordict 的所需裝置。預設值:如果
None
,則torch.device
將保持不變。requires_grad (bool, optional) – 如果 autograd 應記錄對傳回 tensors 的操作。預設值:
False
。layout (torch.layout, optional) – 傳回的 TensorDict 值的所需佈局。預設值:
torch.strided
。pin_memory (bool, optional) – 如果設定,傳回的 tensor 將被分配在釘選的記憶體 (pinned memory) 中。僅適用於 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
且填充特定數值的 TensorDict。預設情況下,傳回的 TensorDict 具有與此 tensordict 相同的
torch.dtype
和torch.device
。- 參數:
size (整數序列) – 一個列表、元組或 torch.Size 的整數,用於定義輸出張量的形狀。
fill_value (純量) – 用於填充輸出張量的數值。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回的 tensordict 的所需型別。預設值:如果
None
,則 torch.dtype 將保持不變。device (torch.device, optional) – 傳回的 tensordict 的所需裝置。預設值:如果
None
,則torch.device
將保持不變。requires_grad (bool, optional) – 如果 autograd 應記錄對傳回 tensors 的操作。預設值:
False
。layout (torch.layout, optional) – 傳回的 TensorDict 值的所需佈局。預設值:
torch.strided
。pin_memory (bool, optional) – 如果設定,傳回的 tensor 將被分配在釘選的記憶體 (pinned memory) 中。僅適用於 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
且填充特定數值的 TensorDict。預設情況下,傳回的 TensorDict 具有與此 tensordict 相同的
torch.dtype
和torch.device
。- 參數:
size (int...) – 一個整數的列表、元組或 torch.Size,用於定義輸出 tensor 的形狀。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回的 tensordict 的所需型別。預設值:如果
None
,則 torch.dtype 將保持不變。device (torch.device, optional) – 傳回的 tensordict 的所需裝置。預設值:如果
None
,則torch.device
將保持不變。requires_grad (bool, optional) – 如果 autograd 應記錄對傳回 tensors 的操作。預設值:
False
。layout (torch.layout, optional) – 傳回的 TensorDict 值的所需佈局。預設值:
torch.strided
。pin_memory (bool, optional) – 如果設定,傳回的 tensor 將被分配在釘選的記憶體 (pinned memory) 中。僅適用於 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)¶
傳回一個新的 TensorDict,其資料為 tensor
data
。預設情況下,傳回的 TensorDict 值與此 tensor 具有相同的
torch.dtype
和torch.device
。data
也可以是 tensor 集合(TensorDict
或tensorclass
),在這種情況下,new_tensor
方法會迭代self
和data
的 tensor 配對。- 參數:
data (torch.Tensor 或 TensorDictBase) – 要複製的資料。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回的 tensordict 的所需型別。預設值:如果
None
,則 torch.dtype 將保持不變。device (torch.device, optional) – 傳回的 tensordict 的所需裝置。預設值:如果
None
,則torch.device
將保持不變。requires_grad (bool, optional) – 如果 autograd 應記錄對傳回 tensors 的操作。預設值:
False
。pin_memory (bool, optional) – 如果設定,傳回的 tensor 將被分配在釘選的記憶體 (pinned memory) 中。僅適用於 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...) – 一個整數的列表、元組或 torch.Size,用於定義輸出 tensor 的形狀。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回的 tensordict 的所需型別。預設值:如果
None
,則 torch.dtype 將保持不變。device (torch.device, optional) – 傳回的 tensordict 的所需裝置。預設值:如果
None
,則torch.device
將保持不變。requires_grad (bool, optional) – 如果 autograd 應記錄對傳回 tensors 的操作。預設值:
False
。layout (torch.layout, optional) – 傳回的 TensorDict 值的所需佈局。預設值:
torch.strided
。pin_memory (bool, optional) – 如果設定,傳回的 tensor 將被分配在釘選的記憶體 (pinned memory) 中。僅適用於 CPU tensors。預設值:
False
。
- norm(*, out=None, dtype: torch.dtype | None = None)¶
計算 tensordict 中每個 tensor 的範數。
- 關鍵字參數:
out (TensorDict, optional) – 輸出 tensordict。
dtype (torch.dtype, optional) – 輸出 dtype (torch>=2.4)。
- numpy()¶
將 tensordict 轉換為 numpy 陣列的(可能為巢狀的)字典。
非 tensor 資料會如此呈現。
範例
>>> 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 ¶
計算參數數量(可索引項目的總數),僅計算 tensor。
- 關鍵字參數:
count_duplicates (bool) – 是否將重複的 tensor 計算為獨立的。 如果
False
,則只會丟棄嚴格相同的 tensors(來自公共基礎 tensor 的相同檢視但不同的 ids 將被計算兩次)。 預設為 True (每個 tensor 都被假定為單一副本)。
- 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(num_threads: Optional[int] = None, inplace: bool = False) T ¶
在儲存的 tensor 上呼叫
pin_memory()
。- 參數:
num_threads (int or str) – 如果提供,則用於在 leaves 上呼叫
pin_memory
的執行緒數量。 預設為None
,這會在ThreadPoolExecutor(max_workers=None)
中設定大量的執行緒。 若要在主執行緒上執行所有對pin_memory()
的呼叫,請傳遞num_threads=0
。inplace (bool, optional) – 如果
True
,則 tensordict 會就地修改。 預設為False
。
- pin_memory_(num_threads: int | str = 0) T ¶
在儲存的 tensor 上呼叫
pin_memory()
,並傳回就地修改的 TensorDict。
- pop(key: NestedKey, default: Any = _NoDefault.ZERO) Tensor ¶
從 tensordict 中移除並傳回一個值。
如果該值不存在且未提供預設值,則會拋出 KeyError。
- 參數:
key (str 或 巢狀鍵 (nested key)) – 要尋找的項目。
default (Any, optional) – 如果找不到鍵,則傳回的值。
範例
>>> td = TensorDict({"1": 1}, []) >>> one = td.pop("1") >>> assert one == 1 >>> none = td.pop("1", default=None) >>> assert none is None
- pow(other: tensordict.base.TensorDictBase | torch.Tensor, *, default: Optional[Union[str, Tensor]] = None) T ¶
計算
self
中每個元素與other
的次方,並傳回包含結果的 tensor。other
可以是單一float
數字、Tensor 或TensorDict
。當
other
是一個 tensor 時,input
和other
的形狀必須是可廣播的 (broadcastable)。- 參數:
other (float, tensor 或 tensordict) – 指數值
- 關鍵字參數:
default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- pow_(other: tensordict.base.TensorDictBase | torch.Tensor) T ¶
pow()
的原地 (in-place) 版本。注意
原地
pow
不支援default
關鍵字引數。
- prod(dim: Union[int, Tuple[int]] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, dtype: Optional[dtype] = None, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor ¶
傳回輸入 tensordict 中所有元素的數值乘積。
- 參數:
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回 tensor 的所需資料類型。如果指定,則在執行操作之前,輸入 tensor 會轉換為 dtype。這對於防止資料類型溢位很有用。預設值:
None
。reduce (bool, optional) – 如果
True
,則將在所有 TensorDict 值上進行歸約,並傳回單個歸約 tensor。預設為False
。
- qint32()¶
將所有張量轉換為
torch.qint32
。
- qint8()¶
將所有張量轉換為
torch.qint8
。
- quint4x2()¶
將所有張量轉換為
torch.quint4x2
。
- quint8()¶
將所有張量轉換為
torch.quint8
。
- reciprocal() T ¶
計算 TensorDict 中每個元素的
reciprocal()
值。
- reciprocal_() T ¶
就地計算 TensorDict 中每個元素的
reciprocal()
值。
- record_stream(stream: Stream)¶
將 tensordict 標記為已被此流使用。
當 tensordict 被釋放時,確保張量記憶體在釋放時佇列在流上的所有工作完成之前,不會被其他張量重複使用。
有關更多資訊,請參閱
record_stream()
。
- recv(src: int, *, group: 'dist.ProcessGroup' | None = None, init_tag: int = 0, pseudo_rand: bool = False) int ¶
接收一個 tensordict 的內容,並使用其更新內容。
請查看 send 方法中的範例以了解上下文。
- 參數:
src (int) – 來源 worker 的 rank。
- 關鍵字參數:
- reduce(dst, op=None, async_op=False, return_premature=False, group=None)¶
在所有機器上簡化 tensordict。
只有具有
rank
dst 的進程才會收到最終結果。
- refine_names(*names) T ¶
根據名稱優化 self 的維度名稱。
優化是重新命名的特殊情況,可以「提升」未命名的維度。None 維度可以被優化為任何名稱;命名的維度只能被優化為相同的名稱。
由於命名的張量可以與未命名的張量共存,因此優化名稱提供了一種很好的方法來編寫同時適用於命名和未命名張量的、能識別命名張量的程式碼。
names 最多可以包含一個 Ellipsis (…)。Ellipsis 會被貪婪地擴展;它會被就地擴展,以使用 self.names 中相應索引的名稱,將 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"]
- rename(*names, **rename_map)¶
傳回一個具有重新命名維度的 tensordict 的副本。
範例
>>> 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) T ¶
使用新的字串重新命名金鑰,並傳回具有更新金鑰名稱的相同 tensordict。
- replace(*args, **kwargs)¶
建立一個 tensordict 的淺層副本,其中的條目已被替換。
接受一個未命名的引數,該引數必須是
TensorDictBase
子類的字典。 此外,可以使用命名的關鍵字引數更新第一層條目。- 傳回:
如果輸入非空,則傳回
self
的副本,其中的條目已更新。如果提供了空字典或沒有提供字典,且 kwargs 為空,則傳回self
。
- requires_grad_(requires_grad=True) T ¶
變更是否讓 autograd 記錄此 tensor 上的操作:原地 (in-place) 設定此 tensor 的 requires_grad 屬性。
傳回此 tensordict。
- 參數:
requires_grad (bool, optional) – 是否讓 autograd 記錄此 tensordict 上的操作。預設為
True
。
- reshape(*args, **kwargs) T ¶
傳回一個連續的、重新塑形的 tensor,具有所需的形狀。
- 參數:
*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 ¶
原地 (in-place) 計算 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: 'dist.ProcessGroup' | None = None, init_tag: int = 0, pseudo_rand: bool = False) None ¶
將 tensordict 的內容發送到遠端 worker。
- 參數:
dst (int) – 應該傳送內容的目的工作人員的等級。
- 關鍵字參數:
範例
>>> 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://127.0.0.1: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://127.0.0.1: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()
- set(key: NestedKey, item: Tensor, inplace: bool = False, *, non_blocking: bool = False, **kwargs: Any) T ¶
設定新的鍵值對。
- 參數:
key (str, str 的 tuple) – 要設定的鍵的名稱。
item (torch.Tensor 或等效類型, TensorDictBase 實例) – 要儲存在 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, *, non_blocking: bool = False) T ¶
設定現有鍵的值,同時保留原始儲存空間。
- 參數:
key (str) – 值的名稱
item (torch.Tensor 或 相容類型, 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, ...]], *, non_blocking: bool = False) T ¶
將
index
所指示的索引處的值就地設定。- 參數:
key (str, str 的 tuple) – 要修改的鍵。
value (torch.Tensor) – 要設定在索引 index 處的值
index (int, tensor 或 tuple) – 寫入值的索引。
- 關鍵字參數:
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_non_tensor(key: NestedKey, value: Any)¶
使用
tensordict.tensorclass.NonTensorData
在 tensordict 中註冊一個非 tensor 值。該值可以使用
TensorDictBase.get_non_tensor()
檢索,也可以直接使用 get 檢索,後者將返回tensordict.tensorclass.NonTensorData
物件。回傳: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)
- setdefault(key: NestedKey, default: Tensor, inplace: bool = False) Tensor ¶
如果
key
不在 tensordict 中,則插入一個key
條目,其值為default
。如果
key
在 tensordict 中,則傳回key
的值,否則傳回default
。- 參數:
key (str 或 巢狀鍵) – 值的名稱。
default (torch.Tensor 或 相容類型, TensorDictBase) – 如果該鍵尚未存在,則要儲存在 tensordict 中的值。
- 傳回:
tensordict 中鍵的值。如果先前未設定該鍵,則將為預設值。
範例
>>> 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
。
將所有 tensor 放入共享記憶體中。
TensorDict 接著會被鎖定,這表示任何非原地 (in-place) 的寫入操作都會拋出例外 (例如,重新命名、設定或移除項目)。相反地,一旦 tensordict 被解鎖,`share_memory` 屬性會被設為
False
,因為跨程序的身分不再能保證。- 傳回:
self
- sigmoid() T ¶
計算 TensorDict 中每個元素的
sigmoid()
值。
- sigmoid_() T ¶
原地 (in-place) 計算 TensorDict 中每個元素的
sigmoid()
值。
- sign() T ¶
計算 TensorDict 中每個元素的
sign()
值。
- sign_() T ¶
原地 (in-place) 計算 TensorDict 中每個元素的
sign()
值。
- sin() T ¶
計算 TensorDict 中每個元素的
sin()
值。
- sin_() T ¶
原地 (in-place) 計算 TensorDict 中每個元素的
sin()
值。
- sinh() T ¶
計算 TensorDict 中每個元素的
sinh()
值。
- sinh_() T ¶
原地 (in-place) 計算 TensorDict 中每個元素的
sinh()
值。
- size(dim: Optional[int] = None) torch.Size | int ¶
返回
dim
所指示維度的大小。如果未指定
dim
,則返回 TensorDict 的batch_size
屬性。
- property sorted_keys: list[tensordict._nestedkey.NestedKey]¶
返回按字母順序排序的鍵。
不支援額外的參數。
如果 TensorDict 被鎖定,則鍵會被快取,直到 tensordict 被解鎖,以加快執行速度。
- split(split_size: int | list[int], dim: int = 0) list[tensordict.base.TensorDictBase] ¶
像 torch.split 一樣,使用指定的大小在給定的維度中分割 TensorDict 中的每個張量。
返回
TensorDict
實例的列表,其中包含分割後區塊項目的視圖 (view)。- 參數:
- 傳回:
具有給定維度中指定大小的 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, strict: bool = True, reproduce_struct: bool = False)¶
將 tensordict 分割成子集合,依據一個或多個鍵值集合。
此方法將返回
N+1
個 tensordict,其中N
是提供的參數數量。- 參數:
inplace (bool, optional) – 如果
True
,則鍵值會從self
中原地移除。預設為False
。strict (bool, optional) – 如果
True
,當鍵值遺失時會引發例外。預設為True
。reproduce_struct (bool, optional) – 如果
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 的所有條目堆疊成單一 tensor。
- 參數:
dim (int, optional) – 條目應該沿著堆疊的維度。
- 關鍵字參數:
sorted (bool 或 NestedKey 的列表) – 如果
True
,則條目將按字母順序堆疊。 如果False
(預設),將使用 dict 的順序。 此外,可以提供金鑰名稱的列表,並且 tensor 將相應地堆疊。 這會產生一些額外負擔,因為金鑰列表將針對 tensordict 中的葉名稱列表進行檢查。out (torch.Tensor, optional) – 用於堆疊操作的可選目標 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(destination=None, prefix='', keep_vars=False, flatten=False) OrderedDict[str, Any] ¶
從 tensordict 產生一個 state_dict。
state-dict 的結構仍然是巢狀的,除非將
flatten
設定為True
。tensordict state-dict 包含重建 tensordict 所需的所有 tensor 和元數據 (目前不支援名稱)。
- 參數:
destination (dict, optional) – 如果提供,tensordict 的狀態將更新到 dict 中,並傳回相同的物件。 否則,將建立並傳回一個
OrderedDict
。 預設值:None
。prefix (str, optional) – 一個加到 tensor 名稱的前綴,用於組成 state_dict 中的金鑰。 預設值:
''
。keep_vars (bool, optional) – 預設情況下,state dict 中傳回的
torch.Tensor
項目與 autograd 分離。 如果設定為True
,則不會執行分離。 預設值:False
。flatten (bool, optional) – 是否要使用
"."
字元來扁平化結構。預設值為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]] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, correction: int = 1, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor ¶
傳回輸入 tensordict 中所有元素的標準差值。
- 參數:
- 關鍵字參數:
- sub(other: tensordict.base.TensorDictBase | float, *, alpha: Optional[float] = None, default: Optional[Union[str, Tensor]] = None)¶
從
self
中減去other
,並按alpha
縮放。\[\text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i\]支援廣播、類型提升以及整數、浮點數和複數輸入。
- 參數:
other (TensorDict, Tensor 或 Number) – 要從
self
減去的張量或數字。- 關鍵字參數:
alpha (Number) –
other
的乘數。default (torch.Tensor 或 str, optional) – 用於獨佔條目的預設值。 如果未提供,則兩個 tensordict 的鍵列表必須完全匹配。 如果傳遞
default="intersection"
,則只會考慮相交的鍵集,而其他鍵將被忽略。 在所有其他情況下,default
將用於運算兩側的所有遺失條目。
- sub_(other: tensordict.base.TensorDictBase | float, alpha: Optional[float] = None)¶
sub()
的原地 (in-place) 版本。注意
原地
sub
不支援default
關鍵字引數。
- sum(dim: Union[int, Tuple[int]] = _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 。keepdim (bool) – 輸出 tensor 是否保留 dim。
- 關鍵字參數:
dtype (torch.dtype, optional) – 傳回 tensor 的所需資料類型。如果指定,則在執行操作之前,輸入 tensor 會轉換為 dtype。這對於防止資料類型溢位很有用。預設值:
None
。reduce (bool, optional) – 如果
True
,則將在所有 TensorDict 值上進行歸約,並傳回單個歸約 tensor。預設為False
。
- tan() T ¶
計算 TensorDict 中每個元素的
tan()
值。
- tan_() T ¶
就地 (in-place) 計算 TensorDict 中每個元素的
tan()
值。
- tanh() T ¶
計算 TensorDict 中每個元素的
tanh()
值。
- tanh_() T ¶
就地 (in-place) 計算 TensorDict 中每個元素的
tanh()
值。
- to(*args, **kwargs) T ¶
將 TensorDictBase 子類別映射到另一個裝置、dtype 或另一個 TensorDictBase 子類別(如果允許)。
不允許將 tensors 轉換為新的 dtype,因為 tensordicts 並非僅限於包含單一 tensor dtype。
- 參數:
device (torch.device, optional) – tensordict 所需的裝置。
dtype (torch.dtype, optional) – tensordict 所需的浮點數或複數 dtype。
tensor (torch.Tensor, optional) – Tensor,其 dtype 和 device 是此 TensorDict 中所有 tensors 所需的 dtype 和 device。
- 關鍵字參數:
non_blocking (bool, optional) – 是否應阻止 (blocking) 操作。
memory_format (torch.memory_format, optional) – 此 tensordict 中 4D 參數和緩衝區所需的記憶體格式。
batch_size (torch.Size, optional) – 輸出 tensordict 的結果 batch-size。
other (TensorDictBase, optional) –
TensorDict 實例,其 dtype 和 device 是此 TensorDict 中所有 tensors 所需的 dtype 和 device。
注意
由於
TensorDictBase
實例沒有 dtype,因此 dtype 是從範例葉節點收集的。 如果有多個 dtype,則不進行 dtype 轉換。non_blocking_pin (bool, optional) –
如果
True
,張量在被傳送到裝置前會先被釘選 (pinned)。這會以非同步方式執行,但可以透過num_threads
參數來控制。注意
呼叫
tensordict.pin_memory().to("cuda")
通常會比tensordict.to("cuda", non_blocking_pin=True)
慢很多,因為在後者的情況下,pin_memory 是以非同步方式呼叫的。如果張量很大且數量眾多,多執行緒的pin_memory
通常會很有幫助:當要傳送的張量太少時,產生執行緒和收集資料的額外開銷會超過多執行緒的優勢;如果張量很小,則遍歷長列表的額外開銷也會非常大。num_threads (int or None, optional) – 如果
non_blocking_pin=True
,則用於pin_memory
的執行緒數量。預設情況下,將產生max(1, torch.get_num_threads())
個執行緒。num_threads=0
將取消 pin_memory() 呼叫的任何多執行緒處理。
- 傳回:
如果裝置與 tensordict 裝置不同,和/或傳遞了 dtype,則為一個新的 tensordict 實例。否則為相同的 tensordict。只有
batch_size
的修改會就地完成。
注意
如果 TensorDict 已整合 (consolidated),則產生的 TensorDict 也會是整合的。每個新的張量都會是已整合儲存體的視圖 (view),並轉換為所需的裝置。
範例
>>> 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_h5(filename, **kwargs)¶
將 tensordict 轉換為具有 h5 後端的 PersistentTensorDict。
- 參數:
filename (str or path) – h5 檔案的路徑。
device (torch.device or compatible, optional) – 期望傳回張量時所在的裝置。預設值為
None
(預設為 cpu)。**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, optional) – 若為
True
,則模組中的參數或張量會就地 (in-place) 更新。預設值為False
。return_swap (bool, optional) – 若為
True
,則會回傳舊的參數設定。預設值為False
。swap_dest (TensorDictBase, optional) – 若
return_swap
為True
,則此為應寫入交換 (swap) 的 tensordict。use_state_dict (bool, optional) – 若為
True
,則會使用 state-dict API 來載入參數 (包含 state-dict hook)。預設值為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 作為上下文管理器 (context manager) 對於進行函數式呼叫 (functional calls) 很有用:.. 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, optional) – 可選擇要使用的 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)¶
將所有巢狀張量 (nested tensors) 轉換為帶填充的版本 (padded version),並相應地調整批次大小 (batch-size)。
- 參數:
padding (float) – tensordict 中張量的填充值。預設值為
0.0
。mask_key (NestedKey, optional) – 若提供,則此為寫入有效值遮罩 (mask) 的鍵。如果異質維度 (heterogeneous dimension) 不是 tensordict 批次大小的一部分,則會導致錯誤。預設值為
None
- to_pytree()¶
將 tensordict 轉換為 PyTree。
如果 tensordict 不是從 pytree 建立的,則此方法僅回傳
self
而不進行修改。有關更多資訊和範例,請參閱
from_pytree()
。
- to_struct_array()¶
將 tensordict 轉換為 numpy 結構化陣列 (structured array)。
在
from_struct_array()
-to_struct_array()
迴圈中,輸入和輸出陣列的內容應相符。但是,to_struct_array 不會保留原始陣列的記憶體內容。有關更多資訊,請參閱
from_struct_array()
。
- to_tensordict(*, retain_none: Optional[bool] = None) T ¶
從 TensorDictBase 回傳一個常規的 TensorDict 實例。
- 參數:
retain_none (bool) –
若為
True
,則來自 tensorclass 實例的None
值將寫入 tensordict。否則,它們將被捨棄。預設值:True
。注意
從 v0.8 開始,預設值將切換為
False
。- 傳回:
一個包含相同值的新 TensorDict 物件。
- transpose(dim0, dim1)¶
傳回一個 tensordict,它是輸入的轉置版本。給定的維度
dim0
和dim1
會被交換。轉置後的 tensordict 的原地 (in-place) 或異地 (out-place) 修改也會影響原始的 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()
值,並進行原地 (in-place) 修改。
- uint16()¶
將所有 tensors 轉換為
torch.uint16
。
- uint32()¶
將所有 tensors 轉換為
torch.uint32
。
- uint64()¶
將所有 tensors 轉換為
torch.uint64
。
- uint8()¶
將所有 tensors 轉換為
torch.uint8
。
- unbind(dim: int) tuple[T, ...] ¶
傳回一個索引 tensordicts 的 tuple,沿指定的維度解綁。
範例
>>> 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) – 指定要展開的輸入 tensor 的維度。
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) T ¶
遞迴地將扁平的 tensordict 轉換為巢狀的 tensordict。
TensorDict 類型將會遺失,結果將是一個簡單的 TensorDict 實例。巢狀 tensordicts 的元資料將從根節點推斷:資料樹中的所有實例將共享相同的批次大小、維度名稱和裝置。
- 參數:
separator (str, optional) – 巢狀項目之間的分隔符號。
inplace (bool, optional) – 如果
True
,則產生的 tensordict 將與進行呼叫的 tensordict 具有相同的標識。預設為False
。
範例
>>> 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-dict 時特別有用,因為它們可以無縫地將扁平字典轉換為模仿模型結構的資料結構。範例
>>> 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 之間的所有 tensors 增加一個維度,並將它們傳回一個新的 tensordict 中。
- 參數:
dim (int) – 要增加維度的維度
範例
>>> 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 的更改將會進行異地 (out-place) 修改,也就是說,原始 tensors 的內容不會被更改。這也假設 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: T, clone: bool = False, *, keys_to_update: Optional[Sequence[NestedKey]] = None, non_blocking: bool = False, is_leaf: Optional[Callable[[Type], bool]] = None, **kwargs: Any) T ¶
使用來自字典或另一個 TensorDict 的值來更新 TensorDict。
- 參數:
input_dict_or_td (TensorDictBase 或 dict) – 要寫入 self 的輸入資料。
clone (bool, optional) – 是否應在設定之前複製輸入 (tensor) 字典中的 tensors。預設值為
False
。inplace (bool, optional) – 如果
True
,且鍵與 tensordict 中的現有鍵匹配,則該鍵值對的更新將就地進行。如果找不到該項目,則會新增它。預設值為False
。
- 關鍵字參數:
keys_to_update (NestedKeys 的序列, optional) – 如果提供,則只會更新
key_to_update
中的鍵清單。目的是避免呼叫data_dest.update(data_src.select(*keys_to_update))
。non_blocking (bool, optional) – 如果
True
且此複製發生在不同裝置之間,則此複製可能相對於主機非同步發生。is_leaf (Callable[[Type], bool], optional) – 一個可呼叫物件,指示物件類型是否應被視為葉節點並進行交換,或作為 tensor 集合。
- 傳回:
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: dict[str, torch.Tensor] | tensordict.base.TensorDictBase, clone: bool = False, *, non_blocking: bool = False, **kwargs: Any) T ¶
使用來自字典或另一個 TensorDict 的值就地更新 TensorDict。
與
update()
不同,如果self
不知道該鍵,此函數將擲回錯誤。- 參數:
input_dict_or_td (TensorDictBase 或 dict) – 要寫入 self 的輸入資料。
clone (bool, optional) – 是否應在設定之前複製輸入 (tensor) 字典中的 tensors。預設值為
False
。
- 關鍵字參數:
keys_to_update (NestedKeys 的序列, optional) – 如果提供,則只會更新
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: dict[str, torch.Tensor] | tensordict.base.TensorDictBase, index: Union[None, int, slice, str, Tensor, List[Any], Tuple[Any, ...]], clone: bool = False, *, non_blocking: bool = False) T ¶
使用來自字典或另一個 TensorDict 的值,在指定的索引位置就地更新 TensorDict。
與 TensorDict.update 不同,如果鍵對於 TensorDict 而言是未知的,此函數將會拋出錯誤。
- 參數:
input_dict_or_td (TensorDictBase 或 dict) – 要寫入 self 的輸入資料。
idx (int, torch.Tensor, iterable, slice) – 應該發生更新的 tensordict 的索引。
clone (bool, optional) – 是否應在設定之前複製輸入(tensor)字典中的 tensors。預設值為 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()
- valid_keys(include_nested: bool = False, leaves_only: bool = False, is_leaf: Optional[Callable[[Type], bool]] = None, *, sort: bool = False) _LazyStackedTensorDictKeysView ¶
返回 tensordict 鍵的產生器 (generator)。
警告
TensorDict 的
keys()
方法返回鍵的延遲視圖 (lazy view)。如果查詢了keys
但沒有迭代它們,然後修改了 tensordict,稍後迭代這些鍵將返回鍵的新配置。- 參數:
- 關鍵字參數:
sort (bool, optional) – 是否應對鍵進行排序。對於巢狀鍵,鍵會根據它們的組合名稱 (joined name) 進行排序(即,
("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')]
- values(include_nested=False, leaves_only=False, is_leaf=None, *, sort: bool = False)¶
傳回表示 tensordict 值的產生器。
- 參數:
- 關鍵字參數:
sort (bool, optional) – 是否應對鍵進行排序。對於巢狀鍵,鍵會根據它們的組合名稱 (joined name) 進行排序(即,
("a", "key")
將被視為"a.key"
進行排序)。請注意,處理大型 tensordict 時,排序可能會產生顯著的效能開銷。預設為False
。
- var(dim: Union[int, Tuple[int]] = _NoDefault.ZERO, keepdim: bool = _NoDefault.ZERO, *, correction: int = 1, reduce: Optional[bool] = None) tensordict.base.TensorDictBase | torch.Tensor ¶
傳回輸入 tensordict 中所有元素的變異數值。
- 參數:
- 關鍵字參數:
- view(*shape: int, size: list | tuple | torch.Size | None = None, batch_size: torch.Size | None = None)¶
傳回一個 tensordict,其中包含根據新形狀檢視的 tensors,該形狀與 tensordict batch_size 相容。
或者,可以提供 dtype 作為第一個未命名的引數。在這種情況下,所有 tensors 都將以相應的 dtype 檢視。請注意,這假設新形狀將與提供的 dtype 相容。有關 dtype 檢視的更多資訊,請參閱
view()
。- 參數:
*shape (int) – 結果 tensordict 的新形狀。
dtype (torch.dtype) – 或者,用於表示 tensor 內容的 dtype。
size – 可迭代物件
- 關鍵字參數:
batch_size (torch.Size, 選用) – 如果提供了 dtype,則可以使用此關鍵字引數重設 batch_size。如果使用形狀呼叫
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) – 在 condition 為
False
的索引處選擇的值(如果other
是標量)。
- 關鍵字參數:
out (TensorDictBase, 選用) – 輸出
TensorDictBase
實例。pad (scalar, 選用) – 如果提供,則來自來源或目標 tensordict 的遺漏鍵將寫為 torch.where(mask, self, pad) 或 torch.where(mask, pad, other)。預設值為
None
,即不允許遺漏鍵。
- zero_() T ¶
原地將 tensordict 中的所有 tensors 歸零。