【环境配置】YOLOX-华为Ascend-Pytorch模型离线推理【项目复盘】

本文主要是介绍【环境配置】YOLOX-华为Ascend-Pytorch模型离线推理【项目复盘】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

      • 推理流程
        • 导出ONNX文件
        • 转换om模型
        • 测试集预处理
          • 前处理脚本
          • 生成预处理数据,得到对应的info文件
        • 离线推理
        • 精度统计
          • 后处理脚本
        • 性能对比
          • npu
          • gpu

前言
本文基于下面的参考
Ascend PyTorch模型离线推理指导

推理流程

导出ONNX文件

这一步参考官方教程

转换om模型
  1. 激活环境source env.sh
    env.sh内容见下

    # export install_path=/usr/local/Ascend/ascend-toolkit/latest
    # export install_path=/home/wgzheng/envs/Ascend/ascend-toolkit/latest
    export install_path=/home/wgzheng/packages/Ascend/ascend-toolkit/latest
    export PATH=/usr/local/python3.7.5/bin:${install_path}/atc/ccec_compiler/bin:${install_path}/atc/bin:$PATH
    export PYTHONPATH=${install_path}/atc/python/site-packages
    export LD_LIBRARY_PATH=${install_path}/atc/lib64:${install_path}/acllib/lib64
    export ASCEND_OPP_PATH=${install_path}/opp
    export ASCEND_AICPU_PATH=${install_path}
    export ASCEND_SLOG_PRINT_TO_STDOUT=0
    export ASCEND_GLOBAL_LOG_LEVEL=0
    # export DUMP_GE_GRAPH=2
    # export DUMP_GRAPH_LEVEL=2
    
  2. 执行下面的转换命令

    atc --framework=5 --model=yolox_x.onnx -output=yolox_x_fix --input_shape="images:1,3,640,640" --input_format=ND --soc_version=Ascend310 --keep_dtype=execeptionlist.cfg
    

    execeptionlist.cfg内容见下图请添加图片描述

测试集预处理
前处理脚本

preprocess.py

import os
import sys
import argparse
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from yolox.data import COCODataset, ValTransform
sys.path.append('../YOLOX-main')def main():parser = argparse.ArgumentParser(description='YOLOX Preprocess')parser.add_argument('--dataroot', dest='dataroot',help='data root dirname', default='./datasets/COCO',type=str)parser.add_argument('--output', dest='output',help='output for prepared data', default='prep_data',type=str)parser.add_argument('--batch',help='validation batch size',type=int)opt = parser.parse_args()valdataset = COCODataset(data_dir=opt.dataroot,json_file='instances_val2017.json',name="val2017",img_size = (640,640),preproc=ValTransform(legacy=False),)sampler = torch.utils.data.SequentialSampler(valdataset)dataloader_kwargs = {"num_workers": 8, "pin_memory": True, "sampler": sampler, "batch_size": opt.batch}val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)for idx, data in tqdm(enumerate(val_loader)):inps = data[0].numpy()output_name = "{:0>12d}.bin".format(idx)output_path = os.path.join('/home/wxd/CODE/YOLOX/prep_data/', output_name)inps.tofile(output_path)if __name__ == "__main__":main()

执行python preprocess.py

生成预处理数据,得到对应的info文件

gen_dataset_info.py

# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.import os
import sys
import cv2
from glob import globdef get_bin_info(file_path, info_name, width, height):bin_images = glob(os.path.join(file_path, '*.bin'))with open(info_name, 'w') as file:for index, img in enumerate(bin_images):content = ' '.join([str(index), img, width, height])file.write(content)file.write('\n')def get_jpg_info(file_path, info_name):extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']image_names = []for extension in extensions:image_names.append(glob(os.path.join(file_path, '*.' + extension)))  with open(info_name, 'w') as file:for image_name in image_names:if len(image_name) == 0:continueelse:for index, img in enumerate(image_name):img_cv = cv2.imread(img)shape = img_cv.shapewidth, height = shape[1], shape[0]content = ' '.join([str(index), img, str(width), str(height)])file.write(content)file.write('\n')if __name__ == '__main__':file_type = sys.argv[1]file_path = sys.argv[2]info_name = sys.argv[3]if file_type == 'bin':width = sys.argv[4]height = sys.argv[5]assert len(sys.argv) == 6, 'The number of input parameters must be equal to 5'get_bin_info(file_path, info_name, width, height)elif file_type == 'jpg':assert len(sys.argv) == 4, 'The number of input parameters must be equal to 3'get_jpg_info(file_path, info_name)

执行python gen_dataset_info.py bin ./prep_data ./prep_bin.info 640 640

离线推理
./benchmark.x86_64 -model_type=vision -device_id=0 -batch_size=1 -om_path=yolox_x_fix.om -input_text_path=../prep_bin.info -input_width=640 -input_height=640 -output_binary=True -useDvpp=False
精度统计
后处理脚本

