torch.utils.dlpack¶
- torch.utils.dlpack.from_dlpack(ext_tensor) Tensor [來源][來源]¶
將來自外部函式庫的張量轉換為
torch.Tensor
。返回的 PyTorch 張量將與輸入張量(可能來自另一個函式庫)共享記憶體。 請注意,原地操作也會影響輸入張量的資料。 這可能會導致意想不到的問題(例如,其他函式庫可能具有唯讀標誌或不可變的資料結構),因此使用者應僅在確定沒問題的情況下才執行此操作。
- 參數
ext_tensor(具有
__dlpack__
屬性的物件,或是一個 DLPack 膠囊)–要轉換的 tensor 或 DLPack 膠囊。
如果
ext_tensor
是一個 tensor (或 ndarray) 物件,它必須支援__dlpack__
協定(也就是說,必須具有ext_tensor.__dlpack__
方法)。否則ext_tensor
可能是一個 DLPack 膠囊,這是一個不透明的PyCapsule
實例,通常是由to_dlpack
函數或方法所產生。- 回傳類型
範例
>>> import torch.utils.dlpack >>> t = torch.arange(4) # Convert a tensor directly (supported in PyTorch >= 1.10) >>> t2 = torch.from_dlpack(t) >>> t2[:2] = -1 # show that memory is shared >>> t2 tensor([-1, -1, 2, 3]) >>> t tensor([-1, -1, 2, 3]) # The old-style DLPack usage, with an intermediate capsule object >>> capsule = torch.utils.dlpack.to_dlpack(t) >>> capsule <capsule object "dltensor" at ...> >>> t3 = torch.from_dlpack(capsule) >>> t3 tensor([-1, -1, 2, 3]) >>> t3[0] = -9 # now we're sharing memory between 3 tensors >>> t3 tensor([-9, -1, 2, 3]) >>> t2 tensor([-9, -1, 2, 3]) >>> t tensor([-9, -1, 2, 3])
- torch.utils.dlpack.to_dlpack(tensor) PyCapsule ¶
回傳一個代表 tensor 的不透明物件(一個 "DLPack 膠囊")。
注意
to_dlpack
是一個舊版的 DLPack 介面。它回傳的膠囊除了作為from_dlpack
的輸入之外,無法在 Python 中用於其他任何用途。更慣用的 DLPack 用法是直接在 tensor 物件上呼叫from_dlpack
- 當該物件具有__dlpack__
方法時,這個方法有效,而 PyTorch 和大多數其他函式庫現在確實都有這個方法。警告
對於用
to_dlpack
產生的每個膠囊,只能呼叫from_dlpack
一次。多次使用膠囊的行為是未定義的。- 參數
tensor – 要匯出的 tensor
DLPack 膠囊共享 tensor 的記憶體。