在 Python 中使用 Torch-TensorRT¶
与仅支持 TorchScript 编译的 CLI 和 C++ API 相比,Torch-TensorRT Python API 支持许多独特的用例。
Torch-TensorRT Python API 可以接受 torch.nn.Module、torch.jit.ScriptModule 或 torch.fx.GraphModule 作为输入。根据提供的内容,将选择 TorchScript 或 FX 中的一个前端来编译模块。只要模块类型受支持,用户就可以使用 compile 的 ir 标志显式设置他们想要使用的前端。如果给定 torch.nn.Module 并且 ir 标志设置为 default 或 torchscript,则该模块将通过 torch.jit.script 运行,将输入模块转换为 TorchScript 模块。
要使用 Torch-TensorRT 编译输入的 torch.nn.Module,您只需将模块和输入提供给 Torch-TensorRT,您将收到一个优化的 TorchScript 模块以供运行或添加到另一个 PyTorch 模块中。输入是一个 torch_tensorrt.Input 类的列表,用于定义输入张量的形状、数据类型和内存格式。或者,如果您的输入是更复杂的数据类型,例如张量元组或列表,您可以使用 input_signature 参数来指定基于集合的输入,例如 (List[Tensor], Tuple[Tensor, Tensor])。请参阅下面的第二个示例。您还可以指定引擎的运行精度或目标设备等设置。编译后,您可以像任何其他模块一样保存该模块,以便在部署应用程序中加载。为了加载 TensorRT/TorchScript 模块,请确保您首先导入 torch_tensorrt。
import torch_tensorrt
...
model = MyModel().eval() # torch module needs to be in eval (not training) mode
inputs = [
torch_tensorrt.Input(
min_shape=[1, 1, 16, 16],
opt_shape=[1, 1, 32, 32],
max_shape=[1, 1, 64, 64],
dtype=torch.half,
)
]
enabled_precisions = {torch.float, torch.half} # Run with fp16
trt_ts_module = torch_tensorrt.compile(
model, inputs=inputs, enabled_precisions=enabled_precisions
)
input_data = input_data.to("cuda").half()
result = trt_ts_module(input_data)
torch.jit.save(trt_ts_module, "trt_ts_module.ts")
# Sample using collection-based inputs via the input_signature argument
import torch_tensorrt
...
model = MyModel().eval()
# input_signature expects a tuple of individual input arguments to the module
# The module below, for example, would have a docstring of the form:
# def forward(self, input0: List[torch.Tensor], input1: Tuple[torch.Tensor, torch.Tensor])
input_signature = (
[torch_tensorrt.Input(shape=[64, 64], dtype=torch.half), torch_tensorrt.Input(shape=[64, 64], dtype=torch.half)],
(torch_tensorrt.Input(shape=[64, 64], dtype=torch.half), torch_tensorrt.Input(shape=[64, 64], dtype=torch.half)),
)
enabled_precisions = {torch.float, torch.half}
trt_ts_module = torch_tensorrt.compile(
model, input_signature=input_signature, enabled_precisions=enabled_precisions
)
input_data = input_data.to("cuda").half()
result = trt_ts_module(input_data)
torch.jit.save(trt_ts_module, "trt_ts_module.ts")
# Deployment application
import torch
import torch_tensorrt
trt_ts_module = torch.jit.load("trt_ts_module.ts")
input_data = input_data.to("cuda").half()
result = trt_ts_module(input_data)
Torch-TensorRT Python API 还提供了 torch_tensorrt.ts.compile(接受 TorchScript 模块作为输入)和 torch_tensorrt.fx.compile(接受 FX GraphModule 作为输入)。