当前位置:   article > 正文

TensorRT学习笔记--Ubuntu20.04安装TensorRT 8.2.5

ubuntu20.04安装tensorrt

目录

前言

1--查看本机环境配置

2--下载并安装Tensor RT

3--实例测试

3-1--验证Onnx模型的可用性

3-2--将Onnx模型转换为推理引擎engine

3-3--基于Tensor RT使用engine模型进行推理

4--参考


前言

        推荐结合官方文档 3.2.3节中的Tar File Installation安装教程进行安装;

1--查看本机环境配置

  1. import torch
  2. print(torch.__version__)
  3. print(torch.version.cuda)
  4. print(torch.backends.cudnn.version())

博主的配置环境:

        ① Ubuntu 20.04

        ② Cuda 11.3

        ③ NVIDIA GeForce RTX 3060

        ④ Pytorch 1.12.0

        ⑤ Python 3.9

2--下载并安装Tensor RT

① 下载地址:Tensor RT官方下载地址

        博主下载的版本为Tensor RT 8.2.5.1。

② 安装依赖:

  1. pip install 'pycuda<2021.1'
  2. # 注意onnxruntime-gpu的版本需与实际环境进行匹配,这里博主选择1.11版本
  3. pip install onnxruntime-gpu==1.11

 ③ 解压并配置环境变量: 

  1. # 解压
  2. tar -zxvf TensorRT-8.2.5.1.Linux.x86_64-gnu.cuda-11.4.cudnn8.2.tar.gz
  1. # 配置环境变量
  2. sudo gedit ~/.bashrc # 也可以使用vim
  3. # 末尾添加以下两条路径,需根据解压的实际路径
  4. export LD_LIBRARY_PATH=$PATH:/home/liujinfu/Downloads/TensorRT-8.2.5.1/lib:$LD_LIBRARY_PATH
  5. export LIBRARY_PATH=$PATH:/home/liujinfu/Downloads/TensorRT-8.2.5.1/lib::$LIBRARY_PATH
  6. # 保存后刷新环境变量
  7. source ~/.bashrc

④ 安装Tensor RT库:

  1. cd TensorRT-8.2.5.1/python
  2. # 根据Python版本安装,博主为python3.9
  3. pip install tensorrt-8.2.5.1-cp39-none-linux_x86_64.whl
  4. # 安装依赖
  5. cd TensorRT-8.2.5.1/graphsurgeon
  6. pip install graphsurgeon-0.4.5-py2.py3-none-any.whl

⑤ 查看安装版本:

  1. import onnxruntime as ort
  2. import tensorrt
  3. print(ort.get_device())
  4. print(ort.get_available_providers())
  5. print(tensorrt.__version__)

3--实例测试

        深度学习模型部署流程一般为:Pytorch → Onnx → TensorRT;这里博主选取一个姿态估计的Onnx模型(ThreeDPose)作为实例测试:Onnx模型下载地址

3-1--验证Onnx模型的可用性

  1. # 导入第三方库
  2. import onnx
  3. import numpy as np
  4. import onnxruntime as ort
  5. import cv2
  6. # 导入下载的Onnx模型
  7. model_path = './Resnet34_3inputs_448x448_20200609.onnx'
  8. onnx_model = onnx.load(model_path)
  9. onnx.checker.check_model(onnx_model)
  10. # 前处理:读入图像并调整为输入维度
  11. img = cv2.imread("data/InitImg.png")
  12. img = cv2.resize(img,(448,448)).transpose(2,0,1)
  13. img = np.array(img)[np.newaxis, :, :, :].astype(np.float32)
  14. # 设置模型session以及输入信息
  15. sess = ort.InferenceSession(model_path,providers= ort.get_available_providers()) # 这一步可能会报错,一般与onnxruntime的版本有关,需根据实际情况进行调整
  16. input_name1 = sess.get_inputs()[0].name
  17. input_name2 = sess.get_inputs()[1].name
  18. input_name3 = sess.get_inputs()[2].name
  19. # 使用Onnx模型进行推理
  20. output = sess.run(None, {input_name1: img, input_name2: img, input_name3: img})
  21. print(output)
  22. # 后处理
  23. # 代码。。。

        正常运行,没有报错就表明下载的Onnx模型没有问题;

3-2--将Onnx模型转换为推理引擎engine

        借助Tensor RT自带的可执行文件trtexec,将Onnx模型转换为推理引擎:

  1. cd TensorRT-8.2.5.1/bin
  2. ./trtexec --onnx=/home/liujinfu/Desktop/Tensor_Test/Resnet34_3inputs_448x448_20200609.onnx --saveEngine=/home/liujinfu/Desktop/Tensor_Test/Resnet34_3inputs_448x448_20200609.trt --workspace=6000
  3. # --onnx=path1 表示待转换的onnx模型
  4. # --saveEngine=path2 表示保存的推理engine模型

