• Docs >
  • Automatically Generate a Converter for a Custom Kernel
Shortcuts

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

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

Torch-TensorRT 支持在 Torch-TensorRT 不知道如何在 TensorRT 中编译操作的情况下回退到 PyTorch 的实现。然而,这会带来图断开的代价,并会降低模型的性能。解决操作支持不足的最简单方法是添加一个分解(参见:为 Dynamo 前端编写降级过程)- 它用 Torch-TensorRT 支持的 PyTorch 操作来定义操作符,或者添加一个转换器(参见:为 Dynamo 前端编写转换器)- 它用 TensorRT 操作符来定义操作符。

在某些情况下,这两种方法都没有很好的解决方案,可能是因为操作符是一个自定义内核,不属于标准的PyTorch,或者TensorRT无法原生支持它。

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

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

在PyTorch中编写自定义运算符

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

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

from typing import Tuple

import tensorrt_bindings.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

元素级操作的元内核只是其中一个输入的形状和数据类型,因为在操作过程中我们不会改变形状。

@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 秒)

Gallery generated by Sphinx-Gallery