diff --git a/official/cv/lenet/ascend310_infer/src/main.cc b/official/cv/lenet/ascend310_infer/src/main.cc
index ae23279ccd4e8f948fd108df0bc65676e72330da..d856e39f472426d3b4deb9bb7f5dfe995b53f8af 100644
--- a/official/cv/lenet/ascend310_infer/src/main.cc
+++ b/official/cv/lenet/ascend310_infer/src/main.cc
@@ -31,6 +31,8 @@
#include "include/dataset/vision_ascend.h"
#include "include/dataset/execute.h"
#include "include/dataset/vision.h"
+#include "include/dataset/vision_lite.h"
+
#include "inc/utils.h"
using mindspore::Context;
@@ -47,6 +49,8 @@ using mindspore::dataset::vision::Resize;
using mindspore::dataset::vision::HWC2CHW;
using mindspore::dataset::vision::Normalize;
using mindspore::dataset::vision::Decode;
+using mindspore::dataset::vision::Rescale;
+using mindspore::dataset::vision::RGB2GRAY;
DEFINE_string(mindir_path, "", "mindir path");
DEFINE_string(dataset_path, ".", "dataset path");
@@ -108,15 +112,14 @@ int main(int argc, char **argv) {
inputs.emplace_back(imgDvpp->Name(), imgDvpp->DataType(), imgDvpp->Shape(),
imgDvpp->Data().get(), imgDvpp->DataSize());
} else {
- std::shared_ptr<TensorTransform> decode(new Decode());
- std::shared_ptr<TensorTransform> hwc2chw(new HWC2CHW());
- std::shared_ptr<TensorTransform> normalize(
- new Normalize({123.675, 116.28, 103.53}, {58.395, 57.120, 57.375}));
+ auto decode = Decode();
+ auto hwc2chw = HWC2CHW();
+ auto togray = RGB2GRAY();
+ auto rescale_op1 = Rescale(1/255.0, 0.0);
+ auto rescale_op2 = Rescale(1/ 0.3081, -1 * 0.1307 / 0.3081);
auto resizeShape = {FLAGS_image_height, FLAGS_image_width};
- std::shared_ptr<TensorTransform> resize(new Resize(resizeShape));
- auto resizeShape1 = {1, FLAGS_image_height};
- std::shared_ptr<TensorTransform> reshape_one_channel(new Resize(resizeShape1));
- Execute composeDecode({decode, resize, normalize, hwc2chw, reshape_one_channel});
+ auto resize = Resize(resizeShape);
+ Execute composeDecode({decode, togray, resize, rescale_op1, rescale_op2, hwc2chw});
auto img = MSTensor();
auto image = ReadFileToTensor(all_files[i]);
composeDecode(image, &img);
diff --git a/research/cv/RefineNet/README.md b/research/cv/RefineNet/README.md
index 4a83b074ec735e286baa20a0b7ef6956c359c44c..e9235bb6f6db9e281875cc4a7b7650a8ae5d3dfa 100644
--- a/research/cv/RefineNet/README.md
+++ b/research/cv/RefineNet/README.md
@@ -23,6 +23,10 @@
- [Ascend处理器环境运行](#ascend处理器环境运行-1)
- [结果](#结果-1)
- [训练准确率](#训练准确率)
+ - [Mindir推理](#Mindir推理)
+ - [导出模型](#导出模型)
+ - [在Ascend310执行推理](#在Ascend310执行推理)
+ - [结果](#结果)
- [模型描述](#模型描述)
- [性能](#性能)
- [评估性能](#评估性能)
@@ -347,6 +351,35 @@ cd ..
| :----------: | :-----: | :-------------: |
| refinenet | 80.3 | 80.3 |
+## Mindir推理
+
+### [导出模型](#contents)
+
+```shell
+python export.py --checkpoint [CKPT_PATH] --file_name [FILE_NAME] --file_format [FILE_FORMAT]
+```
+
+- 参数`checkpoint`为必填项。
+- `file_format` 必须在 ["AIR", "MINDIR"]中选择。
+
+### 在Ascend310执行推理
+
+在执行推理前,mindir文件必须通过`export.py`脚本导出。以下展示了使用mindir模型执行推理的示例。
+目前仅支持batch_size为1的推理。
+
+```shell
+# Ascend310 inference
+bash run_infer_310.sh [MINDIR_PATH] [DATA_ROOT] [DATA_LIST] [DEVICE_ID]
+```
+
+- `DATA_ROOT` 表示进入模型推理数据集的根目录。
+- `DATA_LIST` 表示进入模型推理数据集的文件列表。
+- `DEVICE_ID` 可选,默认值为0。
+
+### 结果
+
+推理结果保存在脚本执行的当前路径,你可以在acc.log中看到以下精度计算结果。
+
# 模型描述
## 性能
diff --git a/research/cv/RefineNet/ascend310_infer/CMakeLists.txt b/research/cv/RefineNet/ascend310_infer/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..671784a2aa030b419c494501dedb5fb27ed5f24e
--- /dev/null
+++ b/research/cv/RefineNet/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)
\ No newline at end of file
diff --git a/research/cv/RefineNet/ascend310_infer/build.sh b/research/cv/RefineNet/ascend310_infer/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c7aac7196661fcfa50c3de063336355bf3831286
--- /dev/null
+++ b/research/cv/RefineNet/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="`pip show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`"
+make
\ No newline at end of file
diff --git a/research/cv/RefineNet/ascend310_infer/inc/utils.h b/research/cv/RefineNet/ascend310_infer/inc/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..8f14820084b4982caf7acfd85f6bb69e1c83b098
--- /dev/null
+++ b/research/cv/RefineNet/ascend310_infer/inc/utils.h
@@ -0,0 +1,34 @@
+/**
+ * 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);
+std::vector<std::string> GetImagesById(const std::string &idFile, const std::string &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::string& segstr,
+ const std::vector<mindspore::MSTensor> &outputs);
+#endif
diff --git a/research/cv/RefineNet/ascend310_infer/src/main.cc b/research/cv/RefineNet/ascend310_infer/src/main.cc
new file mode 100644
index 0000000000000000000000000000000000000000..8833a7054a58397b0d29989fc0ecabed88d5797f
--- /dev/null
+++ b/research/cv/RefineNet/ascend310_infer/src/main.cc
@@ -0,0 +1,226 @@
+/**
+ * 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/types.h"
+#include "include/api/serialization.h"
+#include "include/dataset/vision.h"
+#include "include/dataset/execute.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::TensorTransform;
+using mindspore::dataset::vision::Resize;
+using mindspore::dataset::vision::Pad;
+using mindspore::dataset::vision::HWC2CHW;
+using mindspore::dataset::vision::Normalize;
+using mindspore::dataset::vision::SwapRedBlue;
+using mindspore::dataset::vision::Decode;
+using mindspore::dataset::vision::HorizontalFlip;
+
+
+
+DEFINE_string(mindir_path, "", "mindir path");
+DEFINE_string(image_list, "", "image list");
+DEFINE_string(dataset_path, ".", "dataset path");
+DEFINE_int32(device_id, 0, "device id");
+
+
+int PadImage(const MSTensor& input, MSTensor* output) {
+ std::shared_ptr<TensorTransform> normalize(new Normalize({ 103.53, 116.28, 123.675 },
+ { 57.375, 57.120, 58.395 }));
+ std::shared_ptr<TensorTransform> swapredblue(new SwapRedBlue());
+ Execute NormalizeBgr({normalize, swapredblue});
+ std::vector<int64_t> shape = input.Shape();
+ auto imgResize = MSTensor();
+ auto imgNormalizeBgr = MSTensor();
+ int paddingSize;
+ const int IMAGEWIDTH = 513;
+ const int IMAGEHEIGHT = 513;
+ float widthScale, heightScale;
+ widthScale = static_cast<float>(IMAGEWIDTH) / shape[1];
+ heightScale = static_cast<float>(IMAGEHEIGHT) / shape[0];
+ Status ret;
+ if (widthScale < heightScale) {
+ int heightSize = shape[0] * widthScale;
+ std::shared_ptr<TensorTransform> resize(new Resize({ heightSize, IMAGEWIDTH }));
+ Execute composeResizeWidth({ resize });
+ ret = composeResizeWidth(input, &imgResize);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Resize Width failed." << std::endl;
+ return 1;
+ }
+ ret = NormalizeBgr(imgResize, &imgNormalizeBgr);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Normalize and bgr transfer failed." << std::endl;
+ return 1;
+ }
+ paddingSize = IMAGEHEIGHT - heightSize;
+ std::shared_ptr<TensorTransform> pad(new Pad({ 0, 0, 0, paddingSize }));
+ Execute composePad({ pad });
+ ret = composePad(imgNormalizeBgr, output);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Height Pad failed." << std::endl;
+ return 1;
+ }
+ } else {
+ int widthSize = shape[1] * heightScale;
+ std::shared_ptr<TensorTransform> resize(new Resize({ IMAGEHEIGHT, widthSize }));
+ Execute composeResizeHeight({ resize });
+ ret = composeResizeHeight(input, &imgResize);
+
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Resize Height failed." << std::endl;
+ return 1;
+ }
+ ret = NormalizeBgr(imgResize, &imgNormalizeBgr);
+
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Normalize and bgr transfer failed." << std::endl;
+ return 1;
+ }
+ paddingSize = IMAGEWIDTH - widthSize;
+ std::shared_ptr<TensorTransform> pad(new Pad({ 0, 0, paddingSize, 0 }));
+ Execute composePad({ pad });
+ ret = composePad(imgNormalizeBgr, output);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Width Pad failed." << std::endl;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+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<Context>();
+ auto ascend310 = std::make_shared<mindspore::Ascend310DeviceInfo>();
+ ascend310->SetDeviceID(FLAGS_device_id);
+ context->MutableDeviceInfo().push_back(ascend310);
+ mindspore::Graph graph;
+ Serialization::Load(FLAGS_mindir_path, ModelType::kMindIR, &graph);
+
+ Model model;
+ Status ret = model.Build(GraphCell(graph), context);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Build failed." << std::endl;
+ return 1;
+ }
+ std::vector<MSTensor> model_inputs = model.GetInputs();
+ if (model_inputs.empty()) {
+ std::cout << "Invalid model, inputs is empty." << std::endl;
+ return 1;
+ }
+
+ auto all_files = GetImagesById(FLAGS_image_list, FLAGS_dataset_path);
+ if (all_files.empty()) {
+ std::cout << "ERROR: no input data." << std::endl;
+ return 1;
+ }
+
+ std::map<double, double> costTime_map;
+ size_t size = all_files.size();
+ std::shared_ptr<TensorTransform> decode(new Decode());
+ std::shared_ptr<TensorTransform> swapredblue(new SwapRedBlue());
+ Execute DecodeBgr({decode, swapredblue});
+ Execute hwc2chw(std::make_shared<HWC2CHW>());
+ Execute horizonflip(std::make_shared<HorizontalFlip>());
+
+ for (size_t i = 0; i < size; ++i) {
+ struct timeval start = { 0 }, end = { 0 };
+ double startTimeMs, endTimeMs;
+ std::vector<MSTensor> inputs, outputs, inputFlip, outputFlip;
+ std::cout << "Start predict input files:" << all_files[i] << std::endl;
+ auto image = ReadFileToTensor(all_files[i]);
+ auto imgDecodeBgr = MSTensor();
+ ret = DecodeBgr(image, &imgDecodeBgr);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Decode and RgbToBgr failed." << std::endl;
+ return 1;
+ }
+
+ auto imgPad = MSTensor(), img = MSTensor(), imgFlip = MSTensor(), imgtrans = MSTensor();
+ PadImage(imgDecodeBgr, &imgPad);
+ hwc2chw(imgPad, &img);
+ inputs.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(),
+ img.Data().get(), img.DataSize());
+ horizonflip(imgPad, &imgtrans);
+ hwc2chw(imgtrans, &imgFlip);
+ inputFlip.emplace_back(model_inputs[0].Name(), model_inputs[0].DataType(), model_inputs[0].Shape(),
+ imgFlip.Data().get(), imgFlip.DataSize());
+ gettimeofday(&start, nullptr);
+ ret = model.Predict(inputs, &outputs);
+ gettimeofday(&end, nullptr);
+ auto retFlip = model.Predict(inputFlip, &outputFlip);
+ if ((ret != kSuccess) || (retFlip != kSuccess)) {
+ std::cout << "Predict " << all_files[i] << " failed." << std::endl;
+ return 1;
+ }
+ startTimeMs = (1.0 * start.tv_sec * 1000000 + start.tv_usec) / 1000;
+ endTimeMs = (1.0 * end.tv_sec * 1000000 + end.tv_usec) / 1000;
+ costTime_map.insert(std::pair<double, double>(startTimeMs, endTimeMs));
+ int rst = WriteResult(all_files[i], "", outputs);
+ int rstFlip = WriteResult(all_files[i], "_Flip", outputFlip);
+ if ((rst != 0) || (rstFlip != 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/RefineNet/ascend310_infer/src/utils.cc b/research/cv/RefineNet/ascend310_infer/src/utils.cc
new file mode 100644
index 0000000000000000000000000000000000000000..4685b9162eac127e66186c973382b6d41fc0e4f6
--- /dev/null
+++ b/research/cv/RefineNet/ascend310_infer/src/utils.cc
@@ -0,0 +1,163 @@
+/**
+ * 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::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;
+}
+
+std::vector<std::string> GetImagesById(const std::string &idFile, const std::string &dirName) {
+ std::ifstream readFile(idFile);
+ std::string line;
+ std::vector<std::string> result;
+
+ if (!readFile.is_open()) {
+ std::cout << "can not open image id txt file" << std::endl;
+ return result;
+ }
+
+ while (getline(readFile, line)) {
+ std::size_t pos = line.find(" ");
+ std::string id = line.substr(0, pos);
+ result.emplace_back(dirName + "/" + id);
+ }
+
+ return result;
+}
+
+
+int WriteResult(const std::string& imageFile, const std::string& segstr, const std::vector<MSTensor> &outputs) {
+ std::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;
+ 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) + segstr + ".bin");
+ std::string outFileName = homePath + "/" + fileName;
+ FILE * outputFile = fopen(outFileName.c_str(), "wb");
+ if (outputFile == nullptr) {
+ std::cout << "open result file " << outFileName << " failed" << std::endl;
+ return INVALID_POINTER;
+ }
+ size_t size = fwrite(netOutput.get(), sizeof(char), outputSize, outputFile);
+ if (size != outputSize) {
+ fclose(outputFile);
+ outputFile = nullptr;
+ std::cout << "write result file " << outFileName << " failed, write size[" << size <<
+ "] is smaller than output size[" << outputSize << "], maybe the disk is full." << std::endl;
+ return ERROR;
+ }
+ fclose(outputFile);
+ outputFile = nullptr;
+ }
+ return 0;
+}
+
+MSTensor ReadFileToTensor(const std::string &file) {
+ if (file.empty()) {
+ std::cout << "Pointer file is nullptr" << std::endl;
+ return MSTensor();
+ }
+
+ std::ifstream ifs(file);
+ if (!ifs.good()) {
+ std::cout << "File: " << file << " is not exist" << std::endl;
+ return MSTensor();
+ }
+
+ if (!ifs.is_open()) {
+ std::cout << "File: " << file << "open failed" << std::endl;
+ return MSTensor();
+ }
+
+ ifs.seekg(0, std::ios::end);
+ size_t size = ifs.tellg();
+ 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/RefineNet/export.py b/research/cv/RefineNet/export.py
index b14169ffbf80680785f26d33c88bc249bfc68cf1..47ca67d590ed66fff3c6eeb5b7b6e5807c4bb425 100644
--- a/research/cv/RefineNet/export.py
+++ b/research/cv/RefineNet/export.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
-"""export AIR file."""
+"""export file."""
import argparse
import numpy as np
from mindspore import Tensor, context, load_checkpoint, load_param_into_net, export
@@ -24,13 +24,17 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser(description='checkpoint export')
parser.add_argument('--checkpoint', type=str, default='', help='checkpoint of refinenet (Default: None)')
parser.add_argument('--num_classes', type=int, default=21, help='the number of classes (Default: 21)')
+ parser.add_argument('--batch_size', type=int, default=1, help='batch size')
+ parser.add_argument('--crop_size', type=int, default=513, help='crop size')
+ parser.add_argument('--file_name', type=str, default="refinenet", help='model name')
+ parser.add_argument('--file_format', type=str, choices=["MINDIR", "AIR"], default="MINDIR", help='model format')
args = parser.parse_args()
-
network = RefineNet(Bottleneck, [3, 4, 23, 3], args.num_classes)
param_dict = load_checkpoint(args.checkpoint)
# load the parameter into net
load_param_into_net(network, param_dict)
- input_data = np.random.uniform(0.0, 1.0, size=[32, 3, 513, 513]).astype(np.float32)
- export(network, Tensor(input_data), file_name=args.model + '-300_11.air', file_format='AIR')
+ image_shape = [args.batch_size, 3, args.crop_size, args.crop_size]
+ input_data = np.random.uniform(0.0, 1.0, size=image_shape).astype(np.float32)
+ export(network, Tensor(input_data), file_name=args.file_name, file_format=args.file_format)
diff --git a/research/cv/RefineNet/postprocess.py b/research/cv/RefineNet/postprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac3a3f906693efc7546564c4b3b8f3baddbc5141
--- /dev/null
+++ b/research/cv/RefineNet/postprocess.py
@@ -0,0 +1,85 @@
+# 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
+from PIL import Image
+import cv2
+
+parser = argparse.ArgumentParser(description="refinenet accuracy calculation")
+parser.add_argument('--data_root', type=str, default='./vocaug_single', help='root path of val data')
+parser.add_argument('--data_lst', type=str, default='', help='list of val data')
+parser.add_argument('--crop_size', type=int, default=513, help='crop size')
+parser.add_argument('--num_classes', type=int, default=21, help='number of classes')
+parser.add_argument('--result_path', type=str, default='./result_Files', help='result Files path')
+parser.add_argument('--flip', action='store_true', help='perform left-right flip')
+args, _ = parser.parse_known_args()
+
+def get_img_size(file_name):
+ img = Image.open(file_name)
+ return img.size
+
+def get_resized_size(org_h, org_w, long_size=513):
+ if org_h > org_w:
+ new_h = long_size
+ new_w = int(1.0 * long_size * org_w / org_h)
+ else:
+ new_w = long_size
+ new_h = int(1.0 * long_size * org_h / org_w)
+
+ return new_h, new_w
+
+def cal_hist(a, b, n):
+ k = (a >= 0) & (a < n)
+ return np.bincount(n * a[k].astype(np.int32) + b[k], minlength=n ** 2).reshape(n, n)
+
+def acc_cal():
+ ''' calculate accuarcy'''
+ hist = np.zeros((args.num_classes, args.num_classes))
+ with open(args.data_lst) as f:
+ img_lst = f.readlines()
+
+ for line in enumerate(img_lst):
+ img_path, msk_path = line[1].strip().split(' ')
+ img_file_path = os.path.join(args.data_root, img_path)
+ org_width, org_height = get_img_size(img_file_path)
+ resize_h, resize_w = get_resized_size(org_height, org_width)
+
+ result_file = os.path.join(args.result_path, os.path.basename(img_path).split('.jpg')[0] + '_0.bin')
+ net_out = np.fromfile(result_file, np.float32).reshape(args.num_classes, args.crop_size, args.crop_size)
+ if args.flip:
+ bin_path = os.path.basename(img_path).split('.jpg')[0] + '_0_Flip.bin'
+ net_out_flip = np.fromfile(os.path.join(args.result_path, bin_path), np.float32)
+ net_out_flip = net_out_flip.reshape(args.num_classes, args.crop_size, args.crop_size)
+ net_out += net_out_flip[:, :, ::-1]
+
+ probs_ = net_out[:, :resize_h, :resize_w].transpose((1, 2, 0))
+ probs_ = cv2.resize(probs_, (org_width, org_height))
+
+ result_msk = probs_.argmax(axis=2)
+
+ msk_path = os.path.join(args.data_root, msk_path)
+ mask = cv2.imread(msk_path, cv2.IMREAD_GRAYSCALE)
+
+ hist += cal_hist(mask.flatten(), result_msk.flatten(), args.num_classes)
+
+ print(hist)
+ iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist))
+ print('per-class IoU', iu)
+ print('mean IoU', np.nanmean(iu))
+
+if __name__ == '__main__':
+ acc_cal()
diff --git a/research/cv/RefineNet/scripts/run_infer_310.sh b/research/cv/RefineNet/scripts/run_infer_310.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2e0557a5e6b60452a24b199044578b52228e11e7
--- /dev/null
+++ b/research/cv/RefineNet/scripts/run_infer_310.sh
@@ -0,0 +1,98 @@
+#!/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 3 || $# -gt 4 ]]; then
+ echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [DATA_ROOT] [DATA_LIST] [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_root=$(get_real_path $2)
+data_list_path=$(get_real_path $3)
+
+
+device_id=0
+if [ $# == 4 ]; then
+ device_id=$4
+fi
+
+echo "mindir name: "$model
+echo "data root path: "$data_root
+echo "data list path: "$data_list_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 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_path=$data_root --image_list=$data_list_path --device_id=$device_id &> infer.log
+}
+
+function cal_acc()
+{
+ python ../postprocess.py --data_root=$data_root --data_lst=$data_list_path --scales=1.0 --result_path=./result_Files --flip &> acc.log
+}
+
+compile_app
+if [ $? -ne 0 ]; then
+ echo "compile app code failed"
+ exit 1
+fi
+infer
+if [ $? -ne 0 ]; then
+ echo " execute inference failed"
+ exit 1
+fi
+cal_acc
+if [ $? -ne 0 ]; then
+ echo "calculate accuracy failed"
+ exit 1
+fi
diff --git a/research/cv/meta-baseline/README.md b/research/cv/meta-baseline/README.md
index 2ce8b0478cd0d09b30e6a336428335cc94fcc30e..80a5d3163a8a63e0a5a982f217be9c0ea7906e69 100644
--- a/research/cv/meta-baseline/README.md
+++ b/research/cv/meta-baseline/README.md
@@ -14,6 +14,10 @@
- [1. Training Classifier-Baseline](#1-training-classifier-baseline)
- [2. Training Meta-Baseline](#2-training-meta-baseline)
- [3. Test](#3-test)
+ - [Inference Process](#inference-process)
+ - [Export MindIR](#export-mindir)
+ - [Infer on Ascend310](#infer-on-ascend310)
+ - [result](#result)
- [Performance](#Performance)
- [Citation](#citation)
@@ -200,6 +204,38 @@ python eval.py --load_encoder (dir) --num_shots 1 --root_path ./dataset/ --devic
```
+## Inference Process
+
+### [Export MindIR](#contents)
+
+```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"].
+
+### 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] [ROOT_PATH] [NEED_PREPROCESS] [DEVICE_ID]
+
+```
+
+- `ROOT_PATH` the root path of validation dataset.
+- `NEED_PREPROCESS` means weather need preprocess or not, it's value is 'y' or 'n'.
+- `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.
+
## [Performance](#Contents)
### Training Performance
diff --git a/research/cv/meta-baseline/ascend310_infer/CMakeLists.txt b/research/cv/meta-baseline/ascend310_infer/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ee3c85447340e0449ff2b70ed24f60a17e07b2b6
--- /dev/null
+++ b/research/cv/meta-baseline/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/research/cv/meta-baseline/ascend310_infer/build.sh b/research/cv/meta-baseline/ascend310_infer/build.sh
new file mode 100644
index 0000000000000000000000000000000000000000..713d7f657ddfa5f75b069351c55f8447f77c72d0
--- /dev/null
+++ b/research/cv/meta-baseline/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="`pip show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`"
+make
diff --git a/research/cv/meta-baseline/ascend310_infer/inc/utils.h b/research/cv/meta-baseline/ascend310_infer/inc/utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..efebe03a8c1179f5a1f9d5f7ee07e0352a9937c6
--- /dev/null
+++ b/research/cv/meta-baseline/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 <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);
+#endif
diff --git a/research/cv/meta-baseline/ascend310_infer/src/main.cc b/research/cv/meta-baseline/ascend310_infer/src/main.cc
new file mode 100644
index 0000000000000000000000000000000000000000..dffc0b562622287ad725b8e759a4a612d18fc5e9
--- /dev/null
+++ b/research/cv/meta-baseline/ascend310_infer/src/main.cc
@@ -0,0 +1,129 @@
+/**
+ * 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/execute.h"
+#include "include/dataset/vision.h"
+#include "inc/utils.h"
+
+using mindspore::Context;
+using mindspore::Serialization;
+using mindspore::Model;
+using mindspore::Status;
+using mindspore::MSTensor;
+using mindspore::dataset::Execute;
+using mindspore::ModelType;
+using mindspore::GraphCell;
+using mindspore::kSuccess;
+
+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<Context>();
+ auto ascend310 = std::make_shared<mindspore::Ascend310DeviceInfo>();
+ ascend310->SetDeviceID(FLAGS_device_id);
+ context->MutableDeviceInfo().push_back(ascend310);
+ mindspore::Graph graph;
+ Serialization::Load(FLAGS_mindir_path, ModelType::kMindIR, &graph);
+
+ Model model;
+ Status ret = model.Build(GraphCell(graph), context);
+ if (ret != kSuccess) {
+ std::cout << "ERROR: Build failed." << std::endl;
+ return 1;
+ }
+
+ std::vector<MSTensor> 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: input data empty." << std::endl;
+ return 1;
+ }
+
+ std::map<double, double> 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<MSTensor> inputs;
+ std::vector<MSTensor> outputs;
+ 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);
+ 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));
+ 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/research/cv/meta-baseline/ascend310_infer/src/utils.cc b/research/cv/meta-baseline/ascend310_infer/src/utils.cc
new file mode 100644
index 0000000000000000000000000000000000000000..c947e4d5f451b90bd4728aa3a92c4cfab174f5e6
--- /dev/null
+++ b/research/cv/meta-baseline/ascend310_infer/src/utils.cc
@@ -0,0 +1,129 @@
+/**
+ * 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::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/meta-baseline/export.py b/research/cv/meta-baseline/export.py
index 05998c7d68a84980c103fec148ce48bcff441152..22379f936bd11991c92fa39877d09b0ba35a24ab 100644
--- a/research/cv/meta-baseline/export.py
+++ b/research/cv/meta-baseline/export.py
@@ -25,7 +25,7 @@ from src.model.classifier import Classifier
parser = argparse.ArgumentParser(description='meta-baseline')
parser.add_argument('--device_id', type=int, default=0, help='Device id.')
-parser.add_argument("--batch_size", type=int, default=128, help="batch size")
+parser.add_argument("--batch_size", type=int, default=320, help="batch size")
parser.add_argument('--n_classes', type=int, default=64)
parser.add_argument('--ckpt_file', type=str, required=True, help='Checkpoint file path.')
parser.add_argument('--file_name', type=str, default='meta_baseline', help='Output file name.')
@@ -45,7 +45,7 @@ if __name__ == '__main__':
assert args.ckpt_file is not None, "args.ckpt_file is None."
param_dict = load_checkpoint(args.ckpt_file)
load_param_into_net(network, param_dict)
-
+ network.set_train(mode=False)
img = Tensor(np.ones([args.batch_size, 3, 84, 84]), mstype.float32)
- export(network, img, file_name=args.file_name, file_format=args.file_format)
+ export(network.encoder, img, file_name=args.file_name, file_format=args.file_format)
diff --git a/research/cv/meta-baseline/postprocess.py b/research/cv/meta-baseline/postprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..a55629c61c0636f17cc0f67564a3168205da2c1e
--- /dev/null
+++ b/research/cv/meta-baseline/postprocess.py
@@ -0,0 +1,94 @@
+# 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
+"""
+import os
+import argparse
+from functools import reduce
+import numpy as np
+import mindspore as ms
+from mindspore import ops, Tensor, context
+import src.util as util
+
+def cal_acc(args):
+ """
+ :return: meta-baseline eval
+ """
+ temp = 5.
+ n_shots = [args.num_shots]
+ file_num = int(len(os.listdir(args.post_result_path)) / args.num_shots)
+
+ aves_keys = ['tl', 'ta', 'vl', 'va']
+ for n_shot in n_shots:
+ aves_keys += ['fsa-' + str(n_shot)]
+ aves = {k: util.Averager() for k in aves_keys}
+
+ label_list = np.load(os.path.join(args.pre_result_path, "label.npy"), allow_pickle=True)
+ shape_list = np.load(os.path.join(args.pre_result_path, "shape.npy"), allow_pickle=True)
+ x_shot_shape = shape_list[0]
+ x_query_shape = shape_list[1]
+ shot_shape = x_shot_shape[:-3]
+ query_shape = x_query_shape[:-3]
+ x_shot_len = reduce(lambda x, y: x*y, shot_shape)
+ x_query_len = reduce(lambda x, y: x*y, query_shape)
+
+ for i, n_shot in enumerate(n_shots):
+ np.random.seed(0)
+ label_shot = label_list[i]
+ for j in range(file_num):
+ labels = Tensor(label_shot[j])
+ f = os.path.join(args.post_result_path, "nshot_" + str(i) + "_" + str(j) + "_0.bin")
+ x_tot = Tensor(np.fromfile(f, np.float32).reshape(args.batch_size, 512))
+ x_shot, x_query = x_tot[:x_shot_len], x_tot[-x_query_len:]
+ x_shot = x_shot.view(*shot_shape, -1)
+ x_query = x_query.view(*query_shape, -1)
+
+ ########## cross-class bias ############
+ bs = x_shot.shape[0]
+ fs = x_shot.shape[-1]
+ bias = x_shot.view(bs, -1, fs).mean(1) - x_query.mean(1)
+ x_query = x_query + ops.ExpandDims()(bias, 1)
+
+ x_shot = x_shot.mean(axis=-2)
+ x_shot = ops.L2Normalize(axis=-1)(x_shot)
+ x_query = ops.L2Normalize(axis=-1)(x_query)
+ logits = ops.BatchMatMul()(x_query, x_shot.transpose(0, 2, 1))
+
+ logits = logits * temp
+
+ ret = ops.Argmax()(logits) == labels.astype(ms.int32)
+ acc = ret.astype(ms.float32).mean()
+ aves['fsa-' + str(n_shot)].add(acc.asnumpy())
+
+ for k, v in aves.items():
+ aves[k] = v.item()
+ for n_shot in n_shots:
+ key = 'fsa-' + str(n_shot)
+ print("epoch {}, {}-shot, val acc {:.4f}".format(str(1), n_shot, aves[key]))
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--device_target', type=str, default='CPU', choices=['Ascend', 'GPU', 'CPU'])
+ parser.add_argument('--dataset', default='mini-imagenet')
+ parser.add_argument('--post_result_path', default='./result_Files')
+ parser.add_argument('--pre_result_path', type=str, default='./preprocess_Result')
+ parser.add_argument('--batch_size', type=int, default=320)
+ parser.add_argument('--num_shots', type=int, default=1)
+ args_opt = parser.parse_args()
+ context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, save_graphs=False)
+
+ cal_acc(args_opt)
diff --git a/research/cv/meta-baseline/preprocess.py b/research/cv/meta-baseline/preprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..f770f263fb63343552800ca92b0c9c3d6fc14812
--- /dev/null
+++ b/research/cv/meta-baseline/preprocess.py
@@ -0,0 +1,92 @@
+# 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 mindspore import ops, context
+import mindspore.dataset as ds
+import src.util as util
+from src.data.IterSamplers import CategoriesSampler
+from src.data.mini_Imagenet import MiniImageNet
+
+
+def gen_bin(args):
+ """
+ generate binary files
+ """
+ n_way = 5
+ n_query = 15
+ n_shots = [args.num_shots]
+ root_path = os.path.join(args.root_path, args.dataset)
+ testset = MiniImageNet(root_path, 'test')
+
+ fs_loaders = []
+ for n_shot in n_shots:
+ test_sampler = CategoriesSampler(testset.data, testset.label, n_way, n_shot + n_query,
+ 200,
+ args.ep_per_batch)
+ test_loader = ds.GeneratorDataset(test_sampler, ['data'], shuffle=True)
+ fs_loaders.append(test_loader)
+
+ input_path = os.path.join(args.pre_result_path, "00_data")
+ label_path = os.path.join(args.pre_result_path, "label.npy")
+ shape_path = os.path.join(args.pre_result_path, "shape.npy")
+ if not os.path.exists(input_path):
+ os.makedirs(input_path)
+
+ label_list = []
+ shape_list = []
+ for i, n_shot in enumerate(n_shots):
+ np.random.seed(0)
+ label_shot = []
+ for j, data in enumerate(fs_loaders[i].create_dict_iterator()):
+ x_shot, x_query = data['data'][:, :, :n_shot], data['data'][:, :, n_shot:]
+ img_shape = x_query.shape[-3:]
+ x_query = x_query.view(args.ep_per_batch, -1,
+ *img_shape) # bs*(way*n_query)*3*84*84
+ label = util.make_nk_label(n_way, n_query, args.ep_per_batch) # bs*(way*n_query)
+ if j == 0:
+ shape_list.append(x_shot.shape)
+ shape_list.append(x_query.shape)
+
+ img_shape = x_shot.shape[-3:]
+
+ x_shot = x_shot.view(-1, *img_shape)
+ x_query = x_query.view(-1, *img_shape)
+ input0 = ops.Concat(0)([x_shot, x_query])
+ file_name = "nshot_" + str(i) + "_" + str(j) + ".bin"
+ input0.asnumpy().tofile(os.path.join(input_path, file_name))
+ label_shot.append(label.asnumpy())
+ label_list.append(label_shot)
+
+ np.save(label_path, label_list)
+ np.save(shape_path, shape_list)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--root_path', default='./dataset/')
+ parser.add_argument('--device_target', type=str, default='CPU', choices=['Ascend', 'GPU', 'CPU'])
+ parser.add_argument('--dataset', default='mini-imagenet')
+ parser.add_argument('--ep_per_batch', type=int, default=4)
+ parser.add_argument('--pre_result_path', type=str, default='./preprocess_Result')
+ parser.add_argument('--num_shots', type=int, default=1)
+
+ args_opt = parser.parse_args()
+ context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, save_graphs=False)
+ gen_bin(args_opt)
diff --git a/research/cv/meta-baseline/scripts/run_infer_310.sh b/research/cv/meta-baseline/scripts/run_infer_310.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2bc7d49a55a47fd771b2ee303ec75e89fe3b86c4
--- /dev/null
+++ b/research/cv/meta-baseline/scripts/run_infer_310.sh
@@ -0,0 +1,122 @@
+#!/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 3 || $# -gt 4 ]]; then
+ echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [ROOT_PATH] [NEED_PREPROCESS] [DEVICE_ID]
+ 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)
+dataset_root_path=$(get_real_path $2)
+
+if [ "$3" == "y" ] || [ "$3" == "n" ];then
+ need_preprocess=$3
+else
+ echo "weather need preprocess or not, it's value must be in [y, n]"
+ exit 1
+fi
+
+device_id=0
+if [ $# == 4 ]; then
+ device_id=$4
+fi
+
+echo "mindir name: "$model
+echo "root dataset path: "$dataset_root_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
+
+function preprocess_data()
+{
+ if [ -d preprocess_Result ]; then
+ rm -rf ./preprocess_Result
+ fi
+ mkdir preprocess_Result
+ python ../preprocess.py --root_path $dataset_root_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=./preprocess_Result/00_data --device_id=$device_id &> infer.log
+
+}
+
+function cal_acc()
+{
+ python ../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
+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