diff --git a/model_zoo/research/cv/FaceAttribute/README.md b/model_zoo/research/cv/FaceAttribute/README.md index f29d3648698..5e308c826ba 100644 --- a/model_zoo/research/cv/FaceAttribute/README.md +++ b/model_zoo/research/cv/FaceAttribute/README.md @@ -229,6 +229,42 @@ cd ./scripts sh run_export.sh [BATCH_SIZE] [USE_DEVICE_ID] [PRETRAINED_BACKBONE] ``` +### Inference Process + +#### Export MindIR + +```shell +python export.py --ckpt_file [CKPT_PATH] --file_name [FILE_NAME] --file_format [FILE_FORMAT] +``` + +The ckpt_file parameter is required, +`file_format` should be in ["AIR", "MINDIR"] +`ckpt_path` ckpt file path + +#### 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. +Current batch_Size for imagenet2012 dataset can only be set to 1. + +```shell +# Ascend310 inference +bash run_infer_310.sh [MINDIR_PATH] [DATASET_PATH] [DEVICE_ID] +``` + +- `MINDIR_PATH` specifies path of used "MINDIR" OR "AIR" model. +- `DATASET_PATH` specifies path of cifar10 datasets +- `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 +'age accuracy': 0.4937 +'gen accuracy': 0.9093 +'mask accuracy': 0.9903 +``` + # [Model Description](#contents) ## [Performance](#contents) diff --git a/model_zoo/research/cv/FaceAttribute/ascend310_infer/CMakeLists.txt b/model_zoo/research/cv/FaceAttribute/ascend310_infer/CMakeLists.txt new file mode 100644 index 00000000000..ee3c8544734 --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/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/FaceAttribute/ascend310_infer/build.sh b/model_zoo/research/cv/FaceAttribute/ascend310_infer/build.sh new file mode 100644 index 00000000000..285514e19f2 --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/ascend310_infer/build.sh @@ -0,0 +1,29 @@ +#!/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 + rm -rf out +fi + +mkdir out +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/model_zoo/research/cv/FaceAttribute/ascend310_infer/inc/utils.h b/model_zoo/research/cv/FaceAttribute/ascend310_infer/inc/utils.h new file mode 100644 index 00000000000..f8ae1e5b473 --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/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 +#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); +std::vector GetAllFiles(std::string dir_name); +std::vector> GetAllInputData(std::string dir_name); + +#endif diff --git a/model_zoo/research/cv/FaceAttribute/ascend310_infer/src/main.cc b/model_zoo/research/cv/FaceAttribute/ascend310_infer/src/main.cc new file mode 100644 index 00000000000..cfc5b3dc705 --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/ascend310_infer/src/main.cc @@ -0,0 +1,125 @@ +/** + * 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 "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; + + +DEFINE_string(mindir_path, "", "mindir path"); +DEFINE_string(input0_path, ".", "input0 path"); +DEFINE_int32(device_id, 0, "device id"); + +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); + context->MutableDeviceInfo().push_back(ascend310); + mindspore::Graph graph; + Serialization::Load(FLAGS_mindir_path, ModelType::kMindIR, &graph); + Model model; + Status rst = model.Build(GraphCell(graph), context); + if (rst != kSuccess) { + std::cout << "ERROR: Build failed." << std::endl; + return 1; + } + + std::vector model_inputs = model.GetInputs(); + if (model_inputs.empty()) { + std::cout << "Invalid model, inputs is empty." << std::endl; + return 1; + } + auto input0_files = GetAllFiles(FLAGS_input0_path); + if (input0_files.empty()) { + std::cout << "ERROR: no input data." << std::endl; + return 1; + } + std::map costTime_map; + size_t size = input0_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:" << input0_files[i] <(startTimeMs, endTimeMs)); + WriteResult(input0_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/FaceAttribute/ascend310_infer/src/utils.cc b/model_zoo/research/cv/FaceAttribute/ascend310_infer/src/utils.cc new file mode 100644 index 00000000000..d71f388b83d --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/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 +#include +#include +#include "inc/utils.h" + +using mindspore::MSTensor; +using mindspore::DataType; + + +std::vector> GetAllInputData(std::string dir_name) { + std::vector> ret; + + DIR *dir = OpenDir(dir_name); + if (dir == nullptr) { + return {}; + } + struct dirent *filename; + /* read all the files in the dir ~ */ + std::vector 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 GetAllFiles(std::string dir_name) { + struct dirent *filename; + DIR *dir = OpenDir(dir_name); + if (dir == nullptr) { + return {}; + } + + std::vector 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 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/FaceAttribute/export.py b/model_zoo/research/cv/FaceAttribute/export.py index 6ca7f3e2272..9d76c198394 100644 --- a/model_zoo/research/cv/FaceAttribute/export.py +++ b/model_zoo/research/cv/FaceAttribute/export.py @@ -24,13 +24,13 @@ from mindspore.train.serialization import export, load_checkpoint, load_param_in from src.FaceAttribute.resnet18_softmax import get_resnet18 from src.config import config -devid = int(os.getenv('DEVICE_ID')) +devid = 0 context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=devid) def main(args): network = get_resnet18(args) - ckpt_path = args.model_path + ckpt_path = args.ckpt_file if os.path.isfile(ckpt_path): param_dict = load_checkpoint(ckpt_path) param_dict_new = {} @@ -46,19 +46,19 @@ def main(args): else: print('-----------------------load model failed -----------------------') - input_data = np.random.uniform(low=0, high=1.0, size=(args.batch_size, 3, 112, 112)).astype(np.float32) + input_data = np.random.uniform(low=0, high=1.0, size=(1, 3, 112, 112)).astype(np.float32) tensor_input_data = Tensor(input_data) - export(network, tensor_input_data, file_name=ckpt_path.replace('.ckpt', '_' + str(args.batch_size) + 'b.air'), - file_format='AIR') + export(network, tensor_input_data, file_name=args.file_name, + file_format=args.file_format) print('-----------------------export model success-----------------------') def parse_args(): """parse_args""" - parser = argparse.ArgumentParser(description='Convert ckpt to air') - parser.add_argument('--model_path', type=str, default='', help='pretrained model to load') - parser.add_argument('--batch_size', type=int, default=8, help='batch size') - + parser = argparse.ArgumentParser(description='Convert ckpt to designated format') + parser.add_argument('--ckpt_file', type=str, default='', help='pretrained model to load') + parser.add_argument('--file_name', type=str, default='faceattri', help='file name') + parser.add_argument('--file_format', type=str, default='MINDIR', choices=['MINDIR', 'AIR'], help='file format') args_opt = parser.parse_args() return args_opt diff --git a/model_zoo/research/cv/FaceAttribute/postprocess.py b/model_zoo/research/cv/FaceAttribute/postprocess.py new file mode 100644 index 00000000000..9a1f32e767a --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/postprocess.py @@ -0,0 +1,60 @@ +# 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 + +batch_size = 1 +parser = argparse.ArgumentParser(description="face attribute acc postprocess") +parser.add_argument("--result_path", type=str, required=True, help="result files path.") +parser.add_argument("--label_path", type=str, default="./data/label", required=True, help="image label 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) + +def get_result(result_path, img_label_path): + """get accuracy result""" + files = os.listdir(img_label_path) + preds_age = [] + preds_gen = [] + preds_mask = [] + labels_age = [] + labels_gen = [] + labels_mask = [] + for file in files: + label = np.fromfile(os.path.join(img_label_path, file), dtype=np.int32) + labels_age.append(int(label[0])) + labels_gen.append(int(label[1])) + labels_mask.append(int(label[2])) + file_name = file.split('.')[0] + age_result_path = os.path.join(result_path, file_name+'_0.bin') + gen_result_path = os.path.join(result_path, file_name+'_1.bin') + mask_result_path = os.path.join(result_path, file_name+'_2.bin') + output_age = np.fromfile(age_result_path, dtype=np.float32) + output_gen = np.fromfile(gen_result_path, dtype=np.float32) + output_mask = np.fromfile(mask_result_path, dtype=np.float32) + preds_age.append(np.argmax(output_age, axis=0)) + preds_gen.append(np.argmax(output_gen, axis=0)) + preds_mask.append(np.argmax(output_mask, axis=0)) + age_acc = calcul_acc(labels_age, preds_age) + gen_acc = calcul_acc(labels_gen, preds_gen) + mask_acc = calcul_acc(labels_mask, preds_mask) + print("age accuracy: {}".format(age_acc)) + print("gen accuracy: {}".format(gen_acc)) + print("mask accuracy: {}".format(mask_acc)) +if __name__ == '__main__': + get_result(args.result_path, args.label_path) diff --git a/model_zoo/research/cv/FaceAttribute/preprocess.py b/model_zoo/research/cv/FaceAttribute/preprocess.py new file mode 100644 index 00000000000..bb909b83055 --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/preprocess.py @@ -0,0 +1,80 @@ +# 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 +from src.config import config +import mindspore.dataset as de +import mindspore.dataset.vision.py_transforms as F +import mindspore.dataset.transforms.py_transforms as F2 + +def parse_args(): + """parse_args""" + parser = argparse.ArgumentParser(description='face attribute dataset to bin') + parser.add_argument('--model_path', type=str, default='', help='mindir path referenced') + parser.add_argument('--mindrecord_path', type=str, default='', help='mindir file path') + args_opt = parser.parse_args() + return args_opt + +def eval_data_generator(args): + '''Build eval dataloader.''' + mindrecord_path = args.mindrecord_path + dst_w = args.dst_w + dst_h = args.dst_h + batch_size = 1 + #attri_num = args.attri_num + transform_img = F2.Compose([F.Decode(), + F.Resize((dst_w, dst_h)), + F.ToTensor(), + F.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) + + de_dataset = de.MindDataset(mindrecord_path + "0", columns_list=["image", "label"]) + de_dataset = de_dataset.map(input_columns="image", operations=transform_img, num_parallel_workers=args.workers, + python_multiprocessing=True) + de_dataset = de_dataset.batch(batch_size) + + #de_dataloader = de_dataset.create_tuple_iterator(output_numpy=True) + steps_per_epoch = de_dataset.get_dataset_size() + print("image number:{0}".format(steps_per_epoch)) + #num_classes = attri_num + return de_dataset + +if __name__ == "__main__": + args_1 = parse_args() + args_1.dst_h = config.dst_h + args_1.dst_w = config.dst_w + args_1.attri_num = config.attri_num + args_1.classes = config.classes + args_1.flat_dim = config.flat_dim + args_1.fc_dim = config.fc_dim + args_1.workers = config.workers + ds = eval_data_generator(args_1) + cur_dir = os.getcwd() + image_path = os.path.join(cur_dir, './data/image') + if not os.path.isdir(image_path): + os.makedirs(image_path) + image_label_path = os.path.join(cur_dir, './data/label') + if not os.path.isdir(image_label_path): + os.makedirs(image_label_path) + total = ds.get_dataset_size() + iter_num = 0 + for data in ds.create_dict_iterator(output_numpy=True, num_epochs=1): + file_name = "face_" + str(iter_num) + '.bin' + img_np = data['image'] + image_label = data['label'] + img_np.tofile(os.path.join(image_path, file_name)) + image_label.tofile(os.path.join(image_label_path, file_name)) + iter_num += 1 + print("total num of images:", total) diff --git a/model_zoo/research/cv/FaceAttribute/scripts/run_infer_310.sh b/model_zoo/research/cv/FaceAttribute/scripts/run_infer_310.sh new file mode 100644 index 00000000000..15ba2092691 --- /dev/null +++ b/model_zoo/research/cv/FaceAttribute/scripts/run_infer_310.sh @@ -0,0 +1,120 @@ +#!/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 2 || $# -gt 3 ]]; then + echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [DATASET_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) +input_path=$(get_real_path $2) +device_id=0 +if [ $# == 3 ]; then + device_id=$3 +fi + +echo "mindir name: "$model +echo "input path: "$input_path +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 data ]; then + rm -rf ./data + fi + mkdir data + python3.7 ../preprocess.py --mindrecord_path=$input_path +} + +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 --input0_path=./data/image --device_id=$device_id &> infer.log + +} + +function cal_acc() +{ + python3.7 ../postprocess.py --result_path=./result_Files --label_path=./data/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