• 教程 >
  • 开始使用嵌套张量
快捷键

开始使用嵌套张量指南

创建于:2025 年 4 月 1 日 | 最后更新:2025 年 4 月 1 日 | 最后验证:2024 年 11 月 5 日

嵌套张量将常规密集张量的形状进行了推广,允许表示大小不规则的张量。

  • 对于常规张量,每个维度都是规则的,并且具有大小

  • 对于嵌套张量,并非所有维度都有常规大小;其中一些是参差不齐的

嵌套张量是表示各种领域内序列数据的自然解决方案:

  • 在自然语言处理(NLP)中,句子可以有可变长度,因此句子批次形成一个嵌套张量

  • 在计算机视觉(CV)中,图像可以有可变形状,因此图像批次形成一个嵌套张量

在本教程中,我们将演示嵌套张量的基本用法,并通过实际案例说明它们在处理不同长度的序列数据时的有用性。特别是,它们对于构建能够高效处理不规则序列输入的转换器非常有价值。下面,我们展示了使用嵌套张量的多头注意力机制的实现,其结合使用 torch.compile ,在处理填充张量时表现优于简单操作。

嵌套张量目前是一个原型功能,可能会发生变化。

import numpy as np
import timeit
import torch
import torch.nn.functional as F

from torch import nn

torch.manual_seed(1)
np.random.seed(1)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

嵌套张量初始化

从 Python 前端,可以从张量列表创建嵌套张量。我们用 nt[i]表示嵌套张量的第 i 个张量组件。

nt = torch.nested.nested_tensor([torch.arange(12).reshape(
    2, 6), torch.arange(18).reshape(3, 6)], dtype=torch.float, device=device)
print(f"{nt=}")

通过将每个底层张量填充到相同的形状,可以将嵌套张量转换为常规张量。

padded_out_tensor = torch.nested.to_padded_tensor(nt, padding=0.0)
print(f"{padded_out_tensor=}")

所有张量都拥有一个属性,用于确定它们是否为嵌套张量;

print(f"nt is nested: {nt.is_nested}")
print(f"padded_out_tensor is nested: {padded_out_tensor.is_nested}")

通常从形状不规则的张量批次构建嵌套张量。例如,维度 0 被认为是批次维度。索引维度 0 将返回第一个底层张量组件。

print("First underlying tensor component:", nt[0], sep='\n')
print("last column of 2nd underlying tensor component:", nt[1, :, -1], sep='\n')

# When indexing a nestedtensor's 0th dimension, the result is a regular tensor.
print(f"First underlying tensor component is nested: {nt[0].is_nested}")

重要提示:目前尚不支持维度 0 的切片操作。这意味着目前无法构建结合底层张量组件的视图。

嵌套张量操作

由于每个操作都必须为嵌套张量显式实现,因此嵌套张量的操作覆盖范围目前比常规张量窄。目前仅覆盖基本操作,如索引、dropout、softmax、转置、重塑、线性、bmm 等。然而,覆盖范围正在扩展。如果您需要某些操作,请提交问题以帮助我们优先考虑覆盖范围。

重塑

重塑操作用于改变张量的形状。常规张量的完整语义可以在此处找到。对于常规张量,在指定新形状时,单个维度可以是-1,在这种情况下,它将从剩余维度和元素数量中推断出来。

嵌套张量的语义类似,但-1 不再推断。相反,它继承旧的大小(这里为 nt[0] 的 2 和 nt[1] 的 3)。-1 是唯一可以指定为锯齿状维度的合法大小。

nt_reshaped = nt.reshape(2, -1, 2, 3)
print(f"{nt_reshaped=}")

转置

转置操作用于交换张量的两个维度。其完整语义可以在此处找到。请注意,对于嵌套张量,维度 0 是特殊的;它被假定为批次维度,因此涉及嵌套张量维度 0 的转置不受支持。

nt_transposed = nt_reshaped.transpose(1, 2)
print(f"{nt_transposed=}")

其他

其他操作与常规张量具有相同的语义。对嵌套张量应用操作相当于对底层张量组件应用操作,结果也是一个嵌套张量。

nt_mm = torch.nested.nested_tensor([torch.randn((2, 3, 4)), torch.randn((2, 3, 5))], device=device)
nt3 = torch.matmul(nt_transposed, nt_mm)
print(f"Result of Matmul:\n {nt3}")

nt4 = F.dropout(nt3, 0.1)
print(f"Result of Dropout:\n {nt4}")

nt5 = F.softmax(nt4, -1)
print(f"Result of Softmax:\n {nt5}")

为什么嵌套张量

当数据是序列时,通常每个样本的长度都不同。例如,在一个句子批次中,每个句子都有不同数量的单词。处理可变序列的常见技术是手动填充每个数据张量,使其具有相同的形状,从而形成一个批次。例如,我们有 2 个不同长度的句子和一个词汇表,为了将其表示为单个张量,我们将其填充到批次中的最大长度。

