diff --git a/research/cv/sknet/README.md b/research/cv/sknet/README.md index 65549807e56a101ecabb440651f67597e8c752ed..3d5d3042934b6b62d209f898c4d24786d8854600 100644 --- a/research/cv/sknet/README.md +++ b/research/cv/sknet/README.md @@ -1,21 +1,38 @@ # Contents -- [SK-Net Description](#sK-net-description) +- [Contents](#contents) +- [SK-Net Description](#sk-net-description) +- [Description](#description) +- [Paper](#paper) - [Model Architecture](#model-architecture) - [Dataset](#dataset) - [Features](#features) - - [Mixed Precision](#mixed-precision) +- [Mixed Precision](#mixed-precision) - [Environment Requirements](#environment-requirements) - [Quick Start](#quick-start) - [Script Description](#script-description) - - [Script and Sample Code](#script-and-sample-code) - - [Script Parameters](#script-parameters) - - [Training Process](#training-process) - - [Evaluation Process](#evaluation-process) +- [Script and Sample Code](#script-and-sample-code) +- [Script Parameters](#script-parameters) +- [Training Process](#training-process) +- [Usage](#usage) +- [Running on Ascend](#running-on-ascend) +- [Result](#result) +- [Evaluation Process](#evaluation-process) +- [Usage](#usage-1) +- [Running on Ascend](#running-on-ascend-1) +- [Result](#result-1) +- [Inference Process](#inference-process) +- [Export MindIR](#export-mindir) +- [Infer on Ascend310](#infer-on-ascend310) +- [Result](#result-2) - [Model Description](#model-description) - - [Performance](#performance) - - [Evaluation Performance](#evaluation-performance) - - [Inference Performance](#inference-performance) +- [Performance](#performance) +- [Evaluation Performance](#evaluation-performance) +- [SKNet50 on CIFRA10](#sknet50-on-cifra10) +- [Inference Performance](#inference-performance) +- [SKNet50 on CIFAR10](#sknet50-on-cifar10) +- [310 Inference Performance](#310-inference-performance) +- [SKNet50 on CIFAR10](#sknet50-on-cifar10-1) - [Description of Random Situation](#description-of-random-situation) - [ModelZoo Homepage](#modelzoo-homepage) @@ -93,10 +110,16 @@ python eval.py --checkpoint_path=/resnet/sknet_90.ckpt --dataset_path=/data/cifa ```text 鈹斺攢鈹€SK-Net 鈹溾攢鈹€ README.md + 鈹溾攢鈹€ ascend310_infer + 鈹溾攢鈹€ inc + 鈹溾攢鈹€ src + 鈹溾攢鈹€ build.sh # make process + 鈹溾攢鈹€ CMakeLists.txt # cmake configuration 鈹溾攢鈹€ 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 # launch 310 infer 鈹溾攢鈹€ src 鈹溾攢鈹€ config.py # parameter configuration 鈹溾攢鈹€ CrossEntropySmooth.py # loss definition @@ -108,6 +131,8 @@ python eval.py --checkpoint_path=/resnet/sknet_90.ckpt --dataset_path=/data/cifa 鈹溾攢鈹€ export.py # export model for inference 鈹溾攢鈹€ eval.py # eval net 鈹斺攢鈹€ train.py # train net + 鈹溾攢鈹€ preprocess.py # preprocess scripts + 鈹溾攢鈹€ postprocess.py # postprocess scripts ``` ## [Script Parameters](#contents) @@ -187,6 +212,41 @@ bash run_eval.sh [DATASET_PATH] [CHECKPOINT_PATH] result: {'top_5_accuracy': 0.9982972756410257, 'top_1_accuracy': 0.9449118589743589} ``` +## [Inference Process](#contents) + +### Export MindIR + +```bash +python export.py --ckpt_file [CKPT_PATH] --file_name [FILE_NAME] --file_format [FILE_FORMAT] +``` + +The ckpt_file parameter is required, +`FILE_NAME` is the name of the AIR/ONNX/MINDIR file. +`FILE_FORMAT` should be in ["AIR","ONNX", "MINDIR"] + +### 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] [DATASET_NAME] [DATASET_PATH] [NEED PREPROCESS] [DEVICE_ID] +``` + +- DATASET_NAME can choose from ['cifar10', 'imagenet2012']. +- NEED_PREPROCESS means weather need preprocess or not, it's value is 'y' or 'n'. +- DEVICE_ID is optional, it can be set by environment variable device_id, otherwise the value is zero" +- `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_1_accuracy': 0.9449118589743589} +``` + # [Model Description](#contents) ## [Performance](#contents) @@ -227,6 +287,20 @@ result: {'top_5_accuracy': 0.9982972756410257, 'top_1_accuracy': 0.9449118589743 | batch_size | 32 | | Accuracy | 94.49% | +### 310 Inference Performance + +#### SKNet50 on CIFAR10 + +| Parameters | Ascend | +| ------------------- | --------------------------- | +| Model Version | SKNet50 | +| Resource | Ascend 310 | +| Uploaded Date | 09/23/2021 (month/day/year) | +| MindSpore Version | 1.3.0 | +| Dataset | CIFAR10 | +| batch_size | 32 | +| Accuracy | 95.49% | + # [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/research/cv/sknet/ascend310_infer/CMakeLists.txt b/research/cv/sknet/ascend310_infer/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..49478f950647bd15851ae9b931c04ed190ef9cbf --- /dev/null +++ b/research/cv/sknet/ascend310_infer/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.14.1) +project(Ascend310Infer) +find_package(OpenCV 2 REQUIRED) +find_package(gflags REQUIRED) +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(${OpenCV_INCLUDE_DIRS}) +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} ${OpenCV_LIBS} gflags) diff --git a/research/cv/sknet/ascend310_infer/build.sh b/research/cv/sknet/ascend310_infer/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..922df6cb4d87095802306ba30c7741fe64ca79f1 --- /dev/null +++ b/research/cv/sknet/ascend310_infer/build.sh @@ -0,0 +1,28 @@ +#!/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 + +if [ -f "Makefile" ]; then + make clean +fi + +cmake .. -DMINDSPORE_PATH="`pip3.7 show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`" +make diff --git a/research/cv/sknet/ascend310_infer/inc/utils.h b/research/cv/sknet/ascend310_infer/inc/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f8ae1e5b473d869b77af8d725a280d7c7665527c --- /dev/null +++ b/research/cv/sknet/ascend310_infer/inc/utils.h @@ -0,0 +1,35 @@ +/** + * 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); +std::vector<std::string> GetAllFiles(std::string dir_name); +std::vector<std::vector<std::string>> GetAllInputData(std::string dir_name); + +#endif diff --git a/research/cv/sknet/ascend310_infer/src/main.cc b/research/cv/sknet/ascend310_infer/src/main.cc new file mode 100644 index 0000000000000000000000000000000000000000..9862fcfb6b731c18a1b6d5ec6077c9b248e1461e --- /dev/null +++ b/research/cv/sknet/ascend310_infer/src/main.cc @@ -0,0 +1,148 @@ +/** + * 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 <sstream> + +#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/transforms.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::vision::Decode; +using mindspore::dataset::vision::Resize; +using mindspore::dataset::vision::CenterCrop; +using mindspore::dataset::vision::Normalize; +using mindspore::dataset::vision::HWC2CHW; + + +DEFINE_string(mindir_path, "", "mindir path"); +DEFINE_string(dataset_name, "cifar10", "['cifar10', 'imagenet2012']"); +DEFINE_string(input0_path, ".", "input0 path"); +DEFINE_int32(device_id, 0, "device id"); + +int load_model(Model *model, std::vector<MSTensor> *model_inputs, std::string mindir_path, int device_id) { + if (RealPath(mindir_path).empty()) { + std::cout << "Invalid mindir" << std::endl; + return 1; + } + std::cout << "good mindir" << std::endl; + auto context = std::make_shared<Context>(); + auto ascend310 = std::make_shared<mindspore::Ascend310DeviceInfo>(); + ascend310->SetDeviceID(device_id); + std::cout << "find device" << std::endl; + context->MutableDeviceInfo().push_back(ascend310); + mindspore::Graph graph; + Serialization::Load(mindir_path, ModelType::kMindIR, &graph); + + Status ret = model->Build(GraphCell(graph), context); + if (ret != kSuccess) { + std::cout << "ERROR: Build failed." << std::endl; + return 1; + } + + *model_inputs = model->GetInputs(); + if (model_inputs->empty()) { + std::cout << "Invalid model, inputs is empty." << std::endl; + return 1; + } + return 0; +} + +int main(int argc, char **argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + Model model; + std::vector<MSTensor> model_inputs; + load_model(&model, &model_inputs, FLAGS_mindir_path, FLAGS_device_id); + std::cout << "load model success" << std::endl; + std::map<double, double> costTime_map; + struct timeval start = {0}; + struct timeval end = {0}; + if (FLAGS_dataset_name == "cifar10") { + auto input0_files = GetAllFiles(FLAGS_input0_path); + if (input0_files.empty()) { + std::cout << "ERROR: no input data." << std::endl; + return 1; + } + std::cout << "find input data" << std::endl; + size_t size = input0_files.size(); + for (size_t i = 0; i < size; ++i) { + std::vector<MSTensor> inputs; + std::vector<MSTensor> outputs; + double startTimeMs; + double endTimeMs; + std::cout << "Start predict input files:" << input0_files[i] <<std::endl; + auto input0 = ReadFileToTensor(input0_files[i]); + inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(), + input0.Data().get(), input0.DataSize()); + + gettimeofday(&start, nullptr); + Status ret = model.Predict(inputs, &outputs); + gettimeofday(&end, nullptr); + if (ret != kSuccess) { + std::cout << "Predict " << input0_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<double, double>(startTimeMs, endTimeMs)); + int rst = WriteResult(input0_files[i], outputs); + if (rst != 0) { + std::cout << "write result failed." << std::endl; + return rst; + } + } + } + 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/research/cv/sknet/ascend310_infer/src/utils.cc b/research/cv/sknet/ascend310_infer/src/utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..d71f388b83d23c2813d8bfc883dbcf2e7e0e4ef0 --- /dev/null +++ b/research/cv/sknet/ascend310_infer/src/utils.cc @@ -0,0 +1,185 @@ +/** + * 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 <fstream> +#include <algorithm> +#include <iostream> +#include "inc/utils.h" + +using mindspore::MSTensor; +using mindspore::DataType; + + +std::vector<std::vector<std::string>> GetAllInputData(std::string dir_name) { + std::vector<std::vector<std::string>> ret; + + DIR *dir = OpenDir(dir_name); + if (dir == nullptr) { + return {}; + } + struct dirent *filename; + /* read all the files in the dir ~ */ + std::vector<std::string> sub_dirs; + while ((filename = readdir(dir)) != nullptr) { + std::string d_name = std::string(filename->d_name); + // get rid of "." and ".." + if (d_name == "." || d_name == ".." || d_name.empty()) { + continue; + } + std::string dir_path = RealPath(std::string(dir_name) + "/" + filename->d_name); + struct stat s; + lstat(dir_path.c_str(), &s); + if (!S_ISDIR(s.st_mode)) { + continue; + } + + sub_dirs.emplace_back(dir_path); + } + std::sort(sub_dirs.begin(), sub_dirs.end()); + + (void)std::transform(sub_dirs.begin(), sub_dirs.end(), std::back_inserter(ret), + [](const std::string &d) { return GetAllFiles(d); }); + + return ret; +} + + +std::vector<std::string> GetAllFiles(std::string dir_name) { + struct dirent *filename; + DIR *dir = OpenDir(dir_name); + if (dir == nullptr) { + return {}; + } + + std::vector<std::string> res; + while ((filename = readdir(dir)) != nullptr) { + std::string d_name = std::string(filename->d_name); + if (d_name == "." || d_name == ".." || d_name.size() <= 3) { + continue; + } + res.emplace_back(std::string(dir_name) + "/" + filename->d_name); + } + std::sort(res.begin(), res.end()); + + return res; +} + + +std::vector<std::string> GetAllFiles(std::string_view dirName) { + struct dirent *filename; + DIR *dir = OpenDir(dirName); + if (dir == nullptr) { + return {}; + } + std::vector<std::string> 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<MSTensor> &outputs) { + std::string homePath = "./result_Files"; + 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"); + 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<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; +} diff --git a/research/cv/sknet/eval.py b/research/cv/sknet/eval.py index 6cbd6b3715dcb982923abbecce561929a8278323..073ec53bc0db85f44b40103588b6d1d57ff8c1f8 100644 --- a/research/cv/sknet/eval.py +++ b/research/cv/sknet/eval.py @@ -37,7 +37,7 @@ if __name__ == '__main__': from src.sknet50 import sknet50 as sknet if args_opt.dataset == "cifar10": from src.config import config1 as config - from src.dataset import create_dataset1 as create_dataset + from src.dataset import create_dataset_cifar10 as create_dataset target = args_opt.device_target # init context diff --git a/research/cv/sknet/postprocess.py b/research/cv/sknet/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..98bc55da6ce07acfc2eecb548f5ad77a7dafa257 --- /dev/null +++ b/research/cv/sknet/postprocess.py @@ -0,0 +1,38 @@ +# 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. +# ============================================================================ +"""postprocess for 310 inference""" +import os +import argparse +import numpy as np +from mindspore.nn import Top1CategoricalAccuracy +parser = argparse.ArgumentParser(description="postprocess") +label_path = "./preprocess_Result/cifar10_label_ids.npy" +parser.add_argument("--result_dir", type=str, default="./result_Files", help="result files path.") +parser.add_argument("--label_dir", type=str, default=label_path, help="image file path.") +args = parser.parse_args() + +def calcul_acc(lab, preds): + return sum(1 for x, y in zip(lab, preds) if x == y) / len(lab) +if __name__ == '__main__': + top1_acc = Top1CategoricalAccuracy() + rst_path = args.result_dir + labels = np.load(args.label_dir, allow_pickle=True) + batch_size = 32 + for idx, label in enumerate(labels): + f_name = os.path.join(rst_path, "sknet_data_bs" + str(batch_size) + "_" + str(idx) + "_0.bin") + pred = np.fromfile(f_name, np.float32) + pred = pred.reshape(batch_size, int(pred.shape[0] / batch_size)) + top1_acc.update(pred, labels[idx]) + print("acc: ", top1_acc.eval()) diff --git a/research/cv/sknet/preprocess.py b/research/cv/sknet/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..6b2133f4acddd5a7e1ed4452976f8bbcb4f57f6d --- /dev/null +++ b/research/cv/sknet/preprocess.py @@ -0,0 +1,36 @@ +# 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. +# ============================================================================ +"""preprocess""" +import os +import argparse +import numpy as np +from src.dataset import create_dataset_cifar10 +parser = argparse.ArgumentParser('preprocess') +parser.add_argument('--data_path', type=str, default='', help='eval data dir') + +args = parser.parse_args() +if __name__ == "__main__": + dataset = create_dataset_cifar10(args.data_path, False) + img_path = os.path.join('./preprocess_Result/', "00_data") + os.makedirs(img_path) + label_list = [] + batch_size = 32 + for idx, data in enumerate(dataset.create_dict_iterator(output_numpy=True)): + file_name = "sknet_data_bs" + str(batch_size) + "_" + str(idx) + ".bin" + file_path = os.path.join(img_path, file_name) + data["image"].tofile(file_path) + label_list.append(data["label"]) + np.save(os.path.join('./preprocess_Result/', "cifar10_label_ids.npy"), label_list) + print("=" * 20, "export bin files finished", "=" * 20) diff --git a/research/cv/sknet/scripts/run_infer_310.sh b/research/cv/sknet/scripts/run_infer_310.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c710986ac045cd3323cf4aab7c5332136b731a5 --- /dev/null +++ b/research/cv/sknet/scripts/run_infer_310.sh @@ -0,0 +1,145 @@ +#!/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_NAME] [DATASET_PATH] [NEED_PREPROCESS] [DEVICE_ID] + DATASET_NAME can choose from ['cifar10', 'imagenet2012']. + NEED_PREPROCESS means weather need preprocess or not, it's value is 'y' or 'n'. + 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) +if [ $2 == 'cifar10' ] || [ $2 == 'imagenet2012' ]; then + dataset_name=$2 +else + echo "DATASET_NAME can choose from ['cifar10', 'imagenet2012']" + exit 1 +fi + +dataset_path=$(get_real_path $3) + +if [ "$4" == "y" ] || [ "$4" == "n" ];then + need_preprocess=$4 +else + echo "weather need preprocess or not, it's value must be in [y, n]" + exit 1 +fi + +device_id=0 +if [ $# == 5 ]; then + device_id=$5 +fi + +echo "mindir name: "$model +echo "dataset name: "$dataset_name +echo "dataset path: "$dataset_path +echo "need preprocess: "$need_preprocess +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 +export ASCEND_HOME=/usr/local/Ascend + +export PATH=$ASCEND_HOME/fwkacllib/ccec_compiler/bin:$ASCEND_HOME/fwkacllib/bin:$ASCEND_HOME/toolkit/bin:$PATH + +export LD_LIBRARY_PATH=/usr/local/lib/:/usr/local/fwkacllib/lib64:$ASCEND_HOME/driver/lib64:$ASCEND_HOME/add-ons:/usr/local/Ascend/toolkit/lib64:$LD_LIBRARY_PATH + +export PYTHONPATH=$ASCEND_HOME/fwkacllib/python/site-packages + +export PATH=/usr/local/python375/bin:$PATH +export NPU_HOST_LIB=/usr/local/Ascend/acllib/lib64/stub +export ASCEND_OPP_PATH=/usr/local/Ascend/opp +export ASCEND_AICPU_PATH=/usr/local/Ascend +export LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH +function preprocess_data() +{ + if [ -d preprocess_Result ]; then + rm -rf ./preprocess_Result + fi + mkdir preprocess_Result + python3.7 ../preprocess.py --data_path=$dataset_path #--result_path=./preprocess_Result/ +} + +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 + + ../ascend310_infer/out/main --mindir_path=$model --dataset_name=$dataset_name --input0_path=../scripts/preprocess_Result/00_data --device_id=$device_id &> infer.log +} + +function cal_acc() +{ + python3.7 ../postprocess.py &> acc.log +} + +if [ $need_preprocess == "y" ]; then + preprocess_data + if [ $? -ne 0 ]; then + echo "preprocess dataset failed" + exit 1 + fi +fi +compile_app +if [ $? -ne 0 ]; then + echo "compile app code failed" + exit 1 +fi +echo "compile success" +infer +if [ $? -ne 0 ]; then + echo " execute inference failed" + exit 1 +fi +echo "infer success" +cal_acc +if [ $? -ne 0 ]; then + echo "calculate accuracy failed" + exit 1 +fi +echo "cal_acc success" diff --git a/research/cv/sknet/src/dataset.py b/research/cv/sknet/src/dataset.py index a76103daf2bbb58dade9542c9b8b81e3e987fc34..ee19694bc88afd274ff264bd0e99157f6ed4f436 100644 --- a/research/cv/sknet/src/dataset.py +++ b/research/cv/sknet/src/dataset.py @@ -22,8 +22,8 @@ import mindspore.dataset.vision.c_transforms as C import mindspore.dataset.transforms.c_transforms as C2 from mindspore.communication.management import init, get_rank, get_group_size -def create_dataset1(dataset_path, do_train, repeat_num=1, batch_size=32, target="Ascend", distribute=False, - enable_cache=False, cache_session_id=None): +def create_dataset_cifar10(dataset_path, do_train=False, repeat_num=1, batch_size=32, target="Ascend", distribute=False, + enable_cache=False, cache_session_id=None): """ create a train or evaluate cifar10 dataset for sknet50 Args: