已合并
模型整改 #3326
AtomGit-Bot创建于 2023年1月4日
模型整改 #3326
已合并
AtomGit-Bot创建于 2023年1月4日
refs/pull/3326/head合入到master
57 个文件变更+2070-3150
@@ -1,307 +1,257 @@
1-# DPN131 Onnx模型端到端推理指导1+# DPN131模型-推理指导
2-- [DPN131 Onnx模型端到端推理指导](#dpn131-onnx模型端到端推理指导)2+ 
3- - [1 模型概述](#1--模型概述)3+ 
4- - [1.1 论文地址](#11-论文地址)4+- [概述](#ZH-CN_TOPIC_0000001172161501)
5- - [1.2 代码地址](#12-代码地址)5+ 
6- - [2 环境说明](#2-环境说明)6+ - [输入输出数据](#section540883920406)
7- - [2.1 深度学习框架](#21-深度学习框架)
8- - [2.2 python第三方库](#22-python第三方库)
9- - [3 模型转换](#3-模型转换)
10- - [3.1 pth转onnx模型](#31-pth转onnx模型)
11- - [3.2 onnx转om模型](#32-onnx转om模型)
12- - [4 数据集预处理](#4-数据集预处理)
13- - [4.1 数据集获取](#41-数据集获取)
14- - [4.2 数据集预处理](#42-数据集预处理)
15- - [4.3 生成数据集信息文件](#43-生成数据集信息文件)
16- - [5 离线推理](#5-离线推理)
17- - [5.1 benchmark工具概述](#51-benchmark工具概述)
18- - [5.2 离线推理](#52-离线推理)
19- - [6 精度对比](#6-精度对比)
20- - [6.1 离线推理TopN精度统计](#61-离线推理topn精度统计)
21- - [6.2 开源TopN精度](#62-开源topn精度)
22- - [6.3 精度对比](#63-精度对比)
23- - [7 性能对比](#7-性能对比)
24- - [7.1 npu性能数据-Ascend310性能数据](#71-npu性能数据-ascend310性能数据)
25- - [7.2 T4性能数据](#72-t4性能数据)
26- - [7.3 性能对比](#73-性能对比)
27- - [7.4 npu性能数据-Ascend310P性能数据](#74-npu性能数据-ascend310p性能数据)
28 7 
29 8 
30 9 
31-## 1 模型概述10+- [推理环境准备](#ZH-CN_TOPIC_0000001126281702)
32 11 
33-- **[论文地址](#11-论文地址)**12+- [快速上手](#ZH-CN_TOPIC_0000001126281700)
34 13 
35-- **[地址](#12-代码地址)**14+ - [获取源码](#section4622531142816)
15+ - [准备数据集](#section183221994411)
16+ - [模型推理](#section741711594517)
36 17 
37-### 1.1 论文地址18+- [模型推理性能&精度](#ZH-CN_TOPIC_0000001172201573)
38-[DPN131论文](https://arxiv.org/abs/1707.01629)
39-### 1.2 代码地址
40-[DPN131代码](https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/dpn.py)
41-```
42-branch: master
43-commit id : 0a4df4f3fe46b81e94bf9cc9ee5d9bebee6b9ec5
44-```
45- 
46-## 2 环境说明
47- 
48-- **[深度学习框架](#21-深度学习框架)**
49- 
50-- **[python第三方库](#22-python第三方库)**
51- 
52-### 2.1 深度学习框架
53-```
54-CANN
55-pytorch >= 1.5.0
56-torchvision >= 0.6.0
57-onnx >= 1.7.0
58-```
59- 
60-### 2.2 python第三方库
61- 
62-```
63-numpy == 1.18.5
64-Pillow == 7.2.0
65-opencv-python == 4.5.1.48
66-```
67- 
68-**说明:**
69-> X86架构:pytorch,torchvision和onnx可以通过官方下载whl包安装,其它可以通过pip3.7 install 包名 安装
70->
71-> Arm架构:pytorch,torchvision和onnx可以通过源码编译安装,其它可以通过pip3.7 install 包名 安装
72- 
73-## 3 模型转换
74- 
75-- **[pth转onnx模型](#31-pth转onnx模型)**
76- 
77-- **[onnx转om模型](#32-onnx转om模型)**
78- 
79-### 3.1 pth转onnx模型
80- 
81-1.下载pth权重文件
82-[DPN131预训练pth权重文件](http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth)
83-```
84-文件md5sum: 71e7844aa8646dc75494976c7c86241a
85-wget http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth
86-```
87- 
88-2.安装过程如下所示:若安装过程报错请百度解决
89-```
90-git clone https://github.com/Cadene/pretrained-models.pytorch.git
91-拷贝dpn.diff到pretrainedmodels目录下
92-cd ./pretrainedmodels/models/
93-patch -p1 < ../dpn.diff
94-cd..
95-```
96- 
97-3.执行pth2onnx脚本,生成onnx模型文件
98-```
99-python3.7 dpn131_pth2onnx.py ./dpn131-7af84be88.pth dpn131.onnx
100-```
101- 
102-### 3.2 onnx转om模型
103- 
104-1. 设置环境变量
105- ```
106- source /usr/local/Ascend/ascend-toolkit/set_env.sh
107- ```
108-2. 使用atc将onnx模型转换为om模型文件
109- 
110- ${chip_name}可通过`npu-smi info`指令查看
111-
112- ![Image](https://gitee.com/ascend/ModelZoo-PyTorch/raw/master/ACL_PyTorch/images/310P3.png)
113- ```
114- atc --framework=5 --model=./dpn131.onnx --output=dpn131_bs1 --input_format=NCHW --input_shape="image:1,3,224,224" --log=debug --soc_version=Ascend${chip_name} # Ascend310P3
115- ```
116 19 
117 20 
118-## 4 数据集预处理
119 21 
120-- **[数据集获取](#41-数据集获取)**
121 22 
122-- **[数据集预处理](#42-数据集预处理)**23+# 概述<a name="ZH-CN_TOPIC_0000001172161501"></a>
123 24 
124-- **[生成数据集信息文件](#43-生成数据集信息文件)**25+DPN,简单高效的模块化双路径网络用于图像分类,提出了一种新的拓扑结构。DPN网络共享一些common特征,同时保持灵活性来通过双路径结构来探索新的特征。
125 26 
126-### 4.1 数据集获取27+- 参考实现:
127-该模型使用[ImageNet官网]的5万张验证集进行测试.
128 28 
129-### 4.2 数据集预处理29+ ```
130-1.预处理脚本imagenet_torch_preprocess.py30+ url=https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/dpn.py
31+ commit_id=0a4df4f3fe46b81e94bf9cc9ee5d9bebee6b9ec5
32+ code_path=https://gitee.com/ascend/ModelZoo-PyTorch/tree/master/ACL_PyTorch/contrib/cv/classfication/DPN131
33+ model_name=DPN131
34+ ```
131 35 
132-2.执行预处理脚本,生成数据集预处理后的bin文件
133-```
134-python3.7 imagenet_torch_preprocess.py /root/datasets/imagenet/val ./prep_dataset
135-```
136-### 4.3 生成数据集信息文件
137-1.生成数据集信息文件脚本gen_dataset_info.py
138 36 
139-2.执行生成数据集信息脚本,生成数据集信息文件37+## 输入输出数据<a name="section540883920406"></a>
140-```
141-python3.7 gen_dataset_info.py bin ./prep_dataset ./dpn131_prep_bin.info 224 224
142-```
143-第一个参数为模型输入的类型,第二个参数为生成的bin文件路径,第三个为输出的info文件,后面为宽高信息
144-## 5 离线推理
145 38 
146-- **[benchmark工具概述](#51-benchmark工具概述)**39+- 输入数据
147 40 
148-- **[离线推理](#52-离线推理)**41+ | 输入数据 | 数据类型 | 大小 | 数据排布格式 |
42+ | -------- | -------- | ------------------------- | ------------ |
43+ | input | RGB_FP32 | batchsize x 3 x 224 x 224 | NCHW |
149 44 
150-### 5.1 benchmark工具概述
151 45 
152-benchmark工具为华为自研的模型推理工具,支持多种模型的离线推理,能够迅速统计模型在Ascend310/Ascend310P上的性能,支持真实数据和纯推理两种模式,配合后处理脚本,可以实现诸多模型的端到端过程。46+- 输出数据
153-### 5.2 离线推理
154-1.设置环境变量
155-```
156-source /usr/local/Ascend/ascend-toolkit/set_env.sh
157-```
158-2.执行离线推理
159-```
160-./benchmark.x86_64 -model_type=vision -device_id=0 -batch_size=1 -om_path=dpn131_bs1.om -input_text_path=./dpn131_prep_bin.info -input_width=224 -input_height=224 -output_binary=False -useDvpp=False
161-```
162-输出结果默认保存在当前目录result/dumpOutput_device{0},模型只有一个名为class的输出,shape为bs * 1000,数据类型为FP32,对应1000个分类的预测结果,每个输入对应的输出对应一个_x.txt文件。
163 47 
164-## 6 精度对比48+ | 输出数据 | 数据类型 | 大小 | 数据排布格式 |
49+ | -------- |----------------| -------- | ------------ |
50+ | output1 | FLOAT32 | batchsize x -1 | ND |
165 51 
166-- **[离线推理TopN精度](#61-离线推理TopN精度)**
167-- **[开源TopN精度](#62-开源TopN精度)**
168-- **[精度对比](#63-精度对比)**
169 52 
170-### 6.1 离线推理TopN精度统计
171 53 
172-后处统计TopN精度54+# 推环境准备<a name="ZH-CN_TOPIC_0000001126281702"></a>
173 55 
174-调用imagenet_acc_eval.py脚本推理结果与label比对,可以获得Accuracy Top5数据,结果保存在result.json中。56+- 该模型需要以下插件与驱动
175-```
176-python3.7 imagenet_acc_eval.py result/dumpOutput_device0/ /root/datasets/imagenet/val_label.txt ./ result.json
177-```
178-第一个为benchmark输出目录,第二个为数据集配套标签,第三个是生成文件的保存目录,第四个是生成的文件名。
179-查看输出结果:
180-```
181-{"title": "Overall statistical evaluation", "value": [{"key": "Number of images", "value": "50000"}, {"key": "Number of classes", "value": "1000"}, {"key": "Top1 accuracy", "value": "79.43%"}, {"key": "Top2 accuracy", "value": "88.87%"}, {"key": "Top3 accuracy", "value": "91.98%"}, {"key": "Top4 accuracy", "value": "93.57%"}, {"key": "Top5 accuracy", "value": "94.58%"}]}
182-```
183-经过对bs1与bs16的om测试,本模型batch1的精度与batch16的精度没有差别,精度数据均如上
184 57 
185-### 6.2 开源TopN精度58+ **表 1** 版本配套表
186-[DPN官网精度](https://github.com/rwightman/pytorch-dpn-pretrained)
187-```
188-Model Acc@1 Acc@5
189-dpn131 79.432 94.574
190-```
191-### 6.3 精度对比
192-将得到的om离线模型推理TopN精度与该模型github代码仓上公布的精度对比,精度下降在1%范围之内,故精度达标。
193-**精度调试:**
194->没有遇到精度不达标的问题,故不需要进行精度调试
195 59 
196-## 7 性能对比60+ | 配套 | 版本 | 环境准备指导 |
61+ |---------| ------- | ------------------------------------------------------------ |
62+ | 固件与驱动 | 22.0.3 | [Pytorch框架推理环境准备](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/pies) |
63+ | CANN | 6.0.RC1 | - |
64+ | Python | 3.7.5 | - |
65+ | PyTorch | 1.8.0 | - |
66+ | 说明:Atlas 300I Duo 推理卡请以CANN版本选择实际固件与驱动版本。 | \ | \ |
197 67 
198-- **[310npu性能数据](#71-Ascend310性能数据)**
199-- **[T4性能数据](#72-T4性能数据)**
200-- **[性能对比](#73-性能对比)**
201-- **[310Pnpu性能数据](#74-Ascend310P性能数据)**
202-### 7.1 npu性能数据-Ascend310性能数据
203-benchmark工具在整个数据集上推理时也会统计性能数据,但是推理整个数据集较慢,如果这么测性能那么整个推理期间需要确保独占device,使用npu-smi info可以查看device是否空闲。也可以使用benchmark纯推理功能测得性能数据,但是由于随机数不能模拟数据分布,纯推理功能测的有些模型性能数据可能不太准,benchmark纯推理功能测性能仅为快速获取大概的性能数据以便调试优化使用,可初步确认benchmark工具在整个数据集上推理时由于device也被其它推理任务使用了导致的性能不准的问题。模型的性能以使用benchmark工具在整个数据集上推理得到bs1与bs16的性能数据为准,对于使用benchmark工具测试的batch4,8,32的性能数据在README.md中如下作记录即可。
204-1.benchmark工具在整个数据集上推理获得性能数据
205-batch1的性能,benchmark工具在整个数据集上推理后生成result/perf_vision_batchsize_1_device_0.txt:
206-```
207-[e2e] throughputRate: 34.4577, latency: 1.45105e+06
208-```
209-Interface throughputRate: 37.1687,37.1687x4=148.6748既是batch1 310单卡吞吐率
210 68 
211-batch16的性能,benchmark工具在整个数据集上推理后生成result/perf_vision_batchsize_16_device_1.txt:
212-```
213-[e2e] throughputRate: 36.1546, latency: 1.38295e+06
214-```
215-Interface throughputRate: 39.3897,39.3897x4=157.5588既是batch16 310单卡吞吐率
216-batch4性能:
217-```
218-[INFO] PureInfer result saved in ./result/PureInfer_perf_of_dpn131_bs4_in_device_3.txt
219------------------PureInfer Performance Summary------------------
220-[INFO] ave_throughputRate: 38.4344samples/s, ave_latency: 26.1589ms
221-----------------------------------------------------------------
222-```
223-batch4 310单卡吞吐率:38.4344x4=153.7376fps
224-batch8性能:
225-```
226-[INFO] PureInfer result saved in ./result/PureInfer_perf_of_dpn131_bs8_in_device_3.txt
227------------------PureInfer Performance Summary------------------
228-[INFO] ave_throughputRate: 39.3665samples/s, ave_latency: 25.4697ms
229-----------------------------------------------------------------
230-```
231-batch8 310单卡吞吐率:39.3665x4=157.466fps
232-batch32性能:
233-```
234-[INFO] PureInfer result saved in ./result/PureInfer_perf_of_dpn131_bs32_in_device_3.txt
235------------------PureInfer Performance Summary------------------
236-[INFO] ave_throughputRate: 40.1895samples/s, ave_latency: 24.9015ms
237-----------------------------------------------------------------
238-```
239-batch32 310单卡吞吐率:40.1895x4=160.758fps
240 69 
241-### 7.2 T4性能数据70+# 快速上手<a name="ZH-CN_TOPIC_0000001126281700"></a>
242-在装有T4卡的服务器上测试gpu性能,测试过程请确保卡没有运行其他任务,TensorRT版本:7.2.3.4,cuda版本:11.0,cudnn版本:8.2
243-batch1性能:
244-```
245-trtexec --onnx=dpn131.onnx --fp16 --shapes=image:1x3x224x224
246-```
247-gpu T4是4个device并行执行的结果,mean是时延(tensorrt的时延是batch个数据的推理时间),即吞吐率的倒数乘以batch
248-```
249-mean: 5.51384 ms
250-```
251-batch1 t4单卡吞吐率:1000/(5.51384/1)=181.361809555591fps
252 71 
253-batch16性能:72+## 获取源码<a name="section4622531142816"></a>
254-```
255- trtexec --onnx=dpn131.onnx --fp16 --shapes=image:16x3x224x224
256-```
257-```
258-mean: 54.2503 ms
259-```
260-batch16 t4单卡吞吐率:1000/(54.2503/16)=294.9292446309fps
261 73 
262-batch4性能:74+1. 获取源码。
263-```
264-trtexec --onnx=dpn131.onnx --fp16 --shapes=image:4x3x224x224
265-```
266-```
267-mean: 15.7431 ms
268-```
269-batch4 t4单卡吞吐率:1000/(15.5876/4)=256.614231825297fps
270 75 
271-batch8性能:76+ ```
272-```77+ git clone https://github.com/Cadene/pretrained-models.pytorch.git
273-trtexec --onnx=dpn131.onnx --fp16 --shapes=image:8x3x224x22478+ cd ./pretrainedmodels/models/
274-```79+ patch -p1 < ../dpn.diff,其中dpn.diff是通过git diff > ./dpn.diff生成的
275-```80+ cd..
276-mean: 27.8354 ms81+ ```
277-```
278-batch8 t4单卡吞吐率:1000/(27.8354/8)=287.4038095374954fps
279 82 
280-batch32性能:83+2. 安装依赖。
281-```
282-trtexec --onnx=dpn131.onnx --fp16 --shapes=image:32x3x224x224
283-```
284-```
285-mean: 106.881 ms
286-```
287-batch32 t4单卡吞吐率:1000/(106.881/32)=299.3983963473396fps
288 84 
289-### 7.3 性能对比85+ ```
290-batch1:37.3972x4=149.5888 < 1000/(5.51384/1)86+ pip3 install -r requirements.txt
291-batch16:39.2882x4=157.1528 < 1000/(54.2503/16)87+ ```
292-310单个device的吞吐率乘4即单卡吞吐率比T4单卡的吞吐率小,310性能低于T4性能,性能不达标。88+ 
293-对于batch1与batch16,310性能均低于T4性能,该模型放在Research/cv/classification目录下。89+## 准备数据集<a name="section183221994411"></a>
294-### 7.4 npu性能数据-Ascend310P性能数据90+ 
295-详细测试方法与310相同-下面仅简单记录fp16各个batch的性能数据作为参考,需特别说明的是310P的数据就是benchmark工具输出的 Interface throughputRate 的值,不需要任何计算。91+1. 获取原始数据集。(解压命令参考tar –xvf \*.tar与 unzip \*.zip)
296-```92+ 
297-batch1:158.10893+ 
298-batch4:371.7594+ 该模型使用[ImageNet官网](http://www.image-net.org/)的5万张验证集进行测试,图片与标签分别存放在/local/DPN131/imagenet/val与/local/DPN131/imagenet/val_label.txt。
299-batch8:378.01595+ ```
300-batch16:310.73196+ imagenet
301-batch32:360.54397+ ├── val_label.txt //验证集标注信息
302-batch64:355.64898+ └── val // 验证集文件夹
303-```99+ ```
304- **性能优化:**100+ 
305->待优化101+2. 数据预处理,将原始数据集转换为模型输入的数据。
306-CANN优化了StridedSliceD,使用该版本测102+ 
307-sclice算子引入过多的transdata需要进一步优化103+ 执行imagenet_torch_preprocess.py脚本,完成预处理。
104+ 
105+ ```
106+ python3.7 imagenet_torch_preprocess.py /local/DPN131/imagenet/val ./pre_dataset
107+ 
108+ ```
109+
110+ - 参数说明:
111+
112+ /local/DPN131/imagenet/val,验证集文件所在路径
113+
114+ ./pre_dataset,输出的预处理后数据集路径
115+ 
116+ 
117+ 
118+## 模型推理<a name="section741711594517"></a>
119+ 
120+1. 模型转换。
121+ 
122+ 使用PyTorch将模型权重文件.pth转换为.onnx文件,再使用ATC工具将.onnx文件转为离线推理模型文件.om文件。
123+ 
124+ 1. 获取权重文件。
125+ 
126+ [DPN131预训练pth权重文件](http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth)
127+ 
128+ ```
129+ wget http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth
130+ ```
131+ 
132+ 2. 导出onnx文件。
133+ 
134+ 1. 使用dpn131_pth2onnx.py脚本。
135+ 
136+ 运行dpn131_pth2onnx.py脚本。
137+ 
138+ ```
139+ python3.7 dpn131_pth2onnx.py ./dpn131-7af84be88.pth dpn131.onnx
140+ ```
141+ 
142+ 获得dpn131.onnx文件。
143+ 
144+ 3. 使用ATC工具将ONNX模型转OM模型。
145+ 
146+ 1. 配置环境变量。
147+ 
148+ ```
149+ source /usr/local/Ascend/......
150+ ```
151+ 
152+ 2. 执行命令查看芯片名称($\{chip\_name\})。
153+ 
154+ ```
155+ npu-smi info
156+ #该设备芯片名为Ascend310P3 (自行替换)
157+ 回显如下:
158+ +-------------------+-----------------+------------------------------------------------------+
159+ | NPU Name | Health | Power(W) Temp(C) Hugepages-Usage(page) |
160+ | Chip Device | Bus-Id | AICore(%) Memory-Usage(MB) |
161+ +===================+=================+======================================================+
162+ | 0 310P3 | OK | 15.8 42 0 / 0 |
163+ | 0 0 | 0000:82:00.0 | 0 1074 / 21534 |
164+ +===================+=================+======================================================+
165+ | 1 310P3 | OK | 15.4 43 0 / 0 |
166+ | 0 1 | 0000:89:00.0 | 0 1070 / 21534 |
167+ +===================+=================+======================================================+
168+ ```
169+ 
170+ 3. 执行ATC命令。
171+ 
172+ ```
173+ atc --framework=5 --model=./dpn131.onnx --output=dpn131_bs{batch size} --input_format=NCHW --input_shape="image:{batch size},3,224,224" --log=debug --soc_version=Ascend310P3
174+ 示例
175+ atc --framework=5 --model=./dpn131.onnx --output=dpn131_bs1 --input_format=NCHW --input_shape="image:1,3,224,224" --log=debug --soc_version=Ascend310P3
176+ ```
177+ 
178+ - 参数说明:
179+ 
180+ - --model:为ONNX模型文件。
181+ - --framework:5代表ONNX模型。
182+ - --output:输出的OM模型。
183+ - --input\_format:输入数据的格式。
184+ - --input\_shape:输入数据的shape。
185+ - --log:日志级别。
186+ - --soc\_version:处理器型号。
187+ 
188+ 运行成功后生成dpn131_bs1.om模型文件,batch size为4、8、16、32、64的修改对应的batch size的位置即可。
189+ 
190+2. 开始推理验证。
191+ 
192+ 1. 安装ais_bench推理工具。
193+ 
194+ 请访问[ais_bench推理工具](https://gitee.com/ascend/tools/tree/master/ais-bench_workload/tool/ais_infer)代码仓,根据readme文档进行工具安装。
195+ 
196+ 2. 执行推理。
197+ 
198+ ```
199+ python3 -m ais_bench --model ./dpn131_bs{batch size}.om --input ./pre_dataset/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize {batch size}
200+ 示例
201+ python3 -m ais_bench --model ./dpn131_bs1.om --input ./pre_dataset/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize 1
202+ ```
203+ 
204+ - 参数说明:
205+ 
206+ - model:需要推理om模型的路径。
207+ - input:模型需要的输入bin文件夹路径。
208+ - output:推理结果输出路径。
209+ - outfmt:输出数据的格式。
210+ - output_dirname:推理结果输出子文件夹。
211+ 
212+ 推理后的输出默认在当前目录output的subdir下。
213+ 
214+ 3. 精度验证。
215+ 
216+ 调用vision_metric_ImageNet.py脚本与label比对,可以获得Accuracy Top5数据,结果保存在result.json中。
217+ 
218+ ```
219+ python3.7 vision_metric_ImageNet.py ./output/subdir/ /local/DPN131/imagenet/val_label.txt ./ result.json
220+ ```
221+ 
222+ - 参数说明:
223+ 
224+ - ./output/subdir/:为生成推理结果所在路径
225+ 
226+ - /local/DPN131/imagenet/val_label.txt:为标签数据所在路径
227+ 
228+ - ./ result.json:为生成结果文件所在路径
229+ 
230+ 4. 性能验证。
231+ 
232+ 可使用ais_bench推理工具的纯推理模式验证不同batch_size的om模型的性能,参考命令如下:
233+ 
234+ ```
235+ python3.7 -m ais_bench --model=./dpn131_bs{batch size}.om --loop=1000 --batchsize={batch size}
236+ 示例
237+ python3.7 -m ais_bench --model=./dpn131_bs1.om --loop=1000 --batchsize=1
238+ ```
239+ 
240+ - 参数说明:
241+ - --model:需要验证om模型所在路径
242+ - --batchsize:验证模型的batch size,按实际进行修改
243+ 
244+ 
245+ 
246+# 模型推理性能&精度<a name="ZH-CN_TOPIC_0000001172201573"></a>
247+ 
248+调用ACL接口推理计算,性能参考下列数据。
249+ 
250+| 芯片型号 | Batch Size | 数据集 | 精度 | 性能 |
251+| --------- |------------| ---------- |-----------------------|-----|
252+| 310P3 | 1 | ImageNet | 79.47/Top1 94.54/Top5 | 384 |
253+| 310P3 | 4 | ImageNet | 79.47/Top1 94.54/Top5 | 567 |
254+| 310P3 | 8 | ImageNet | 79.47/Top1 94.54/Top5 | 483 |
255+| 310P3 | 16 | ImageNet | 79.47/Top1 94.54/Top5 | 388 |
256+| 310P3 | 32 | ImageNet | 79.47/Top1 94.54/Top5 | 353 |
257+| 310P3 | 64 | ImageNet | 79.47/Top1 94.54/Top5 | 348 |
@@ -1,60 +0,0 @@
1-# Copyright 2021 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import os
16-import sys
17-import cv2
18-from glob import glob
19- 
20- 
21-def get_bin_info(file_path, info_name, width, height):
22- bin_images = glob(os.path.join(file_path, '*.bin'))
23- with open(info_name, 'w') as file:
24- for index, img in enumerate(bin_images):
25- content = ' '.join([str(index), img, width, height])
26- file.write(content)
27- file.write('\n')
28- 
29- 
30-def get_jpg_info(file_path, info_name):
31- extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
32- image_names = []
33- for extension in extensions:
34- image_names.append(glob(os.path.join(file_path, '*.' + extension)))
35- with open(info_name, 'w') as file:
36- for image_name in image_names:
37- if len(image_name) == 0:
38- continue
39- else:
40- for index, img in enumerate(image_name):
41- img_cv = cv2.imread(img)
42- shape = img_cv.shape
43- width, height = shape[1], shape[0]
44- content = ' '.join([str(index), img, str(width), str(height)])
45- file.write(content)
46- file.write('\n')
47- 
48- 
49-if __name__ == '__main__':
50- file_type = sys.argv[1]
51- file_path = sys.argv[2]
52- info_name = sys.argv[3]
53- if file_type == 'bin':
54- width = sys.argv[4]
55- height = sys.argv[5]
56- assert len(sys.argv) == 6, 'The number of input parameters must be equal to 5'
57- get_bin_info(file_path, info_name, width, height)
58- elif file_type == 'jpg':
59- assert len(sys.argv) == 4, 'The number of input parameters must be equal to 3'
60- get_jpg_info(file_path, info_name)
@@ -1,223 +1,255 @@
1-# AlexNet Onnx模型端到端推理指导1+# AlexNet模型-推理指导
2-- [1. 模型概述](#1)
3- - [论文地址](#11)
4- - [代码地址](#12)
5-- [2. 环境说明](#2)
6- - [深度学习框架](#21)
7- - [python第三方库](#22)
8-- [3. 模型转换](#3)
9- - [pth转onnx模型](#31)
10-- [4. 数据预处理](#4)
11- - [数据集获取](#41)
12- - [数据集预处理](#42)
13- - [生成数据集信息文件](#43)
14-- [5. 离线推理](#5)
15- - [benchmark工具概述](#51)
16- - [离线推理](#52)
17-- [6. 精度对比](#6)
18- - [离线推理TopN精度](#61)
19- - [开源TopN精度](#62)
20- - [精度对比](#63)
21-- [7. 性能对比](#7)
22- - [npu性能数据](#71)
23 2 
24-## <a name="1">1. 模型概述</a>
25-- [论文地址](#11)
26-- [代码地址](#12)
27-### <a name="11">1.1 论文地址</a>
28-[AlexNet论文](https://wmathor.com/usr/uploads/2019/05/3327542327.pdf)
29-### <a name="12">1.2 代码地址</a>
30-[AlexNet代码](https://github.com/pytorch/examples/tree/master/imagenet)
31-> branch: master
32 3 
33-> commit id: 49e1a8847c8c4d8d3c576479cb2fe2fd2ac583de4+- [概述](#ZH-CN_TOPIC_0000001172161501)
34-## <a name="2">2. 环境说明</a>
35-- [深度学习框架](#21)
36-- [python第三方库](#22)
37-### <a name="21">2.1 深度学习框架</a>
38 5 
39-```6+ - [输入输出数据](#section540883920406)
40-CANN 5.0.1
41-torch==1.8.1
42-torchvision==0.9.1
43-onnx==1.7.0
44-```
45-### <a name="22">2.2 python第三方库</a>
46 7 
47-```
48-opencv-python==4.2.0.34
49-numpy==1.18.5
50-Pillow==7.2.0
51-```
52- **说明:**
53-> X86架构:pytorch,torchvision和onnx可以通过官方下载whl包安装,其它可以通过pip3.7 install 包名 安装
54-> Arm架构:pytorch,torchvision和onnx可以通过源码编译安装,其它可以通过pip3.7 install 包名 安装
55-## <a name="3">3. 模型转换</a>
56-- [pth转onnx模型](#31)
57-- [onnx转om模型](#32)
58-### <a name="31">3.1 pth转onnx模型</a>
59-1. 下载pth权重文件
60-[AlexNet预训练pth权重文件](https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth)
61 8 
62-```
63-wget https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth
64-```
65 9 
66-> 该pth文件的md5sum值为:aed0662f397a0507305ac94ea551930910+- [推理环境准备](#ZH-CN_TOPIC_0000001126281702)
67-2. AlexNet模型代码在torchvision里,需要安装torchvision
68-3. 编写pth2onnx脚本,生成onnx文件
69-> **说明**
70-> 注意目前ATC支持的onnx算子版本为11
71-4. 执行pth2onnx.py脚本,生成onnx模型文件
72-```
73-python3.7 pth2onnx.py alexnet-owt-4df8aa71.pth alexnet.onnx
74-```
75-### <a name="32">3.2 onnx转om模型</a>
76-1. 设置环境变量,请以实际安装环境配置环境变量。
77-```
78-source /usr/local/Ascend/ascend-toolkit/set_env.sh
79 11 
80-```12+- [快速上手](#ZH-CN_TOPIC_0000001126281700)
81 13 
82-2. 使用atc将onnx模型转换为om模型文件,工具使用方法可以参考[CANN V100R020C10 开发辅助工具指南 (推理) 01](https://support.huawei.com/enterprise/zh/doc/EDOC1100164868?idPath=23710424%7C251366513%7C22892968%7C251168373)14+ - [获取源码](#section4622531142816)
15+ - [准备数据集](#section183221994411)
16+ - [模型推理](#section741711594517)
83 17 
84-```18+- [模型推理性能&精度](#ZH-CN_TOPIC_0000001172201573)
85-atc --model=./alexnet.onnx --framework=5 --output=./onnx_alexnet_bs1 --input_format=NCHW --input_shape="actual_input_1:1,3,224,224" --log=debug --soc_version=Ascend310
86-```
87-若生成batch size为16的om模型,对应的命令为:
88 19 
89-```
90-atc --model=./alexnet.onnx --framework=5 --output=./onnx_alexnet_bs16 --input_format=NCHW --input_shape="actual_input_1:16,3,224,224" --log=debug --soc_version=Ascend310
91-```
92-batch size为4、8、32的同上
93-## <a name="4">4. 数据预处理</a>
94-- [数据集获取](#41)
95-- [数据集预处理](#42)
96-- [生成数据集信息文件](#43)
97-### <a name="41">4.1 数据集获取</a>
98-该模型使用[ImageNet官网](http://www.image-net.org/)的5万张验证集进行测试,图片与标签分别存放在/opt/npu/imagenet/val与/opt/npu/imagenet/val_label.txt。
99-### <a name="42">4.2 数据集预处理</a>
100-1. 编写预处理脚本imagenet_torch_preprocess.py
101-预处理方式有两种:不使用aipp的二进制输入,以及使用aipp的jpg输入。这里使用第一种,需要先用脚本仿照github官网训练预处理方法处理数据,以获得最佳精度;
102-2. 执行预处理脚本,生成数据集预处理后的bin文件
103-```
104-python3.7 imagenet_torch_preprocess.py /opt/npu/imagenet/val ./pre_dataset
105-```
106-### <a name="43">4.3 生成数据集信息文件</a>
107-1. 编写生成数据集信息文件脚本get_info.py
108-2. 执行生成数据集信息脚本,生成数据集信息文件
109-第一个参数为模型输入的类型,第二个参数为生成的bin文件路径,第三个为输出的info文件,后面为宽高信息
110 20 
111-```
112-python3.7 get_info.py bin ./pre_dataset/ ./imagenet_prep_bin.info 224 224
113-```
114-## <a name="5">5. 离线推理</a>
115-- [benchmark工具概述](#51)
116-- [离线推理](#52)
117-### <a name="51">5.1 benchmark工具概述</a>
118-benchmark工具为华为自研的模型推理工具,支持多种模型的离线推理,能够迅速统计出模型在Ascend310上的性能,支持真实数据和纯推理两种模式,配合后处理脚本,可以实现诸多模型的端到端过程,获取工具及使用方法可以参考[CANN V100R020C10 推理benchmark工具用户指南 01](https://gitee.com/ascend/modelzoo/tree/master/built-in/ACL_PyTorch/Benchmark/cv/classification/ResNext50#https://support.huawei.com/enterprise/zh/doc/EDOC1100164874?idPath=23710424%7C251366513%7C22892968%7C251168373)
119-将获取的工具包并解压,将benchmark工具放在当前目录下
120-### <a name="52">5.2 离线推理</a>
121-1. 设置环境变量
122 21 
123-```
124-source /usr/local/Ascend/ascend-toolkit/set_env.sh
125-```
126-2. 执行离线推理
127-运行如下命令进行离线推理:
128 22 
129-```23+# 概述<a name="ZH-CN_TOPIC_0000001172161501"></a>
130-./benchmark.x86_64 -model_type=vision -batch_size=1 -device_id=0 -om_path=./onnx_alexnet_bs1.om -input_text_path=./imagenet_prep_bin.info -input_width=224 -input_height=224 -useDvpp=false -output_binary=false
131-```
132-输出结果默认保存在当前目录/result/dumpOutput_device0中,模型只有一个名为class的输出,shape为bs * 1000,数据类型为FP32,对应1000个分类的预测结果,每个输入对应的输出对应一个txt文件。
133-## <a name="6">6. 精度对比</a>
134-- [离线推理TopN精度](#61)
135-- [开源TopN精度](#62)
136-- [精度对比](#63)
137-### <a name="61">6.1 离线推理TopN精度</a>
138-后处理与精度统计
139 24 
140-调用vision_metric_ImageNet.py脚本与label比对,可以获得Accuracy Top5数据,果保存result/result.json中。25+Alex在2012年提出的alexnet网络构模型,首次CNN成功应用了ReLU、Dropout和LRN等Trick,引爆了神经网络的应用热潮,并赢得了2012届图像识别大赛的冠军,使得CNN成为在图像分类上的核心算法模型
141 26 
142-```
143-python3.7 vision_metric.py --benchmark_out ./result/dumpOutput_device0/ --anno_file /opt/npu/imagenet/val_label.txt --result_file ./result/result.json
144-```
145-查看输出的结果:
146 27 
147-```28+- 参考实现:
148-{"title": "Overall statistical evaluation", "value": [{"key": "Number of images", "value": "50000"}, {"key": "Number of classes", "value": "1000"}, {"key": "Top1 accuracy", "value": "56.53%"}, {"key": "Top2 accuracy", "value": "68.23%"}, {"key": "Top3 accuracy", "value": "73.49%"}, {"key": "Top4 accuracy", "value": "76.79%"}, {"key": "Top5 accuracy", "value": "79.08%"}]}
149-```
150 29 
151-经过对bs1与bs16的om测试,本模型batch1的精度与batch16的精度没有差别,精度数据均如上30+ ```
152-### <a name="62">6.2 开源TopN精度</a>31+ url=https://github.com/pytorch/examples/tree/master/imagenet
153-GPU上对torchvision里提供的pth文件进行推理,参考连接:[推理pth](https://github.com/pytorch/examples/tree/master/imagenet)32+ commit_id=49e1a8847c8c4d8d3c576479cb2fe2fd2ac583de
154-得到的结果是:33+ code_path=https://gitee.com/ascend/ModelZoo-PyTorch/tree/master/ACL_PyTorch/contrib/cv/classfication/AlexNet
155-```34+ model_name=AlexNet
156-Acc@1 56.52735+ ```
157-Acc@5 79.068
158-```
159-### <a name="63">6.3 精度对比</a>
160-将得到的om离线模型推理TopN精度与该模型github代码仓上公布的精度对比,如下表所示,精度下降在1%范围之内,故精度达标。
161-| 模型 | Acc@1 | Acc@5 |
162-|-------|-------|-------|
163-|pth模型推理结果(官方)| 56.527 | 79.068 |
164-| om模型离线推理结果| 56.530 | 79.080 |
165 36 
166- **说明:**
167-> 没有遇到精度不达标的问题,故不需要进行精度调试
168-## <a name="7">7. 性能对比</a>
169-- [npu性能数据](#71)
170-### <a name="71">7.1 npu性能数据</a>
171-benchmark工具在整个数据集上推理时也会统计性能数据,但是推理整个数据集较慢,如果这么测性能那么整个推理期间需要确保独占device,使用npu-smi info可以查看device是否空闲。也可以使用benchmark纯推理功能测得性能数据,但是由于随机数不能模拟数据分布,纯推理功能测的有些模型性能数据可能不太准,benchmark纯推理功能测性能仅为快速获取大概的性能数据以便调试优化使用,可初步确认benchmark工具在整个数据集上推理时由于device也被其它推理任务使用了导致的性能不准的问题。模型的性能以使用benchmark工具在整个数据集上推理得到bs1与bs16的性能数据为准,对于使用benchmark工具测试的batch4,8,32的性能数据在README.md中如下作记录即可。
172- **benchmark工具在整个数据集上推理获得性能数据:**
173-1. batch1的性能,benchmark工具在整个数据集上推理后生成result/perf_vision_batchsize_1_device_0.txt:
174 37 
175-```38+## 输入输出数据<a name="section540883920406"></a>
176-[e2e] throughputRate: 211.301, latency: 236629
177-[data read] throughputRate: 225.214, moduleLatency: 4.44023
178-[preprocess] throughputRate: 224.859, moduleLatency: 4.44723
179-[infer] throughputRate: 212.679, Interface throughputRate: 317.707, moduleLatency: 4.03848
180-[post] throughputRate: 212.678, moduleLatency: 4.70194
181-```
182-Interface throughputRate: 317.707,317.707x4=1270.828fps。即是batch1 310单卡吞吐率
183 39 
184-2. batch16的性能,benchmark工具在整个数据集上推理后生成result/perf_vision_batchsize_16_device_0.txt。40+- 输入数据
185 41 
186-得到的结果为:42+ | 输入数据 | 数据类型 | 大小 | 数据排布格式 |
43+ | -------- | -------- | ------------------------- | ------------ |
44+ | input | RGB_FP32 | batchsize x 3 x 224 x 224 | NCHW |
187 45 
188-```
189-[e2e] throughputRate: 312.638, latency: 159929
190-[data read] throughputRate: 321.245, moduleLatency: 3.11289
191-[preprocess] throughputRate: 319.722, moduleLatency: 3.12772
192-[infer] throughputRate: 314.855, Interface throughputRate: 1891.73, moduleLatency: 2.01078
193-[post] throughputRate: 19.6777, moduleLatency: 50.8189
194-```
195-Interface throughputRate: 1891.73,1891.73x4=7566.92fps。即是batch16 310单卡吞吐率
196-> 为了避免长期占用device, bs4,8,32使用纯推理测性能,其中,对bs4进行纯推理输入命令如下所示,其中batch_size=4表示bs的值,在对不同bs值对应的om模型进行推理时需要做出相应的更改:
197-> `./benchmark.x86_64 -device_id=0 -om_path=./onnx_alexnet_bs4.om -round=30 -batch_size=4`
198-> 推理结果保存在/result/PureInfer_perf_of_onnx_alexnet_bs4_in_device_0.txt中
199 46 
200-3. 测试batch4的性能:47+- 输出数据
201 48 
202-```49+ | 输出数据 | 数据类型 | 大小 | 数据排布格式 |
203-ave_throughputRate = 974.27samples/s, ave_latency = 1.02917ms50+ | -------- | -------- | -------- | ------------ |
51+ | output1 | FLOAT32 | batchsize x 1000 | ND |
204 52 
205-```
206-ave_throughputRate = 974.27, 974.27x4=3897.08fps。即是batch4 310单卡吞吐率
207 53 
208-4. 测试batch8的性能:
209 54 
210-```55+# 推理环境准备<a name="ZH-CN_TOPIC_0000001126281702"></a>
211-ave_throughputRate = 1435.99samples/s, ave_latency = 0.697617ms
212-```
213-ave_throughputRate = 1435.99, 1435.99x4=5743.96fps。即是batch8 310单卡吞吐率
214 56 
215-5. 测试batch32的性能57+- 该模型需要以下插件与驱动
216 58 
217-```59+ **表 1** 版本配套表
218-ave_throughputRate = 2186.17samples/s, ave_latency = 0.457931ms60+ 
219-```61+ | 配套 | 版本 | 环境准备指导 |
220-ave_throughputRate = 2186.17, 2186.17x4=8744.68fps。即是batch32 310单卡吞吐率62+ |---------| ------- | ------------------------------------------------------------ |
221- 63+ | 固件与驱动 | 22.0.3 | [Pytorch框架推理环境准备](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/pies) |
222-**性能优化** 64+ | CANN | 6.0.RC1 | - |
223-> 从profiling看出MatMulV2耗时大,影响了网络性能,故不需要进行性能优化65+ | Python | 3.7.5 | - |
66+ | PyTorch | 1.8.1 | - |
67+ | 说明:Atlas 300I Duo 推理卡请以CANN版本选择实际固件与驱动版本。 | \ | \ |
68+ 
69+ 
70+ 
71+# 快速上手<a name="ZH-CN_TOPIC_0000001126281700"></a>
72+ 
73+## 获取源码<a name="section4622531142816"></a>
74+ 
75+1. 获取源码。
76+ 
77+ ```
78+ 直接可以调用torch内的alexNet模型,无需下载源码
79+ ```
80+ 
81+2. 安装依赖。
82+ 
83+ ```
84+ pip3 install -r requirements.txt
85+ ```
86+ 
87+## 准备数据集<a name="section183221994411"></a>
88+ 
89+1. 获取原始数据集。(解压命令参考tar –xvf \*.tar与 unzip \*.zip)
90+ 
91+ 
92+ 该模型使用[ImageNet官网](http://www.image-net.org/)的5万张验证集进行测试,图片与标签分别存放在/local/AlexNet/imagenet/val与/local/AlexNet/imagenet/val_label.txt。
93+ ```
94+ imagenet
95+ ├── val_label.txt //验证集标注信息
96+ └── val // 验证集文件夹
97+ ```
98+ 
99+2. 数据预处理,将原始数据集转换为模型输入的数据。
100+ 
101+ 执行imagenet_torch_preprocess.py脚本,完成预处理。
102+ 
103+ ```
104+ python3.7 imagenet_torch_preprocess.py /local/AlexNet/imagenet/val ./pre_dataset
105+ 
106+ ```
107+
108+ - 参数说明:
109+
110+ /local/AlexNet/imagenet/val,验证集文件所在路径
111+
112+ ./pre_dataset,输出的预处理后数据集路径
113+ 
114+ 
115+ 
116+## 模型推理<a name="section741711594517"></a>
117+ 
118+1. 模型转换。
119+ 
120+ 使用PyTorch将模型权重文件.pth转换为.onnx文件,再使用ATC工具将.onnx文件转为离线推理模型文件.om文件。
121+ 
122+ 1. 获取权重文件。
123+ 
124+ [AlexNet预训练pth权重文件](https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth)
125+ 
126+ ```
127+ wget https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth
128+ ```
129+ 
130+ 2. 导出onnx文件。
131+ 
132+ 1. 使用pth2onnx.py脚本。
133+ 
134+ 运行pth2onnx.py脚本。
135+ 
136+ ```
137+ python3.7 pth2onnx.py alexnet-owt-4df8aa71.pth alexnet.onnx
138+ ```
139+ 
140+ 获得alexnet.onnx文件。
141+ 
142+ 3. 使用ATC工具将ONNX模型转OM模型。
143+ 
144+ 1. 配置环境变量。
145+ 
146+ ```
147+ source /usr/local/Ascend/......
148+ ```
149+ 
150+ 2. 执行命令查看芯片名称($\{chip\_name\})。
151+ 
152+ ```
153+ npu-smi info
154+ #该设备芯片名为Ascend310P3 (自行替换)
155+ 回显如下:
156+ +-------------------+-----------------+------------------------------------------------------+
157+ | NPU Name | Health | Power(W) Temp(C) Hugepages-Usage(page) |
158+ | Chip Device | Bus-Id | AICore(%) Memory-Usage(MB) |
159+ +===================+=================+======================================================+
160+ | 0 310P3 | OK | 15.8 42 0 / 0 |
161+ | 0 0 | 0000:82:00.0 | 0 1074 / 21534 |
162+ +===================+=================+======================================================+
163+ | 1 310P3 | OK | 15.4 43 0 / 0 |
164+ | 0 1 | 0000:89:00.0 | 0 1070 / 21534 |
165+ +===================+=================+======================================================+
166+ ```
167+ 
168+ 3. 执行ATC命令。
169+ 
170+ ```
171+ atc --model=./alexnet.onnx --framework=5 --output=./onnx_alexnet_bs{batch size} --input_format=NCHW --input_shape="actual_input_1:{batch size},3,224,224" --log=debug --soc_version=Ascend310P3
172+ 示例
173+ atc --model=./alexnet.onnx --framework=5 --output=./onnx_alexnet_bs1 --input_format=NCHW --input_shape="actual_input_1:1,3,224,224" --log=debug --soc_version=Ascend310P3
174+ ```
175+ 
176+ - 参数说明:
177+ 
178+ - --model:为ONNX模型文件。
179+ - --framework:5代表ONNX模型。
180+ - --output:输出的OM模型。
181+ - --input\_format:输入数据的格式。
182+ - --input\_shape:输入数据的shape。
183+ - --log:日志级别。
184+ - --soc\_version:处理器型号。
185+ 
186+ 运行成功后生成onnx_alexnet_bs1.om模型文件,batch size为4、8、16、32、64的修改对应的batch size的位置即可。
187+ 
188+2. 开始推理验证。
189+ 
190+ 1. 安装ais_bench推理工具。
191+ 
192+ 请访问[ais_bench推理工具](https://gitee.com/ascend/tools/tree/master/ais-bench_workload/tool/ais_infer)代码仓,根据readme文档进行工具安装。
193+ 
194+ 2. 执行推理。
195+ 
196+ ```
197+ python3 -m ais_bench --model ./onnx_alexnet_bs{batch size}.om --input ./pre_dataset/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize {batch size}
198+ 示例
199+ python3 -m ais_bench --model ./onnx_alexnet_bs1.om --input ./pre_dataset/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize 1
200+ ```
201+ 
202+ - 参数说明:
203+ 
204+ - model:需要推理om模型的路径。
205+ - input:模型需要的输入bin文件夹路径。
206+ - output:推理结果输出路径。
207+ - outfmt:输出数据的格式。
208+ - output_dirname:推理结果输出子文件夹。
209+ 
210+ 推理后的输出默认在当前目录output的subdir下。
211+ 
212+ 3. 精度验证。
213+ 
214+ 调用vision_metric_ImageNet.py脚本与label比对,可以获得Accuracy Top5数据,结果保存在result.json中。
215+ 
216+ ```
217+ python3.7 vision_metric.py --benchmark_out ./output/subdir/ --anno_file /local/AlexNet/imagenet/val_label.txt --result_file ./result.json
218+ ```
219+ 
220+ - 参数说明:
221+ 
222+ - benchmark_out:为生成推理结果所在路径
223+ 
224+ - anno_file:为标签数据所在路径
225+ 
226+ - result_file:为生成结果文件所在路径
227+ 
228+ 4. 性能验证。
229+ 
230+ 可使用ais_bench推理工具的纯推理模式验证不同batch_size的om模型的性能,参考命令如下:
231+ 
232+ ```
233+ python3.7 -m ais_bench --model=./onnx_alexnet_bs{batch size}.om --loop=1000 --batchsize={batch size}
234+ 示例
235+ python3.7 -m ais_bench --model=./onnx_alexnet_bs1.om --loop=1000 --batchsize=1
236+ ```
237+ 
238+ - 参数说明:
239+ - --model:需要验证om模型所在路径
240+ - --batchsize:验证模型的batch size,按实际进行修改
241+ 
242+ 
243+ 
244+# 模型推理性能&精度<a name="ZH-CN_TOPIC_0000001172201573"></a>
245+ 
246+调用ACL接口推理计算,性能参考下列数据。
247+ 
248+| 芯片型号 | Batch Size | 数据集 | 精度 | 性能 |
249+| --------- |------------| ---------- |----------------------|-------|
250+| 310P3 | 1 | ImageNet | 56.56/Top1 79.1/Top5 | 1266 |
251+| 310P3 | 4 | ImageNet | 56.56/Top1 79.1/Top5 | 4324 |
252+| 310P3 | 8 | ImageNet | 56.56/Top1 79.1/Top5 | 7266 |
253+| 310P3 | 16 | ImageNet | 56.56/Top1 79.1/Top5 | 9975 |
254+| 310P3 | 32 | ImageNet | 56.56/Top1 79.1/Top5 | 11055 |
255+| 310P3 | 64 | ImageNet | 56.56/Top1 79.1/Top5 | 12672 |
@@ -1,60 +0,0 @@
1-# Copyright 2020 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import os
16-import sys
17-import cv2
18-from glob import glob
19- 
20- 
21-def get_bin_info(file_path, info_name, width, height):
22- bin_images = glob(os.path.join(file_path, '*.bin'))
23- with open(info_name, 'w') as file:
24- for index, img in enumerate(bin_images):
25- content = ' '.join([str(index), img, width, height])
26- file.write(content)
27- file.write('\n')
28- 
29- 
30-def get_jpg_info(file_path, info_name):
31- extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
32- image_names = []
33- for extension in extensions:
34- image_names.append(glob(os.path.join(file_path, '*.' + extension)))
35- with open(info_name, 'w') as file:
36- for image_name in image_names:
37- if len(image_name) == 0:
38- continue
39- else:
40- for index, img in enumerate(image_name):
41- img_cv = cv2.imread(img)
42- shape = img_cv.shape
43- width, height = shape[1], shape[0]
44- content = ' '.join([str(index), img, str(width), str(height)])
45- file.write(content)
46- file.write('\n')
47- 
48- 
49-if __name__ == '__main__':
50- file_type = sys.argv[1]
51- file_path = sys.argv[2]
52- info_name = sys.argv[3]
53- if file_type == 'bin':
54- width = sys.argv[4]
55- height = sys.argv[5]
56- assert len(sys.argv) == 6, 'The number of input parameters must be equal to 5'
57- get_bin_info(file_path, info_name, width, height)
58- elif file_type == 'jpg':
59- assert len(sys.argv) == 4, 'The number of input parameters must be equal to 3'
60- get_jpg_info(file_path, info_name)
@@ -0,0 +1,3 @@
1+FuncStatus:OK
2+PerfStatus:OK
3+PrecisionStatus:OK
@@ -1,26 +0,0 @@
1-环境准备:
2- 
3-1.数据集路径
4-本模型数据集放在/opt/npu/下
5- 
6-2.进入工作目录
7-cd AlexNet
8- 
9-3.安装必要的依赖,测试环境可能已经安装其中的一些不同版本的库了,故手动测试时 **不推荐**使用该命令安装
10-pip3.7 install -r requirements.txt
11- 
12-4.获取模型代码
13-git clone https://github.com/pytorch/vision
14- 
15-5.获取权重文件
16-wget https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth
17- 
18-6.获取benchmark工具
19- 
20-将 benchmark工具放在当前目录下
21- 
22-7.310上执行,执行时确保device空闲
23- 
24-bash test/pth2om.sh
25- 
26-bash test/eval_acc_perf.sh --datasets_path=/opt/npu/
@@ -1,78 +0,0 @@
1-#!/bin/bash
2- 
3-datasets_path="/opt/npu"
4- 
5-for para in $*
6-do
7- if [[ $para == --datasets_path* ]]; then
8- datasets_path=`echo ${para#*=}`
9- fi
10-done
11- 
12-arch=`uname -m`
13-rm -rf ./prep_dataset
14-python3.7 imagenet_torch_preprocess.py ${datasets_path}/imagenet/val ./pre_dataset
15-if [ $? != 0 ]; then
16- echo "fail!"
17- exit -1
18-fi
19-echo '==> 1. creating ./prep_dataset successfully.'
20- 
21-python3.7 get_info.py bin ./pre_dataset/ ./imagenet_prep_bin.info 224 224
22-if [ $? != 0 ]; then
23- echo "fail!"
24- exit -1
25-fi
26-echo '==> 2. creating ./imagenet_prep_bin.info successfully.'
27- 
28-source /usr/local/Ascend/ascend-toolkit/set_env.sh
29-rm -rf ./result/*
30- 
31-./benchmark.${arch} -model_type=vision -batch_size=1 -device_id=2 -om_path=./onnx_alexnet_bs1.om -input_text_path=./imagenet_prep_bin.info -input_width=224 -input_height=224 -useDvpp=false -output_binary=false
32-if [ $? != 0 ]; then
33- echo "fail!"
34- exit -1
35-fi
36-echo '==> 3. conducting onnx_alexnet_bs1.om on device 2 successfully.'
37- 
38-./benchmark.${arch} -model_type=vision -batch_size=16 -device_id=3 -om_path=./onnx_alexnet_bs16.om -input_text_path=./imagenet_prep_bin.info -input_width=224 -input_height=224 -useDvpp=false -output_binary=false
39-if [ $? != 0 ]; then
40- echo "fail!"
41- exit -1
42-fi
43-echo '==> 4. conducting onnx_alexnet_bs16.om on device 3 successfully.'
44-python3.7 vision_metric.py --benchmark_out ./result/dumpOutput_device2/ --anno_file ${datasets_path}/imagenet/val_label.txt --result_file ./result/result_bs1.json
45-if [ $? != 0 ]; then
46- echo "fail!"
47- exit -1
48-fi
49-echo '==> 5. calculate acc on bs1 successfully.'
50-python3.7 vision_metric.py --benchmark_out ./result/dumpOutput_device3/ --anno_file ${datasets_path}/imagenet/val_label.txt --result_file ./result/result_bs16.json
51-if [ $? != 0 ]; then
52- echo "fail!"
53- exit -1
54-fi
55-echo '==> 6. calculate acc on bs16 successfully.'
56-echo "====accuracy data===="
57-python3.7 test/parse.py ./result/result_bs1.json
58-if [ $? != 0 ]; then
59- echo "fail!"
60- exit -1
61-fi
62-python3.7 test/parse.py ./result/result_bs16.json
63-if [ $? != 0 ]; then
64- echo "fail!"
65- exit -1
66-fi
67-echo "====performance data===="
68-python3.7 test/parse.py ./result/perf_vision_batchsize_1_device_2.txt
69-if [ $? != 0 ]; then
70- echo "fail!"
71- exit -1
72-fi
73-python3.7 test/parse.py ./result/perf_vision_batchsize_16_device_3.txt
74-if [ $? != 0 ]; then
75- echo "fail!"
76- exit -1
77-fi
78-echo "success"
@@ -1,32 +0,0 @@
1-# Copyright 2021 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import sys
16-import json
17-import re
18- 
19-if __name__ == '__main__':
20- if sys.argv[1].endswith('.json'):
21- result_json = sys.argv[1]
22- with open(result_json, 'r') as f:
23- content = f.read()
24- tops = [i.get('value') for i in json.loads(content).get('value') if 'Top' in i.get('key')]
25- print('om {} top1:{} top5:{}'.format(result_json.split('_')[1].split('.')[0], tops[0], tops[4]))
26- elif sys.argv[1].endswith('.txt'):
27- result_txt = sys.argv[1]
28- with open(result_txt, 'r') as f:
29- content = f.read()
30- txt_data_list = [i.strip() for i in re.findall(r':(.*?),', content.replace('\n', ',') + ',')]
31- fps = float(txt_data_list[7].replace('samples/s', '')) * 4
32- print('310 bs{} fps:{}'.format(result_txt.split('_')[3], fps))
@@ -1,16 +0,0 @@
1-#!/bin/bash
2- 
3-# 生成onnx文件
4-rm -rf alexnet.onnx
5-python3.7 pth2onnx.py alexnet-owt-4df8aa71.pth alexnet.onnx
6-# 配置环境变量
7-source /usr/local/Ascend/ascend-toolkit/set_env.sh
8-# 生成om文件
9-rm -rf onnx_alexnet_bs1.om onnx_alexnet_bs16.om
10-atc --model=./alexnet.onnx --framework=5 --output=./onnx_alexnet_bs1 --input_format=NCHW --input_shape="actual_input_1:1,3,224,224" --log=debug --soc_version=Ascend310
11-atc --model=./alexnet.onnx --framework=5 --output=./onnx_alexnet_bs16 --input_format=NCHW --input_shape="actual_input_1:16,3,224,224" --log=debug --soc_version=Ascend310
12-if [ -f "onnx_alexnet_bs1.om" ] && [ -f "onnx_alexnet_bs16.om" ]; then
13- echo "success"
14-else
15- echo "fail!"
16-fi
@@ -1,251 +1,258 @@
1-# DPN131 Onnx模型端到端推理指导1+# DPN131模型-推理指导
2-- [1 模型概述](#1-模型概述)
3- - [1.1 论文地址](#11-论文地址)
4- - [1.2 代码地址](#12-代码地址)
5-- [2 环境说明](#2-环境说明)
6- - [2.1 深度学习框架](#21-深度学习框架)
7- - [2.2 python第三方库](#22-python第三方库)
8-- [3 模型转换](#3-模型转换)
9- - [3.1 pth转onnx模型](#31-pth转onnx模型)
10- - [3.2 onnx转om模型](#32-onnx转om模型)
11-- [4 数据集预处理](#4-数据集预处理)
12- - [4.1 数据集获取](#41-数据集获取)
13- - [4.2 数据集预处理](#42-数据集预处理)
14- - [4.3 生成数据集信息文件](#43-生成数据集信息文件)
15-- [5 离线推理](#5-离线推理)
16- - [5.1 benchmark工具概述](#51-benchmark工具概述)
17- - [5.2 离线推理](#52-离线推理)
18-- [6 精度对比](#6-精度对比)
19- - [6.1 离线推理TopN精度统计](#61-离线推理TopN精度统计)
20- - [6.2 开源TopN精度](#62-开源TopN精度)
21- - [6.3 精度对比](#63-精度对比)
22-- [7 性能对比](#7-性能对比)
23- - [7.1 npu性能数据](#71-npu性能数据)
24- 
25-
26- 
27-## 1 模型概述
28- 
29-- **[论文地址](#11-论文地址)**
30- 
31-- **[代码地址](#12-代码地址)**
32- 
33-### 1.1 论文地址
34-[DPN131论文](https://arxiv.org/abs/1707.01629)
35-### 1.2 代码地址
36-[DPN131代码](https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/dpn.py)
37-branch: master
38-commit id : 0a4df4f3fe46b81e94bf9cc9ee5d9bebee6b9ec5
39 2 
40 3 
41-## 2 环境说明4+- [概述](#ZH-CN_TOPIC_0000001172161501)
42 5 
43-- **[深度学习框架](#21-深度学习框架)** 6+ - [输入输出数据](#section540883920406)
44- 
45-- **[python第三方库](#22-python第三方库)**
46- 
47-### 2.1 深度学习框架
48-```
49-CANN 5.0.1
50- 
51-pytorch >= 1.5.0
52-torchvision >= 0.6.0
53-onnx >= 1.7.0
54-```
55- 
56-### 2.2 python第三方库
57- 
58-```
59-numpy == 1.18.5
60-Pillow == 7.2.0
61-opencv-python == 4.5.1.48
62-```
63- 
64-**说明:**
65-> X86架构:pytorch,torchvision和onnx可以通过官方下载whl包安装,其它可以通过pip3.7 install 包名 安装
66->
67-> Arm架构:pytorch,torchvision和onnx可以通过源码编译安装,其它可以通过pip3.7 install 包名 安装
68- 
69-## 3 模型转换
70- 
71-- **[pth转onnx模型](#31-pth转onnx模型)**
72- 
73-- **[onnx转om模型](#32-onnx转om模型)**
74- 
75-### 3.1 pth转onnx模型
76- 
77-1.下载pth权重文件
78-[DPN131预训练pth权重文件](http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth)
79-文件md5sum: 71e7844aa8646dc75494976c7c86241a
80-```
81-wget http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth
82-```
83- 
84-2.安装过程如下所示:若安装过程报错请百度解决
85-```
86-git clone https://github.com/Cadene/pretrained-models.pytorch.git
87-cd ./pretrainedmodels/models/
88-patch -p1 < ../dpn.diff,其中dpn.diff是通过git diff > ./dpn.diff生成的
89-cd..
90-```
91-3.编写pth2onnx脚本dpn131_pth2onnx.py
92- 
93- **说明:**
94->注意目前ATC支持的onnx算子版本为11
95- 
96-4.执行pth2onnx脚本,生成onnx模型文件
97-```
98-python3.7 dpn131_pth2onnx.py ./dpn131-7af84be88.pth dpn131.onnx
99-```
100- 
101- **模型转换要点:**
102->由于包含动态shape需要修改模型代码以固定shape
103 7 
104 8 
105-### 3.2 onnx转om模型
106 9 
107-1.设置环境变量,请以实际安装环境配置环境变量。10+- [推理环境准备](#ZH-CN_TOPIC_0000001126281702)
108-```
109-source /usr/local/Ascend/ascend-toolkit/set_env.sh
110-```
111-2.使用atc将onnx模型转换为om模型文件,工具使用方法可以参考[CANN V100R020C10 开发辅助工具指南 (推理) 01](https://support.huawei.com/enterprise/zh/doc/EDOC1100164868?idPath=23710424%7C251366513%7C22892968%7C251168373)
112-```
113-atc --framework=5 --model=./dpn131.onnx --output=dpn131_bs1 --input_format=NCHW --input_shape="image:1,3,224,224" --log=debug --soc_version=Ascend310
114 11 
115-```12+- [快速上手](#ZH-CN_TOPIC_0000001126281700)
116 13 
117-## 4 数据集预处理14+ - [获取源码](#section4622531142816)
15+ - [准备数据集](#section183221994411)
16+ - [模型推理](#section741711594517)
118 17 
119-- **[数据集获取](#41-数据集获取)** 18+- [模型推理性能&精度](#ZH-CN_TOPIC_0000001172201573)
120- 
121-- **[数据集预处理](#42-数据集预处理)**
122- 
123-- **[生成数据集信息文件](#43-生成数据集信息文件)**
124- 
125-### 4.1 数据集获取
126-该模型使用[ImageNet官网](http://www.image-net.org)的5万张验证集进行测试,图片与标签分别存放在/opt/npu/imagenet/val与/opt/npu/imagenet/val_label.txt。
127- 
128-### 4.2 数据集预处理
129-1.预处理脚本imagenet_torch_preprocess.py
130- 
131-2.执行预处理脚本,生成数据集预处理后的bin文件
132-```
133-python3.7 imagenet_torch_preprocess.py dpn131 /root/datasets/imagenet/val ./prep_dataset
134-```
135-### 4.3 生成数据集信息文件
136-1.生成数据集信息文件脚本gen_dataset_info.py
137- 
138-2.执行生成数据集信息脚本,生成数据集信息文件
139-```
140-python3.7 gen_dataset_info.py bin ./prep_dataset ./dpn131_prep_bin.info 224 224
141-```
142-第一个参数为模型输入的类型,第二个参数为生成的bin文件路径,第三个为输出的info文件,后面为宽高信息
143-## 5 离线推理
144- 
145-- **[benchmark工具概述](#51-benchmark工具概述)**
146- 
147-- **[离线推理](#52-离线推理)**
148- 
149-### 5.1 benchmark工具概述
150- 
151-benchmark工具为华为自研的模型推理工具,支持多种模型的离线推理,能够迅速统计出模型在Ascend310上的性能,支持真实数据和纯推理两种模式,配合后处理脚本,可以实现诸多模型的端到端过程,获取工具及使用方法可以参考[CANN V100R020C10 推理benchmark工具用户指南 01](https://support.huawei.com/enterprise/zh/doc/EDOC1100164874?idPath=23710424%7C251366513%7C22892968%7C251168373)
152-### 5.2 离线推理
153-1.设置环境变量,请以实际安装环境配置环境变量。
154-```
155-source /usr/local/Ascend/ascend-toolkit/set_env.sh
156-```
157-2.执行离线推理
158-```
159-./benchmark.x86_64 -model_type=vision -device_id=0 -batch_size=1 -om_path=dpn131_bs1.om -input_text_path=./dpn131_prep_bin.info -input_width=224 -input_height=224 -output_binary=False -useDvpp=False
160-```
161-输出结果默认保存在当前目录result/dumpOutput_device{0},模型只有一个名为class的输出,shape为bs * 1000,数据类型为FP32,对应1000个分类的预测结果,每个输入对应的输出对应一个_x.bin文件。
162- 
163-## 6 精度对比
164- 
165-- **[离线推理TopN精度](#61-离线推理TopN精度)**
166-- **[开源TopN精度](#62-开源TopN精度)**
167-- **[精度对比](#63-精度对比)**
168- 
169-### 6.1 离线推理TopN精度统计
170- 
171-后处理统计TopN精度
172- 
173-调用imagenet_acc_eval.py脚本推理结果与label比对,可以获得Accuracy Top5数据,结果保存在result.json中。
174-```
175-python3.7 imagenet_acc_eval.py result/dumpOutput_device0/ /root/datasets/imagenet/val_label.txt ./ result.json
176-```
177-第一个为benchmark输出目录,第二个为数据集配套标签,第三个是生成文件的保存目录,第四个是生成的文件名。
178-查看输出结果:
179-```
180-{"title": "Overall statistical evaluation", "value": [{"key": "Number of images", "value": "50000"}, {"key": "Number of classes", "value": "1000"}, {"key": "Top1 accuracy", "value": "79.43%"}, {"key": "Top2 accuracy", "value": "88.87%"}, {"key": "Top3 accuracy", "value": "91.98%"}, {"key": "Top4 accuracy", "value": "93.57%"}, {"key": "Top5 accuracy", "value": "94.58%"}]}
181-```
182-经过对bs1与bs16的om测试,本模型batch1的精度与batch16的精度没有差别,精度数据均如上
183- 
184-### 6.2 开源TopN精度
185-[DPN官网精度](https://github.com/rwightman/pytorch-dpn-pretrained)
186-```
187-Model Acc@1 Acc@5
188-dpn131 79.432 94.574
189-```
190-### 6.3 精度对比
191-将得到的om离线模型推理TopN精度与该模型github代码仓上公布的精度对比,精度下降在1%范围之内,故精度达标。
192- **精度调试:**
193->没有遇到精度不达标的问题,故不需要进行精度调试
194- 
195-## 7 性能对比
196- 
197-- **[npu性能数据](#71-npu性能数据)**
198- 
199-### 7.1 npu性能数据
200-benchmark工具在整个数据集上推理时也会统计性能数据,但是推理整个数据集较慢,如果这么测性能那么整个推理期间需要确保独占device,使用npu-smi info可以查看device是否空闲。也可以使用benchmark纯推理功能测得性能数据,但是由于随机数不能模拟数据分布,纯推理功能测的有些模型性能数据可能不太准,benchmark纯推理功能测性能仅为快速获取大概的性能数据以便调试优化使用,可初步确认benchmark工具在整个数据集上推理时由于device也被其它推理任务使用了导致的性能不准的问题。模型的性能以使用benchmark工具在整个数据集上推理得到bs1与bs16的性能数据为准,对于使用benchmark工具测试的batch4,8,32的性能数据在README.md中如下作记录即可。
201-1.benchmark工具在整个数据集上推理获得性能数据
202-batch1的性能,benchmark工具在整个数据集上推理后生成result/perf_vision_batchsize_1_device_0.txt:
203-```
204-[e2e] throughputRate: 34.4577, latency: 1.45105e+06
205-[data read] throughputRate: 36.63, moduleLatency: 27.3
206-[preprocess] throughputRate: 36.5006, moduleLatency: 27.3968
207-[infer] throughputRate: 34.6141, Interface throughputRate: 37.1687, moduleLatency: 28.3242
208-[post] throughputRate: 34.614, moduleLatency: 28.89
209-```
210-Interface throughputRate: 37.1687,37.1687x4=148.6748既是batch1 310单卡吞吐率
211- 
212-batch16的性能,benchmark工具在整个数据集上推理后生成result/perf_vision_batchsize_16_device_1.txt:
213-```
214-[e2e] throughputRate: 36.1546, latency: 1.38295e+06
215-[data read] throughputRate: 38.3744, moduleLatency: 26.059
216-[preprocess] throughputRate: 38.2771, moduleLatency: 26.1253
217-[infer] throughputRate: 36.2854, Interface throughputRate: 39.3897, moduleLatency: 26.8079
218-[post] throughputRate: 2.26783, moduleLatency: 440.951
219-```
220-Interface throughputRate: 39.3897,39.3897x4=157.5588既是batch16 310单卡吞吐率
221-batch4性能:
222-```
223-[INFO] PureInfer result saved in ./result/PureInfer_perf_of_dpn131_bs4_in_device_3.txt
224------------------PureInfer Performance Summary------------------
225-[INFO] ave_throughputRate: 38.4344samples/s, ave_latency: 26.1589ms
226-----------------------------------------------------------------
227-```
228-batch4 310单卡吞吐率:38.4344x4=153.7376fps
229-batch8性能:
230-```
231-[INFO] PureInfer result saved in ./result/PureInfer_perf_of_dpn131_bs8_in_device_3.txt
232------------------PureInfer Performance Summary------------------
233-[INFO] ave_throughputRate: 39.3665samples/s, ave_latency: 25.4697ms
234-----------------------------------------------------------------
235-```
236-batch8 310单卡吞吐率:39.3665x4=157.466fps
237-batch32性能:
238-```
239-[INFO] PureInfer result saved in ./result/PureInfer_perf_of_dpn131_bs32_in_device_3.txt
240------------------PureInfer Performance Summary------------------
241-[INFO] ave_throughputRate: 40.1895samples/s, ave_latency: 24.9015ms
242-----------------------------------------------------------------
243-```
244-batch32 310单卡吞吐率:40.1895x4=160.758fps
245- 
246- **性能优化:**
247->待优化
248-蓝区社区版本CANN 5.0.2.alpha003优化了StridedSliceD,使用该版本测
249-sclice算子引入过多的transdata需要进一步优化
250 19 
251 20 
21+ 
22+ 
23+# 概述<a name="ZH-CN_TOPIC_0000001172161501"></a>
24+ 
25+DPN,简单高效的模块化双路径网络用于图像分类,提出了一种新的拓扑结构。DPN网络共享一些common特征,同时保持灵活性来通过双路径结构来探索新的特征。
26+ 
27+- 参考实现:
28+ 
29+ ```
30+ url=https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/dpn.py
31+ commit_id=0a4df4f3fe46b81e94bf9cc9ee5d9bebee6b9ec5
32+ code_path=https://gitee.com/ascend/ModelZoo-PyTorch/tree/master/ACL_PyTorch/contrib/cv/classfication/DPN131
33+ model_name=DPN131
34+ ```
35+ 
36+ 
37+## 输入输出数据<a name="section540883920406"></a>
38+ 
39+- 输入数据
40+ 
41+ | 输入数据 | 数据类型 | 大小 | 数据排布格式 |
42+ | -------- | -------- | ------------------------- | ------------ |
43+ | input | RGB_FP32 | batchsize x 3 x 224 x 224 | NCHW |
44+ 
45+ 
46+- 输出数据
47+ 
48+ | 输出数据 | 数据类型 | 大小 | 数据排布格式 |
49+ | -------- |----------------| -------- | ------------ |
50+ | output1 | FLOAT32 | batchsize x -1 | ND |
51+ 
52+ 
53+ 
54+# 推理环境准备<a name="ZH-CN_TOPIC_0000001126281702"></a>
55+ 
56+- 该模型需要以下插件与驱动
57+ 
58+ **表 1** 版本配套表
59+ 
60+ | 配套 | 版本 | 环境准备指导 |
61+ |---------| ------- | ------------------------------------------------------------ |
62+ | 固件与驱动 | 22.0.3 | [Pytorch框架推理环境准备](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/pies) |
63+ | CANN | 6.0.RC1 | - |
64+ | Python | 3.7.5 | - |
65+ | PyTorch | 1.8.0 | - |
66+ | 说明:Atlas 300I Duo 推理卡请以CANN版本选择实际固件与驱动版本。 | \ | \ |
67+ 
68+ 
69+ 
70+# 快速上手<a name="ZH-CN_TOPIC_0000001126281700"></a>
71+ 
72+## 获取源码<a name="section4622531142816"></a>
73+ 
74+1. 获取源码。
75+ 
76+ ```
77+ git clone https://github.com/Cadene/pretrained-models.pytorch.git
78+ cd ./pretrainedmodels/models/
79+ patch -p1 < ../dpn.diff,其中dpn.diff是通过git diff > ./dpn.diff生成的
80+ cd..
81+ ```
82+ 
83+2. 安装依赖。
84+ 
85+ ```
86+ pip3 install -r requirements.txt
87+ ```
88+ 
89+## 准备数据集<a name="section183221994411"></a>
90+ 
91+1. 获取原始数据集。(解压命令参考tar –xvf \*.tar与 unzip \*.zip)
92+ 
93+ 
94+ 该模型使用[ImageNet官网](http://www.image-net.org/)的5万张验证集进行测试,图片与标签分别存放在/local/DPN131/imagenet/val与/local/DPN131/imagenet/val_label.txt。
95+ ```
96+ imagenet
97+ ├── val_label.txt //验证集标注信息
98+ └── val // 验证集文件夹
99+ ```
100+ 
101+2. 数据预处理,将原始数据集转换为模型输入的数据。
102+ 
103+ 执行imagenet_torch_preprocess.py脚本,完成预处理。
104+ 
105+ ```
106+ mkdir pre_dataset
107+ python3.7 imagenet_torch_preprocess.py /local/DPN131/imagenet/val ./pre_dataset
108+ 
109+ ```
110+
111+ - 参数说明:
112+
113+ /local/DPN131/imagenet/val,验证集文件所在路径
114+
115+ ./pre_dataset,输出的预处理后数据集路径
116+ 
117+ 
118+ 
119+## 模型推理<a name="section741711594517"></a>
120+ 
121+1. 模型转换。
122+ 
123+ 使用PyTorch将模型权重文件.pth转换为.onnx文件,再使用ATC工具将.onnx文件转为离线推理模型文件.om文件。
124+ 
125+ 1. 获取权重文件。
126+ 
127+ [DPN131预训练pth权重文件](http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth)
128+ 
129+ ```
130+ wget http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth
131+ ```
132+ 
133+ 2. 导出onnx文件。
134+ 
135+ 1. 使用dpn131_pth2onnx.py脚本。
136+ 
137+ 运行dpn131_pth2onnx.py脚本。
138+ 
139+ ```
140+ python3.7 dpn131_pth2onnx.py ./dpn131-7af84be88.pth dpn131.onnx
141+ ```
142+ 
143+ 获得dpn131.onnx文件。
144+ 
145+ 3. 使用ATC工具将ONNX模型转OM模型。
146+ 
147+ 1. 配置环境变量。
148+ 
149+ ```
150+ source /usr/local/Ascend/......
151+ ```
152+ 
153+ 2. 执行命令查看芯片名称($\{chip\_name\})。
154+ 
155+ ```
156+ npu-smi info
157+ #该设备芯片名为Ascend310P3 (自行替换)
158+ 回显如下:
159+ +-------------------+-----------------+------------------------------------------------------+
160+ | NPU Name | Health | Power(W) Temp(C) Hugepages-Usage(page) |
161+ | Chip Device | Bus-Id | AICore(%) Memory-Usage(MB) |
162+ +===================+=================+======================================================+
163+ | 0 310P3 | OK | 15.8 42 0 / 0 |
164+ | 0 0 | 0000:82:00.0 | 0 1074 / 21534 |
165+ +===================+=================+======================================================+
166+ | 1 310P3 | OK | 15.4 43 0 / 0 |
167+ | 0 1 | 0000:89:00.0 | 0 1070 / 21534 |
168+ +===================+=================+======================================================+
169+ ```
170+ 
171+ 3. 执行ATC命令。
172+ 
173+ ```
174+ atc --framework=5 --model=./dpn131.onnx --output=dpn131_bs{batch size} --input_format=NCHW --input_shape="image:{batch size},3,224,224" --log=debug --soc_version=Ascend310P3
175+ 示例
176+ atc --framework=5 --model=./dpn131.onnx --output=dpn131_bs1 --input_format=NCHW --input_shape="image:1,3,224,224" --log=debug --soc_version=Ascend310P3
177+ ```
178+ 
179+ - 参数说明:
180+ 
181+ - --model:为ONNX模型文件。
182+ - --framework:5代表ONNX模型。
183+ - --output:输出的OM模型。
184+ - --input\_format:输入数据的格式。
185+ - --input\_shape:输入数据的shape。
186+ - --log:日志级别。
187+ - --soc\_version:处理器型号。
188+ 
189+ 运行成功后生成dpn131_bs1.om模型文件,batch size为4、8、16、32、64的修改对应的batch size的位置即可。
190+ 
191+2. 开始推理验证。
192+ 
193+ 1. 安装ais_bench推理工具。
194+ 
195+ 请访问[ais_bench推理工具](https://gitee.com/ascend/tools/tree/master/ais-bench_workload/tool/ais_infer)代码仓,根据readme文档进行工具安装。
196+ 
197+ 2. 执行推理。
198+ 
199+ ```
200+ python3 -m ais_bench --model ./dpn131_bs{batch size}.om --input ./pre_dataset/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize {batch size}
201+ 示例
202+ python3 -m ais_bench --model ./dpn131_bs1.om --input ./pre_dataset/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize 1
203+ ```
204+ 
205+ - 参数说明:
206+ 
207+ - model:需要推理om模型的路径。
208+ - input:模型需要的输入bin文件夹路径。
209+ - output:推理结果输出路径。
210+ - outfmt:输出数据的格式。
211+ - output_dirname:推理结果输出子文件夹。
212+ 
213+ 推理后的输出默认在当前目录output的subdir下。
214+ 
215+ 3. 精度验证。
216+ 
217+ 调用imagenet_acc_eval.py脚本与label比对,可以获得Accuracy Top5数据,结果保存在result.json中。
218+ 
219+ ```
220+ python3.7 imagenet_acc_eval.py ./output/subdir/ /local/DPN131/imagenet/val_label.txt ./ result.json
221+ ```
222+ 
223+ - 参数说明:
224+ 
225+ - ./output/subdir/:为生成推理结果所在路径
226+ 
227+ - /local/DPN131/imagenet/val_label.txt:为标签数据所在路径
228+ 
229+ - ./ result.json:为生成结果文件所在路径
230+ 
231+ 4. 性能验证。
232+ 
233+ 可使用ais_bench推理工具的纯推理模式验证不同batch_size的om模型的性能,参考命令如下:
234+ 
235+ ```
236+ python3.7 -m ais_bench --model=./dpn131_bs{batch size}.om --loop=1000 --batchsize={batch size}
237+ 示例
238+ python3.7 -m ais_bench --model=./dpn131_bs1.om --loop=1000 --batchsize=1
239+ ```
240+ 
241+ - 参数说明:
242+ - --model:需要验证om模型所在路径
243+ - --batchsize:验证模型的batch size,按实际进行修改
244+ 
245+ 
246+ 
247+# 模型推理性能&精度<a name="ZH-CN_TOPIC_0000001172201573"></a>
248+ 
249+调用ACL接口推理计算,性能参考下列数据。
250+ 
251+| 芯片型号 | Batch Size | 数据集 | 精度 | 性能 |
252+| --------- |------------| ---------- |-----------------------|------|
253+| 310P3 | 1 | ImageNet | 79.47/Top1 94.54/Top5 | 384 |
254+| 310P3 | 4 | ImageNet | 79.47/Top1 94.54/Top5 | 567 |
255+| 310P3 | 8 | ImageNet | 79.47/Top1 94.54/Top5 | 483 |
256+| 310P3 | 16 | ImageNet | 79.47/Top1 94.54/Top5 | 388 |
257+| 310P3 | 32 | ImageNet | 79.47/Top1 94.54/Top5 | 353 |
258+| 310P3 | 64 | ImageNet | 79.47/Top1 94.54/Top5 | 348 |
@@ -1,61 +0,0 @@
1-# Copyright 2020 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import os
16-import sys
17-import cv2
18-from glob import glob
19- 
20- 
21-def get_bin_info(file_path, info_name, width, height):
22- bin_images = glob(os.path.join(file_path, '*.bin'))
23- with open(info_name, 'w') as file:
24- for index, img in enumerate(bin_images):
25- content = ' '.join([str(index), img, width, height])
26- file.write(content)
27- file.write('\n')
28- 
29- 
30-def get_jpg_info(file_path, info_name):
31- extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
32- image_names = []
33- for extension in extensions:
34- image_names.append(glob(os.path.join(file_path, '*.' + extension)))
35- with open(info_name, 'w') as file:
36- for image_name in image_names:
37- if len(image_name) == 0:
38- continue
39- else:
40- for index, img in enumerate(image_name):
41- img_cv = cv2.imread(img)
42- shape = img_cv.shape
43- width, height = shape[1], shape[0]
44- content = ' '.join([str(index), img, str(width), str(height)])
45- file.write(content)
46- file.write('\n')
47- 
48- 
49-if __name__ == '__main__':
50- file_type = sys.argv[1]
51- file_path = sys.argv[2]
52- info_name = sys.argv[3]
53- if file_type == 'bin':
54- width = sys.argv[4]
55- height = sys.argv[5]
56- assert len(sys.argv) == 6, 'The number of input parameters must be equal to 5'
57- get_bin_info(file_path, info_name, width, height)
58- elif file_type == 'jpg':
59- assert len(sys.argv) == 4, 'The number of input parameters must be equal to 3'
60- get_jpg_info(file_path, info_name)
61- 
@@ -0,0 +1,3 @@
1+FuncStatus:OK
2+PerfStatus:OK
3+PrecisionStatus:OK
@@ -1,4 +1,4 @@
1-torch == 1.5.01+torch == 1.8.0
2torchvision == 0.6.02torchvision == 0.6.0
3onnx == 1.9.03onnx == 1.9.0
4numpy == 1.19.24numpy == 1.19.2
@@ -1,28 +0,0 @@
1-环境准备:
2- 
3-1.数据集路径
4-数据集统一放在/root/datasets/或/opt/npu/
5-本模型数据集放在/root/datasets/
6- 
7-2.进入工作目录
8-cd DPN131
9- 
10-3.安装必要的依赖
11-pip3.7 install -r requirements.txt
12- 
13-4.获取,修改与安装开源模型代码
14-git clone https://github.com/Cadene/pretrained-models.pytorch.git
15-cd pretrained-models.pytorch
16-patch -p1 < ../dpn.diff,其中dpn.diff是通过git diff > ./dpn.diff生成的
17-如果模型代码需要安装,则安装模型代码(如果没有安装脚本,pth2onnx等脚本需要引用模型代码的类或函数,可通过sys.path.append(r"./pretrained-models.pytorch")添加搜索路径的方式)
18-cd ..
19- 
20-5.获取权重文件
21-wget http://data.lip6.fr/cadene/pretrainedmodels/dpn131-7af84be88.pth
22- 
23-6.获取benchmark工具
24-将benchmark.x86_64放在当前目录
25- 
26-7.310上执行,执行时确保device空闲
27-bash test/pth2om.sh
28-bash test/eval_acc_perf.sh --datasets_path=/root/datasets
@@ -1,69 +0,0 @@
1-#!/bin/bash
2- 
3-datasets_path="/root/datasets/"
4- 
5-for para in $*
6-do
7- if [[ $para == --datasets_path* ]]; then
8- datasets_path=`echo ${para#*=}`
9- fi
10-done
11- 
12-arch=`uname -m`
13-rm -rf ./prep_dataset
14-python3.7 imagenet_torch_preprocess.py dpn131 ${datasets_path}/imagenet/val ./prep_dataset
15-if [ $? != 0 ]; then
16- echo "fail!"
17- exit -1
18-fi
19-python3.7 gen_dataset_info.py bin ./prep_dataset ./dpn131_prep_bin.info 224 224
20-if [ $? != 0 ]; then
21- echo "fail!"
22- exit -1
23-fi
24-source /usr/local/Ascend/ascend-toolkit/set_env.sh
25-rm -rf result/dumpOutput_device0
26-./benchmark.${arch} -model_type=vision -device_id=0 -batch_size=1 -om_path=dpn131_bs1.om -input_text_path=./dpn131_prep_bin.info -input_width=224 -input_height=224 -output_binary=False -useDvpp=False
27-if [ $? != 0 ]; then
28- echo "fail!"
29- exit -1
30-fi
31-rm -rf result/dumpOutput_device1
32-./benchmark.${arch} -model_type=vision -device_id=1 -batch_size=16 -om_path=dpn131_bs16.om -input_text_path=./dpn131_prep_bin.info -input_width=224 -input_height=224 -output_binary=False -useDvpp=False
33-if [ $? != 0 ]; then
34- echo "fail!"
35- exit -1
36-fi
37-python3.7 imagenet_acc_eval.py result/dumpOutput_device0/ ${datasets_path}/imagenet/val_label.txt ./ result_bs1.json
38-if [ $? != 0 ]; then
39- echo "fail!"
40- exit -1
41-fi
42-python3.7 imagenet_acc_eval.py result/dumpOutput_device1/ ${datasets_path}/imagenet/val_label.txt ./ result_bs16.json
43-if [ $? != 0 ]; then
44- echo "fail!"
45- exit -1
46-fi
47-echo "====accuracy data===="
48-python3.7 test/parse.py result_bs1.json
49-if [ $? != 0 ]; then
50- echo "fail!"
51- exit -1
52-fi
53-python3.7 test/parse.py result_bs16.json
54-if [ $? != 0 ]; then
55- echo "fail!"
56- exit -1
57-fi
58-echo "====performance data===="
59-python3.7 test/parse.py result/perf_vision_batchsize_1_device_0.txt
60-if [ $? != 0 ]; then
61- echo "fail!"
62- exit -1
63-fi
64-python3.7 test/parse.py result/perf_vision_batchsize_16_device_1.txt
65-if [ $? != 0 ]; then
66- echo "fail!"
67- exit -1
68-fi
69-echo "success"
@@ -1,32 +0,0 @@
1-# Copyright 2020 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import sys
16-import json
17-import re
18- 
19-if __name__ == '__main__':
20- if sys.argv[1].endswith('.json'):
21- result_json = sys.argv[1]
22- with open(result_json, 'r') as f:
23- content = f.read()
24- tops = [i.get('value') for i in json.loads(content).get('value') if 'Top' in i.get('key')]
25- print('om {} top1:{} top5:{}'.format(result_json.split('_')[1].split('.')[0], tops[0], tops[4]))
26- elif sys.argv[1].endswith('.txt'):
27- result_txt = sys.argv[1]
28- with open(result_txt, 'r') as f:
29- content = f.read()
30- txt_data_list = [i.strip() for i in re.findall(r':(.*?),', content.replace('\n', ',') + ',')]
31- fps = float(txt_data_list[7].replace('samples/s', '')) * 4
32- print('310 bs{} fps:{}'.format(result_txt.split('_')[3], fps))
@@ -1,15 +0,0 @@
1-#!/bin/bash
2-rm -rf dpn131.onnx
3-pip3.7 uninstall pretrainedmodels
4-python3.7 dpn131_pth2onnx.py dpn131-7af84be88.pth dpn131.onnx
5- 
6-source /usr/local/Ascend/ascend-toolkit/set_env.sh
7- 
8-rm -rf dpn131_bs1.om dpn131_bs16.om
9-atc --framework=5 --model=./dpn131.onnx --input_format=NCHW --input_shape="image:1,3,224,224" --output=dpn131_bs1 --log=debug --soc_version=Ascend310
10-atc --framework=5 --model=./dpn131.onnx --input_format=NCHW --input_shape="image:16,3,224,224" --output=dpn131_bs16 --log=debug --soc_version=Ascend310
11-if [ -f "dpn131_bs1.om" ] && [ -f "dpn131_bs16.om" ]; then
12- echo "success"
13-else
14- echo "fail!"
15-fi
@@ -12,48 +12,173 @@
12# See the License for the specific language governing permissions and12# See the License for the specific language governing permissions and
13# limitations under the License.13# limitations under the License.
14 14 
15-import os
16-import argparse
17-import numpy as np
18import json15import json
16+import os
17+import sys
18+import time
19+import numpy as np
19 20 
20-def process_pred(pred_file):
21- """Get predicted label from predction
22 21 
23- Args:22+np.set_printoptions(threshold=sys.maxsize)
24- pred_file (str): prediction file
25 23 
26- Returns:24+LABEL_FILE = "HiAI_label.json"
27- int: predicted label25+ 
26+ 
27+def gen_file_name(img_name):
28+ full_name = img_name.split('/')[-1]
29+ index = full_name.rfind('.')
30+ return full_name[:index]
31+ 
32+ 
33+def cre_groundtruth_dict(gtfile_path):
28 """34 """
29- data = np.loadtxt(pred_file)35+ :param filename: file contains the imagename and label number
30- assert len(data) == 100036+ :return: dictionary key imagename, value is label number
31- pred_label = data.argmax()
32- return pred_label
33- 
34- 
35-def pred_eval(label_file, pred_dir):
36- """evaluate predictions
37- 
38- Args:
39- label_file (str): path of groundtruth file
40- pred_dir (str): path of predictions
41 """37 """
42- with open(label_file, 'r') as f:38+ img_gt_dict = {}
43- gt = json.load(f)39+ for gtfile in os.listdir(gtfile_path):
44- output_file_list = os.listdir(pred_dir)40+ if (gtfile != LABEL_FILE):
45- result = []41+ with open(os.path.join(gtfile_path, gtfile), 'r') as f:
46- for output_file in output_file_list:42+ gt = json.load(f)
47- output_name = '_'.join(output_file.split('_')[:3])43+ ret = gt["image"]["annotations"][0]["category_id"]
48- gt_label = gt[output_name]44+ img_gt_dict[gen_file_name(gtfile)] = ret
49- pred_label = process_pred(os.path.join(pred_dir, output_file))45+ return img_gt_dict
50- result.append(gt_label == pred_label)46+ 
51- print('Validation Results for', pred_dir)47+ 
52- print("Top 1 Accuracy: {:.1%}".format(sum(result) / len(result)))48+def cre_groundtruth_dict_fromtxt(gtfile_path):
49+ """
50+ :param filename: file contains the imagename and label number
51+ :return: dictionary key imagename, value is label number
52+ """
53+ img_gt_dict = {}
54+ with open(gtfile_path, 'r')as f:
55+ for line in f.readlines():
56+ temp = line.strip().split(" ")
57+ imgname = temp[0].split(".")[0]
58+ imglab = temp[1]
59+ img_gt_dict[imgname] = imglab
60+ return img_gt_dict
61+ 
62+ 
63+def load_statistical_predict_result(filepath):
64+ """
65+ function:
66+ the prediction result file data extraction
67+ input:
68+ result file:filepath
69+ output:
70+ n_label:number of label
71+ data_vec: the probabilities of prediction in the 1000
72+ :return: probabilities, number of label, in_type, color
73+ """
74+ with open(filepath, 'r')as f:
75+ data = f.readline()
76+ temp = data.strip().split(" ")
77+ n_label = len(temp)
78+ if data == '':
79+ n_label = 0
80+ data_vec = np.zeros((n_label), dtype=np.float32)
81+ in_type = ''
82+ color = ''
83+ if n_label == 0:
84+ in_type = f.readline()
85+ color = f.readline()
86+ else:
87+ for ind, prob in enumerate(temp):
88+ data_vec[ind] = np.float32(prob)
89+ return data_vec, n_label, in_type, color
90+ 
91+ 
92+def create_visualization_statistical_result(prediction_file_path,
93+ result_store_path, json_file_name,
94+ img_gt_dict, topn=5):
95+ """
96+ :param prediction_file_path:
97+ :param result_store_path:
98+ :param json_file_name:
99+ :param img_gt_dict:
100+ :param topn:
101+ :return:
102+ """
103+ writer = open(os.path.join(result_store_path, json_file_name), 'w')
104+ table_dict = {}
105+ table_dict["title"] = "Overall statistical evaluation"
106+ table_dict["value"] = []
107+ 
108+ count = 0
109+ rescnt = 0
110+ n_labels = 0
111+ count_hit = np.zeros(topn)
112+ for tfile_name in os.listdir(prediction_file_path):
113+ count += 1
114+ temp = tfile_name.split('.')[0]
115+ index = temp.rfind('_')
116+ img_name = temp[:index]
117+ filepath = os.path.join(prediction_file_path, tfile_name)
118+ ret = load_statistical_predict_result(filepath)
119+ prediction = ret[0]
120+ n_labels = ret[1]
121+ sort_index = np.argsort(-prediction)
122+ gt = img_gt_dict[img_name]
123+ if (n_labels == 1000):
124+ reallabel = int(gt)
125+ elif (n_labels == 1001):
126+ reallabel = int(gt) + 1
127+ else:
128+ reallabel = int(gt)
129+ 
130+ rescnt = min(len(sort_index), topn)
131+ for i in range(rescnt):
132+ if (str(reallabel) == str(sort_index[i])):
133+ count_hit[i] += 1
134+ break
135+ 
136+ if 'value' not in table_dict.keys():
137+ print("the item value does not exist!")
138+ else:
139+ table_dict["value"].extend(
140+ [{"key": "Number of images", "value": str(count)},
141+ {"key": "Number of classes", "value": str(n_labels)}])
142+ if count == 0:
143+ accuracy = 0
144+ else:
145+ accuracy = np.cumsum(count_hit) / count
146+ for i in range(rescnt):
147+ table_dict["value"].append({"key": "Top" + str(i + 1) + " accuracy",
148+ "value": str(
149+ round(accuracy[i] * 100, 2)) + '%'})
150+ json.dump(table_dict, writer)
151+ writer.close()
152+ 
53 153 
54if __name__ == '__main__':154if __name__ == '__main__':
55- parser = argparse.ArgumentParser()155+ start = time.time()
56- parser.add_argument("--label_file", default="/home/Datasets/imagenet/imagenet_labels_fixres.json")156+ try:
57- parser.add_argument("--pred_dir", default="./result/dumpOutput_device0_bs1/")157+ # txt file path
58- args = parser.parse_args()158+ folder_davinci_target = sys.argv[1]
59- pred_eval(args.label_file, args.pred_dir)159+ # annotation files path, "val_label.txt"
160+ annotation_file_path = sys.argv[2]
161+ # the path to store the results json path
162+ result_json_path = sys.argv[3]
163+ # result json file name
164+ json_file_name = sys.argv[4]
165+ except IndexError:
166+ print("Stopped!")
167+ exit(1)
168+ 
169+ if not (os.path.exists(folder_davinci_target)):
170+ print("target file folder does not exist.")
171+ 
172+ if not (os.path.exists(annotation_file_path)):
173+ print("Ground truth file does not exist.")
174+ 
175+ if not (os.path.exists(result_json_path)):
176+ print("Result folder doesn't exist.")
177+ 
178+ img_label_dict = cre_groundtruth_dict_fromtxt(annotation_file_path)
179+ create_visualization_statistical_result(folder_davinci_target,
180+ result_json_path, json_file_name,
181+ img_label_dict, topn=5)
182+ 
183+ elapsed = (time.time() - start)
184+ print("Time used:", elapsed)
@@ -1,314 +1,247 @@
1-# FixRes Onnx模型端到端推理指导1+# FixRes模型-推理指导
2 2 
3-## 1 模型概述3+ 
4+- [概述](#ZH-CN_TOPIC_0000001172161501)
5+ 
6+ - [输入输出数据](#section540883920406)
7+ 
8+ 
9+ 
10+- [推理环境准备](#ZH-CN_TOPIC_0000001126281702)
11+ 
12+- [快速上手](#ZH-CN_TOPIC_0000001126281700)
13+ 
14+ - [获取源码](#section4622531142816)
15+ - [准备数据集](#section183221994411)
16+ - [模型推理](#section741711594517)
17+ 
18+- [模型推理性能&精度](#ZH-CN_TOPIC_0000001172201573)
19+ 
20+ 
21+ 
22+ 
23+# 概述<a name="ZH-CN_TOPIC_0000001172161501"></a>
4 24 
5FixRes是图像分类任务的卷积神经网络,该网络基于ResNet50进行了改进,相比ResNet网络,FixRes在测试时采用更大的分辨率输入图像,以此降低训练、测试时图像增强方法不同对分类准确率造成的负面影响。25FixRes是图像分类任务的卷积神经网络,该网络基于ResNet50进行了改进,相比ResNet网络,FixRes在测试时采用更大的分辨率输入图像,以此降低训练、测试时图像增强方法不同对分类准确率造成的负面影响。
26+- 参考实现:
6 27 
7-### 1.1 论文地址28+ ```
29+ url=https://github.com/facebookresearch/FixRes
30+ commit_id=c9be6acc7a6b32f896e62c28a97c20c2348327d3
31+ code_path=https://gitee.com/ascend/ModelZoo-PyTorch/tree/master/ACL_PyTorch/contrib/cv/classfication/FixRes
32+ model_name=FixRes
33+ ```
8 34 
9-[Hugo Touvron and Andrea Vedaldi and Matthijs Douze and Hervé Jégou (2020). Fixing the train-test resolution discrepancy: FixEfficientNet. CoRR, abs/2003.08237.](https://arxiv.org/pdf/2003.08237.pdf)
10 35 
11-### 1.2 代码地址36+## 输入输出数据<a name="section540883920406"></a>
12 37 
13-```shell38+- 输入数据
14-ur=https://github.com/facebookresearch/FixRes
15-branch=master
16-commit_id=c9be6acc7a6b32f896e62c28a97c20c2348327d3
17-```
18 39 
19-## 2 环境准备 40+ | 输入数据 | 数据类型 | 大小 | 数据排布格式 |
41+ | -------- | -------- | ------------------------- | ------------ |
42+ | input | RGB_FP32 | batchsize x 3 x 224 x 224 | NCHW |
20 43 
21-### 2.1 深度学习框架
22 44 
23-```45+- 输出数据
24-CANN 5.1.RC1
25-pytorch == 1.8.0
26-torchvision == 0.9.0
27-onnx == 1.8.0
28-```
29 46 
30-### 2.2 python第三方库47+ | 输出数据 | 数据类型 | 大小 | 数据排布格式 |
48+ | -------- |------------------| -------- | ------------ |
49+ | output1 | FLOAT32 | batchsize x 1000 | ND |
31 50 
32-```
33-numpy == 1.18.5
34-opencv-python == 4.5.2.54
35-Pillow == 7.2.0
36-```
37 51 
38-**说明:**
39 52 
40-> X86架构:pytorch,torchvision和onnx可以通过官方下载whl包安装,其它可以通过pip3.7 install 包名 安装53+# 推理环境准备<a name="ZH-CN_TOPIC_0000001126281702"></a>
41->
42-> Arm架构:pytorch,torchvision和onnx可以通过源码编译安装,其它可以通过pip3.7 install 包名 安装
43 54 
44-## 3 模型转换55+- 模型需要以下插件与驱动
45 56 
46-使用PyTorch将模型权重文件.pth转换为.onnx文件,再使用ATC工具将.onnx文件转为离线推理模型文件.om文件。57+ **表 1** 版本配套表
47 58 
48-### 3.1 pth转onnx模型59+ | 配套 | 版本 | 环境准备指导 |
60+ |---------| ------- | ------------------------------------------------------------ |
61+ | 固件与驱动 | 22.0.3 | [Pytorch框架推理环境准备](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/pies) |
62+ | CANN | 6.0.RC1 | - |
63+ | Python | 3.7.5 | - |
64+ | PyTorch | 1.9.0 | - |
65+ | 说明:Atlas 300I Duo 推理卡请以CANN版本选择实际固件与驱动版本。 | \ | \ |
49 66 
50-1. 准备pth权重文件
51- 使用训练好的pkl权重文件:ResNetFinetune.pth
52 67 
53-下载地址: [https://dl.fbaipublicfiles.com/FixRes_data/FixRes_Pretrained_Models/ResNetFinetune.pth](https://github.com/facebookresearch/FixRes)
54 68 
55-2. 导出onnx文件。69+# 快速上手<a name="ZH-CN_TOPIC_0000001126281700"></a>
56 70 
57- 1. 使用“ResNetFinetune.pth”导出onnx文件。71+## 获取源码<a name="section4622531142816"></a>
58 72 
59- 运行“FixRes_pth2onnx.py”脚本,得“FixRes.onnx”文件73+1. 取源码
60 74 
61- ```shell75+ ```
62- python3.7 FixRes_pth2onnx.py --pretrain_path ResNetFinetune.pth76+ git clone https://github.com/facebookresearch/FixRes.git
63- ```
64- 
65- 使用ATC工具将.onnx文件转换为.om文件,导出.onnx模型文件时需设置算子版本为11。
66- 
67-### 3.2 onnx模型转om模型
68- 
69-使用ATC工具将ONNX模型转OM模型。
70- 
71-1. 配置环境变量。
72- 
73- ```shell
74- source /usr/local/Ascend/ascend-toolkit/set_env.sh
75 ```77 ```
76 78 
77-2. 使用atc将onnx模型79+2. 安装依赖。
78- ${chip_name}可通过npu-smi info指令查看,例:310P3
79- ![Image](https://gitee.com/ascend/ModelZoo-PyTorch/raw/master/ACL_PyTorch/images/310P3.png)
80 80 
81-执行ATC命令:81+ ```
82+ pip3 install -r requirements.txt
83+ ```
82 84 
83-```shell85+## 准备数据集<a name="section183221994411"></a>
84-atc --framework=5
85---model=FixRes.onnx
86---output=FixRes_bs1
87---input_format=NCHW
88---input_shape="image:1,3,384,384"
89---log=debug
90---soc_version=Ascend${chip_name}
91---auto_tune_mode="RL,GA"
92-```
93 86 
94-说明:87+1. 获取原始据集。(解压命令参考tar –xvf \*.tar与 unzip \*.zip)
95---model:为ONNX模型文件。
96 88 
97---framework:5代表ONNX模型。
98 89 
99---output:输出的OM模型。90+模型使用[ImageNet官网](http://www.image-net.org/)的5万张验证集进行测试,图片与标签分别存放在/local/FixRes/imagenet/val与/local/FixRes/imagenet/val_label.txt
91+ ```
92+ imagenet
93+ ├── val_label.txt //验证集标注信息
94+ └── val // 验证集文件夹
95+ ```
100 96 
101---input_format:输入数据的格式97+2. 数据预处理,将原始数据集转换为模型输入数据。
102 98 
103---input_shape:输入数据的shape99+ 执行FixRes_preprocess.py脚本,完成预处理
104 100 
105---log:日志级别。101+ ```
102+ python3.7 FixRes_preprocess.py --src-path /local/FixRes/imagenet/val --save-path ./val_FixRes
106 103 
107---soc_version:处理器型号。104+ ```
105+
106+ - 参数说明:
107+
108+ --src-path,原始数据验证集(.jpeg)所在路径。
109+
110+ --save-path,输出的二进制文件(.bin)所在路径。
108 111 
109-## 4 数据集预处理
110 112 
111-### 4.1 数据集获取
112 113 
113-模型支持ImageNet 50000张图片的验证集。以ILSVRC2012为例,请用户需自行获取ILSVRC2012数据集,上传数据集到服务器任意目录并解压(如:/home/HwHiAiUser/dataset)。本模型将使用到ILSVRC2012_img_val.tar验证集,请自行下载验证需要的标签文件“imagenet_labels_fixres.json”。114+## 模型推理<a name="section741711594517"></a>
114 115 
115-数据目录结构请参考:116+1. 模型转换。
116 117 
117-```118+ 使用PyTorch将模型权重文件.pth转换为.onnx文件,再使用ATC工具将.onnx文件转为离线推理模型文件.om文件。
118-├──ImageNet
119- ├──ILSVRC2012_img_val
120- ├──imagenet_labels_fixres.json
121-```
122 119 
123-### 4.2 数据预处理120+ 1. 获取权重文件
124 121 
125-数据处理将原始数据集转换为模型输入的数据。122+ [FixRes训练pth权重文件](https://dl.fbaipublicfiles.com/FixRes_data/FixRes_Pretrained_Models/ResNetFinetune.pth)
126 123 
127-执行“FixRes_preprocess.py”脚本,完成预处理124+ 2. 导出onnx文件
128 125 
129-```shell126+ 1. 使用FixRes_pth2onnx.py脚本。
130-python3.7 FixRes_preprocess.py
131---src-path /home/HwHiAiUser/dataset/imagenet/val
132---save-path ./val_FixRes
133-```
134 127 
135---src-path:原始数据验证集(.jpeg)所在路径128+ 运行FixRes_pth2onnx.py脚本
136 129 
137---save-path:输出的二进制文件(.bin)所在路径。130+ ```
131+ python3.7 FixRes_pth2onnx.py --pretrain_path ResNetFinetune.pth
132+ ```
138 133 
139-每个图像对应生成一个二进制文件。运行成功后,在当前目录下生成“val_FixRes”二进制文件夹。134+ 获得FixRes.onnx文件。
140 135 
141-### 4.3 生成数据集info文件136+ 3. 使用ATC工具将ONNX模型转OM模型
142 137 
143-生成bin文件的输入info文件138+ 1. 配置环境变量
144 139 
145-使用benchmark推理需要输入图片数据集的info文件,用于获取数据集。使用“gen_dataset_info.py”脚本,输入已经获得的图片文件,输出生成图片数据集的info文件。运行“gen_dataset_info.py”脚本。140+ ```
141+ source /usr/local/Ascend/......
142+ ```
146 143 
147-```shell144+ 2. 执行命令查看芯片名称($\{chip\_name\})。
148-python3.7 gen_dataset_info.py bin ./val_FixRes ./prep_bin.info 384 384
149-```
150 145 
151-“bin”:生成的数据集文件格式。146+ ```
147+ npu-smi info
148+ #该设备芯片名为Ascend310P3 (自行替换)
149+ 回显如下:
150+ +-------------------+-----------------+------------------------------------------------------+
151+ | NPU Name | Health | Power(W) Temp(C) Hugepages-Usage(page) |
152+ | Chip Device | Bus-Id | AICore(%) Memory-Usage(MB) |
153+ +===================+=================+======================================================+
154+ | 0 310P3 | OK | 15.8 42 0 / 0 |
155+ | 0 0 | 0000:82:00.0 | 0 1074 / 21534 |
156+ +===================+=================+======================================================+
157+ | 1 310P3 | OK | 15.4 43 0 / 0 |
158+ | 0 1 | 0000:89:00.0 | 0 1070 / 21534 |
159+ +===================+=================+======================================================+
160+ ```
152 161 
153-./val_FixRes”:预处理后的数据文件的**相对路径**162+ 3. 执行ATC命令
154 163 
155-“./prep_bin.info”:生成的数据集文件保存的路径。164+ ```
165+ atc --framework=5 --model=FixRes.onnx --output=FixRes_bs{batch size} --input_format=NCHW --input_shape="image:{batch size},3,384,384" --log=debug --soc_version=Ascend310P3
166+ 示例
167+ atc --framework=5 --model=FixRes.onnx --output=FixRes_bs1 --input_format=NCHW --input_shape="image:1,3,384,384" --log=debug --soc_version=Ascend310P3
168+ ```
156 169 
157-“384”图片的宽和高。170+ - 参数说明
158 171 
159-运行成功后,在当前目录中生成“prep_bin.info”172+ - --model:为ONNX模型文件
173+ - --framework:5代表ONNX模型。
174+ - --output:输出的OM模型。
175+ - --input\_format:输入数据的格式。
176+ - --input\_shape:输入数据的shape。
177+ - --log:日志级别。
178+ - --soc\_version:处理器型号。
160 179 
161-## 5 离线推理180+ 运行成功后生成FixRes_bs1.om模型文件,batch size为4、8、16、32、64的修改对应的batch size的位置即可。
162 181 
163-### 5.1 benchmark工具概述182+2. 开始推理验证。
164 183 
165-benchmark工具为华为自研的模型推理工具,支持多种模型的离线推理,能够迅速统计出模型在Ascend310上的性能,支持真实数据和纯推理两种模式,配合后处理脚本,可以实现诸多模型的端到端过程,获取工具及使用方法可以参考[CANN V100R020C10 推理benchmark工具用户指南 01](https://support.huawei.com/enterprise/zh/doc/EDOC1100164874?idPath=23710424%7C251366513%7C22892968%7C251168373)184+ 1. 安装ais_bench推理工具。
166 185 
167-### 5.2 离线推理186+ 请访问[ais_bench推理工具](https://gitee.com/ascend/tools/tree/master/ais-bench_workload/tool/ais_infer)代码仓,根据readme文档进行工具安装。
168 187 
169-1.设置环境变量188+ 2. 执行推理。
170 189 
171-```shell190+ ```
172-source /usr/local/Ascend/ascend-toolkit/set_env.sh191+ python3 -m ais_bench --model ./FixRes_bs{batch size}.om --input ./val_FixRes/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize {batch size}
173-```192+ 示例
193+ python3 -m ais_bench --model ./FixRes_bs1.om --input ./val_FixRes/ --output ./output --output_dirname subdir --outfmt 'TXT' --batchsize 1
194+ ```
174 195 
175-2.执行离线推理196+ - 参数说明:
176-增加benchmark.{arch}可执行权限
177 197 
178-```shell198+ - model:需要推理om模型的路径。
179-chmod u+x benchmark.x86_64199+ - input:模型需要的输入bin文件夹路径。
180-```200+ - output:推理结果输出路径。
201+ - outfmt:输出数据的格式。
202+ - output_dirname:推理结果输出子文件夹。
181 203 
182-执行推理。执行时使npu-smi info查看设备状态,确保device空闲。204+ 推理后的输出默认在当前目录output的subdir下
183 205 
184-```shell206+ 3. 精度验证。
185- ./benchmark.x86_64 -model_type=vision
186- -device_id=0
187- -batch_size=1
188- -om_path=./FixRes_bs1.om
189- -input_text_path=./prep_bin.info
190- -input_width=384
191- -input_height=384
192- -output_binary=False
193- -useDvpp=False
194-```
195 207 
196-说明:208+ 调用FixRes_postprocess.py脚本与label比对,可以获得Accuracy Top1据,结果保存在result.json中。
197 209 
198---model_type:模型类型。210+ ```
211+ python3.7 FixRes_postprocess.py ./output/subdir/ /local/DPN131/imagenet/val_label.txt ./ result.json
212+ ```
199 213 
200---om_pathom文件路径。214+ - 参数说明
201 215 
202---device_idNPU设备编号。216+ - ./output/subdir/为生成推理结果所在路径
203 217 
204---batch_size规模。218+ - /local/FixRes/imagenet/val_label.txt为标签据所在路径
205 219 
206---input_text_path:图片二进制信息220+ 4. 性能验证
207 221 
208---input_width输入图片宽度。222+ 可使用ais_bench推理工具的纯推理模式验证不同batch_size的om模型的性能,参考命令如下
209 223 
210---input_height:输入图片高度。224+ ```
225+ python3.7 -m ais_bench --model=./FixRes_bs{batch size}.om --loop=1000 --batchsize={batch size}
226+ 示例
227+ python3.7 -m ais_bench --model=./FixRes_bs1.om --loop=1000 --batchsize=1
228+ ```
211 229 
212---useDvpp是否使用Dvpp。230+ - 参数说明
231+ - --model:需要验证om模型所在路径
232+ - --batchsize:验证模型的batch size,按实际进行修改
213 233 
214---output_binary:输出二进制形式。
215 234 
216-推理后的输出默认在当前目录result下。
217 235 
218-推理后的输出默认在当前目录“result/dumpOutput_device0”下。236+# 模型推理性能&精度<a name="ZH-CN_TOPIC_0000001172201573"></a>
219 237 
220-## 6 精度对比238+调用ACL接口推理计算,性能参考下列数据。
221 239 
222-### 6.1 离线推理Acc精度统计240+| 芯片型号 | Batch Size | 数据集 | 精度 | 性能 |
223- 241+| --------- |------------| ---------- |-----------|-----|
224-调用“FixRes_postprocess.py”脚本与数据集标签“imagenet_labels_fixres.json”比对,可以获得Top 1 Accuracy数据,结果保存在“result.json”中。242+| 310P3 | 1 | ImageNet | 79.0/Top1 | 973 |
225- 243+| 310P3 | 4 | ImageNet | 79.0/Top1 | 984 |
226-```shell244+| 310P3 | 8 | ImageNet | 79.0/Top1 | 952 |
227-python3.7 FixRes_postprocess.py 245+| 310P3 | 16 | ImageNet | 79.0/Top1 | 933 |
228---label_file=./imagenet_labels_fixres.json 246+| 310P3 | 32 | ImageNet | 79.0/Top1 | 957 |
229---pred_dir=./result/dumpOutput_device0 > result.json247+| 310P3 | 64 | ImageNet | 79.0/Top1 | 949 |
230-```
231- 
232-参数说明:
233- 
234---label_file:生成推理结果所在路径。
235- 
236---pred_dir:标签数据。
237- 
238-“result.json”:生成结果文件。
239- 
240-执行完后得到310P上的精度。
241- 
242-```
243-Top 1 Accuracy: 79.1%
244-```
245- 
246-### 6.2 精度对比
247- 
248- **评测结果:**官网pth精度[rank1:79.0%](https://github.com/facebookresearch/FixRes), 310离线推理精度rank1:79.1%。
249- 
250-## 7 性能对比
251- 
252-### 7.1 310性能数据
253- 
254-**性能测试:** 测试npu性能要确保device空闲,使用npu-smi info命令可查看device是否在运行其它推理任务。性能测试可使用`benchmark`工具。
255- 
256-```
257-./benchmark.x86_64 -round=20 -om_path=./FixRes_bs4.om -device_id=0 -batch_size=4
258-```
259- 
260-执行20次纯推理取均值,统计吞吐率与其倒数时延(benchmark的时延是单个数据的推理时间),npu性能是一个device执行的结果。
261- 
262-`benchmark`工具在整个数据集上推理方式测性能可能时间较长,纯推理方式测性能可能不准确,因此bs1要使用在整个数据集上推理的方式测性能。
263- 
264-```
265-./benchmark.x86_64 -model_type=vision -device_id=0 -batch_size=1 -om_path=./FixRes_bs1.om -input_text_path=./prep_bin.info -input_width=384 -input_height=384 -output_binary=False -useDvpp=False
266-```
267- 
268-**Interface throughputRate:** 183.263 * 4 = 733.052, 即是batch1 310单卡吞吐率。
269- 
270-### 7.2 310P性能数据
271- 
272-**Interface throughputRate:** 893.562, 即是batch1 310P单卡吞吐率。
273- 
274-### 7.3 T4性能数据
275- 
276-在装有T4卡的服务器上使用`onnxruntime-gpu`工具测试gpu性能,测试代码如下。测试过程请确保卡没有运行其他任务。
277- 
278-```python
279-import time
280-from turtle import width
281-import numpy as np
282-import onnxruntime as rt
283-print(rt.get_device())
284- 
285-batch_size=1
286-length=224
287-width=224
288-providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
289- 
290-sess = rt.InferenceSession("./FixRes.onnx", providers=providers)
291-print("providers:",sess.get_providers())
292-input_name = sess.get_inputs()[0].name
293-outputs = ["output"]
294- 
295-# onnx模型输入节点
296-data = np.random.randn(batch_size,3, length, width).astype(np.float32)
297- 
298-# 推理200次,
299-for K in range(200):
300- start_time = time.time()
301- result = sess.run([], {input_name: data})
302- end_time = time.time() - start_time
303- time_list.append(end_time)
304- 
305-print("Batch_size: ",batch_size)
306-print("Time used: ", np.mean(time_list), 's')
307-print("T4 Throughput: ",batch_size/np.mean(time_list))
308-```
309- 
310-**T4 Throughput:** 200.616,即是batch1 T4单卡吞吐率。
311- 
312-### 7.4 性能对比
313- 
314-性能在310P上的性能达到310的1.2倍,达到T4性能的1.6倍,性能达标。
@@ -1,74 +0,0 @@
1-# Copyright 2021 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import os
16-import sys
17-import cv2
18-from glob import glob
19- 
20- 
21-def get_bin_info(file_path, info_name, width, height):
22- """generate dataset info
23- 
24- Args:
25- file_path (str): path of input bin files
26- info_name (str): file to save the information
27- width (int): input width
28- height (int): input height
29- """
30- bin_images = glob(os.path.join(file_path, '*.bin'))
31- with open(info_name, 'w') as file:
32- for index, img in enumerate(bin_images):
33- content = ' '.join([str(index), img, width, height])
34- file.write(content)
35- file.write('\n')
36- 
37- 
38-def get_jpg_info(file_path, info_name):
39- """get information of jpg images
40- 
41- Args:
42- file_path (str): path of image files
43- info_name (str): file to save the information
44- """
45- extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
46- image_names = []
47- for extension in extensions:
48- image_names.append(glob(os.path.join(file_path, '*.' + extension)))
49- with open(info_name, 'w') as file:
50- for image_name in image_names:
51- if len(image_name) == 0:
52- continue
53- else:
54- for index, img in enumerate(image_name):
55- img_cv = cv2.imread(img)
56- shape = img_cv.shape
57- width, height = shape[1], shape[0]
58- content = ' '.join([str(index), img, str(width), str(height)])
59- file.write(content)
60- file.write('\n')
61- 
62- 
63-if __name__ == '__main__':
64- file_type = sys.argv[1]
65- file_path = sys.argv[2]
66- info_name = sys.argv[3]
67- if file_type == 'bin':
68- width = sys.argv[4]
69- height = sys.argv[5]
70- assert len(sys.argv) == 6, 'The number of input parameters must be equal to 5'
71- get_bin_info(file_path, info_name, width, height)
72- elif file_type == 'jpg':
73- assert len(sys.argv) == 4, 'The number of input parameters must be equal to 3'
74- get_jpg_info(file_path, info_name)
@@ -1,63 +0,0 @@
1-#!/bin/bash
2- 
3-datasets_path="/home/Datasets/"
4- 
5-python3.7 FixRes_preprocess.py --src-path ${datasets_path}/imagenet/val --save-path ${datasets_path}/imagenet/val_FixRes
6-if [ $? != 0 ]; then
7- echo "fail!"
8- exit -1
9-fi
10-python3.7 gen_dataset_info.py bin ../Datasets/imagenet/val_FixRes ./prep_bin.info 384 384
11-if [ $? != 0 ]; then
12- echo "fail!"
13- exit -1
14-fi
15-source /usr/local/Ascend/ascend-toolkit/set_env.sh
16-rm -rf result/dumpOutput_device0
17-rm -rf result/dumpOutput_device0_bs1
18-rm -rf result/dumpOutput_device0_bs16
19-./benchmark.x86_64 -model_type=vision -device_id=0 -batch_size=1 -om_path=./FixRes_bs1.om -input_text_path=./prep_bin.info -input_width=384 -input_height=384 -output_binary=False -useDvpp=False
20-if [ $? != 0 ]; then
21- echo "fail!"
22- exit -1
23-fi
24-mv result/dumpOutput_device0 result/dumpOutput_device0_bs1
25-./benchmark.x86_64 -model_type=vision -device_id=0 -batch_size=16 -om_path=./FixRes_bs16.om -input_text_path=./prep_bin.info -input_width=384 -input_height=384 -output_binary=False -useDvpp=False
26-if [ $? != 0 ]; then
27- echo "fail!"
28- exit -1
29-fi
30-mv result/dumpOutput_device0 result/dumpOutput_device0_bs16
31-python3.7 FixRes_postprocess.py --label_file=/home/Datasets/imagenet/imagenet_labels_fixres.json --pred_dir=./result/dumpOutput_device0_bs1 > result_bs1.json
32-if [ $? != 0 ]; then
33- echo "fail!"
34- exit -1
35-fi
36-python3.7 FixRes_postprocess.py --label_file=/home/Datasets/imagenet/imagenet_labels_fixres.json --pred_dir=./result/dumpOutput_device0_bs16 > result_bs16.json
37-if [ $? != 0 ]; then
38- echo "fail!"
39- exit -1
40-fi
41-echo "====accuracy data===="
42-python3.7 test/parse.py result_bs1.json
43-if [ $? != 0 ]; then
44- echo "fail!"
45- exit -1
46-fi
47-python3.7 test/parse.py result_bs16.json
48-if [ $? != 0 ]; then
49- echo "fail!"
50- exit -1
51-fi
52-echo "====performance data===="
53-python3.7 test/parse.py result/perf_vision_batchsize_1_device_0.txt
54-if [ $? != 0 ]; then
55- echo "fail!"
56- exit -1
57-fi
58-python3.7 test/parse.py result/perf_vision_batchsize_16_device_0.txt
59-if [ $? != 0 ]; then
60- echo "fail!"
61- exit -1
62-fi
63-echo "success"
@@ -1,33 +0,0 @@
1-# Copyright 2021 Huawei Technologies Co., Ltd
2-#
3-# Licensed under the Apache License, Version 2.0 (the "License");
4-# you may not use this file except in compliance with the License.
5-# You may obtain a copy of the License at
6-#
7-# http://www.apache.org/licenses/LICENSE-2.0
8-#
9-# Unless required by applicable law or agreed to in writing, software
10-# distributed under the License is distributed on an "AS IS" BASIS,
11-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12-# See the License for the specific language governing permissions and
13-# limitations under the License.
14- 
15-import sys
16-import json
17-import re
18- 
19-if __name__ == '__main__':
20- if sys.argv[1].endswith('.json'):
21- result_json = sys.argv[1]
22- with open(result_json, 'r') as f:
23- content = f.read()
24- #tops = [i.get('value') for i in json.loads(content).get('value') if 'Top' in i.get('key')]
25- #print('om {} top1:{} top5:{}'.format(result_json.split('_')[1].split('.')[0], tops[0], tops[4]))
26- print(content)
27- elif sys.argv[1].endswith('.txt'):
28- result_txt = sys.argv[1]
29- with open(result_txt, 'r') as f:
30- content = f.read()
31- txt_data_list = [i.strip() for i in re.findall(r':(.*?),', content.replace('\n', ',') + ',')]
32- fps = float(txt_data_list[7].replace('samples/s', '')) * 4
33- print('310 bs{} fps:{}'.format(result_txt.split('_')[3], fps))
@@ -1,26 +0,0 @@
1-#!/bin/bash
2- 
3-rm -rf logs
4-mkdir logs
5- 
6-rm -rf FixRes.onnx
7-python3.7 FixRes_pth2onnx.py --pretrain_path ResNetFinetune.pth --output_name FixRes.onx
8-if [ -f "FixRes.onnx" ]; then
9- echo "onnx success"
10-else
11- echo "onnx fail!"
12-fi
13- 
14-rm -rf FixRes_bs1.om FixRes_bs16.om
15-source /usr/local/Ascend/ascend-toolkit/set_env.sh
16-# export ASCEND_SLOG_PRINT_TO_STDOUT=1
17-# export ASCEND_GLOBAL_LOG_LEVEL=1 #debug 0 --> info 1 --> warning 2 --> error 3
18-# export DUMP_GE_GRAPH=2
19-atc --framework=5 --model=FixRes.onnx --output=FixRes_bs1 --input_format=NCHW --input_shape="image:1,3,384,384" --log=debug --soc_version=Ascend310 --auto_tune_mode="RL,GA"
20-atc --framework=5 --model=FixRes.onnx --output=FixRes_bs16 --input_format=NCHW --input_shape="image:16,3,384,384" --log=debug --soc_version=Ascend310 --auto_tune_mode="RL,GA"
21- 
22-if [ -f "FixRes_bs1.om" ] && [ -f "FixRes_bs16.om" ]; then
23- echo "success"
24-else
25- echo "fail!"
26-fi