From 66477506cbf616f3982119783ec61b5005145a76 Mon Sep 17 00:00:00 2001 From: yuzhenhua Date: Tue, 15 Jun 2021 11:02:39 +0800 Subject: [PATCH] ascend 310 inference for cnn --- .../official/cv/cnn_direction_model/README.md | 38 +++++ .../ascend310_infer/CMakeLists.txt | 14 ++ .../ascend310_infer/build.sh | 23 +++ .../ascend310_infer/inc/utils.h | 32 ++++ .../ascend310_infer/src/main.cc | 132 ++++++++++++++++ .../ascend310_infer/src/utils.cc | 147 ++++++++++++++++++ .../cnn_direction_model/default_config.yaml | 6 + .../official/cv/cnn_direction_model/export.py | 36 +++++ .../cv/cnn_direction_model/postprocess.py | 49 ++++++ .../cv/cnn_direction_model/preprocess.py | 68 ++++++++ .../scripts/run_infer_310.sh | 119 ++++++++++++++ model_zoo/official/cv/googlenet/export.py | 2 +- .../official/cv/googlenet/postprocess.py | 2 +- model_zoo/official/cv/unet/postprocess.py | 2 +- model_zoo/official/cv/unet/preprocess.py | 2 +- 15 files changed, 668 insertions(+), 4 deletions(-) create mode 100644 model_zoo/official/cv/cnn_direction_model/ascend310_infer/CMakeLists.txt create mode 100644 model_zoo/official/cv/cnn_direction_model/ascend310_infer/build.sh create mode 100644 model_zoo/official/cv/cnn_direction_model/ascend310_infer/inc/utils.h create mode 100644 model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/main.cc create mode 100644 model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/utils.cc create mode 100644 model_zoo/official/cv/cnn_direction_model/export.py create mode 100644 model_zoo/official/cv/cnn_direction_model/postprocess.py create mode 100644 model_zoo/official/cv/cnn_direction_model/preprocess.py create mode 100644 model_zoo/official/cv/cnn_direction_model/scripts/run_infer_310.sh diff --git a/model_zoo/official/cv/cnn_direction_model/README.md b/model_zoo/official/cv/cnn_direction_model/README.md index d7594a1c360..bbb43fb3b23 100644 --- a/model_zoo/official/cv/cnn_direction_model/README.md +++ b/model_zoo/official/cv/cnn_direction_model/README.md @@ -12,6 +12,10 @@ - [Training](#training) - [Evaluation Process](#evaluation-process) - [Evaluation](#evaluation) + - [Export Process](#Export-process) + - [Export](#Export) + - [Inference Process](#Inference-process) + - [Inference](#Inference) - [Model Description](#model-description) - [Performance](#performance) - [Evaluation Performance](#evaluation-performance) @@ -87,10 +91,12 @@ sh run_standalone_train.sh [DATASET_PATH] [PRETRAINED_CKPT_PATH] ├── cv ├── cnn_direction_model ├── README.md // descriptions about cnn_direction_model + ├── ascend310_infer // application for 310 inference ├── requirements.txt // packages needed ├── scripts │ ├──run_distribute_train_ascend.sh // distributed training in ascend │ ├──run_standalone_eval_ascend.sh // evaluate in ascend + │ ├──run_eval.sh // shell script for evaluation on Ascend │ ├──run_standalone_train_ascend.sh // train standalone in ascend ├── src │ ├──dataset.py // creating dataset @@ -104,6 +110,8 @@ sh run_standalone_train.sh [DATASET_PATH] [PRETRAINED_CKPT_PATH] ├── train.py // training script ├── eval.py // evaluation script ├── default_config.yaml // config file + ├── postprogress.py // post process for 310 inference + ├── export.py // export checkpoint files into air/mindir ``` ## [Script Parameters](#contents) @@ -222,6 +230,36 @@ sh scripts/run_distribute_train_ascend.sh /home/rank_table.json /home/fsns/train # (7) Start model inference。 ``` +## [Export Process](#contents) + +### [Export](#content) + +```shell +python export.py --ckpt_file [CKPT_PATH] --device_target [DEVICE_TARGET] --file_format[EXPORT_FORMAT] +``` + +`EXPORT_FORMAT` should be in ["AIR", "MINDIR"] + +## [Inference Process](#contents) + +### Usage + +Before performing inference, we need to export model first. Air model can only be exported in Ascend 910 environment, mindir model can be exported in any environment. + +```shell +# Ascend310 inference +bash run_infer_310.sh [MINDIR_PATH] [DATA_PATH] [DEVICE_ID] +``` + +### result + +Inference result is saved in current path, you can find result like this in acc.log file. + +```python +top1_correct=10096, total=10202, acc=98.96% +top1_correct=8888, total=10202, acc=87.12% +``` + # [Model Description](#contents) ## [Performance](#contents) diff --git a/model_zoo/official/cv/cnn_direction_model/ascend310_infer/CMakeLists.txt b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/CMakeLists.txt new file mode 100644 index 00000000000..ee3c8544734 --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/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/official/cv/cnn_direction_model/ascend310_infer/build.sh b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/build.sh new file mode 100644 index 00000000000..770a8851efa --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/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/official/cv/cnn_direction_model/ascend310_infer/inc/utils.h b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/inc/utils.h new file mode 100644 index 00000000000..efebe03a8c1 --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/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/official/cv/cnn_direction_model/ascend310_infer/src/main.cc b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/main.cc new file mode 100644 index 00000000000..be39426ed73 --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/main.cc @@ -0,0 +1,132 @@ +/** + * 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 "../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; + +DEFINE_string(model_path, "", "model path"); +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; + } + + auto context = std::make_shared(); + auto ascend310_info = std::make_shared(); + 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 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::map 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 inputs; + std::vector outputs; + + std::cout << "Start predict input files:" << all_files[i] << std::endl; + mindspore::MSTensor image = ReadFileToTensor(all_files[i]); + + 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(startTime_ms, endTime_ms)); + WriteResult(all_files[i], outputs); + } + double average = 0.0; + int infer_cnt = 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::stringstream timeCost; + timeCost << "NN inference cost average time: "<< average << " ms of infer_count " << infer_cnt << std::endl; + 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 << timeCost.str(); + file_stream.close(); + costTime_map.clear(); + return 0; +} diff --git a/model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/utils.cc b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/utils.cc new file mode 100644 index 00000000000..d231193e799 --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/ascend310_infer/src/utils.cc @@ -0,0 +1,147 @@ +/** + * 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 dirs; + std::vector 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 &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/official/cv/cnn_direction_model/default_config.yaml b/model_zoo/official/cv/cnn_direction_model/default_config.yaml index 783d395cf33..adfad461983 100644 --- a/model_zoo/official/cv/cnn_direction_model/default_config.yaml +++ b/model_zoo/official/cv/cnn_direction_model/default_config.yaml @@ -61,6 +61,12 @@ eval_dataset_path: "" checkpoint_path: "" # export options +ckpt_file: "" +file_name: "cnn" +file_format: "MINDIR" + +#310 inferenct options +result_path: "./preprocess_Result/" --- # Help description for each configuration diff --git a/model_zoo/official/cv/cnn_direction_model/export.py b/model_zoo/official/cv/cnn_direction_model/export.py new file mode 100644 index 00000000000..51bf1a60676 --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/export.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. +# ============================================================================ +"""export script""" + +import numpy as np +import mindspore as ms +from mindspore import Tensor, context, load_checkpoint, export +from src.cnn_direction_model import CNNDirectionModel +from src.model_utils.config import config +from src.model_utils.device_adapter import get_device_id + +context.set_context(mode=context.GRAPH_MODE, device_target=config.device_target) +device_id = get_device_id() +context.set_context(device_id=device_id) + +if __name__ == '__main__': + net = CNNDirectionModel([3, 64, 48, 48, 64], [64, 48, 48, 64, 64], [256, 64], [64, 512]) + + param_dict = load_checkpoint(config.ckpt_file, net=net) + net.set_train(False) + + input_data = Tensor(np.zeros([1, 3, config.im_size_h, config.im_size_w]), ms.float32) + + export(net, input_data, file_name=config.file_name, file_format=config.file_format) diff --git a/model_zoo/official/cv/cnn_direction_model/postprocess.py b/model_zoo/official/cv/cnn_direction_model/postprocess.py new file mode 100644 index 00000000000..f53e713a91c --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/postprocess.py @@ -0,0 +1,49 @@ +# 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 cnn') +parser.add_argument("--result_path", type=str, required=True, help="result file path") +parser.add_argument("--label_path", type=str, required=True, help="label file") +args = parser.parse_args() + +def cal_acc(result_path, label_path): + img_total = 0 + top1_correct = 0 + + result_shape = (1, 2) + + 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) + label_file = os.path.join(label_path, file.split(".bin")[0][:-2] + ".bin") + gt_classes = np.fromfile(label_file, dtype=np.int32) + + top1_output = np.argmax(result, (-1)) + + t1_correct = np.equal(top1_output, gt_classes).sum() + top1_correct += t1_correct + img_total += 1 + + acc1 = 100.0 * top1_correct / img_total + print('top1_correct={}, total={}, acc={:.2f}%'.format(top1_correct, img_total, acc1)) + +if __name__ == "__main__": + cal_acc(args.result_path, args.label_path) diff --git a/model_zoo/official/cv/cnn_direction_model/preprocess.py b/model_zoo/official/cv/cnn_direction_model/preprocess.py new file mode 100644 index 00000000000..2053ae2b43e --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/preprocess.py @@ -0,0 +1,68 @@ +# 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 for cnn""" + +import os +import random + +import numpy as np +from src.model_utils.config import config +from src.dataset import create_dataset_eval + +from mindspore import dataset as de + +random.seed(1) +np.random.seed(1) +de.config.set_seed(1) + +def preprocess(): + dataset_name = config.dataset_name + dataset_lr, dataset_rl = create_dataset_eval(config.data_root_test + "/" + dataset_name + + ".mindrecord0", config=config, dataset_name=dataset_name) + + lr_img_path = os.path.join(config.result_path, "lr_dataset/" + "img_data") + lr_label_path = os.path.join(config.result_path, "lr_dataset/" + "label") + os.makedirs(lr_img_path) + os.makedirs(lr_label_path) + + for idx, data in enumerate(dataset_lr.create_dict_iterator(output_numpy=True, num_epochs=1)): + img_data = data["image"] + img_label = data["label"] + + file_name = "cnn_fsns_1_" + str(idx) + ".bin" + img_file_path = os.path.join(lr_img_path, file_name) + img_data.tofile(img_file_path) + + label_file_path = os.path.join(lr_label_path, file_name) + img_label.tofile(label_file_path) + + rl_img_path = os.path.join(config.result_path, "rl_dataset/" + "img_data") + rl_label_path = os.path.join(config.result_path, "rl_dataset/" + "label") + os.makedirs(rl_img_path) + os.makedirs(rl_label_path) + + for idx, data in enumerate(dataset_rl.create_dict_iterator(output_numpy=True, num_epochs=1)): + img_data = data["image"] + img_label = data["label"] + + file_name = "cnn_fsns_1_" + str(idx) + ".bin" + img_file_path = os.path.join(rl_img_path, file_name) + img_data.tofile(img_file_path) + + label_file_path = os.path.join(rl_label_path, file_name) + img_label.tofile(label_file_path) + +if __name__ == '__main__': + preprocess() diff --git a/model_zoo/official/cv/cnn_direction_model/scripts/run_infer_310.sh b/model_zoo/official/cv/cnn_direction_model/scripts/run_infer_310.sh new file mode 100644 index 00000000000..2b5097ce1eb --- /dev/null +++ b/model_zoo/official/cv/cnn_direction_model/scripts/run_infer_310.sh @@ -0,0 +1,119 @@ +#!/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 1 || $# -gt 2 ]]; then + echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [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) + +device_id=0 +if [ $# == 2 ]; then + device_id=$2 +fi + +echo "mindir name: "$model +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 preprocess_data() +{ + if [ -d preprocess_Result ]; then + rm -rf ./preprocess_Result + fi + mkdir preprocess_Result + # python3.7 ../preprocess.py --dataset_path=$dataset_path --result_path=./preprocess_Result/ + python3.7 ../preprocess.py +} + +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 --model_path=$model --dataset_path=./preprocess_Result/lr_dataset/img_data --device_id=$device_id &> lr_infer.log + mv result_Files result_Files_lr + mv time_Result time_Result_lr + + mkdir result_Files + mkdir time_Result + ../ascend310_infer/out/main --model_path=$model --dataset_path=./preprocess_Result/rl_dataset/img_data --device_id=$device_id &> rl_infer.log + mv result_Files result_Files_rl + mv time_Result time_Result_rl +} + +function cal_acc() +{ + python3.7 ../postprocess.py --result_path=./result_Files_lr --label_path=./preprocess_Result/lr_dataset/label &> acc.log + python3.7 ../postprocess.py --result_path=./result_Files_rl --label_path=./preprocess_Result/rl_dataset/label &>> acc.log +} + +preprocess_data +if [ $? -ne 0 ]; then + echo "preprocess dataset failed" + exit 1 +fi + +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 diff --git a/model_zoo/official/cv/googlenet/export.py b/model_zoo/official/cv/googlenet/export.py index fbdf7402e7f..5aa36768980 100644 --- a/model_zoo/official/cv/googlenet/export.py +++ b/model_zoo/official/cv/googlenet/export.py @@ -33,7 +33,7 @@ if config.device_target == "Ascend": if __name__ == '__main__': net = GoogleNet(num_classes=config.num_classes) - assert config.checkpoint_path is not None, "config.checkpoint_path is None." + assert config.ckpt_file is not None, "config.ckpt_file is None." param_dict = load_checkpoint(config.ckpt_file) load_param_into_net(net, param_dict) diff --git a/model_zoo/official/cv/googlenet/postprocess.py b/model_zoo/official/cv/googlenet/postprocess.py index a8dd642b0fa..bded431ef66 100644 --- a/model_zoo/official/cv/googlenet/postprocess.py +++ b/model_zoo/official/cv/googlenet/postprocess.py @@ -17,7 +17,7 @@ import os import argparse import numpy as np -parser = argparse.ArgumentParser(description='fasterrcnn_export') +parser = argparse.ArgumentParser(description='postprocess for googlenet') 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") diff --git a/model_zoo/official/cv/unet/postprocess.py b/model_zoo/official/cv/unet/postprocess.py index 45b481630b2..73328a39478 100644 --- a/model_zoo/official/cv/unet/postprocess.py +++ b/model_zoo/official/cv/unet/postprocess.py @@ -78,7 +78,7 @@ if __name__ == '__main__': metrics = dice_coeff() if config.dataset == "Cell_nuclei": - img_size = tuple(config.img_size) + img_size = tuple(config.image_size) for i, bin_name in enumerate(os.listdir('./preprocess_Result/')): f = bin_name.replace(".png", "") bin_name_softmax = f + "_0.bin" diff --git a/model_zoo/official/cv/unet/preprocess.py b/model_zoo/official/cv/unet/preprocess.py index eafaf05c48a..eada87c1098 100644 --- a/model_zoo/official/cv/unet/preprocess.py +++ b/model_zoo/official/cv/unet/preprocess.py @@ -24,7 +24,7 @@ from src.model_utils.config import config def preprocess_dataset(data_dir, result_path, cross_valid_ind=1): _, valid_dataset = create_dataset(data_dir, 1, 1, False, cross_valid_ind, False, do_crop=config.crop, - img_size=config.img_size) + img_size=config.image_size) labels_list = [] for i, data in enumerate(valid_dataset):