【环境配置】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

相关文章

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

定价129元!支持双频 Wi-Fi 5的华为AX1路由器发布

《定价129元!支持双频Wi-Fi5的华为AX1路由器发布》华为上周推出了其最新的入门级Wi-Fi5路由器——华为路由AX1,建议零售价129元,这款路由器配置如何?详细请看下文介... 华为 Wi-Fi 5 路由 AX1 已正式开售,新品支持双频 1200 兆、配有四个千兆网口、提供可视化智能诊断功能,建

golang内存对齐的项目实践

《golang内存对齐的项目实践》本文主要介绍了golang内存对齐的项目实践,内存对齐不仅有助于提高内存访问效率,还确保了与硬件接口的兼容性,是Go语言编程中不可忽视的重要优化手段,下面就来介绍一下... 目录一、结构体中的字段顺序与内存对齐二、内存对齐的原理与规则三、调整结构体字段顺序优化内存对齐四、内

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的

Spring Boot整合log4j2日志配置的详细教程

《SpringBoot整合log4j2日志配置的详细教程》:本文主要介绍SpringBoot项目中整合Log4j2日志框架的步骤和配置,包括常用日志框架的比较、配置参数介绍、Log4j2配置详解... 目录前言一、常用日志框架二、配置参数介绍1. 日志级别2. 输出形式3. 日志格式3.1 PatternL

配置springboot项目动静分离打包分离lib方式

《配置springboot项目动静分离打包分离lib方式》本文介绍了如何将SpringBoot工程中的静态资源和配置文件分离出来,以减少jar包大小,方便修改配置文件,通过在jar包同级目录创建co... 目录前言1、分离配置文件原理2、pom文件配置3、使用package命令打包4、总结前言默认情况下,

python实现简易SSL的项目实践

《python实现简易SSL的项目实践》本文主要介绍了python实现简易SSL的项目实践,包括CA.py、server.py和client.py三个模块,文中通过示例代码介绍的非常详细,对大家的学习... 目录运行环境运行前准备程序实现与流程说明运行截图代码CA.pyclient.pyserver.py参