本教程详细记录了ubuntu上配置使用 torch2trt 的方法。

1 库配置
1.1 安装 tensorrt python 接口
下载 trt 包 .tar.gz

https://developer.nvidia.com/nvidia-tensorrt-7x-download

解压

tar xvf TensorRT-7.2.1.6.Ubuntu-18.04.x86_64-gnu.cuda-11.1.cudnn8.0.tar.gz

安装 trt python 接口

cd python

pip install tensorrt-7.2.1.6-cp37-none-linux_x86_64.whl

安装 uff

cd uff

pip install uff-0.6.9-py2.py3-none-any.whl

验证trt是否安装成功
python
import tensorrt
以上是配置 TRT7 的方法,你要是想配置 TRT8,方法一致。

1.2 安装 torch2trt

sudo apt-get install libprotobuf* protobuf-compiler ninja-build

适用于 TRT7

git clone https://github.com/NVIDIA-AI-IOT/torch2trt

适用于 TRT8

git clone -b support_trt_8 https://gitee.com/jeremyjj/torch2trt-trt8.git


cd torch2trt

sudo python setup.py install --plugins #或许不用sudo也行

2 代码演示
可以参考以下代码示例将你自己的模型进行 torch2trt 转换和推理。

import torch 
import torchvision
from torch2trt import torch2trt
​
batch_size = 1
## export resnet50  input: batchsize 3 224 224
net = torchvision.models.resnet50(pretrained=True).cuda()
​
input_data = torch.rand((batch_size, 3, 224, 224), dtype=torch.float).cuda()
​

convert to TensorRT int8 model

model_trt_int8 = torch2trt(net.eval(), [input_data], max_batch_size=batch_size, int8_mode=True)
​
out_trt = model_trt_int8(input_data)

3 性能测试
torch2trt 工程里也内置了典型模型性能测试脚本。如下使用:

./test.sh TEST_OUTPUT.md

4 作者注

最后修改:2022 年 11 月 08 日
如果觉得我的文章对你有用,请随意赞赏