postprocess.py

import os
import sys
import argparse
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from yolox.data import COCODataset, ValTransform
from yolox.evaluators import COCOEvaluator
from yolox.utils.boxes import postprocessfrom yolox.utils.demo_utils import demo_postprocess,multiclass_nms
import numpy as np
sys.path.append('../YOLOX-main')def get_output_data(dump_dir,idx,dtype=np.float32):output_shape = [1,8400,85]input_file = os.path.join(dump_dir, "{:0>12d}_1.bin".format(idx))input_data = np.fromfile(input_file, dtype=dtype).reshape(output_shape)return torch.from_numpy(input_data)def main():parser = argparse.ArgumentParser(description='YOLOX Postprocess')parser.add_argument('--dataroot', dest='dataroot',help='data root dirname', default='./datasets/COCO',type=str)parser.add_argument('--dump_dir', dest='dump_dir',help='dump dir for bin files', default='./result/dumpOutput_device0/',type=str)parser.add_argument('--batch', dest='batch',help='batch for dataloader',default=1,type=int)opt = parser.parse_args()valdataset = COCODataset(data_dir=opt.dataroot,json_file='instances_val2017.json',name="val2017",img_size = (640,640),preproc=ValTransform(legacy=False),)sampler = torch.utils.data.SequentialSampler(valdataset)dataloader_kwargs = {"num_workers": 8, "pin_memory": True, "sampler": sampler, "batch_size": opt.batch}val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)data_list = []coco_evaluator = COCOEvaluator(val_loader,img_size=(640,640),confthre=0.001,nmsthre=0.65,num_classes=80)for cur_iter, (imgs, _, info_imgs, ids) in enumerate(tqdm(val_loader)):outputs = get_output_data(opt.dump_dir,cur_iter)outputs = demo_postprocess(outputs,[640,640])outputs = postprocess(outputs, num_classes=80, conf_thre=0.001, nms_thre=0.65)data_list.extend(coco_evaluator.convert_to_coco_format(outputs,info_imgs,ids))results = coco_evaluator.evaluate_prediction(data_list)print(results)if __name__ == "__main__":main()

执行python postprocess.py

性能对比

由于310上无法导出yolox在batch=16的onnx,以下是基于batch=1多脚本。

npu
/benchmark.x86_64 -round=20 -om_path=yolox_x_fix.om -device_id=0 -batch_size=1
gpu
trtexec --onnx=yolox_x.onnx --fp16 --shapes=images:1x3x640x640

这篇关于【环境配置】YOLOX-华为Ascend-Pytorch模型离线推理【项目复盘】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/260858

相关文章

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

浅谈配置MMCV环境,解决报错,版本不匹配问题

《浅谈配置MMCV环境,解决报错,版本不匹配问题》:本文主要介绍浅谈配置MMCV环境,解决报错,版本不匹配问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录配置MMCV环境,解决报错,版本不匹配错误示例正确示例总结配置MMCV环境,解决报错,版本不匹配在col

Nginx中配置HTTP/2协议的详细指南

《Nginx中配置HTTP/2协议的详细指南》HTTP/2是HTTP协议的下一代版本,旨在提高性能、减少延迟并优化现代网络环境中的通信效率,本文将为大家介绍Nginx配置HTTP/2协议想详细步骤,需... 目录一、HTTP/2 协议概述1.HTTP/22. HTTP/2 的核心特性3. HTTP/2 的优

Python 安装和配置flask, flask_cors的图文教程

《Python安装和配置flask,flask_cors的图文教程》:本文主要介绍Python安装和配置flask,flask_cors的图文教程,本文通过图文并茂的形式给大家介绍的非常详细,... 目录一.python安装:二,配置环境变量,三:检查Python安装和环境变量,四:安装flask和flas

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

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

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

springboot security之前后端分离配置方式

《springbootsecurity之前后端分离配置方式》:本文主要介绍springbootsecurity之前后端分离配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的... 目录前言自定义配置认证失败自定义处理登录相关接口匿名访问前置文章总结前言spring boot secu

一文详解SpringBoot响应压缩功能的配置与优化

《一文详解SpringBoot响应压缩功能的配置与优化》SpringBoot的响应压缩功能基于智能协商机制,需同时满足很多条件,本文主要为大家详细介绍了SpringBoot响应压缩功能的配置与优化,需... 目录一、核心工作机制1.1 自动协商触发条件1.2 压缩处理流程二、配置方案详解2.1 基础YAML

springboot简单集成Security配置的教程

《springboot简单集成Security配置的教程》:本文主要介绍springboot简单集成Security配置的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录集成Security安全框架引入依赖编写配置类WebSecurityConfig(自定义资源权限规则