• 文档 >
  • 自动为自定义内核生成转换器
快捷方式

自动为自定义内核生成转换器

我们将演示如何使用 TensorRT 10.7 中新的基于 Python 的插件系统,使用 Torch-TensorRT 自动为自定义内核生成转换器。

如果 Torch-TensorRT 不知道如何在 TensorRT 中编译操作,Torch-TensorRT 支持回退到 PyTorch 操作的实现。但是,这会以图形中断为代价,并会降低模型的性能。修复缺少操作支持的最简单方法是添加分解(参见:为 Dynamo 前端编写 lowering passes)- 它定义了使用 Torch-TensorRT 中支持的 PyTorch 操作的运算符,或者添加转换器(参见:为 Dynamo 前端编写转换器)- 它定义了使用 TensorRT 运算符的运算符。

在某些情况下,这两种方法都不是很好,可能是因为运算符是自定义内核,它不是标准 PyTorch 的一部分,或者 TensorRT 无法原生支持它。

对于这些情况,可以使用 TensorRT 插件来替换 TensorRT 引擎内部的运算符,从而避免图形中断带来的性能和资源开销。

以前,这涉及到一个复杂的过程,不仅要构建高性能内核,还要设置它在 TensorRT 中运行(参见:在带有 Torch-TensorRT 的 TensorRT 引擎中使用自定义内核)。借助 TensorRT 10.7,出现了一个新的 Python 原生插件系统,它大大简化了这个过程。该插件系统还允许 Torch-TensorRT 自动生成必要的转换代码,以将 PyTorch 中的操作转换为 TensorRT。

在 PyTorch 中编写自定义运算符

之前的教程已经介绍了在 PyTorch 中创建自定义运算符,这些运算符稍后将与 Torch-TensorRT 一起使用。

在这里,我们在 Triton 中定义一个简单的逐元素乘法运算符。然后,该运算符在 PyTorch 中注册为自定义操作。它带有主机启动代码以及“元内核”。元内核是一个函数,它描述了运算符将执行的形状和数据类型转换。Dynamo 和 Torch-TensorRT 使用此元内核,因此有必要定义它。

from typing import Tuple

import tensorrt.plugin as trtp
import torch
import torch_tensorrt
import triton
import triton.language as tl


@triton.jit
def elementwise_mul_kernel(X, Y, Z, BLOCK_SIZE: tl.constexpr):
    # Program ID determines the block of data each thread will process
    pid = tl.program_id(0)
    # Compute the range of elements that this thread block will work on
    block_start = pid * BLOCK_SIZE
    # Range of indices this thread will handle
    offsets = block_start + tl.arange(0, BLOCK_SIZE)
    # Load elements from the X and Y tensors
    x_vals = tl.load(X + offsets)
    y_vals = tl.load(Y + offsets)
    # Perform the element-wise multiplication
    z_vals = x_vals * y_vals
    # Store the result in Z
    tl.store(Z + offsets, z_vals)


@torch.library.custom_op("torchtrt_ex::elementwise_mul", mutates_args=())  # type: ignore[misc]
def elementwise_mul(
    X: torch.Tensor, Y: torch.Tensor, b: float = 0.2, a: int = 2
) -> torch.Tensor:
    # Ensure the tensors are on the GPU
    assert X.is_cuda and Y.is_cuda, "Tensors must be on CUDA device."
    assert X.shape == Y.shape, "Tensors must have the same shape."

    # Create output tensor
    Z = torch.empty_like(X)

    # Define block size
    BLOCK_SIZE = 1024

    # Grid of programs
    grid = lambda meta: (X.numel() // meta["BLOCK_SIZE"],)

    # Launch the kernel
    elementwise_mul_kernel[grid](X, Y, Z, BLOCK_SIZE=BLOCK_SIZE)

    return Z

逐元素操作的元内核只是其中一个输入的形状和 dtype,因为我们不会在操作过程中更改形状。

@torch.library.register_fake("torchtrt_ex::elementwise_mul")
def _(x: torch.Tensor, y: torch.Tensor, b: float = 0.2, a: int = 2) -> torch.Tensor:
    return x

使用快速部署插件系统为 TensorRT 编写插件

TensorRT 10.7 中的快速部署插件系统允许在 Python 中创建自定义插件,而样板代码大大减少。它使用类似于 PyTorch 的系统,您可以在其中定义一个函数,该函数描述了运算符将执行的形状和数据类型转换,然后定义用于启动内核的代码(给定 GPU 内存句柄)。

就像 PyTorch 元内核一样,输入和输出之间在形状或数据类型上没有转换,因此我们可以告诉 TensorRT 期望与我们输入时相同的形状

@trtp.register("torchtrt_ex::elementwise_mul")
def _(
    x: trtp.TensorDesc, y: trtp.TensorDesc, b: float, a: int
) -> Tuple[trtp.TensorDesc]:
    return x.like()

在这里,我们重用与 PyTorch 类似的主机启动代码,但是我们需要在启动内核之前将 TensorRT 张量转换为 PyTorch 张量。这些操作也是就地操作,因此结果必须放入 TensorRT 提供的输出张量中。

@trtp.impl("torchtrt_ex::elementwise_mul")
def _(
    x: trtp.Tensor,
    y: trtp.Tensor,
    b: float,
    a: int,
    outputs: Tuple[trtp.Tensor],
    stream: int,
):
    # Define block size
    BLOCK_SIZE = 1024

    # Grid of programs
    grid = lambda meta: (x.numel() // meta["BLOCK_SIZE"],)

    x_t = torch.as_tensor(x, device="cuda")
    y_t = torch.as_tensor(y, device="cuda")
    z_t = torch.as_tensor(outputs[0], device="cuda")
    # Launch the kernel
    elementwise_mul_kernel[grid](x_t, y_t, z_t, BLOCK_SIZE=BLOCK_SIZE)

生成转换器

鉴于我们已经在 PyTorch 和 TensorRT 中定义了自定义运算符,我们现在可以为该操作生成转换器。只要命名空间和名称匹配,以下函数将自动为该操作生成转换器。

torch_tensorrt.dynamo.conversion.plugins.generate_plugin_converter(
    "torchtrt_ex::elementwise_mul", supports_dynamic_shapes=True
)

将我们的转换器用于模型

现在我们可以在模型中使用我们的自定义运算符,并使用 Torch-TensorRT 编译它。我们可以看到,自定义运算符被用作模型前向传递中的操作之一。此时编译模型的过程与标准 Torch-TensorRT 用法相同。

class MyModel(torch.nn.Module):  # type: ignore[misc]
    def __init__(self):
        super().__init__()

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        z = torch.add(x, y)
        res = torch.ops.torchtrt_ex.elementwise_mul.default(x, z, a=1)

        return res


my_model = MyModel().to("cuda")
m = torch.full((64, 64), 2, device="cuda", dtype=torch.float)
n = torch.full((64, 64), 3, device="cuda", dtype=torch.float)

with torch_tensorrt.logging.errors():
    model_trt = torch_tensorrt.compile(
        my_model, inputs=[m, n], debug=True, min_block_size=1
    )
    for i in range(300):
        res = model_trt(m, n)
        assert torch.allclose(res, my_model(m, n))

print("Ran with custom plugin!")

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

由 Sphinx-Gallery 生成的图库

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

查找开发资源并获得解答

查看资源