從 PyTorch 直接使用 Torch-TensorRT¶
您現在可以直接從 PyTorch API 存取 TensorRT。使用此功能的過程與在 Python 中使用 Torch-TensorRT 中描述的編譯工作流程非常相似
首先將 torch_tensorrt
載入您的應用程式。
import torch
import torch_tensorrt
然後,給定一個 TorchScript 模組,您可以使用 torch._C._jit_to_backend("tensorrt", ...)
API 使用 TensorRT 編譯它。
import torchvision.models as models
model = models.mobilenet_v2(pretrained=True)
script_model = torch.jit.script(model)
與 Torch-TensorRT 中假設您嘗試編譯模組的 forward
函式或將指定函式轉換為 TensorRT 引擎的 convert_method_to_trt_engine
的 compile
API 不同,後端 API 將採用一個字典,該字典將要編譯的函式名稱映射到 Compilation Spec 物件,這些物件包裝了您要提供給 compile
的相同類型的字典。有關編譯規格字典的更多資訊,請查看 Torch-TensorRT TensorRTCompileSpec
API 的文件。
spec = {
"forward": torch_tensorrt.ts.TensorRTCompileSpec(
**{
"inputs": [torch_tensorrt.Input([1, 3, 300, 300])],
"enabled_precisions": {torch.float, torch.half},
"refit": False,
"debug": False,
"device": {
"device_type": torch_tensorrt.DeviceType.GPU,
"gpu_id": 0,
"dla_core": 0,
"allow_gpu_fallback": True,
},
"capability": torch_tensorrt.EngineCapability.default,
"num_avg_timing_iters": 1,
}
)
}
現在,要使用 Torch-TensorRT 進行編譯,請將目標模組物件和規格字典提供給 torch._C._jit_to_backend("tensorrt", ...)
trt_model = torch._C._jit_to_backend("tensorrt", script_model, spec)
若要執行,請明確呼叫您要執行的函式的函式(相較於您如何在標準 PyTorch 中只呼叫模組本身)
input = torch.randn((1, 3, 300, 300)).to("cuda").to(torch.half)
print(trt_model.forward(input))