• 文件 >
  • 操作 TensorDict 的形狀
快捷方式

Manipulating the shape of a TensorDict

作者: Tom Begley

在本教程中,您將學習如何操作 TensorDict 及其內容的形狀。

當我們建立 TensorDict 時,我們會指定一個 batch_size,該 batch_size 必須與 TensorDict 中的所有條目的前導維度一致。由於我們保證所有條目共享這些共同的維度,因此 TensorDict 能夠公開許多方法,我們可以用它們來操作 TensorDict 及其內容的形狀。

import torch
from tensordict.tensordict import TensorDict

Indexing a TensorDict

由於保證批處理維度存在於所有條目上,我們可以按需對其進行索引,並且 TensorDict 的每個條目都將以相同的方式進行索引。

a = torch.rand(3, 4)
b = torch.rand(3, 4, 5)
tensordict = TensorDict({"a": a, "b": b}, batch_size=[3, 4])

indexed_tensordict = tensordict[:2, 1]
assert indexed_tensordict["a"].shape == torch.Size([2])
assert indexed_tensordict["b"].shape == torch.Size([2, 5])

Reshaping a TensorDict

TensorDict.reshape 的工作方式與 torch.Tensor.reshape() 類似。它應用於 TensorDict 沿批處理維度的所有內容——請注意下面示例中 b 的形狀。它還會更新 batch_size 屬性。

reshaped_tensordict = tensordict.reshape(-1)
assert reshaped_tensordict.batch_size == torch.Size([12])
assert reshaped_tensordict["a"].shape == torch.Size([12])
assert reshaped_tensordict["b"].shape == torch.Size([12, 5])

Splitting a TensorDict

TensorDict.split 類似於 torch.Tensor.split()。它將 TensorDict 分成塊。每個塊都是一個 TensorDict,其結構與原始 TensorDict 相同,但其條目是原始 TensorDict 中對應條目的檢視。

chunks = tensordict.split([3, 1], dim=1)
assert chunks[0].batch_size == torch.Size([3, 3])
assert chunks[1].batch_size == torch.Size([3, 1])
torch.testing.assert_close(chunks[0]["a"], tensordict["a"][:, :-1])

注意

每當函式或方法接受 dim 引數時,負維度都將相對於函式或方法所呼叫的 TensorDictbatch_size 進行解釋。特別是,如果存在具有不同批處理大小的巢狀 TensorDict 值,則負維度始終相對於根的批處理維度進行解釋。

>>> tensordict = TensorDict(
...     {
...         "a": torch.rand(3, 4),
...         "nested": TensorDict({"b": torch.rand(3, 4, 5)}, [3, 4, 5])
...     },
...     [3, 4],
... )
>>> # dim = -2 will be interpreted as the first dimension throughout, as the root
>>> # TensorDict has 2 batch dimensions, even though the nested TensorDict has 3
>>> chunks = tensordict.split([2, 1], dim=-2)
>>> assert chunks[0].batch_size == torch.Size([2, 4])
>>> assert chunks[0]["nested"].batch_size == torch.Size([2, 4, 5])

從這個例子中可以看到,TensorDict.split 方法的作用與我們在呼叫之前將 dim=-2 替換為 dim=tensordict.batch_dims - 2 之前呼叫是完全一樣的。

Unbind

TensorDict.unbind 類似於 torch.Tensor.unbind(),並且在概念上類似於 TensorDict.split。它會移除指定的維度,並沿著該維度返回所有切片組成的 tuple

slices = tensordict.unbind(dim=1)
assert len(slices) == 4
assert all(s.batch_size == torch.Size([3]) for s in slices)
torch.testing.assert_close(slices[0]["a"], tensordict["a"][:, 0])

Stacking and concatenating

TensorDict 可以與 torch.cattorch.stack 結合使用。

Stacking TensorDict

堆疊可以是惰性的或連續的。惰性堆疊只是一個 tensordicts 列表,表示為 tensordicts 的堆疊。它允許使用者攜帶具有不同內容形狀、裝置或鍵集的 tensordicts 包。另一個優點是堆疊操作可能很昂貴,如果只需要一小部分鍵,惰性堆疊將比真正的堆疊快得多。它依賴於 LazyStackedTensorDict 類。在這種情況下,值將在訪問時才按需堆疊。

from tensordict import LazyStackedTensorDict

