• 文档 >
  • 使用新权重重新适配 Torch-TensorRT 程序
快捷方式

使用新权重重新适配 Torch-TensorRT 程序

编译是一个昂贵的操作,因为它涉及对模型进行大量的图转换、翻译和优化。在模型权重可能偶尔更新的情况下(例如插入 LoRA 适配器),如果每次都需要从头开始构建编译好的程序,则重新编译的巨大成本可能会导致无法使用 TensorRT。Torch-TensorRT 提供了一种 PyTorch 原生机制,通过权重重适配来更新已编译的 TensorRT 程序的权重,而无需从头重新编译。

在本教程中,我们将介绍

  1. 将 PyTorch 模型编译为 TensorRT 图模块

  2. 保存和加载图模块

  3. 重新适配图模块

本教程主要关注 AOT 工作流程,用户在这种工作流程中很可能需要手动重新适配模块。在 JIT 工作流程中,权重变化会触发重新编译。由于引擎之前已经构建过,启用引擎缓存后,Torch-TensorRT 可以自动识别之前构建的引擎,触发重新适配并代表用户跳过重新编译(参见:引擎缓存)。

标准工作流程

导入和模型定义

import numpy as np
import torch
import torch_tensorrt as torch_trt
import torchvision.models as models
from torch_tensorrt.dynamo import refit_module_weights

np.random.seed(0)
torch.manual_seed(0)
inputs = [torch.rand((1, 3, 224, 224)).to("cuda")]

创建可重新适配的编译程序

初始步骤是编译一个模块并像通常一样保存它。请注意,还有一个额外参数 immutable_weights 设置为 False。该参数用于指示正在构建的引擎稍后应支持权重重新适配。未设置这些参数构建的引擎将无法进行重新适配。

在此示例中,我们将编译一个使用随机初始化权重的 ResNet18 模型并保存它。

model = models.resnet18(pretrained=False).eval().to("cuda")
exp_program = torch.export.export(model, tuple(inputs))
enabled_precisions = {torch.float}
debug = False
workspace_size = 20 << 30
min_block_size = 0
use_python_runtime = False
torch_executed_ops = {}
trt_gm = torch_trt.dynamo.compile(
    exp_program,
    tuple(inputs),
    use_python_runtime=use_python_runtime,
    enabled_precisions=enabled_precisions,
    debug=debug,
    min_block_size=min_block_size,
    torch_executed_ops=torch_executed_ops,
    immutable_weights=False,
    reuse_cached_engines=False,
)  # Output is a torch.fx.GraphModule

# Save the graph module as an exported program
torch_trt.save(trt_gm, "./compiled.ep", inputs=inputs)

使用预训练权重重新适配程序

随机权重对于推理没有用。但现在,我们可以使用预训练权重重新适配模型,而不是重新编译模型。这可以通过设置另一个包含目标权重的 PyTorch 模块并将其导出为 ExportedProgram 来完成。然后使用 refit_module_weights 函数更新已编译模块中的权重为新权重。

# Create and compile the updated model
model2 = models.resnet18(pretrained=True).eval().to("cuda")
exp_program2 = torch.export.export(model2, tuple(inputs))


compiled_trt_ep = torch_trt.load("./compiled.ep")

# This returns a new module with updated weights
new_trt_gm = refit_module_weights(
    compiled_module=compiled_trt_ep,
    new_weight_module=exp_program2,
    arg_inputs=inputs,
)

# Check the output
expected_outputs, refitted_outputs = exp_program2.module()(*inputs), new_trt_gm(*inputs)
for expected_output, refitted_output in zip(expected_outputs, refitted_outputs):
    assert torch.allclose(
        expected_output, refitted_output, 1e-2, 1e-2
    ), "Refit Result is not correct. Refit failed"

print("Refit successfully!")

高级用法

您可以使用多种设置来控制重新适配过程

权重映射缓存

权重重新适配的工作原理是将已编译模块的权重与用户提供的 ExportedProgram 中的新权重进行匹配。由于从 PyTorch 到 TensorRT 的 1:1 名称匹配难以实现,因此在重新适配时匹配权重的唯一可靠方法是将新的 ExportedProgram 通过编译过程的早期阶段,以生成几乎相同的权重名称。这可能很昂贵,并非总是必要。

为了避免这种情况,在初始编译时,Torch-TensorRT 将尝试缓存从 PyTorch 权重到 TensorRT 权重的直接映射。此缓存作为元数据存储在已编译模块中,可用于加快重新适配速度。如果缓存不存在,重新适配系统将回退到在重新适配时重建映射。此缓存的使用由 use_weight_map_cache 参数控制。

由于缓存使用基于启发式的方法来匹配 PyTorch 和 TensorRT 权重,您可能需要验证重新适配。这可以通过将 verify_output 设置为 `True` 并提供示例 arg_inputskwarg_inputs 来完成。完成此操作后,重新适配系统将在相同的输入上运行重新适配后的模块和用户提供的模块,并比较输出。

原地重新适配

in_place 参数允许用户在原地重新适配模块。当用户想要更新已编译模块的权重而无需创建新模块时,此功能非常有用。

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

由 Sphinx-Gallery 生成的画廊

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取针对初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得解答

查看资源