快捷方式

dense_stack_tds

class tensordict.dense_stack_tds(td_list: Union[Sequence[TensorDictBase], LazyStackedTensorDict], dim: Optional[int] = None)

密集堆叠 TensorDictBase 对象列表(或 LazyStackedTensorDict),前提是它们具有相同的结构。

此函数使用 TensorDictBase 列表调用(可以直接传递,也可以从 LazyStackedTensorDict 获取)。而不是调用 torch.stack(td_list),这将返回 LazyStackedTensorDict,此函数展开输入列表的第一个元素,并将输入列表堆叠到该元素上。仅当输入列表的所有元素具有相同的结构时,此操作才有效。返回的 TensorDictBase 将具有与输入列表元素相同的类型。

当需要堆叠的一些 TensorDictBase 对象是 LazyStackedTensorDict,或者在条目(或嵌套条目)中包含 LazyStackedTensorDict 时,此函数非常有用。在这些情况下,调用 torch.stack(td_list).to_tensordict() 是不可行的。因此,此函数为密集堆叠提供的列表提供了一种替代方案。

参数:
  • td_list (TensorDictBase 列表LazyStackedTensorDict) – 要堆叠的 tds。

  • dim (int, 可选) – 堆叠它们的维度。如果 td_list 是 LazyStackedTensorDict,它将自动检索。

示例

>>> import torch
>>> from tensordict import TensorDict
>>> from tensordict import dense_stack_tds
>>> from tensordict.tensordict import assert_allclose_td
>>> td0 = TensorDict({"a": torch.zeros(3)},[])
>>> td1 = TensorDict({"a": torch.zeros(4), "b": torch.zeros(2)},[])
>>> td_lazy = torch.stack([td0, td1], dim=0)
>>> td_container = TensorDict({"lazy": td_lazy}, [])
>>> td_container_clone = td_container.clone()
>>> td_stack = torch.stack([td_container, td_container_clone], dim=0)
>>> td_stack
LazyStackedTensorDict(
    fields={
        lazy: LazyStackedTensorDict(
            fields={
                a: Tensor(shape=torch.Size([2, 2, -1]), device=cpu, dtype=torch.float32, is_shared=False)},
            exclusive_fields={
            },
            batch_size=torch.Size([2, 2]),
            device=None,
            is_shared=False,
            stack_dim=0)},
    exclusive_fields={
    },
    batch_size=torch.Size([2]),
    device=None,
    is_shared=False,
    stack_dim=0)
>>> td_stack = dense_stack_tds(td_stack) # Automatically use the LazyStackedTensorDict stack_dim
TensorDict(
    fields={
        lazy: LazyStackedTensorDict(
            fields={
                a: Tensor(shape=torch.Size([2, 2, -1]), device=cpu, dtype=torch.float32, is_shared=False)},
            exclusive_fields={
                1 ->
                    b: Tensor(shape=torch.Size([2, 2]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([2, 2]),
            device=None,
            is_shared=False,
            stack_dim=1)},
    batch_size=torch.Size([2]),
    device=None,
    is_shared=False)
# Note that
# (1) td_stack is now a TensorDict
# (2) this has pushed the stack_dim of "lazy" (0 -> 1)
# (3) this has revealed the exclusive keys.
>>> assert_allclose_td(td_stack, dense_stack_tds([td_container, td_container_clone], dim=0))
# This shows it is the same to pass a list or a LazyStackedTensorDict

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得解答

查看资源