注意
转到末尾 以下载完整的示例代码
使用新权重重新适配Torch-TensorRT程序¶
编译是一个昂贵的操作,因为它涉及许多应用于模型的图转换、翻译和优化。在模型权重可能偶尔更新的情况下(例如插入LoRA适配器),如果每次都需要从头开始构建编译程序,那么重新编译的巨大成本可能会使得使用TensorRT变得不可行。Torch-TensorRT 提供了一个PyTorch原生机制,通过权重重新适配来更新已编译的TensorRT程序的权重,而无需从头开始重新编译。
在本教程中,我们将逐步讲解
将PyTorch模型编译为TensorRT图模块
保存和加载图模块
重新拟合图形模块
本教程主要关注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_inputs和kwarg_inputs来完成。当这样做时,重新拟合系统将在相同的输入上运行重新拟合的模块和用户提供的模块,并比较输出。
原地改装¶
in_place 允许用户就地重新拟合模块。当用户希望更新已编译模块的权重而不创建新模块时,这非常有用。
脚本总运行时间: ( 0 分钟 0.000 秒)