cloned_tensordict = tensordict.clone()
stacked_tensordict = LazyStackedTensorDict.lazy_stack(
    [tensordict, cloned_tensordict], dim=0
)
print(stacked_tensordict)

# Previously, torch.stack was always returning a lazy stack. For consistency with
# the regular PyTorch API, this behaviour will soon be adapted to deliver only
# dense tensordicts. To control which behaviour you are relying on, you can use
# the :func:`~tensordict.utils.set_lazy_legacy` decorator/context manager:

from tensordict.utils import set_lazy_legacy

with set_lazy_legacy(True):  # old behaviour
    lazy_stack = torch.stack([tensordict, cloned_tensordict])
assert isinstance(lazy_stack, LazyStackedTensorDict)

with set_lazy_legacy(False):  # new behaviour
    dense_stack = torch.stack([tensordict, cloned_tensordict])
assert isinstance(dense_stack, TensorDict)
LazyStackedTensorDict(
    fields={
        a: Tensor(shape=torch.Size([2, 3, 4]), device=cpu, dtype=torch.float32, is_shared=False),
        b: Tensor(shape=torch.Size([2, 3, 4, 5]), device=cpu, dtype=torch.float32, is_shared=False)},
    exclusive_fields={
    },
    batch_size=torch.Size([2, 3, 4]),
    device=None,
    is_shared=False,
    stack_dim=0)

如果我們沿著堆疊維度索引 LazyStackedTensorDict,我們將恢復原始的 TensorDict

assert stacked_tensordict[0] is tensordict
assert stacked_tensordict[1] is cloned_tensordict

訪問 LazyStackedTensorDict 中的鍵會導致這些值被堆疊。如果鍵對應於巢狀的 TensorDict,那麼我們將恢復另一個 LazyStackedTensorDict

assert stacked_tensordict["a"].shape == torch.Size([2, 3, 4])

注意

由於值是按需堆疊的,多次訪問一個項意味著它會被堆疊多次,這是低效的。如果您需要多次訪問堆疊的 TensorDict 中的一個值,您可能希望考慮將 LazyStackedTensorDict 轉換為連續的 TensorDict,這可以透過 LazyStackedTensorDict.to_tensordictLazyStackedTensorDict.contiguous 方法完成。

>>> assert isinstance(stacked_tensordict.contiguous(), TensorDict)
>>> assert isinstance(stacked_tensordict.contiguous(), TensorDict)

呼叫這些方法中的任何一個之後,我們將擁有一個包含堆疊值的常規 TensorDict,並且在訪問值時不會執行額外的計算。

Concatenating TensorDict

連線不是按需進行的,而是呼叫 torch.cat()TensorDict 例項列表,只需返回一個 TensorDict,其條目是列表中元素的連線條目。

concatenated_tensordict = torch.cat([tensordict, cloned_tensordict], dim=0)
assert isinstance(concatenated_tensordict, TensorDict)
assert concatenated_tensordict.batch_size == torch.Size([6, 4])
assert concatenated_tensordict["b"].shape == torch.Size([6, 4, 5])

Expanding TensorDict

我們可以使用 TensorDict.expand 來擴充套件 TensorDict 的所有條目。

exp_tensordict = tensordict.expand(2, *tensordict.batch_size)
assert exp_tensordict.batch_size == torch.Size([2, 3, 4])
torch.testing.assert_close(exp_tensordict["a"][0], exp_tensordict["a"][1])

Squeezing and Unsqueezing TensorDict

我們可以使用 squeeze()unsqueeze() 方法來壓縮或解壓 TensorDict 的內容。

tensordict = TensorDict({"a": torch.rand(3, 1, 4)}, [3, 1, 4])
squeezed_tensordict = tensordict.squeeze()
assert squeezed_tensordict["a"].shape == torch.Size([3, 4])
print(squeezed_tensordict, end="\n\n")