sentences = [["goodbye", "padding"],
             ["embrace", "nested", "tensor"]]
vocabulary = {"goodbye": 1.0, "padding": 2.0,
              "embrace": 3.0, "nested": 4.0, "tensor": 5.0}
padded_sentences = torch.tensor([[1.0, 2.0, 0.0],
                                 [3.0, 4.0, 5.0]])
nested_sentences = torch.nested.nested_tensor([torch.tensor([1.0, 2.0]),
                                               torch.tensor([3.0, 4.0, 5.0])])
print(f"{padded_sentences=}")
print(f"{nested_sentences=}")

这种将一批数据填充到最大长度的技术并不理想。填充的数据对于计算并不需要,通过分配比必要的更大的张量来浪费内存。此外,并非所有操作在应用于填充数据时都具有相同的语义。例如,在进行矩阵乘法时,为了忽略填充的条目,需要用 0 进行填充,而对于 softmax,则需要用-∞进行填充以忽略特定的条目。嵌套张量的主要目标是利用标准的 PyTorch 张量 UX 来简化对不规则数据的操作,从而消除低效且复杂的填充和掩码的需求。

padded_sentences_for_softmax = torch.tensor([[1.0, 2.0, float("-inf")],
                                             [3.0, 4.0, 5.0]])
print(F.softmax(padded_sentences_for_softmax, -1))
print(F.softmax(nested_sentences, -1))

让我们来看一个实际例子:在 Transformers 中使用的多头注意力组件。我们可以实现它,使其能够对填充或嵌套张量进行操作。

class MultiHeadAttention(nn.Module):
    """
    Computes multi-head attention. Supports nested or padded tensors.

    Args:
        E_q (int): Size of embedding dim for query
        E_k (int): Size of embedding dim for key
        E_v (int): Size of embedding dim for value
        E_total (int): Total embedding dim of combined heads post input projection. Each head
            has dim E_total // nheads
        nheads (int): Number of heads
        dropout_p (float, optional): Dropout probability. Default: 0.0
    """
    def __init__(self, E_q: int, E_k: int, E_v: int, E_total: int,
                 nheads: int, dropout_p: float = 0.0):
        super().__init__()
        self.nheads = nheads
        self.dropout_p = dropout_p
        self.query_proj = nn.Linear(E_q, E_total)
        self.key_proj = nn.Linear(E_k, E_total)
        self.value_proj = nn.Linear(E_v, E_total)
        E_out = E_q
        self.out_proj = nn.Linear(E_total, E_out)
        assert E_total % nheads == 0, "Embedding dim is not divisible by nheads"
        self.E_head = E_total // nheads

    def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
        """
        Forward pass; runs the following process:
            1. Apply input projection
            2. Split heads and prepare for SDPA
            3. Run SDPA
            4. Apply output projection

        Args:
            query (torch.Tensor): query of shape (N, L_t, E_q)
            key (torch.Tensor): key of shape (N, L_s, E_k)
            value (torch.Tensor): value of shape (N, L_s, E_v)

        Returns:
            attn_output (torch.Tensor): output of shape (N, L_t, E_q)
        """
        # Step 1. Apply input projection
        # TODO: demonstrate packed projection
        query = self.query_proj(query)
        key = self.key_proj(key)
        value = self.value_proj(value)

        # Step 2. Split heads and prepare for SDPA
        # reshape query, key, value to separate by head
        # (N, L_t, E_total) -> (N, L_t, nheads, E_head) -> (N, nheads, L_t, E_head)
        query = query.unflatten(-1, [self.nheads, self.E_head]).transpose(1, 2)
        # (N, L_s, E_total) -> (N, L_s, nheads, E_head) -> (N, nheads, L_s, E_head)
        key = key.unflatten(-1, [self.nheads, self.E_head]).transpose(1, 2)
        # (N, L_s, E_total) -> (N, L_s, nheads, E_head) -> (N, nheads, L_s, E_head)
        value = value.unflatten(-1, [self.nheads, self.E_head]).transpose(1, 2)

        # Step 3. Run SDPA
        # (N, nheads, L_t, E_head)
        attn_output = F.scaled_dot_product_attention(
            query, key, value, dropout_p=dropout_p, is_causal=True)
        # (N, nheads, L_t, E_head) -> (N, L_t, nheads, E_head) -> (N, L_t, E_total)
        attn_output = attn_output.transpose(1, 2).flatten(-2)

        # Step 4. Apply output projection
        # (N, L_t, E_total) -> (N, L_t, E_out)
        attn_output = self.out_proj(attn_output)

        return attn_output

按照 Transformer 论文设置超参数

N = 512
E_q, E_k, E_v, E_total = 512, 512, 512, 512
E_out = E_q
nheads = 8

除了 dropout 概率:为了正确性检查,设置为 0

dropout_p = 0.0

让我们从 Zipf 定律生成一些逼真的假数据。

