From 0126a6e963fa4939e83bb22e464b51024fa8e962 Mon Sep 17 00:00:00 2001 From: chenweitao_295 Date: Wed, 16 Jun 2021 16:02:45 +0800 Subject: [PATCH] SE-net add 310 infer --- model_zoo/research/cv/SE-Net/README.md | 59 ++++++- .../cv/SE-Net/ascend310_infer/CMakeLists.txt | 14 ++ .../cv/SE-Net/ascend310_infer/build.sh | 23 +++ .../cv/SE-Net/ascend310_infer/inc/utils.h | 32 ++++ .../cv/SE-Net/ascend310_infer/src/main.cc | 158 ++++++++++++++++++ .../cv/SE-Net/ascend310_infer/src/utils.cc | 130 ++++++++++++++ model_zoo/research/cv/SE-Net/export.py | 2 +- model_zoo/research/cv/SE-Net/postprocess.py | 73 ++++++++ .../cv/SE-Net/scripts/run_infer_310.sh | 107 ++++++++++++ 9 files changed, 596 insertions(+), 2 deletions(-) create mode 100644 model_zoo/research/cv/SE-Net/ascend310_infer/CMakeLists.txt create mode 100644 model_zoo/research/cv/SE-Net/ascend310_infer/build.sh create mode 100644 model_zoo/research/cv/SE-Net/ascend310_infer/inc/utils.h create mode 100644 model_zoo/research/cv/SE-Net/ascend310_infer/src/main.cc create mode 100644 model_zoo/research/cv/SE-Net/ascend310_infer/src/utils.cc create mode 100644 model_zoo/research/cv/SE-Net/postprocess.py create mode 100644 model_zoo/research/cv/SE-Net/scripts/run_infer_310.sh diff --git a/model_zoo/research/cv/SE-Net/README.md b/model_zoo/research/cv/SE-Net/README.md index b33da92531a..7cbdf150b48 100644 --- a/model_zoo/research/cv/SE-Net/README.md +++ b/model_zoo/research/cv/SE-Net/README.md @@ -12,10 +12,15 @@ - [Script Parameters](#script-parameters) - [Training Process](#training-process) - [Evaluation Process](#evaluation-process) + - [Inference Process](#inference-process) + - [Export MindIR](#export-mindir) + - [Infer on Ascend310](#infer-on-ascend310) + - [result](#result) - [Model Description](#model-description) - [Performance](#performance) - [Evaluation Performance](#evaluation-performance) - [Inference Performance](#inference-performance) + - [310Inference Performance](#310inference-performance) - [Description of Random Situation](#description-of-random-situation) - [ModelZoo Homepage](#modelzoo-homepage) @@ -91,19 +96,22 @@ python eval.py --net=se-resnet50 --dataset=imagenet2012 --checkpoint_path=[CHECK . └──SE-Net ├── README.md + ├── ascend310_infer # application for 310 inference ├── scripts ├── run_distribute_train.sh # launch ascend distributed training(8 pcs) ├── run_eval.sh # launch ascend evaluation ├── run_standalone_train.sh # launch ascend standalone training(1 pcs) + └─ run_infer_310.sh # shell script for 310inference on ascend ├── src ├── config.py # parameter configuration ├── CrossEntropySmooth.py # loss definition for ImageNet2012 dataset ├── dataset.py # data preprocessing ├── lr_generator.py # generate learning rate for each step ├── resnet.py # resnet50 backbone - └── se.py # se-block definition + └── se.py # se-block definition ├── export.py # export model for inference ├── eval.py # eval net + ├── postprocess.py # postprocess scripts └── train.py # train net ``` @@ -195,6 +203,39 @@ bash run_eval.sh /imagenet/val/ /path/to/resnet-90_625.ckpt result: {'top_5_accuracy': 0.9385269007731959, 'top_1_accuracy': 0.7774645618556701} ``` +## [Inference Process](#contents) + +### Export MindIR + +```shell +python export.py --ckpt_file [CKPT_PATH] --batch_size [BATCH_SIZE] --file_format [FILE_FORMAT] +``` + +The ckpt_file parameter is required, +`FILE_FORMAT` should be in ["AIR", "MINDIR"] +`BATCH_SIZE` current batch_size can only be set to 1. + +### Infer on Ascend310 + +Before performing inference, the mindir file must be exported by `export.py` script. We only provide an example of inference using MINDIR model. + +```shell +# Ascend310 inference +bash run_infer_310.sh [MINDIR_PATH] [DATA_PATH] [LABEL_FILE] [DVPP] [DEVICE_ID] +``` + +- `LABEL_FILE` label.txt path. Write a py script to sort the category under the dataset, map the file names under the categories and category sort values,Such as[file name : sort value], and write the mapping results to the labe.txt file. +- `DVPP` is mandatory, and must choose from ["DVPP", "CPU"], it's case-insensitive. SE-net only support CPU mode. +- `DEVICE_ID` is optional, default value is 0. + +### result + +Inference result is saved in current path, you can find result like this in acc.log file. + +```bash +result: {'top_5_accuracy': 93.86%, 'top_1_accuracy': 77.80%} +``` + # [Model Description](#contents) ## [Performance](#contents) @@ -236,6 +277,22 @@ result: {'top_5_accuracy': 0.9385269007731959, 'top_1_accuracy': 0.7774645618556 | Accuracy | 77.74% | | Model for inference | # (.air file) | +### 310Inference Performance + +#### SE-ResNet50 on ImageNet2012 + +| Parameters | Ascend | +| ------------------- | --------------------------- | +| Model Version | SE-ResNet50 | +| Resource | Ascend 310; OS Euler2.8 | +| Uploaded Date | 06/16/2021 (month/day/year) | +| MindSpore Version | 1.2.0 | +| Dataset | ImageNet2012 | +| batch_size | 1 | +| outputs | Accuracy | +| Accuracy | 77.80% | +| Model for inference | 285M(.ckpt file) | + # [Description of Random Situation](#contents) In dataset.py, we set the seed inside "create_dataset" function. We also use random seed in train.py. diff --git a/model_zoo/research/cv/SE-Net/ascend310_infer/CMakeLists.txt b/model_zoo/research/cv/SE-Net/ascend310_infer/CMakeLists.txt new file mode 100644 index 00000000000..ee3c8544734 --- /dev/null +++ b/model_zoo/research/cv/SE-Net/ascend310_infer/CMakeLists.txt @@ -0,0 +1,14 @@ +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) diff --git a/model_zoo/research/cv/SE-Net/ascend310_infer/build.sh b/model_zoo/research/cv/SE-Net/ascend310_infer/build.sh new file mode 100644 index 00000000000..770a8851efa --- /dev/null +++ b/model_zoo/research/cv/SE-Net/ascend310_infer/build.sh @@ -0,0 +1,23 @@ +#!/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 diff --git a/model_zoo/research/cv/SE-Net/ascend310_infer/inc/utils.h b/model_zoo/research/cv/SE-Net/ascend310_infer/inc/utils.h new file mode 100644 index 00000000000..efebe03a8c1 --- /dev/null +++ b/model_zoo/research/cv/SE-Net/ascend310_infer/inc/utils.h @@ -0,0 +1,32 @@ +/** + * 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 +#include +#include +#include +#include +#include "include/api/types.h" + +std::vector 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 &outputs); +#endif diff --git a/model_zoo/research/cv/SE-Net/ascend310_infer/src/main.cc b/model_zoo/research/cv/SE-Net/ascend310_infer/src/main.cc new file mode 100644 index 00000000000..63de8d92bff --- /dev/null +++ b/model_zoo/research/cv/SE-Net/ascend310_infer/src/main.cc @@ -0,0 +1,158 @@ +/** + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "include/api/model.h" +#include "include/api/context.h" +#include "include/api/types.h" +#include "include/api/serialization.h" +#include "include/dataset/vision_ascend.h" +#include "include/dataset/execute.h" +#include "include/dataset/vision.h" +#include "inc/utils.h" + +using mindspore::Context; +using mindspore::Serialization; +using mindspore::Model; +using mindspore::Status; +using mindspore::ModelType; +using mindspore::GraphCell; +using mindspore::kSuccess; +using mindspore::MSTensor; +using mindspore::dataset::Execute; +using mindspore::dataset::MapTargetDevice; +using mindspore::dataset::TensorTransform; +using mindspore::dataset::vision::Resize; +using mindspore::dataset::vision::HWC2CHW; +using mindspore::dataset::vision::Normalize; +using mindspore::dataset::vision::Decode; +using mindspore::dataset::vision::CenterCrop; + + + +DEFINE_string(mindir_path, "", "mindir path"); +DEFINE_string(dataset_path, ".", "dataset path"); +DEFINE_int32(device_id, 0, "device id"); +DEFINE_string(aipp_path, "../../scripts/aipp.cfg", "aipp path"); +DEFINE_string(cpu_dvpp, "", "cpu or dvpp process"); +DEFINE_int32(image_height, 224, "image height"); +DEFINE_int32(image_width, 224, "image width"); + +int main(int argc, char **argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + if (RealPath(FLAGS_mindir_path).empty()) { + std::cout << "Invalid mindir" << std::endl; + return 1; + } + + auto context = std::make_shared(); + auto ascend310 = std::make_shared(); + ascend310->SetDeviceID(FLAGS_device_id); + ascend310->SetBufferOptimizeMode("off_optimize"); + context->MutableDeviceInfo().push_back(ascend310); + mindspore::Graph graph; + Serialization::Load(FLAGS_mindir_path, ModelType::kMindIR, &graph); + if (FLAGS_cpu_dvpp == "DVPP") { + if (RealPath(FLAGS_aipp_path).empty()) { + std::cout << "Invalid aipp path" << std::endl; + return 1; + } else { + ascend310->SetInsertOpConfigPath(FLAGS_aipp_path); + } + } + + Model model; + Status ret = model.Build(GraphCell(graph), context); + if (ret != kSuccess) { + std::cout << "ERROR: Build failed." << std::endl; + return 1; + } + + auto decode = Decode(); + auto resize = Resize({256}); + auto center_crop = CenterCrop({FLAGS_image_height, FLAGS_image_width}); + auto normalize = Normalize({123.675, 116.28, 103.53}, {58.395, 57.120, 57.375}); + auto hwc2chw = HWC2CHW(); + Execute dvpptransform({decode, resize, center_crop, normalize}, MapTargetDevice::kAscend310); + Execute transform({decode, resize, center_crop, normalize, hwc2chw}); + + auto all_files = GetAllFiles(FLAGS_dataset_path); + std::map costTime_map; + size_t size = all_files.size(); + + for (size_t i = 0; i < size; ++i) { + struct timeval start = {0}; + struct timeval end = {0}; + double startTimeMs; + double endTimeMs; + std::vector inputs; + std::vector outputs; + std::cout << "Start predict input files:" << all_files[i] << std::endl; + if (FLAGS_cpu_dvpp == "DVPP") { + auto imgDvpp = std::make_shared(); + dvpptransform(ReadFileToTensor(all_files[i]), imgDvpp.get()); + inputs.emplace_back(imgDvpp->Name(), imgDvpp->DataType(), imgDvpp->Shape(), + imgDvpp->Data().get(), imgDvpp->DataSize()); + } else { + auto img = MSTensor(); + auto image = ReadFileToTensor(all_files[i]); + transform(image, &img); + std::vector model_inputs = model.GetInputs(); + inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(), + img.Data().get(), img.DataSize()); + } + + gettimeofday(&start, nullptr); + ret = model.Predict(inputs, &outputs); + gettimeofday(&end, nullptr); + if (ret != kSuccess) { + std::cout << "Predict " << all_files[i] << " failed." << std::endl; + return 1; + } + startTimeMs = (1.0 * start.tv_sec * 1000000 + start.tv_usec) / 1000; + endTimeMs = (1.0 * end.tv_sec * 1000000 + end.tv_usec) / 1000; + costTime_map.insert(std::pair(startTimeMs, endTimeMs)); + WriteResult(all_files[i], outputs); + } + double average = 0.0; + int inferCount = 0; + + for (auto iter = costTime_map.begin(); iter != costTime_map.end(); iter++) { + double diff = 0.0; + diff = iter->second - iter->first; + average += diff; + inferCount++; + } + average = average / inferCount; + std::stringstream timeCost; + timeCost << "NN inference cost average time: "<< average << " ms of infer_count " << inferCount << std::endl; + std::cout << "NN inference cost average time: "<< average << "ms of infer_count " << inferCount << std::endl; + std::string fileName = "./time_Result" + std::string("/test_perform_static.txt"); + std::ofstream fileStream(fileName.c_str(), std::ios::trunc); + fileStream << timeCost.str(); + fileStream.close(); + costTime_map.clear(); + return 0; +} diff --git a/model_zoo/research/cv/SE-Net/ascend310_infer/src/utils.cc b/model_zoo/research/cv/SE-Net/ascend310_infer/src/utils.cc new file mode 100644 index 00000000000..b509c57f823 --- /dev/null +++ b/model_zoo/research/cv/SE-Net/ascend310_infer/src/utils.cc @@ -0,0 +1,130 @@ +/** + * 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 +#include +#include + +using mindspore::MSTensor; +using mindspore::DataType; + +std::vector GetAllFiles(std::string_view dirName) { + struct dirent *filename; + DIR *dir = OpenDir(dirName); + if (dir == nullptr) { + return {}; + } + std::vector res; + while ((filename = readdir(dir)) != nullptr) { + std::string dName = std::string(filename->d_name); + if (dName == "." || dName == ".." || filename->d_type != DT_REG) { + continue; + } + res.emplace_back(std::string(dirName) + "/" + filename->d_name); + } + std::sort(res.begin(), res.end()); + for (auto &f : res) { + std::cout << "image file: " << f << std::endl; + } + return res; +} + +int WriteResult(const std::string& imageFile, const std::vector &outputs) { + std::string homePath = "./result_Files"; + for (size_t i = 0; i < outputs.size(); ++i) { + size_t outputSize; + std::shared_ptr 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"); + fwrite(netOutput.get(), outputSize, sizeof(char), outputFile); + 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(size)}, nullptr, size); + + ifs.seekg(0, std::ios::beg); + ifs.read(reinterpret_cast(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; +} diff --git a/model_zoo/research/cv/SE-Net/export.py b/model_zoo/research/cv/SE-Net/export.py index 4b1785e2f6b..429c09e1cef 100644 --- a/model_zoo/research/cv/SE-Net/export.py +++ b/model_zoo/research/cv/SE-Net/export.py @@ -32,7 +32,7 @@ parser.add_argument("--ckpt_file", type=str, required=True, help="Checkpoint fil parser.add_argument("--file_name", type=str, default="resnet", help="output file name.") parser.add_argument('--width', type=int, default=224, help='input width') parser.add_argument('--height', type=int, default=224, help='input height') -parser.add_argument("--file_format", type=str, choices=["AIR", "ONNX", "MINDIR"], default="AIR", help="file format") +parser.add_argument("--file_format", type=str, choices=["AIR", "MINDIR"], default="AIR", help="file format") parser.add_argument("--device_target", type=str, default="Ascend", choices=["Ascend", "GPU", "CPU"], help="device target(default: Ascend)") args = parser.parse_args() diff --git a/model_zoo/research/cv/SE-Net/postprocess.py b/model_zoo/research/cv/SE-Net/postprocess.py new file mode 100644 index 00000000000..c5d97b13286 --- /dev/null +++ b/model_zoo/research/cv/SE-Net/postprocess.py @@ -0,0 +1,73 @@ +# 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='SE_net calcul acc') +parser.add_argument("--result_path", type=str, required=True, default='', help="result file path") +parser.add_argument("--label_file", type=str, required=True, default='', help="label file") +args = parser.parse_args() + + +def get_top5_acc(top_arg, gt_class): + sub_count = 0 + for top5, gt in zip(top_arg, gt_class): + if gt in top5: + sub_count += 1 + return sub_count + + +def read_label(label_file): + with open(label_file, 'r') as f: + lines = f.readlines() + img_dict = {} + for line in lines: + img_id = line.split(':')[0] + label = line.split(':')[1] + img_dict[img_id] = label + return img_dict + + +def cal_acc_imagenet(result_path, label_file): + """ calcul acc """ + img_label = read_label(label_file) + img_tot = 0 + top1_correct = 0 + top5_correct = 0 + result_shape = (1, 1001) + 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(result_shape) + gt_classes = int(img_label[file.split('.')[0][:-2]]) + + 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 + acc1 = 100 * top1_correct / img_tot + acc5 = 100 * top5_correct / img_tot + print('total={}, top1_correct={}, acc={:.2f}%'.format(img_tot, top1_correct, acc1)) + print('total={}, top5_correct={}, acc={:.2f}%'.format(img_tot, top5_correct, acc5)) + + +if __name__ == '__main__': + cal_acc_imagenet(args.result_path, args.label_file) diff --git a/model_zoo/research/cv/SE-Net/scripts/run_infer_310.sh b/model_zoo/research/cv/SE-Net/scripts/run_infer_310.sh new file mode 100644 index 00000000000..070fa93b2e1 --- /dev/null +++ b/model_zoo/research/cv/SE-Net/scripts/run_infer_310.sh @@ -0,0 +1,107 @@ +#!/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] [DATA_PATH] [LABEL_FILE] [DVPP] [DEVICE_ID] + DVPP is mandatory, and must choose from [DVPP|CPU], it's case-insensitive,the net only support CPU mode. + 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) +data_path=$(get_real_path $2) +label_file=$(get_real_path $3) +DVPP=${4^^} + +device_id=0 +if [ $# == 5 ]; then + device_id=$5 +fi + +echo "mindir name: "$model +echo "dataset path: "$data_path +echo "label file: "$label_file +echo "image process mode: "$DVPP +echo "device id: "$device_id + +export ASCEND_HOME=/usr/local/Ascend/ +if [ -d ${ASCEND_HOME}/ascend-toolkit ]; then + export PATH=$ASCEND_HOME/fwkacllib/bin:$ASCEND_HOME/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/ascend-toolkit/latest/atc/bin:$PATH + export LD_LIBRARY_PATH=$ASCEND_HOME/fwkacllib/lib64:/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=$ASCEND_HOME/fwkacllib/python/site-packages:${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/fwkacllib/bin:$ASCEND_HOME/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/atc/ccec_compiler/bin:$ASCEND_HOME/atc/bin:$PATH + export LD_LIBRARY_PATH=$ASCEND_HOME/fwkacllib/lib64:/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/fwkacllib/python/site-packages:$ASCEND_HOME/atc/python/site-packages:$PYTHONPATH + export ASCEND_OPP_PATH=$ASCEND_HOME/opp +fi + +function compile_app() +{ + cd ../ascend310_infer || exit + bash build.sh &> build.log +} + +function infer() +{ + cd - || exit + 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 + if [ "$DVPP" == "DVPP" ];then + echo "only support CPU mode" + elif [ "$DVPP" == "CPU" ]; then + ../ascend310_infer/out/main --mindir_path=$model --dataset_path=$data_path --cpu_dvpp=$DVPP --device_id=$device_id --image_height=224 --image_width=224 &> infer.log + else + echo "image process mode must be in [DVPP|CPU]" + exit 1 + fi +} + +function cal_acc() +{ + python3.7 ../postprocess.py --label_file=$label_file --result_path=./result_Files &> acc.log & +} + +compile_app +if [ $? -ne 0 ]; then + echo "compile app code failed" + exit 1 +fi +infer +if [ $? -ne 0 ]; then + echo " execute inference failed" + exit 1 +fi +cal_acc +if [ $? -ne 0 ]; then + echo "calculate accuracy failed" + exit 1 +fi \ No newline at end of file