unsqueezed_tensordict = tensordict.unsqueeze(-1)
assert unsqueezed_tensordict["a"].shape == torch.Size([3, 1, 4, 1])
print(unsqueezed_tensordict)
TensorDict(
    fields={
        a: 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)

TensorDict(
    fields={
        a: Tensor(shape=torch.Size([3, 1, 4, 1]), device=cpu, dtype=torch.float32, is_shared=False)},
    batch_size=torch.Size([3, 1, 4, 1]),
    device=None,
    is_shared=False)

注意

到目前為止,像 unsqueeze()squeeze()view()permute()transpose() 這樣的操作,都返回這些操作的惰性版本(即,一個儲存原始 tensordict 的容器,並且每次訪問鍵時都會應用該操作)。這種行為將來會被棄用,並且已經可以透過 set_lazy_legacy() 函式來控制。

>>> with set_lazy_legacy(True):
...     lazy_unsqueeze = tensordict.unsqueeze(0)
>>> with set_lazy_legacy(False):
...     dense_unsqueeze = tensordict.unsqueeze(0)

請記住,一如既往,這些操作僅適用於批處理維度。條目的任何非批處理維度都不會受到影響。

tensordict = TensorDict({"a": torch.rand(3, 1, 1, 4)}, [3, 1])
squeezed_tensordict = tensordict.squeeze()
# only one of the singleton dimensions is dropped as the other
# is not a batch dimension
assert squeezed_tensordict["a"].shape == torch.Size([3, 1, 4])

Viewing a TensorDict

TensorDict 也支援 view。這會建立一個 _ViewedTensorDict,當訪問其內容時,它會惰性地建立其內容的檢視。

tensordict = TensorDict({"a": torch.arange(12)}, [12])
# no views are created at this step
viewed_tensordict = tensordict.view((2, 3, 2))

# the view of "a" is created on-demand when we access it
assert viewed_tensordict["a"].shape == torch.Size([2, 3, 2])

Permuting batch dimensions

TensorDict.permute 方法可以用於置換批處理維度,就像 torch.permute() 一樣。非批處理維度保持不變。

此操作是惰性的,因此只有在嘗試訪問條目時才會置換批處理維度。一如既往,如果您可能需要多次訪問特定條目,請考慮將其轉換為 TensorDict

tensordict = TensorDict({"a": torch.rand(3, 4), "b": torch.rand(3, 4, 5)}, [3, 4])
# swap the batch dimensions
permuted_tensordict = tensordict.permute([1, 0])

assert permuted_tensordict["a"].shape == torch.Size([4, 3])
assert permuted_tensordict["b"].shape == torch.Size([4, 3, 5])

Using tensordicts as decorators

對於許多可逆操作,tensordicts 可以用作裝飾器。這些操作包括用於函式呼叫的 to_module()unlock_()lock_(),或形狀操作,例如 view()permute() transpose()squeeze()unsqueeze()。下面是一個使用 transpose 函式的簡短示例。

tensordict = TensorDict({"a": torch.rand(3, 4), "b": torch.rand(3, 4, 5)}, [3, 4])

with tensordict.transpose(1, 0) as tdt:
    tdt.set("c", torch.ones(4, 3))  # we have permuted the dims

# the ``"c"`` entry is now in the tensordict we used as decorator:
#

assert (tensordict.get("c") == 1).all()

Gathering values in TensorDict

TensorDict.gather 方法可以用於沿著批處理維度進行索引,並將結果收集到一個維度中,就像 torch.gather() 一樣。

index = torch.randint(4, (3, 4))
gathered_tensordict = tensordict.gather(dim=1, index=index)
print("index:\n", index, end="\n\n")
print("tensordict['a']:\n", tensordict["a"], end="\n\n")
print("gathered_tensordict['a']:\n", gathered_tensordict["a"], end="\n\n")
index:
 tensor([[3, 2, 3, 2],
        [0, 0, 2, 1],
        [2, 3, 3, 0]])

tensordict['a']:
 tensor([[0.8872, 0.9961, 0.1898, 0.6842],
        [0.8439, 0.8043, 0.0636, 0.3626],
        [0.3030, 0.8839, 0.7533, 0.9503]])

gathered_tensordict['a']:
 tensor([[0.6842, 0.1898, 0.6842, 0.1898],
        [0.8439, 0.8439, 0.0636, 0.8043],
        [0.7533, 0.9503, 0.9503, 0.3030]])

指令碼總執行時間: (0 分鐘 0.008 秒)

由 Sphinx-Gallery 生成的畫廊

文件

訪問全面的 PyTorch 開發者文件

檢視文件

教程

為初學者和高階開發者提供深入的教程

檢視教程

資源

查詢開發資源並讓您的問題得到解答

檢視資源