TensorRT教程12:使用PythonAPI部署推理(重点)

使用PythonAPI部署推理(重点)

step1:创建runtime

step2:反序列化创建engine

step3:创建context

step4:获取输入输出索引

step5:创建buffers

step6:为输入输出开辟GPU显存

step7:创建cuda流

step8:从CPU到GPU----拷贝input数据

step9:异步推理

step10:从GPU到CPU----拷贝output数据

step10:同步cuda流

step11:释放资源

#导入模块
import tensorrt as trt
import pycuda.autoinit  #负责数据初始化,内存管理,销毁等
import pycuda.driver as cuda  #GPU CPU之间的数据传输
import numpy as np
from PIL import Image
import matlotlib.pyplot as plt
import os

#step1:创建logger:日志记录器
logger = trt.Logger(trt.Logger.WARNING)

#step2:创建runtime并反序列化生成engine
with open(“sample.engine”, “rb”) as f, trt.Runtime(logger) as runtime:
    engine = runtime.deserialize_cuda_engine(f.read())

#step3:分配CPU锁页内存和GPU显存
h_input = cuda.pagelocked_empty(trt.volume(context.get_binding_shape(0)), dtype=np.float32)
h_output = cuda.pagelocked_empty(trt.volume(context.get_binding_shape(1)), dtype=np.float32)
d_input = cuda.mem_alloc(h_input.nbytes)
d_output = cuda.mem_alloc(h_output.nbytes)
#step4:创建cuda流
stream = cuda.Stream()

#step5:创建context并进行推理
with engine.create_execution_context() as context:
    # Transfer input data to the GPU.
    cuda.memcpy_htod_async(d_input, h_input, stream)
    # Run inference.
    context.execute_async_v2(bindings=[int(d_input), int(d_output)], stream_handle=stream.handle)
    # Transfer predictions back from the GPU.
    cuda.memcpy_dtoh_async(h_output, d_output, stream)
    # Synchronize the stream
    stream.synchronize()
    # Return the host output. 
    return h_output
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
TensorRT是一个高性能深度学习推理引擎,可以将训练好的模型优化并部署在GPU上进行推理。在Python使用TensorRT进行深度学习模型的部署,可以通过以下步骤实现: 1. 安装TensorRT 在官网上下载适合自己系统的TensorRT安装包,然后按照官方文档进行安装。 2. 利用TensorFlow或PyTorch训练好模型 使用TensorFlow或PyTorch训练好模型,保存模型文件。 3. 使用TensorRT优化模型 使用TensorRT提供的工具将训练好的模型优化成可在GPU上进行推理的模型。具体操作可以参考TensorRT官方文档。 4. 在Python中加载TensorRT模型 使用TensorRT提供的Python API,在Python中加载优化后的模型,进行推理操作。具体操作可以参考TensorRT官方文档。 下面是一个使用TensorRT进行图像分类的Python示例代码: ```python import tensorrt as trt import pycuda.driver as cuda import pycuda.autoinit import numpy as np import cv2 # 加载优化后的模型 def load_engine(engine_path): with open(engine_path, 'rb') as f: engine_data = f.read() engine = trt.lite.Engine(None, engine_data) return engine # 进行推理操作 def inference(engine, input_image): # 获取输入输出张量 input_tensor = engine.get_input_tensor(0) output_tensor = engine.get_output_tensor(0) # 将输入图像转换为模型输入张量格式 input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB) input_image = cv2.resize(input_image, (input_tensor.shape[3], input_tensor.shape[2])) input_image = np.transpose(input_image, [2, 0, 1]) input_image = np.expand_dims(input_image, axis=0) # 创建输入输出映射表 bindings = [int(input_tensor.device_buffer), int(output_tensor.device_buffer)] # 创建执行上下文 context = engine.create_execution_context() # 将输入数据复制到GPU cuda.memcpy_htod(input_tensor.device_buffer, input_image) # 执行推理 context.execute_v2(bindings) # 将输出数据从GPU复制回CPU output = np.empty(output_tensor.shape, dtype=np.float32) cuda.memcpy_dtoh(output, output_tensor.device_buffer) # 获取分类结果 class_id = np.argmax(output) return class_id # 加载优化后的模型 engine_path = 'model.trt' engine = load_engine(engine_path) # 进行推理操作 input_image = cv2.imread('test.jpg') class_id = inference(engine, input_image) print('预测结果:{}'.format(class_id)) ``` 需要注意的是,TensorRT只支持FP16和INT8数据类型,如果模型中有其他数据类型,需要进行转换。同时,TensorRT只支持静态图模型,如果使用动态图框架训练的模型,需要先将其转换为静态图模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

米斯特龙_ZXL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值