• 文档 >
  • 使用 Torch-TensorRT 编译的模型的保存
快捷方式

使用 Torch-TensorRT 编译的模型的保存

可以使用 torch_tensorrt.save API 完成使用 Torch-TensorRT 编译的模型的保存。

Dynamo IR

Torch-TensorRT 的 ir=dynamo 编译的输出类型默认为 torch.fx.GraphModule 对象。我们可以通过指定 output_format 标志,以 TorchScript (torch.jit.ScriptModule) 或 ExportedProgram (torch.export.ExportedProgram) 格式保存此对象。以下是 output_format 将接受的选项

  • exported_program : 这是默认设置。我们首先对 graphmodule 执行转换,然后使用 torch.export.save 保存模块。

  • torchscript : 我们通过 torch.jit.trace 跟踪 graphmodule,并通过 torch.jit.save 保存它。

a) ExportedProgram

这是一个示例用法

import torch
import torch_tensorrt

model = MyModel().eval().cuda()
inputs = [torch.randn((1, 3, 224, 224)).cuda()]
# trt_ep is a torch.fx.GraphModule object
trt_gm = torch_tensorrt.compile(model, ir="dynamo", inputs=inputs)
torch_tensorrt.save(trt_gm, "trt.ep", inputs=inputs)

# Later, you can load it and run inference
model = torch.export.load("trt.ep").module()
model(*inputs)

b) Torchscript

import torch
import torch_tensorrt

model = MyModel().eval().cuda()
inputs = [torch.randn((1, 3, 224, 224)).cuda()]
# trt_gm is a torch.fx.GraphModule object
trt_gm = torch_tensorrt.compile(model, ir="dynamo", inputs=inputs)
torch_tensorrt.save(trt_gm, "trt.ts", output_format="torchscript", inputs=inputs)

# Later, you can load it and run inference
model = torch.jit.load("trt.ts").cuda()
model(*inputs)

Torchscript IR

在 Torch-TensorRT 1.X 版本中,使用 Torchscript IR 是编译和运行 Torch-TensorRT 推理的主要方法。对于 ir=ts,此行为在 2.X 版本中保持不变。

import torch
import torch_tensorrt

model = MyModel().eval().cuda()
inputs = [torch.randn((1, 3, 224, 224)).cuda()]
trt_ts = torch_tensorrt.compile(model, ir="ts", inputs=inputs) # Output is a ScriptModule object
torch.jit.save(trt_ts, "trt_model.ts")

# Later, you can load it and run inference
model = torch.jit.load("trt_model.ts").cuda()
model(*inputs)

加载模型

我们可以直接使用 PyTorch 的 torch.jit.loadtorch.export.load API 加载 torchscript 或 exported_program 模型。或者,我们提供了一个轻量级包装器 torch_tensorrt.load(file_path),它可以加载上述任何一种模型类型。

这是一个示例用法

import torch
import torch_tensorrt

# file_path can be trt.ep or trt.ts file obtained via saving the model (refer to the above section)
inputs = [torch.randn((1, 3, 224, 224)).cuda()]
model = torch_tensorrt.load(<file_path>).module()
model(*inputs)

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

查找开发资源并获得问题解答

查看资源