Skip to content
Snippets Groups Projects
Commit b68ac685 authored by gaozeyang's avatar gaozeyang
Browse files

add cvt model densenet resnest wide-resnet

parent 12fd816f
No related branches found
No related tags found
No related merge requests found
Showing
with 4740 additions and 0 deletions
......@@ -9,3 +9,6 @@
"models/official/cv" "missing-docstring"
"models/official/cv" "c-extension-no-member"
"models/official/nlp/bert_thor/src/bert_model.py" "redefined-outer-name"
# research
"models/research/cvtmodel" "missing-docstring"
\ No newline at end of file
......@@ -5,3 +5,20 @@
#
models/official/recommend/wide_and_deep/src/wide_and_deep.py:__init__
models/official/recommend/wide_and_deep_multitable/src/wide_and_deep.py:__init__
models/research/cvtmodel/wide_resnet/src/wide_resnet101_2.py:__init__
models/research/cvtmodel/resnest/src/resnest200.py:__init__
models/research/cvtmodel/resnest/src/resnest200.py:construct
models/research/cvtmodel/resnest/src/resnest101.py:__init__
models/research/cvtmodel/resnest/src/resnest101.py:construct
models/research/cvtmodel/resnest/src/resnest50.py:__init__
models/research/cvtmodel/resnest/src/resnest50.py:construct
models/research/cvtmodel/resnest/src/resnest269.py:__init__
models/research/cvtmodel/resnest/src/resnest269.py:construct
models/research/cvtmodel/densenet/src/densenet169.py:__init__
models/research/cvtmodel/densenet/src/densenet169.py:construct
models/research/cvtmodel/densenet/src/densenet201.py:__init__
models/research/cvtmodel/densenet/src/densenet201.py:construct
models/research/cvtmodel/densenet/src/densenet121.py:__init__
models/research/cvtmodel/densenet/src/densenet121.py:construct
models/research/cvtmodel/densenet/src/densenet161.py:__init__
models/research/cvtmodel/densenet/src/densenet161.py:construct
# Cvtmodel说明与要求
## Cvtmodel介绍
Cvtmodel文件夹中包含的模型,均是通过Mindconverter直接转换Pytorch所提供的pth模型,并实现了对该网络的Ascend 310推理。
## Cvtmodel使用流程
### 模型下载
以densenet系列网络为例, 首先需要在pytorch提供网页上找到模型的下载方式,按照指南将pth模型文件下载并转化为onnx模型文件。(参考https://pytorch.org/hub/pytorch_vision_densenet/)
### 模型转换
在成功获得onnx文件以后,使用Mindconverter对onnx进行转化,示例如下。
'''shell
export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp
mindconverter --model_file ./onnx/densenet-121.onnx --shape 1,3,224,224 --input_nodes images --output_nodes output --output ./
'''
### 模型推理
Mindconverter转换出ckpt文件后,再使用export.py脚本导出MINDIR文件,根据模型文件夹内readme所写的指令进行Ascend 310推理即可。
## 环境要求
- 硬件(Ascend/GPU)
- 准备Ascend或GPU处理器搭建硬件环境。
- 框架
- [MindSpore](https://www.mindspore.cn/install)
- [MindInsight] (https://www.mindspore.cn/mindinsight/docs/zh-CN/master/mindinsight_install.html)
- 如需查看详情,请参见如下资源:
- [MindSpore教程](https://www.mindspore.cn/tutorials/zh-CN/master/index.html)
- [MindSpore Python API](https://www.mindspore.cn/docs/api/zh-CN/master/index.html)
- [MindConverter教程] (https://www.mindspore.cn/mindinsight/docs/zh-CN/master/migrate_3rd_scripts_mindconverter.html)
\ No newline at end of file
# 目录
<!-- TOC -->
- [目录](#目录)
- [DenseNet描述](#densenet描述)
- [模型架构](#模型架构)
- [数据集](#数据集)
- [环境要求](#环境要求)
- [脚本说明](#脚本说明)
- [脚本及样例代码](#脚本及样例代码)
- [导出过程](#导出过程)
- [导出](#导出)
- [推理过程](#推理过程)
- [推理](#推理)
- [ModelZoo主页](#modelzoo主页)
<!-- /TOC -->
# DenseNet描述
DenseNet是一个基于卷积的神经网络,用于图像分类。有关该模型的描述,可查阅[此论文](https://arxiv.org/abs/1608.06993)
本仓库中是基于提供的模型文件,使用MindConverter工具转化出Mindspore框架内的ckpt文件,进行全量推理以验证模型文件精度。
模型可从网址中下载https://pytorch.org/hub/pytorch_vision_densenet/。
# 模型架构
DenseNet模型支持四种模式:DenseNet-121, DenseNet-161,DenseNet-169, DenseNet-201。数字表示网络中包含的卷积层数量。
# 数据集
DenseNet使用的数据集: ImageNet
数据集的默认配置如下:
- 测试数据集预处理:
- 图像的输入尺寸:224\*224(将图像缩放到256\*256,然后在中央区域裁剪图像)
- 根据平均值和标准偏差对输入图像进行归一化
# 环境要求
- 硬件(Ascend/GPU)
- 准备Ascend或GPU处理器搭建硬件环境。
- 框架
- [MindSpore](https://www.mindspore.cn/install)
- 如需查看详情,请参见如下资源:
- [MindSpore教程](https://www.mindspore.cn/tutorials/zh-CN/master/index.html)
- [MindSpore Python API](https://www.mindspore.cn/docs/api/zh-CN/master/index.html)
# 脚本说明
## 脚本及样例代码
```shell
├── model_zoo
├── README.md // 所有模型的说明
├── densenet
├── README_CN.md // DenseNet相关说明
├── ascend310_infer // 实现310推理源代码
├── scripts
│ ├── run_infer_310.sh // Ascend 310 推理shell脚本
├── src
│ ├── densenet121.py // densenet-121模型文件
│ ├── densenet161.py // densenet-161模型文件
│ ├── densenet169.py // densenet-169模型文件
│ ├── densenet201.py // densenet-201模型文件
├── export.py // 导出脚本
├── postprocess.py // 310 推理后处理脚本
```
## 导出过程
### 导出
```shell
python export.py --backbone [NET_NAME] --ckpt_path [CKPT_PATH] --device_target [DEVICE_TARGET] --device_id 0 --file_format [EXPORT_FORMAT] --file_name [FILE_NAME]
```
`backbone` 可选 ["densenet121", "densenet161", "densenet169", "densenet201"]
`EXPORT_FORMAT` 可选 ["AIR", "MINDIR"]
## 推理过程
### 推理
在推理之前需要先导出模型,AIR模型只能在昇腾910环境上导出,MINDIR可以在任意环境上导出。
```shell
# 昇腾310 推理
bash run_infer_310.sh [MINDIR_PATH] [DATASET] [DATA_PATH] [LABEL_FILE] [DEVICE_ID]
```
-注: Densnet系列网络使用ImageNet数据集,图片的label是将文件夹排序后从0开始编号所得的数字.
推理的结果保存在当前目录下,在acc.log日志文件中可以找到类似以下的结果。
Densenet-121网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=37244, tot=50000, acc=74.49%
after allreduce eval: top5_correct=46060, tot=50000, acc=92.12%
```
Densenet-161网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=38773, tot=50000, acc=77.55%
after allreduce eval: top5_correct=46971, tot=50000, acc=93.94%
```
Densenet-169网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=38076, tot=50000, acc=76.15%
after allreduce eval: top5_correct=46563, tot=50000, acc=93.13%
```
Densenet-201网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=38469, tot=50000, acc=76.94%
after allreduce eval: top5_correct=46776, tot=50000, acc=93.55%
```
# ModelZoo主页
请浏览官网[主页](https://gitee.com/mindspore/models)
cmake_minimum_required(VERSION 3.14.1)
project(Ascend310Infer)
add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g -std=c++17 -Werror -Wall -fPIE -Wl,--allow-shlib-undefined")
set(PROJECT_SRC_ROOT ${CMAKE_CURRENT_LIST_DIR}/)
option(MINDSPORE_PATH "mindspore install path" "")
include_directories(${MINDSPORE_PATH})
include_directories(${MINDSPORE_PATH}/include)
include_directories(${PROJECT_SRC_ROOT})
find_library(MS_LIB libmindspore.so ${MINDSPORE_PATH}/lib)
file(GLOB_RECURSE MD_LIB ${MINDSPORE_PATH}/_c_dataengine*)
add_executable(main src/main.cc src/utils.cc)
target_link_libraries(main ${MS_LIB} ${MD_LIB} gflags)
#!/bin/bash
# Copyright 2021 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.
# ============================================================================
if [ ! -d out ]; then
mkdir out
fi
cd out || exit
cmake .. \
-DMINDSPORE_PATH="`pip show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`"
make
/**
* Copyright 2021 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.
*/
#ifndef MINDSPORE_INFERENCE_UTILS_H_
#define MINDSPORE_INFERENCE_UTILS_H_
#include <sys/stat.h>
#include <dirent.h>
#include <vector>
#include <string>
#include <memory>
#include "include/api/types.h"
std::vector<std::string> GetAllFiles(std::string_view dirName);
DIR *OpenDir(std::string_view dirName);
std::string RealPath(std::string_view path);
mindspore::MSTensor ReadFileToTensor(const std::string &file);
int WriteResult(const std::string& imageFile, const std::vector<mindspore::MSTensor> &outputs);
#endif
/**
* Copyright 2021 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.
*/
#include <sys/time.h>
#include <gflags/gflags.h>
#include <dirent.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <iosfwd>
#include <vector>
#include <fstream>
#include "../inc/utils.h"
#include "include/dataset/execute.h"
#include "include/dataset/transforms.h"
#include "include/dataset/vision.h"
#include "include/dataset/vision_ascend.h"
#include "include/api/types.h"
#include "include/api/model.h"
#include "include/api/serialization.h"
#include "include/api/context.h"
using mindspore::Serialization;
using mindspore::Model;
using mindspore::Context;
using mindspore::Status;
using mindspore::ModelType;
using mindspore::Graph;
using mindspore::GraphCell;
using mindspore::kSuccess;
using mindspore::MSTensor;
using mindspore::DataType;
using mindspore::dataset::Execute;
using mindspore::dataset::TensorTransform;
using mindspore::dataset::vision::Decode;
using mindspore::dataset::vision::Resize;
using mindspore::dataset::vision::CenterCrop;
using mindspore::dataset::vision::Normalize;
using mindspore::dataset::vision::HWC2CHW;
using mindspore::dataset::transforms::TypeCast;
DEFINE_string(model_path, "", "model path");
DEFINE_string(dataset, "ImageNet", "dataset: ImageNet or Cifar10");
DEFINE_string(dataset_path, ".", "dataset path");
DEFINE_int32(device_id, 0, "device id");
int main(int argc, char **argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (RealPath(FLAGS_model_path).empty()) {
std::cout << "Invalid model" << std::endl;
return 1;
}
std::transform(FLAGS_dataset.begin(), FLAGS_dataset.end(), FLAGS_dataset.begin(), ::tolower);
auto context = std::make_shared<Context>();
auto ascend310_info = std::make_shared<mindspore::Ascend310DeviceInfo>();
ascend310_info->SetDeviceID(FLAGS_device_id);
context->MutableDeviceInfo().push_back(ascend310_info);
Graph graph;
Status ret = Serialization::Load(FLAGS_model_path, ModelType::kMindIR, &graph);
if (ret != kSuccess) {
std::cout << "Load model failed." << std::endl;
return 1;
}
Model model;
ret = model.Build(GraphCell(graph), context);
if (ret != kSuccess) {
std::cout << "ERROR: Build failed." << std::endl;
return 1;
}
std::vector<MSTensor> modelInputs = model.GetInputs();
auto all_files = GetAllFiles(FLAGS_dataset_path);
if (all_files.empty()) {
std::cout << "ERROR: no input data." << std::endl;
return 1;
}
std::shared_ptr<TensorTransform> decode(new Decode());
std::shared_ptr<TensorTransform> resize(new Resize({256, 256}));
std::shared_ptr<TensorTransform> centerCrop(new CenterCrop({224, 224}));
std::shared_ptr<TensorTransform> normImageNet(new Normalize({123.675, 116.28, 103.53}, {58.395, 57.12, 57.375}));
std::shared_ptr<TensorTransform> normCifar10(new Normalize({127.5, 127.5, 127.5}, {127.5, 127.5, 127.5}));
std::shared_ptr<TensorTransform> hwc2chw(new HWC2CHW());
mindspore::dataset::Execute transformImageNet({decode, resize, centerCrop, normImageNet, hwc2chw});
mindspore::dataset::Execute transformCifar10({decode, normCifar10, hwc2chw});
std::map<double, double> costTime_map;
size_t size = all_files.size();
for (size_t i = 0; i < size; ++i) {
struct timeval start;
struct timeval end;
double startTime_ms;
double endTime_ms;
std::vector<MSTensor> inputs;
std::vector<MSTensor> outputs;
std::cout << "Start predict input files:" << all_files[i] << std::endl;
mindspore::MSTensor image = ReadFileToTensor(all_files[i]);
if (FLAGS_dataset.compare("cifar10") == 0) {
transformCifar10(image, &image);
} else if (FLAGS_dataset.compare("imagenet") == 0) {
transformImageNet(image, &image);
} else {
std::cout << "unsupported dataset ...";
return 1;
}
inputs.emplace_back(modelInputs[0].Name(), modelInputs[0].DataType(), modelInputs[0].Shape(),
image.Data().get(), image.DataSize());
gettimeofday(&start, NULL);
model.Predict(inputs, &outputs);
gettimeofday(&end, NULL);
startTime_ms = (1.0 * start.tv_sec * 1000000 + start.tv_usec) / 1000;
endTime_ms = (1.0 * end.tv_sec * 1000000 + end.tv_usec) / 1000;
costTime_map.insert(std::pair<double, double>(startTime_ms, endTime_ms));
int rst = WriteResult(all_files[i], outputs);
if (rst != 0) {
std::cout << "write result failed." << std::endl;
return rst;
}
}
double average = 0.0;
int infer_cnt = 0;
char tmpCh[256] = {0};
for (auto iter = costTime_map.begin(); iter != costTime_map.end(); iter++) {
double diff = 0.0;
diff = iter->second - iter->first;
average += diff;
infer_cnt++;
}
average = average/infer_cnt;
std::cout << "NN inference cost average time: "<< average << "ms of infer_count " << infer_cnt << std::endl;
std::string file_name = "./time_Result" + std::string("/test_perform_static.txt");
std::ofstream file_stream(file_name.c_str(), std::ios::trunc);
file_stream << tmpCh;
file_stream.close();
costTime_map.clear();
return 0;
}
/**
* Copyright 2021 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.
*/
#include "inc/utils.h"
#include <fstream>
#include <algorithm>
#include <iostream>
using mindspore::MSTensor;
using mindspore::DataType;
std::vector<std::string> GetAllFiles(std::string_view dirName) {
struct dirent *filename;
DIR *dir = OpenDir(dirName);
if (dir == nullptr) {
return {};
}
std::vector<std::string> dirs;
std::vector<std::string> files;
while ((filename = readdir(dir)) != nullptr) {
std::string dName = std::string(filename->d_name);
if (dName == "." || dName == "..") {
continue;
} else if (filename->d_type == DT_DIR) {
dirs.emplace_back(std::string(dirName) + "/" + filename->d_name);
} else if (filename->d_type == DT_REG) {
files.emplace_back(std::string(dirName) + "/" + filename->d_name);
} else {
continue;
}
}
for (auto d : dirs) {
dir = OpenDir(d);
while ((filename = readdir(dir)) != nullptr) {
std::string dName = std::string(filename->d_name);
if (dName == "." || dName == ".." || filename->d_type != DT_REG) {
continue;
}
files.emplace_back(std::string(d) + "/" + filename->d_name);
}
}
std::sort(files.begin(), files.end());
for (auto &f : files) {
std::cout << "image file: " << f << std::endl;
}
return files;
}
int WriteResult(const std::string& imageFile, const std::vector<MSTensor> &outputs) {
std::string homePath = "./result_Files";
const int INVALID_POINTER = -1;
const int ERROR = -2;
for (size_t i = 0; i < outputs.size(); ++i) {
size_t outputSize;
std::shared_ptr<const void> netOutput;
netOutput = outputs[i].Data();
outputSize = outputs[i].DataSize();
int pos = imageFile.rfind('/');
std::string fileName(imageFile, pos + 1);
fileName.replace(fileName.find('.'), fileName.size() - fileName.find('.'), '_' + std::to_string(i) + ".bin");
std::string outFileName = homePath + "/" + fileName;
FILE * outputFile = fopen(outFileName.c_str(), "wb");
if (outputFile == nullptr) {
std::cout << "open result file " << outFileName << " failed" << std::endl;
return INVALID_POINTER;
}
size_t size = fwrite(netOutput.get(), sizeof(char), outputSize, outputFile);
if (size != outputSize) {
fclose(outputFile);
outputFile = nullptr;
std::cout << "write result file " << outFileName << " failed, write size[" << size <<
"] is smaller than output size[" << outputSize << "], maybe the disk is full." << std::endl;
return ERROR;
}
fclose(outputFile);
outputFile = nullptr;
}
return 0;
}
mindspore::MSTensor ReadFileToTensor(const std::string &file) {
if (file.empty()) {
std::cout << "Pointer file is nullptr" << std::endl;
return mindspore::MSTensor();
}
std::ifstream ifs(file);
if (!ifs.good()) {
std::cout << "File: " << file << " is not exist" << std::endl;
return mindspore::MSTensor();
}
if (!ifs.is_open()) {
std::cout << "File: " << file << "open failed" << std::endl;
return mindspore::MSTensor();
}
ifs.seekg(0, std::ios::end);
size_t size = ifs.tellg();
mindspore::MSTensor buffer(file, mindspore::DataType::kNumberTypeUInt8, {static_cast<int64_t>(size)}, nullptr, size);
ifs.seekg(0, std::ios::beg);
ifs.read(reinterpret_cast<char *>(buffer.MutableData()), size);
ifs.close();
return buffer;
}
DIR *OpenDir(std::string_view dirName) {
if (dirName.empty()) {
std::cout << " dirName is null ! " << std::endl;
return nullptr;
}
std::string realPath = RealPath(dirName);
struct stat s;
lstat(realPath.c_str(), &s);
if (!S_ISDIR(s.st_mode)) {
std::cout << "dirName is not a valid directory !" << std::endl;
return nullptr;
}
DIR *dir;
dir = opendir(realPath.c_str());
if (dir == nullptr) {
std::cout << "Can not open dir " << dirName << std::endl;
return nullptr;
}
std::cout << "Successfully opened the dir " << dirName << std::endl;
return dir;
}
std::string RealPath(std::string_view path) {
char realPathMem[PATH_MAX] = {0};
char *realPathRet = nullptr;
realPathRet = realpath(path.data(), realPathMem);
if (realPathRet == nullptr) {
std::cout << "File: " << path << " is not exist.";
return "";
}
std::string realPath(realPathMem);
std::cout << path << " realpath is: " << realPath << std::endl;
return realPath;
}
# Copyright 2020-2021 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.
# ============================================================================
"""export checkpoint file into air, onnx, mindir models
Suggest run as python export.py --file_name [file_name] --ckpt_files [ckpt path] --file_format [file format]
"""
import argparse
import numpy as np
import mindspore as ms
from mindspore import context, Tensor
from mindspore.train.serialization import export, load_checkpoint, load_param_into_net
parser = argparse.ArgumentParser(description='post process for 310 inference')
parser.add_argument("--backbone", type=str, required=True, default="densenet161", help="model backbone")
parser.add_argument("--ckpt_path", type=str, required=True, help="checkpoint file path")
parser.add_argument("--file_name", type=str, default="densenet161", help="file name")
parser.add_argument("--file_format", type=str, default="MINDIR", choices=["MINDIR", "AIR"], help="file format")
parser.add_argument("--device_target", type=str, default="Ascend", choices=["Ascend", "GPU"], help="device target")
parser.add_argument("--device_id", type=int, default=0, help="device target")
args = parser.parse_args()
context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
def model_export():
'''main export func'''
if args.device_target == "Ascend":
context.set_context(device_id=args.device_id)
if args.backbone == "densenet121":
from src.densenet121 import MainModel
elif args.backbone == "densenet161":
from src.densenet161 import MainModel
elif args.backbone == "densenet169":
from src.densenet169 import MainModel
elif args.backbone == "densenet201":
from src.densenet201 import MainModel
net = MainModel()
param_dict = load_checkpoint(args.ckpt_path)
load_param_into_net(net, param_dict)
input_arr = Tensor(np.zeros([1, 3, 224, 224]), ms.float32)
export(net, input_arr, file_name=args.file_name, file_format=args.file_format)
if __name__ == '__main__':
model_export()
# Copyright 2021 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.
# ============================================================================
'''post process for 310 inference'''
import os
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='post process for 310 inference')
parser.add_argument("--dataset", type=str, default="imagenet", help="result file path")
parser.add_argument("--result_path", type=str, required=True, help="result file path")
parser.add_argument("--label_file", type=str, required=True, help="label file")
args = parser.parse_args()
def get_top5_acc(top5_arg, gt_class):
sub_count = 0
for top5, gt in zip(top5_arg, gt_class):
if gt in top5:
sub_count += 1
return sub_count
def read_label(label_file):
'''read label file'''
f = open(label_file, "r")
lines = f.readlines()
img_label = {}
for line in lines:
img_id = line.split(":")[0]
label = line.split(":")[1]
img_label[img_id] = label
return img_label
def cal_acc(dataset, result_path, label_file):
'''main acc calculation function'''
img_label = read_label(label_file)
img_tot = 0
top1_correct = 0
top5_correct = 0
files = os.listdir(result_path)
for file in files:
full_file_path = os.path.join(result_path, file)
if os.path.isfile(full_file_path):
result = np.fromfile(full_file_path, dtype=np.float32).reshape(1, 1000)
gt_classes = int(img_label[file[:-6]])
top1_output = np.argmax(result, (-1))
top5_output = np.argsort(result)[:, -5:]
t1_correct = np.equal(top1_output, gt_classes).sum()
top1_correct += t1_correct
top5_correct += get_top5_acc(top5_output, [gt_classes])
img_tot += 1
results = [[top1_correct], [top5_correct], [img_tot]]
results = np.array(results)
top1_correct = results[0, 0]
top5_correct = results[1, 0]
img_tot = results[2, 0]
acc1 = 100.0 * top1_correct / img_tot
acc5 = 100.0 * top5_correct / img_tot
print('after allreduce eval: top1_correct={}, tot={}, acc={:.2f}%'.format(top1_correct, img_tot, acc1))
if dataset == 'imagenet':
print('after allreduce eval: top5_correct={}, tot={}, acc={:.2f}%'.format(top5_correct, img_tot, acc5))
if __name__ == "__main__":
cal_acc(args.dataset, args.result_path, args.label_file)
#!/bin/bash
# Copyright 2021 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.
# ============================================================================
if [[ $# -lt 4 || $# -gt 5 ]]; then
echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [DATASET] [DATA_PATH] [LABEL_FILE] [DEVICE_ID]
DEVICE_ID is optional, it can be set by environment variable device_id, otherwise the value is zero"
exit 1
fi
get_real_path(){
if [ "${1:0:1}" == "/" ]; then
echo "$1"
else
echo "$(realpath -m $PWD/$1)"
fi
}
model=$(get_real_path $1)
dataset=$2
data_path=$(get_real_path $3)
label_file=$(get_real_path $4)
device_id=0
if [ $# == 4 ]; then
device_id=$4
fi
echo $model
echo $dataset
echo $data_path
echo $label_file
echo $device_id
export ASCEND_HOME=/usr/local/Ascend/
if [ -d ${ASCEND_HOME}/ascend-toolkit ]; then
export PATH=$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/ascend-toolkit/latest/atc/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/lib:$ASCEND_HOME/ascend-toolkit/latest/atc/lib64:$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/lib64:$ASCEND_HOME/driver/lib64:$ASCEND_HOME/add-ons:$LD_LIBRARY_PATH
export TBE_IMPL_PATH=$ASCEND_HOME/ascend-toolkit/latest/opp/op_impl/built-in/ai_core/tbe
export PYTHONPATH=${TBE_IMPL_PATH}:$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/python/site-packages:$PYTHONPATH
export ASCEND_OPP_PATH=$ASCEND_HOME/ascend-toolkit/latest/opp
else
export PATH=$ASCEND_HOME/atc/ccec_compiler/bin:$ASCEND_HOME/atc/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/lib:$ASCEND_HOME/atc/lib64:$ASCEND_HOME/acllib/lib64:$ASCEND_HOME/driver/lib64:$ASCEND_HOME/add-ons:$LD_LIBRARY_PATH
export PYTHONPATH=$ASCEND_HOME/atc/python/site-packages:$PYTHONPATH
export ASCEND_OPP_PATH=$ASCEND_HOME/opp
fi
function compile_app()
{
cd ../ascend310_infer || exit
if [ -f "Makefile" ]; then
make clean
fi
sh build.sh &> build.log
if [ $? -ne 0 ]; then
echo "compile app code failed"
exit 1
fi
cd - || exit
}
function infer()
{
if [ -d result_Files ]; then
rm -rf ./result_Files
fi
if [ -d time_Result ]; then
rm -rf ./time_Result
fi
mkdir result_Files
mkdir time_Result
../ascend310_infer/out/main --model_path=$model --dataset=$dataset --dataset_path=$data_path --device_id=$device_id &> infer.log
if [ $? -ne 0 ]; then
echo "execute inference failed"
exit 1
fi
}
function cal_acc()
{
python ../postprocess.py --dataset=$dataset --label_file=$label_file --result_path=result_Files &> acc.log
if [ $? -ne 0 ]; then
echo "calculate accuracy failed"
exit 1
fi
}
compile_app
infer
cal_acc
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# 目录
<!-- TOC -->
- [目录](#目录)
- [ResNeSt描述](#resnest描述)
- [模型架构](#模型架构)
- [数据集](#数据集)
- [环境要求](#环境要求)
- [脚本说明](#脚本说明)
- [脚本及样例代码](#脚本及样例代码)
- [导出过程](#导出过程)
- [导出](#导出)
- [推理过程](#推理过程)
- [推理](#推理)
- [ModelZoo主页](#modelzoo主页)
<!-- /TOC -->
# ResNeSt描述
ResNeSt是一个基于卷积的神经网络,用于图像分类。有关该模型的描述,可查阅(https://pytorch.org/hub/pytorch_vision_resnest/)。
本仓库中是基于torch提供的模型文件,使用MindConverter工具转化出Mindspore来ckpt文件,进行全量推理以验证模型文件精度。
# 模型架构
ResNeSt模型支持四种模式:ResNeSt-50, ResNeSt-101,ResNeSt-201, ResNeSt-269。
# 数据集
ResNeSt使用的数据集: ImageNet
数据集的默认配置如下:
- 测试数据集预处理:
- 图像的输入尺寸(ResNeSt-50):224\*224(将图像缩放到256\*256,然后在中央区域裁剪图像)
- 图像的输入尺寸(ResNeSt-101):256\*256(将图像缩放到256\*256,然后在中央区域裁剪图像)
- 图像的输入尺寸(ResNeSt-200):320\*320(将图像缩放到320\*320,然后在中央区域裁剪图像)
- 图像的输入尺寸(ResNeSt-269):416\*416(将图像缩放到416\*416,然后在中央区域裁剪图像)
- 根据平均值和标准偏差对输入图像进行归一化
# 环境要求
- 硬件(Ascend/GPU)
- 准备Ascend或GPU处理器搭建硬件环境。
- 框架
- [MindSpore](https://www.mindspore.cn/install)
- 如需查看详情,请参见如下资源:
- [MindSpore教程](https://www.mindspore.cn/tutorials/zh-CN/master/index.html)
- [MindSpore Python API](https://www.mindspore.cn/docs/api/zh-CN/master/index.html)
# 脚本说明
## 脚本及样例代码
```shell
├── model_zoo
├── README.md // 所有模型的说明
├── ResNeSt
├── README_CN.md // ResNeSt相关说明
├── ascend310_infer // 实现310推理源代码
├── scripts
│ ├── run_infer_310.sh // Ascend 310 推理shell脚本
├── src
│ ├── resnest50.py // resnest-50模型文件
│ ├── resnest101.py // resnest-101模型文件
│ ├── resnest200.py // resnest-200模型文件
│ ├── resnest269.py // resnest-269模型文件
├── export.py // 导出脚本
├── postprocess.py // 310 推理后处理脚本
```
## 导出过程
### 导出
```shell
python export.py --backbone [NET_NAME] --ckpt_path [CKPT_PATH] --device_target [DEVICE_TARGET] --device_id 0 --file_format [EXPORT_FORMAT] --file_name [FILE_NAME]
```
`backbone` 可选 ["ResNeSt50", "ResNeSt101", "ResNeSt200", "ResNeSt269"]
`EXPORT_FORMAT` 可选 ["AIR", "MINDIR"]
## 推理过程
### 推理
在推理之前需要先导出模型,AIR模型只能在昇腾910环境上导出,MINDIR可以在任意环境上导出。
```shell
# 昇腾310 推理
bash run_infer_310.sh [MINDIR_PATH] [BACKBONE] [DATASET] [DATA_PATH] [LABEL_FILE] [DEVICE_ID]
```
-注: Densnet系列网络使用ImageNet数据集,图片的label是将文件夹排序后从0开始编号所得的数字.
推理的结果保存在当前目录下,在acc.log日志文件中可以找到类似以下的结果。
ResNeSt-50网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=40560, tot=50000, acc=81.12%
after allreduce eval: top5_correct=47792, tot=50000, acc=95.58%
```
ResNeSt-101网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=41330, tot=50000, acc=82.66%
after allreduce eval: top5_correct=48151, tot=50000, acc=96.30%
```
ResNeSt-200网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=42082, tot=50000, acc=84.16%
after allreduce eval: top5_correct=48469, tot=50000, acc=96.94%
```
ResNeSt-269网络使用ImageNet推理得到的结果如下:
```log
after allreduce eval: top1_correct=42288, tot=50000, acc=84.58%
after allreduce eval: top5_correct=48562, tot=50000, acc=97.12%
```
# ModelZoo主页
请浏览官网[主页](https://gitee.com/mindspore/models)
cmake_minimum_required(VERSION 3.14.1)
project(Ascend310Infer)
add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g -std=c++17 -Werror -Wall -fPIE -Wl,--allow-shlib-undefined")
set(PROJECT_SRC_ROOT ${CMAKE_CURRENT_LIST_DIR}/)
option(MINDSPORE_PATH "mindspore install path" "")
include_directories(${MINDSPORE_PATH})
include_directories(${MINDSPORE_PATH}/include)
include_directories(${PROJECT_SRC_ROOT})
find_library(MS_LIB libmindspore.so ${MINDSPORE_PATH}/lib)
file(GLOB_RECURSE MD_LIB ${MINDSPORE_PATH}/_c_dataengine*)
add_executable(main src/main.cc src/utils.cc)
target_link_libraries(main ${MS_LIB} ${MD_LIB} gflags)
#!/bin/bash
# Copyright 2021 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.
# ============================================================================
if [ ! -d out ]; then
mkdir out
fi
cd out || exit
cmake .. \
-DMINDSPORE_PATH="`pip show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`"
make
/**
* Copyright 2021 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.
*/
#ifndef MINDSPORE_INFERENCE_UTILS_H_
#define MINDSPORE_INFERENCE_UTILS_H_
#include <sys/stat.h>
#include <dirent.h>
#include <vector>
#include <string>
#include <memory>
#include "include/api/types.h"
std::vector<std::string> GetAllFiles(std::string_view dirName);
DIR *OpenDir(std::string_view dirName);
std::string RealPath(std::string_view path);
mindspore::MSTensor ReadFileToTensor(const std::string &file);
int WriteResult(const std::string& imageFile, const std::vector<mindspore::MSTensor> &outputs);
#endif
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment