diff --git a/research/cv/ProtoNet/README.md b/research/cv/ProtoNet/README.md index 84d821c65bfb810493c041f428bbe3e7f00fe777..4f17b2f33bddf91e981771412879e7b7fe094ddd 100644 --- a/research/cv/ProtoNet/README.md +++ b/research/cv/ProtoNet/README.md @@ -157,6 +157,38 @@ Test Acc in Ascend: 0.9954400658607483 Loss: 0.02102319709956646 Test Acc in GPU: 0.996999979019165 Loss: 0.013885765336453915 ``` +## [Inference Process](#contents) + +### [Export MindIR](#contents) + +```shell +python export.py --ckpt_file [CKPT_PATH] --file_format [FILE_FORMAT] +``` + +The ckpt_file parameter is required, +`EXPORT_FORMAT` should be in ["AIR", "MINDIR"] + +### [Infer on Ascend310](#contents) + +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_PATH] [DEVICE_ID] +``` + +- `MINDIR_PATH` specifies path of used "MINDIR" OR "AIR" model. +- `DATASET_PATH` specifies path of omniglot datasets +- `DEVICE_ID` is optional, default value is 0. + +### [Result](#contents) + +Inference result is saved in current path, you can find result like this in acc.log file. + +```bash +'acc': 0.9956 +``` + # [Model Description](#contents) ## [Performance](#contents) diff --git a/research/cv/ProtoNet/ascend310_infer/CMakeLists.txt b/research/cv/ProtoNet/ascend310_infer/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d580e7e6d96afc8ff0449eef913f908585e46e67 --- /dev/null +++ b/research/cv/ProtoNet/ascend310_infer/CMakeLists.txt @@ -0,0 +1,20 @@ +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*) +find_package(gflags REQUIRED) + +add_executable(main src/main.cc src/utils.cc) +target_link_libraries(main ${MS_LIB} ${MD_LIB} gflags) + diff --git a/research/cv/ProtoNet/ascend310_infer/build.sh b/research/cv/ProtoNet/ascend310_infer/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..770a8851efade7f352039fc8665d307ae1abbb00 --- /dev/null +++ b/research/cv/ProtoNet/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/research/cv/ProtoNet/ascend310_infer/inc/utils.h b/research/cv/ProtoNet/ascend310_infer/inc/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..52f9eb4354787c4cc67fc3c284bd849e29db5e86 --- /dev/null +++ b/research/cv/ProtoNet/ascend310_infer/inc/utils.h @@ -0,0 +1,41 @@ +/** + * 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" + +namespace ms = mindspore; +// using namespace std; +using std::vector; +using std::string; +using std::string_view; + + +vector<string> GetAllFiles(string_view dir_name); +DIR *OpenDir(string_view dir_name); +string RealPath(string_view path); +ms::MSTensor ReadFile(const string &file); +size_t GetMax(ms::MSTensor data); +int WriteResult(const string& imageFile, const vector<mindspore::MSTensor> &outputs); + +#endif diff --git a/research/cv/ProtoNet/ascend310_infer/src/main.cc b/research/cv/ProtoNet/ascend310_infer/src/main.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac2b9e9038ce4508bde3b1f62c31be81280c99dd --- /dev/null +++ b/research/cv/ProtoNet/ascend310_infer/src/main.cc @@ -0,0 +1,135 @@ +/** + * 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/context.h" +#include "include/api/model.h" +#include "include/api/serialization.h" +#include "include/dataset/execute.h" +#include "include/api/types.h" +#include "include/dataset/vision_ascend.h" +#include "include/dataset/vision.h" +#include "../inc/utils.h" + +namespace ms = mindspore; +namespace ds = mindspore::dataset; + + +DEFINE_string(mindir_path, ".", "mindir path"); +DEFINE_string(dataset_path, ".", "dataset path"); +DEFINE_int32(device_id, 0, "device id"); + + + + +int main(int argc, char **argv) { + using std::cout; + using std::endl; + using std::string; + using std::vector; + using std::make_shared; + using std::ofstream; + using std::stringstream; + using std::map; + using std::pair; + using std::ios; + gflags::ParseCommandLineFlags(&argc, &argv, true); + cout << FLAGS_mindir_path << endl; + cout << FLAGS_dataset_path << endl; + cout << FLAGS_device_id << endl; + // set context + auto context = make_shared<ms::Context>(); + auto ascend310_info = make_shared<ms::Ascend310DeviceInfo>(); + ascend310_info->SetDeviceID(FLAGS_device_id); + context->MutableDeviceInfo().push_back(ascend310_info); + // define model + ms::Graph graph; + ms::Status ret = ms::Serialization::Load(FLAGS_mindir_path, ms::ModelType::kMindIR, &graph); + if (ret != ms::kSuccess) { + cout << "Load model failed." << endl; + return 1; + } + ms::Model protoNet; + // build model + ret = protoNet.Build(ms::GraphCell(graph), context); + if (ret != ms::kSuccess) { + cout << "Build model failed." << endl; + return 1; + } + // get model input info + vector<ms::MSTensor> model_inputs = protoNet.GetInputs(); + if (model_inputs.empty()) { + cout << "Invalid model, inputs is empty." << endl; + return 1; + } + // load data + vector<string> images = GetAllFiles(FLAGS_dataset_path); + map<double, double> costTime_map; + size_t size = images.size(); + // start infer + for (size_t i = 0; i < size; ++i) { + struct timeval start = {0}; + struct timeval end = {0}; + double startTimeMs; + double endTimeMs; + vector<ms::MSTensor> outputs; + vector<ms::MSTensor> inputs; + auto image = ReadFile(images[i]); + inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(), + image.Data().get(), image.DataSize()); + gettimeofday(&start, nullptr); + ret = protoNet.Predict(inputs, &outputs); + gettimeofday(&end, nullptr); + if (ret != ms::kSuccess) { + cout << "Predict model failed." << 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(pair<double, double>(startTimeMs, endTimeMs)); + WriteResult(images[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; + stringstream timeCost; + timeCost << "NN inference cost average time: "<< average << " ms of infer_count " << inferCount << endl; + cout << "NN inference cost average time: "<< average << "ms of infer_count " << inferCount << endl; + string fileName = "./time_Result" + string("/test_perform_static.txt"); + ofstream fileStream(fileName.c_str(), ios::trunc); + fileStream << timeCost.str(); + fileStream.close(); + costTime_map.clear(); + return 0; +} + + diff --git a/research/cv/ProtoNet/ascend310_infer/src/utils.cc b/research/cv/ProtoNet/ascend310_infer/src/utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..6469c6396420b0654577ba47c8aeadf960ba5189 --- /dev/null +++ b/research/cv/ProtoNet/ascend310_infer/src/utils.cc @@ -0,0 +1,170 @@ +/** + * 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" + +namespace ms = mindspore; +using mindspore::MSTensor; +using std::vector; +using std::string; +using std::string_view; +using std::sort; +using std::shared_ptr; +using std::cout; +using std::endl; +using std::ifstream; +using std::ios; + +vector<string> GetAllFiles(string_view dir_name) { + struct dirent *filename; + DIR *dir = OpenDir(dir_name); + if (dir == nullptr) { + return {}; + } + + /* read all the files in the dir ~ */ + vector<string> res; + while ((filename = readdir(dir)) != nullptr) { + string d_name = string(filename->d_name); + // get rid of "." and ".." + if (d_name == "." || d_name == ".." || filename->d_type != DT_REG) + continue; + res.emplace_back(string(dir_name) + "/" + filename->d_name); + } + + sort(res.begin(), res.end()); + return res; +} + + +int WriteResult(const string& imageFile, const vector<MSTensor> &outputs) { + string homePath = "./result_Files/"; + const int INVALID_POINTER = -1; + const int ERROR = -2; + for (size_t i = 0; i < outputs.size(); ++i) { + size_t outputSize; + shared_ptr<const void> netOutput = outputs[i].Data(); + outputSize = outputs[i].DataSize(); + int pos = imageFile.rfind('/'); + string fileName(imageFile, pos + 1); + string outFileName = homePath + "/" + fileName; + FILE *outputFile = fopen(outFileName.c_str(), "wb"); + if (outputFile == nullptr) { + cout << "open result file " << outFileName << " failed" << endl; + return INVALID_POINTER; + } + size_t size = fwrite(netOutput.get(), sizeof(char), outputSize, outputFile); + if (size != outputSize) { + fclose(outputFile); + outputFile = nullptr; + cout << "write result file " << outFileName << " failed, write size[" << size << + "] is smaller than output size[" << outputSize << "], maybe the disk is full." << endl; + return ERROR; + } + fclose(outputFile); + outputFile = nullptr; + } + return 0; +} + + + + + +DIR *OpenDir(string_view dir_name) { + // check the parameter ! + if (dir_name.empty()) { + cout << " dir_name is null ! " << endl; + return nullptr; + } + + string real_path = RealPath(dir_name); + + // check if dir_name is a valid dir + struct stat s; + lstat(real_path.c_str(), &s); + if (!S_ISDIR(s.st_mode)) { + cout << "dir_name is not a valid directory !" << endl; + return nullptr; + } + + DIR *dir; + dir = opendir(real_path.c_str()); + if (dir == nullptr) { + cout << "Can not open dir " << dir_name << endl; + return nullptr; + } + return dir; +} + + + +string RealPath(string_view path) { + char real_path_mem[PATH_MAX] = {0}; + char *real_path_ret = realpath(path.data(), real_path_mem); + + if (real_path_ret == nullptr) { + cout << "File: " << path << " is not exist."; + return ""; + } + + return string(real_path_mem); +} + + + +ms::MSTensor ReadFile(const string &file) { + if (file.empty()) { + cout << "Pointer file is nullptr" << endl; + return ms::MSTensor(); + } + + ifstream ifs(file); + if (!ifs.good()) { + cout << "File: " << file << " is not exist" << endl; + return ms::MSTensor(); + } + + if (!ifs.is_open()) { + cout << "File: " << file << "open failed" << endl; + return ms::MSTensor(); + } + + ifs.seekg(0, ios::end); + size_t size = ifs.tellg(); + ms::MSTensor buffer(file, ms::DataType::kNumberTypeUInt8, {static_cast<int64_t>(size)}, nullptr, size); + + ifs.seekg(0, ios::beg); + ifs.read(reinterpret_cast<char *>(buffer.MutableData()), size); + ifs.close(); + + return buffer; +} +size_t GetMax(ms::MSTensor data) { + float max_value = -1; + size_t max_idx = 0; + const float *p = reinterpret_cast<const float *>(data.MutableData()); + for (size_t i = 0; i < data.DataSize() / sizeof(float); ++i) { + if (p[i] > max_value) { + max_value = p[i]; + max_idx = i; + } + } + return max_idx; +} diff --git a/research/cv/ProtoNet/export.py b/research/cv/ProtoNet/export.py index 69e0ab363b753203639bd7c411d38d2fa46eadd9..8ec5f0b78aec755bf40858e2ea4519ef4ba9c04b 100644 --- a/research/cv/ProtoNet/export.py +++ b/research/cv/ProtoNet/export.py @@ -24,10 +24,10 @@ from src.protonet import ProtoNet as protonet parser = argparse.ArgumentParser(description='MindSpore MNIST Example') parser.add_argument("--device_id", type=int, default=0, help="Device id") -parser.add_argument("--batch_size", type=int, default=1, help="batch size") +parser.add_argument("--batch_size", type=int, default=100, help="batch size") parser.add_argument("--ckpt_file", type=str, required=True, help="Checkpoint file path.") parser.add_argument("--file_name", type=str, default="protonet", help="output file name.") -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", "ONNX", "MINDIR"], default="MINDIR", help="file format") parser.add_argument("--device_target", type=str, choices=["Ascend", "GPU", "CPU"], default="Ascend", help="device target") args = parser.parse_args() @@ -40,6 +40,7 @@ if __name__ == "__main__": # define fusion network network = protonet() + # load network checkpoint param_dict = load_checkpoint(args.ckpt_file) load_param_into_net(network, param_dict) diff --git a/research/cv/ProtoNet/loss_for_infer.py b/research/cv/ProtoNet/loss_for_infer.py new file mode 100644 index 0000000000000000000000000000000000000000..721b5c056da0f565ceb1eee4642431b04b790313 --- /dev/null +++ b/research/cv/ProtoNet/loss_for_infer.py @@ -0,0 +1,102 @@ +# 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. +# ============================================================================ +""" +loss function script. +""" +import heapq +import numpy as np + + +def calculate_loss(inp, target, classes, n_support, n_query, n_class, is_train=True): + """ + loss construct + """ + n_classes = len(classes) + support_idxs = () + query_idxs = () + + for ind, _ in enumerate(classes): + class_c = classes[ind] + matrix = np.equal(target, class_c).astype(np.float32) + K = n_support + n_query + a = heapq.nlargest(K, range(len(matrix)), matrix.take) + support_idx = np.squeeze(a[:n_support]) + support_idxs += (support_idx,) + query_idx = a[n_support:] + query_idxs += (query_idx,) + + prototypes = () + for idx_list in support_idxs: + prototypes += (np.mean(inp[idx_list], axis=0),) + prototypes = np.stack(prototypes) + query_idxs = np.stack(query_idxs).reshape(-1) + query_samples = inp[query_idxs] + + + dists = euclidean_dist(query_samples, prototypes) + log_p_y = np.log(np.exp(-dists) / np.sum(np.exp(-dists))) + log_p_y = log_p_y.reshape((n_classes, n_query, -1)) + + target_inds = np.arange(0, n_class, dtype=np.int32).reshape((n_classes, 1, 1)) + target_inds = np.broadcast_to(target_inds, (n_classes, n_query, 1)) + loss_val = -np.mean(np.squeeze(gather(log_p_y, 2, target_inds).reshape(-1))) + + y_hat = np.argmax(log_p_y, axis=2) + acc_val = np.mean(np.equal(y_hat, np.squeeze(target_inds)).astype(np.float32)) + if is_train: + return loss_val + return acc_val, loss_val + +def supp_idxs(target, c): + return np.squeeze(nonZero(np.equal(target, c))[:n_support]) + +def nonZero(inpbool): + out = [] + for _, inp in enumerate(inpbool): + if inp: + out.append(inp) + return np.array(out, dtype=np.int32) + +def acc(): + return acc_val + +def gather(self, dim, index): + ''' + gather + ''' + idx_xsection_shape = index.shape[:dim] + \ + index.shape[dim + 1:] + self_xsection_shape = self.shape[:dim] + self.shape[dim + 1:] + if idx_xsection_shape != self_xsection_shape: + raise ValueError("Except for dimension " + str(dim) + + ", all dimensions of index and self should be the same size") + data_swaped = np.swapaxes(self, 0, dim) + index_swaped = np.swapaxes(index, 0, dim) + gathered = np.choose(index_swaped, data_swaped) + return np.swapaxes(gathered, 0, dim) + +def euclidean_dist(x, y): + ''' + Compute euclidean distance between two tensors + ''' + # x: N x D + # y: M x D + n = x.shape[0] + m = y.shape[0] + d = x.shape[1] + x = np.broadcast_to(np.expand_dims(x, axis=1), (n, m, d)) + y = np.broadcast_to(np.expand_dims(y, axis=0), (n, m, d)) + + return np.sum(np.power(x - y, 2), 2) diff --git a/research/cv/ProtoNet/postprocess.py b/research/cv/ProtoNet/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..e2b6fa6e6ab0cc581d4240b26910ec564479c582 --- /dev/null +++ b/research/cv/ProtoNet/postprocess.py @@ -0,0 +1,51 @@ +''' +calculate the accuracy using the infer result which are binary files +''' +import os +import argparse +import numpy as np +from loss_for_infer import calculate_loss + +parser = argparse.ArgumentParser() +parser.add_argument('--result_path', default=None, help='Location of result.') +parser.add_argument('--label_classses_path', default=None, help='Location of label and classes.') +parser.add_argument('--classes_per_it_val', type=int, + help='number of random classes per episode for validation, default=5', default=5) +parser.add_argument('--num_support_val', type=int, + help='number of samples per class to use as support for validation, default=5', default=5) +parser.add_argument('--num_query_val', type=int, + help='number of samples per class to use as query for validation, default=15', default=15) + +def get_result(options): + ''' + calculate the acc + ''' + files = os.listdir(options.result_path) + acc = list() + loss = list() + for file in files: + result_file_name = file + num = result_file_name.split('_')[1] + + result_file_path = options.result_path + os.sep + result_file_name + label_file_path = options.label_classses_path + os.sep + 'label_' + str(num) + classes_file_path = options.label_classses_path + os.sep + 'classes_' + str(num) + + output = np.fromfile(result_file_path, dtype=np.float32) + label = np.fromfile(label_file_path, dtype=np.int32) + classes = np.fromfile(classes_file_path, dtype=np.int32) + batch_size = (options.num_support_val + options.num_query_val) * options.classes_per_it_val + # 64 is the fixed output dimension of the model + output = np.reshape(output, (batch_size, 64)) + + acc_val, loss_val = calculate_loss(output, label, classes, options.num_support_val, + options.num_query_val, options.classes_per_it_val, is_train=False) + acc.append(acc_val) + loss.append(loss_val) + mean_acc = sum(acc) / len(acc) + mean_loss = sum(loss) / len(loss) + print("accuracy: {} loss:{}".format(mean_acc, mean_loss)) + +if __name__ == '__main__': + options_ = parser.parse_args() + get_result(options_) diff --git a/research/cv/ProtoNet/preprocess.py b/research/cv/ProtoNet/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..813c33e5cb5d959eae9b17bc9398d1660291942d --- /dev/null +++ b/research/cv/ProtoNet/preprocess.py @@ -0,0 +1,50 @@ +''' +preprocess the source data and generate the result data with binary file +''' +import os +import argparse +from model_init import init_dataloader +from mindspore import dataset as ds + + +parser = argparse.ArgumentParser() +parser.add_argument('--dataset_path', default=None, help='Location of data.') +parser.add_argument('--data_output_path', default=None, help='Location of converted data.') +parser.add_argument('--label_classses_output_path', default=None, + help='Location of converted label and classes.') +parser.add_argument('-its', '--iterations', type=int, help='number of episodes per epoch, default=100', + default=100) +parser.add_argument('-cTr', '--classes_per_it_tr', type=int, + help='number of random classes per episode for training, default=60', default=20) +parser.add_argument('-nsTr', '--num_support_tr', type=int, + help='number of samples per class to use as support for training, default=5', default=5) +parser.add_argument('-nqTr', '--num_query_tr', type=int, + help='number of samples per class to use as query for training, default=5', default=5) +parser.add_argument('-cVa', '--classes_per_it_val', type=int, + help='number of random classes per episode for validation, default=5', default=5) +parser.add_argument('-nsVa', '--num_support_val', type=int, + help='number of samples per class to use as support for validation, default=5', default=5) +parser.add_argument('-nqVa', '--num_query_val', type=int, + help='number of samples per class to use as query for validation, default=15', default=15) + +def convert_img_to_bin(options_, root, output_path, label_classses_path): + ''' + convert the image to binary file + ''' + val_dataloader = init_dataloader(options_, 'val', root) + inp = ds.GeneratorDataset(val_dataloader, column_names=['data', 'label', 'classes']) + i = 1 + for batch in inp.create_dict_iterator(): + x = batch['data'] + y = batch['label'] + classes = batch['classes'] + x_array = x.asnumpy() + y_array = y.asnumpy() + classes_array = classes.asnumpy() + x_array.tofile(output_path + os.sep +"data_" + str(i) + ".bin") + y_array.tofile(label_classses_path + os.sep +"label_" + str(i) + ".bin") + classes_array.tofile(label_classses_path + os.sep +"classes_" + str(i) + ".bin") + i = i + 1 +if __name__ == '__main__': + options = parser.parse_args() + convert_img_to_bin(options, options.dataset_path, options.data_output_path, options.label_classses_output_path) diff --git a/research/cv/ProtoNet/scripts/run_infer_310.sh b/research/cv/ProtoNet/scripts/run_infer_310.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed6c5cf78405076de14b3ddffe62ccb88cbfffb6 --- /dev/null +++ b/research/cv/ProtoNet/scripts/run_infer_310.sh @@ -0,0 +1,113 @@ +#!/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] [DATA_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) +data_path=$(get_real_path $2) +device_id=0 +if [ $# == 3 ]; then + device_id=$3 +fi + +echo "mindir name: "$model +echo "dataset path: "$data_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 + +function preprocess_data() +{ + if [ -d data_preprocess_Result ]; then + rm -rf ./data_preprocess_Result + fi + if [ -d label_classes_preprocess_Result ]; then + rm -rf ./label_classes_preprocess_Result + fi + mkdir data_preprocess_Result + mkdir label_classes_preprocess_Result + python ../preprocess.py --dataset_path=$data_path --data_output_path=./data_preprocess_Result --label_classses_output_path=./label_classes_preprocess_Result &> preprocess.log + data_path=./data_preprocess_Result + label_classes_path=./label_classes_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 + mkdir result_Files + ../ascend310_infer/out/main --mindir_path=$model --dataset_path=$data_path --device_id=$device_id &> infer.log +} + +function cal_acc() +{ + python3.7 ../postprocess.py --result_path=./result_Files/ --label_classses_path=$label_classes_path &> acc.log & +} + + + +preprocess_data +if [ $? -ne 0 ]; then + echo "preprocess data 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