def zipf_sentence_lengths(alpha: float, batch_size: int) -> torch.Tensor:
    # generate fake corpus by unigram Zipf distribution
    # from wikitext-2 corpus, we get rank "." = 3, "!" = 386, "?" = 858
    sentence_lengths = np.empty(batch_size, dtype=int)
    for ibatch in range(batch_size):
        sentence_lengths[ibatch] = 1
        word = np.random.zipf(alpha)
        while word != 3 and word != 386 and word != 858:
            sentence_lengths[ibatch] += 1
            word = np.random.zipf(alpha)
    return torch.tensor(sentence_lengths)

创建嵌套张量批量输入。

def gen_batch(N, E_q, E_k, E_v, device):
    # generate semi-realistic data using Zipf distribution for sentence lengths
    sentence_lengths = zipf_sentence_lengths(alpha=1.2, batch_size=N)

    # Note: the torch.jagged layout is a nested tensor layout that supports a single ragged
    # dimension and works with torch.compile. The batch items each have shape (B, S*, D)
    # where B = batch size, S* = ragged sequence length, and D = embedding dimension.
    query = torch.nested.nested_tensor([
        torch.randn(l.item(), E_q, device=device)
        for l in sentence_lengths
    ], layout=torch.jagged)

    key = torch.nested.nested_tensor([
        torch.randn(s.item(), E_k, device=device)
        for s in sentence_lengths
    ], layout=torch.jagged)

    value = torch.nested.nested_tensor([
        torch.randn(s.item(), E_v, device=device)
        for s in sentence_lengths
    ], layout=torch.jagged)

    return query, key, value, sentence_lengths

query, key, value, sentence_lengths = gen_batch(N, E_q, E_k, E_v, device)

生成用于比较的查询、键、值的填充形式。

def jagged_to_padded(jt, padding_val):
    # TODO: do jagged -> padded directly when this is supported
    return torch.nested.to_padded_tensor(
        torch.nested.nested_tensor(list(jt.unbind())),
        padding_val)

padded_query, padded_key, padded_value = (
    jagged_to_padded(t, 0.0) for t in (query, key, value)
)

构建模型。

mha = MultiHeadAttention(E_q, E_k, E_v, E_total, nheads, dropout_p).to(device=device)

检查正确性和性能

def benchmark(func, *args, **kwargs):
    torch.cuda.synchronize()
    begin = timeit.default_timer()
    output = func(*args, **kwargs)
    torch.cuda.synchronize()
    end = timeit.default_timer()
    return output, (end - begin)

output_nested, time_nested = benchmark(mha, query, key, value)
output_padded, time_padded = benchmark(mha, padded_query, padded_key, padded_value)

# padding-specific step: remove output projection bias from padded entries for fair comparison
for i, entry_length in enumerate(sentence_lengths):
    output_padded[i, entry_length:] = 0.0

print("=== without torch.compile ===")
print("nested and padded calculations differ by", (jagged_to_padded(output_nested, 0.0) - output_padded).abs().max().item())
print("nested tensor multi-head attention takes", time_nested, "seconds")
print("padded tensor multi-head attention takes", time_padded, "seconds")

# warm up compile first...
compiled_mha = torch.compile(mha)
compiled_mha(query, key, value)
# ...now benchmark
compiled_output_nested, compiled_time_nested = benchmark(
    compiled_mha, query, key, value)

# warm up compile first...
compiled_mha(padded_query, padded_key, padded_value)
# ...now benchmark
compiled_output_padded, compiled_time_padded = benchmark(
    compiled_mha, padded_query, padded_key, padded_value)

# padding-specific step: remove output projection bias from padded entries for fair comparison
for i, entry_length in enumerate(sentence_lengths):
    compiled_output_padded[i, entry_length:] = 0.0

print("=== with torch.compile ===")
print("nested and padded calculations differ by", (jagged_to_padded(compiled_output_nested, 0.0) - compiled_output_padded).abs().max().item())
print("nested tensor multi-head attention takes", compiled_time_nested, "seconds")
print("padded tensor multi-head attention takes", compiled_time_padded, "seconds")

注意,如果没有 torch.compile ,Python 子类嵌套张量的开销可能会使其比在填充张量上的等效计算慢。然而,一旦启用 torch.compile ,对嵌套张量的操作可以提供多倍的速度提升。随着批处理中填充百分比的增加,避免在填充上的浪费计算变得更加有价值。

print(f"Nested speedup: {compiled_time_padded / compiled_time_nested:.3f}")

结论 ¶

在本教程中,我们学习了如何使用嵌套张量执行基本操作,以及如何实现避免在填充上计算的多头注意力机制,用于变压器。有关更多信息,请参阅 torch.nested 命名空间的相关文档。

脚本总运行时间:(0 分钟 0.000 秒)

由 Sphinx-Gallery 生成的画廊


评分这个教程

© 版权所有 2024,PyTorch。

使用 Sphinx 构建,主题由 Read the Docs 提供。
//暂时添加调查链接

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源