pytorch/TensorRT

PyTorch/TorchScript/FX compiler for NVIDIA GPUs using TensorRT

Torch‑TensorRT — 在 NVIDIA GPU 上加速 PyTorch 推論

它是什麼

  • 一個開源函式庫,橋接 PyTorch 和 NVIDIA 的 TensorRT 推論引擎。它讓您可以取得任何 PyTorch 模型,並以 TensorRT 等級的速度執行,而無需重寫模型。

主要功能

  • 單行加速 – 使用 torch.compile(..., backend="tensorrt") 或 torch_tensorrt.compile API,與一般 eager PyTorch 相比,延遲最多可降低 5×。
  • 兩種部署路徑:
    1. 透過 torch.compile 進行即時(JIT)編譯 – 完全在 Python 中運作。
    2. 提前匯出 – 編譯一次,序列化為 ExportedProgram(.ep)或 TorchScript(.ts)檔案,然後在 Python 或 C++(libtorch)中載入以用於生產環境。
  • 支援現代硬體 – 可在 Linux(x86‑64、ARM aarch64)、Windows(Dynamo 後端)、Jetson 裝置(GPU/DLA)上運作,並需要 CUDA 13.4 + TensorRT 11.3。
  • 混合精度與 FP8 – 教學示範如何以較低精度格式執行模型以獲得額外速度。

典型工作流程

import torch, torch_tensorrt
model = MyModel().eval().cuda()
inputs = [torch.randn(1,3,224,224).cuda()]
# 編譯與序列化
trt_mod = torch_tensorrt.compile(model, ir="dynamo", inputs=inputs)
torch_tensorrt.save(trt_mod, "model.ts", output_format="torchscript", inputs=inputs)

稍後,在 Python 或 C++ 中:

mod = torch.export.load("model.ep").module()
mod(*inputs)   # 快速推論
auto mod = torch::jit::load("model.ts");
auto out = mod.forward({input_tensor});

誰應該使用

  • 需要在 NVIDIA GPU 上獲得生產級推論速度的 PyTorch 開發人員。
  • 部署大型視覺或語言模型(例如 Stable Diffusion、Hugging‑Face LLM)並希望獲得即插即用速度提升的團隊。
  • 偏好留在 PyTorch 生態系統中但需要 TensorRT 等級效能的工程師。

安裝

  • 穩定版:pip install torch-tensorrt
  • 每日建置(CUDA 13.4):pip install --pre torch-tensorrt --index-url https://download.pytorch.org/whl/nightly/cu134
  • 也可在 NVIDIA NGC PyTorch 容器中取得。

資源

  • 官方文件:https://nvidia.github.io/Torch-TensorRT/
  • 關於加速擴散模型、Stable Diffusion 和 Hugging‑Face LLM 的部落格文章與教學。
  • YouTube 技術演講(GTC ’23)提供更深入的架構細節。

授權

  • BSD‑3‑Clause,允許商業和研究使用。

Torch‑TensorRT 是一個真正的 AI 導向專案,可在 NVIDIA 硬體上為 PyTorch 模型實現高效能推論。

相关

  • 项目
  • 项目
  • 项目
  • 项目
  • 项目