PyTorch随笔 - 获取TensorRT(TRT)模型输入和输出

2024-02-29 03:20

本文主要是介绍PyTorch随笔 - 获取TensorRT(TRT)模型输入和输出,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

获取TensorRT(TRT)模型输入和输出,用于创建TRT的模型服务使用,具体参考脚本check_trt_script.py,如下:

  • 脚本输入:TRT的模型路径和输入图像尺寸
  • 脚本输出:模型的输入和输出结点信息,同时验证TRT模型是否可用
#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2021. All rights reserved.
Created by C. L. Wang on 16.9.21
"""import argparseimport numpy as npdef check_trt(model_path, image_size):"""检查TRT模型"""import pycuda.driver as cudaimport tensorrt as trt# 必须导入包,import pycuda.autoinit,否则报错import pycuda.autoinitprint('[Info] model_path: {}'.format(model_path))img_shape = (1, 3, image_size, image_size)print('[Info] img_shape: {}'.format(img_shape))trt_logger = trt.Logger(trt.Logger.WARNING)trt_path = model_path  # TRT模型路径with open(trt_path, 'rb') as f, trt.Runtime(trt_logger) as runtime:engine = runtime.deserialize_cuda_engine(f.read())for binding in engine:binding_idx = engine.get_binding_index(binding)size = engine.get_binding_shape(binding_idx)dtype = trt.nptype(engine.get_binding_dtype(binding))print("[Info] binding: {}, binding_idx: {}, size: {}, dtype: {}".format(binding, binding_idx, size, dtype))input_image = np.random.randn(*img_shape).astype(np.float32)  # 图像尺寸input_image = np.ascontiguousarray(input_image)print('[Info] input_image: {}'.format(input_image.shape))with engine.create_execution_context() as context:stream = cuda.Stream()bindings = [0] * len(engine)for binding in engine:idx = engine.get_binding_index(binding)if engine.binding_is_input(idx):input_memory = cuda.mem_alloc(input_image.nbytes)bindings[idx] = int(input_memory)cuda.memcpy_htod_async(input_memory, input_image, stream)else:dtype = trt.nptype(engine.get_binding_dtype(binding))shape = context.get_binding_shape(idx)output_buffer = np.empty(shape, dtype=dtype)output_buffer = np.ascontiguousarray(output_buffer)output_memory = cuda.mem_alloc(output_buffer.nbytes)bindings[idx] = int(output_memory)context.execute_async_v2(bindings, stream.handle)stream.synchronize()cuda.memcpy_dtoh(output_buffer, output_memory)print("[Info] output_buffer: {}".format(output_buffer))def parse_args():"""处理脚本参数"""parser = argparse.ArgumentParser(description='检查TRT模型')parser.add_argument('-m', dest='model_path', required=True, help='TRT模型路径', type=str)parser.add_argument('-s', dest='image_size', required=False, help='图像尺寸,如336', type=int, default=336)args = parser.parse_args()arg_model_path = args.model_pathprint("[Info] 模型路径: {}".format(arg_model_path))arg_image_size = args.image_sizeprint("[Info] image_size: {}".format(arg_image_size))return arg_model_path, arg_image_sizedef main():arg_model_path, arg_image_size = parse_args()check_trt(arg_model_path, arg_image_size)  # 检查TRT模型if __name__ == '__main__':main()

注意:必须导入包,import pycuda.autoinit,否则cuda.Stream()报错,如下:
image-20210916162952425

输出信息如下:

[Info] 模型路径: ../mydata/trt_models/model_best_c2_20210915_cuda.trt
[Info] image_size: 336
[Info] model_path: ../mydata/trt_models/model_best_c2_20210915_cuda.trt
[Info] img_shape: (1, 3, 336, 336)
[Info] binding: input_0, binding_idx: 0, size: (1, 3, 336, 336), dtype: <class 'numpy.float32'>
[Info] binding: output_0, binding_idx: 1, size: (1, 2), dtype: <class 'numpy.float32'>
[Info] input_image: (1, 3, 336, 336)
[Info] output_buffer: [[ 0.23275298 -0.2184143 ]]

有效信息为:

  • 输入结点binding: input_0,输入尺寸size: (1, 3, 336, 336),输入类型dtype: <class 'numpy.float32'>
  • 输出结果binding: output_0,输出尺寸size: (1, 2),输出类型dtype: <class 'numpy.float32'>

相应的json文件如下:

{"model_path": "model_best_c2_20210915_cuda.trt","model_format": "trt","quant_type": "FP32","gpu_index": 0,"inputs": {"input_0": {"shapes": [1,3,336,336],"type": "FP32"}},"outputs": {"output_0": {"shapes": [1,2],"type": "FP32"}}
}

这篇关于PyTorch随笔 - 获取TensorRT(TRT)模型输入和输出的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/u012515223/article/details/120333320
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/757429

相关文章

C# foreach 循环中获取索引的实现方式

《C#foreach循环中获取索引的实现方式》:本文主要介绍C#foreach循环中获取索引的实现方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、手动维护索引变量二、LINQ Select + 元组解构三、扩展方法封装索引四、使用 for 循环替代

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

在PyCharm中安装PyTorch、torchvision和OpenCV详解

《在PyCharm中安装PyTorch、torchvision和OpenCV详解》:本文主要介绍在PyCharm中安装PyTorch、torchvision和OpenCV方式,具有很好的参考价值,... 目录PyCharm安装PyTorch、torchvision和OpenCV安装python安装PyTor

pytorch之torch.flatten()和torch.nn.Flatten()的用法

《pytorch之torch.flatten()和torch.nn.Flatten()的用法》:本文主要介绍pytorch之torch.flatten()和torch.nn.Flatten()的用... 目录torch.flatten()和torch.nn.Flatten()的用法下面举例说明总结torch

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法

《golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法》:本文主要介绍golang获取当前时间、时间戳和时间字符串及它们之间的相互转换,本文通过实例代码给大家介绍的非常详细,感兴趣... 目录1、获取当前时间2、获取当前时间戳3、获取当前时间的字符串格式4、它们之间的相互转化上篇文章给大家介

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA