部署 Torch-TensorRT 程序¶
在编译和保存 Torch-TensorRT 程序后,不再严格依赖完整的 Torch-TensorRT 库。运行编译后的程序只需要运行时环境。因此,除了随应用程序一起发布完整的 Torch-TensorRT 编译器之外,还有几种部署程序的方法。
Torch-TensorRT 包 / libtorchtrt.so¶
程序编译完成后,您可以使用标准的 PyTorch API 运行它。只需要在 Python 中导入包或在 C++ 中链接库即可。
运行时库¶
C++ 发行版附带 libtorchtrt_runtime.so
。此库仅包含运行 Torch-TensorRT 程序所需的组件。您可以链接 libtorchtrt_runtime.so
而不是链接 libtorchtrt.so
或导入 torch_tensorrt
到您的部署程序中,或者使用 DL_OPEN
或 LD_PRELOAD
。对于 Python,您可以使用 torch.ops.load_library("libtorchtrt_runtime.so")
加载运行时环境。然后,您可以像往常一样通过 PyTorch API 继续使用程序。
注意
如果您在 x86 上使用 Python 中的标准 PyTorch 发行版,则可能需要 libtorchtrt_runtime.so
的 pre-cxx11-abi 变体,请查看 安装 文档以获取更多详细信息。
注意
如果您正在链接 libtorchtrt_runtime.so
,则以下标志可能会有所帮助 -Wl,--no-as-needed -ltorchtrt -Wl,--as-needed
,因为对于大多数 Torch-TensorRT 运行时应用程序,Torch-TensorRT 运行时中没有任何直接的符号依赖项
有关如何使用 libtorchtrt_runtime.so
的示例,请参见此处:https://github.com/pytorch/TensorRT/tree/master/examples/torchtrt_runtime_example
插件库¶
如果您将 Torch-TensorRT 用作 TensorRT 引擎的转换器,并且您的引擎使用 Torch-TensorRT 提供的插件,则 Torch-TensorRT 会发布库 libtorchtrt_plugins.so
,其中包含 Torch-TensorRT 在编译期间使用的 TensorRT 插件的实现。此库可以像其他 TensorRT 插件库一样进行 DL_OPEN
或 LD_PRELOAD
。
多设备安全模式¶
多设备安全模式是 Torch-TensorRT 中的一项设置,允许用户确定运行时是否在每次推理调用之前检查设备一致性。
启用多设备安全模式时,每次推理调用都会产生不可忽略的固定成本,这就是为什么现在默认禁用它的原因。它可以通过以下便捷功能进行控制,该功能兼作上下文管理器。
# Enables Multi Device Safe Mode
torch_tensorrt.runtime.set_multi_device_safe_mode(True)
# Disables Multi Device Safe Mode [Default Behavior]
torch_tensorrt.runtime.set_multi_device_safe_mode(False)
# Enables Multi Device Safe Mode, then resets the safe mode to its prior setting
with torch_tensorrt.runtime.set_multi_device_safe_mode(True):
...
TensorRT 要求每个引擎都与从中调用的活动线程中的 CUDA 上下文相关联。因此,如果设备要在活动线程中更改(在同一 Python 进程中在多个 GPU 上调用引擎时可能会发生这种情况),则安全模式将导致 Torch-TensorRT 显示警报并相应地切换 GPU。如果未启用安全模式,则引擎设备和 CUDA 上下文设备可能会不匹配,这可能会导致程序崩溃。
一种在不同 GPU 上管理多个 TRT 引擎,同时又不牺牲多设备安全模式的性能的技术是使用 Python 线程。每个线程负责单个 GPU 上的所有 TRT 引擎,并且每个线程上的默认 CUDA 设备都对应于其负责的 GPU(可以通过 torch.cuda.set_device(...)
设置)。这样,可以在同一 Python 脚本中使用多个线程,而无需切换 CUDA 上下文并产生性能开销。
CUDA Graphs 模式¶
CUDA Graphs 模式是 Torch-TensorRT 中的一项设置,允许用户确定运行时是否使用 CUDA Graphs 来加速某些情况下的推理。
CUDA Graphs 可以通过减少内核开销来加速某些模型,如 [此处](https://pytorch.ac.cn/blog/accelerating-pytorch-with-cuda-graphs/) 的文档进一步说明。
# Enables Cudagraphs Mode
torch_tensorrt.runtime.set_cudagraphs_mode(True)
# Disables Cudagraphs Mode [Default Behavior]
torch_tensorrt.runtime.set_cudagraphs_mode(False)
# Enables Cudagraphs Mode, then resets the mode to its prior setting
with torch_tensorrt.runtime.enable_cudagraphs(trt_module):
...
在当前的实现中,使用新的输入形状(例如在动态形状情况下)将导致 CUDA Graphs 重新记录。CUDA Graphs 记录通常不是延迟密集型的,未来的改进包括缓存多个输入形状的 CUDA Graphs。