3-3--基于Tensor RT使用engine模型进行推理

  1. # 导入第三方库
  2. import torch
  3. import cv2
  4. import tensorrt as trt
  5. import numpy as np
  6. def trt_version():
  7. return trt.__version__
  8. def torch_device_from_trt(device):
  9. if device == trt.TensorLocation.DEVICE:
  10. return torch.device("cuda")
  11. elif device == trt.TensorLocation.HOST:
  12. return torch.device("cpu")
  13. else:
  14. return TypeError("%s is not supported by torch" % device)
  15. def torch_dtype_from_trt(dtype):
  16. if dtype == trt.int8:
  17. return torch.int8
  18. elif trt_version() >= '7.0' and dtype == trt.bool:
  19. return torch.bool
  20. elif dtype == trt.int32:
  21. return torch.int32
  22. elif dtype == trt.float16:
  23. return torch.float16
  24. elif dtype == trt.float32:
  25. return torch.float32
  26. else:
  27. raise TypeError("%s is not supported by torch" % dtype)
  28. class TRTModule(torch.nn.Module):
  29. def __init__(self, engine=None, input_names=None, output_names=None):
  30. super(TRTModule, self).__init__()
  31. self.engine = engine
  32. if self.engine is not None:
  33. # engine创建执行context
  34. self.context = self.engine.create_execution_context()
  35. self.input_names = input_names
  36. self.output_names = output_names
  37. def forward(self, *inputs):
  38. batch_size = inputs[0].shape[0]
  39. bindings = [None] * (len(self.input_names) + len(self.output_names))
  40. # 创建输出tensor,并分配内存
  41. outputs = [None] * len(self.output_names)
  42. for i, output_name in enumerate(self.output_names):
  43. idx = self.engine.get_binding_index(output_name) # 通过binding_name找到对应的input_id
  44. dtype = torch_dtype_from_trt(self.engine.get_binding_dtype(idx)) # 找到对应的数据类型
  45. shape = (batch_size,) + tuple(self.engine.get_binding_shape(idx)) # 找到对应的形状大小
  46. device = torch_device_from_trt(self.engine.get_location(idx))
  47. output = torch.empty(size=shape, dtype=dtype, device=device)
  48. outputs[i] = output
  49. bindings[idx] = output.data_ptr() # 绑定输出数据指针
  50. for i, input_name in enumerate(self.input_names):
  51. idx = self.engine.get_binding_index(input_name)
  52. bindings[idx] = inputs[0].contiguous().data_ptr() # 应当为inputs[i],对应3个输入。但由于我们使用的是单张图片,所以将3个输入全设置为相同的图片。
  53. self.context.execute_async(
  54. batch_size, bindings, torch.cuda.current_stream().cuda_stream
  55. ) # 执行推理
  56. outputs = tuple(outputs)
  57. if len(outputs) == 1:
  58. outputs = outputs[0]
  59. return outputs
  60. if __name__ == "__main__":
  61. logger = trt.Logger(trt.Logger.INFO)
  62. # 加载推理引擎,返回ICudaEngine对象
  63. with open("./Resnet34_3inputs_448x448_20200609.trt", "rb") as f, trt.Runtime(logger) as runtime:
  64. engine = runtime.deserialize_cuda_engine(f.read())
  65. # 查看输入输出的名字,类型,大小
  66. for idx in range(engine.num_bindings):
  67. is_input = engine.binding_is_input(idx)
  68. name = engine.get_binding_name(idx)
  69. op_type = engine.get_binding_dtype(idx)
  70. shape = engine.get_binding_shape(idx)
  71. print('input id:', idx, ' is input: ', is_input, ' binding name:', name, ' shape:', shape, 'type: ', op_type)
  72. trt_model = TRTModule(engine, ["input.1", "input.4", "input.7"], ["499", "504", "516", "530"])
  73. # 加载测试图片
  74. image = cv2.imread("./test1.jpg")
  75. # 前处理
  76. image = cv2.resize(image, (200,64))
  77. image = image.transpose(2,0,1)
  78. img_input = image.astype(np.float32)
  79. img_input = torch.from_numpy(img_input)
  80. img_input = img_input.unsqueeze(0)
  81. img_input = img_input.to('cuda:0')
  82. # 运行模型进行推理
  83. result_trt = trt_model(img_input)

4--参考

TensorRT8.2最新版入门教程

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/432743
推荐阅读
相关标签
  

闽ICP备14008679号