diff --git a/research/cv/SRGAN/README.md b/research/cv/SRGAN/README.md index d1bce2c0c4562041a5885513d67d5286339ed680..25e9d87290e28d8753ec23ff279421f728769e46 100644 --- a/research/cv/SRGAN/README.md +++ b/research/cv/SRGAN/README.md @@ -9,6 +9,10 @@ - [Script and Sample Code](#script-and-sample-code) - [Script Parameters](#script-parameters) - [Training Process](#training-process) +- [Inference Process](#inference-process) + - [Export MindIR](#export-mindir) + - [Infer on Ascend310](#infer-on-ascend310) + - [Result](#result) - [Model Description](#model-description) - [Performance](#performance) - [Training Performance](#training-performance) @@ -123,6 +127,34 @@ eg: sh run_eval.sh ./ckpt/best.ckpt ./Set14/LR ./Set14/HR 0 Evaluation result will be stored in the scripts/result. Under this, you can find generator pictures. +# [Inference Process](#contents) + +## [Export MindIR](#contents) + +```shell +python export.py --config_path [CONFIG_PATH] --ckpt_file [CKPT_PATH] --file_name [FILE_NAME] --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] [TEST_LR_PATH] [TEST_GT_PATH] [NEED_PREPROCESS] [DEVICE_ID] +``` + +### [Result](#contents) + +Inference result is saved in current path, you can find result like this in acc.log file. + +```bash +'avg psnr': 27.4 +``` + # [Model Description](#contents) ## [Performance](#contents) diff --git a/research/cv/SRGAN/ascend310_infer/CMakeLists.txt b/research/cv/SRGAN/ascend310_infer/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..49478f950647bd15851ae9b931c04ed190ef9cbf --- /dev/null +++ b/research/cv/SRGAN/ascend310_infer/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.14.1) +project(Ascend310Infer) +find_package(OpenCV 2 REQUIRED) +find_package(gflags REQUIRED) +add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g -std=c++17 -Werror -Wall -fPIE -Wl,--allow-shlib-undefined") +set(PROJECT_SRC_ROOT ${CMAKE_CURRENT_LIST_DIR}/) +option(MINDSPORE_PATH "mindspore install path" "") +include_directories(${OpenCV_INCLUDE_DIRS}) +include_directories(${MINDSPORE_PATH}) +include_directories(${MINDSPORE_PATH}/include) +include_directories(${PROJECT_SRC_ROOT}) +find_library(MS_LIB libmindspore.so ${MINDSPORE_PATH}/lib) +file(GLOB_RECURSE MD_LIB ${MINDSPORE_PATH}/_c_dataengine*) +add_executable(main src/main.cc src/utils.cc) +target_link_libraries(main ${MS_LIB} ${MD_LIB} ${OpenCV_LIBS} gflags) diff --git a/research/cv/SRGAN/ascend310_infer/build.sh b/research/cv/SRGAN/ascend310_infer/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..922df6cb4d87095802306ba30c7741fe64ca79f1 --- /dev/null +++ b/research/cv/SRGAN/ascend310_infer/build.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# Copyright 2021 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ + +if [ ! -d out ]; then + mkdir out +fi + +cd out || exit + +if [ -f "Makefile" ]; then + make clean +fi + +cmake .. -DMINDSPORE_PATH="`pip3.7 show mindspore-ascend | grep Location | awk '{print $2"/mindspore"}' | xargs realpath`" +make diff --git a/research/cv/SRGAN/ascend310_infer/inc/utils.h b/research/cv/SRGAN/ascend310_infer/inc/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b052ca372f90e10fbaecde73e2459650e17c8474 --- /dev/null +++ b/research/cv/SRGAN/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/SRGAN/ascend310_infer/src/main.cc b/research/cv/SRGAN/ascend310_infer/src/main.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e8c1169ca76a972ec3ac1e844cfb6e4a3751cc1 --- /dev/null +++ b/research/cv/SRGAN/ascend310_infer/src/main.cc @@ -0,0 +1,131 @@ +/* + * 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, "./SRGAN_model.mindir", "mindir path"); +DEFINE_string(input0_path, "./scripts/preprocess_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/SRGAN/ascend310_infer/src/utils.cc b/research/cv/SRGAN/ascend310_infer/src/utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..4af8a81639144d8a57421256a66d8011dbe5e09f --- /dev/null +++ b/research/cv/SRGAN/ascend310_infer/src/utils.cc @@ -0,0 +1,127 @@ +/* + * 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/SRGAN/eval.py b/research/cv/SRGAN/eval.py index 8ad35559472b734326138944c8f8b04204fa5d5f..8dd9bec7363ae5e12d9e9b07fc0694f08d0a7fc1 100644 --- a/research/cv/SRGAN/eval.py +++ b/research/cv/SRGAN/eval.py @@ -24,15 +24,15 @@ from mindspore import context import mindspore.ops as ops from src.model.generator import Generator from src.dataset.testdataset import create_testdataset - +from PIL import Image set_seed(1) parser = argparse.ArgumentParser(description="SRGAN eval") -parser.add_argument("--test_LR_path", type=str, default='/data/Set14/LR') -parser.add_argument("--test_GT_path", type=str, default='/data/Set14/HR') +parser.add_argument("--test_LR_path", type=str, default='../Set14/LR') +parser.add_argument("--test_GT_path", type=str, default='../Set14/HR') parser.add_argument("--res_num", type=int, default=16) parser.add_argument("--scale", type=int, default=4) -parser.add_argument("--generator_path", type=str, default='./ckpt/best.ckpt') +parser.add_argument("--generator_path", type=str, default='./ckpt/pre_trained_model_400.ckpt') parser.add_argument("--mode", type=str, default='train') parser.add_argument("--device_id", type=int, default=0, help="device id, default: 0.") i = 0 @@ -46,12 +46,11 @@ if __name__ == '__main__': load_param_into_net(generator, params) op = ops.ReduceSum(keep_dims=False) psnr_list = [] - + i = 0 print("=======starting test=====") for data in test_data_loader: lr = data['LR'] gt = data['HR'] - bs, c, h, w = lr.shape[:4] gt = gt[:, :, : h * args.scale, : w *args.scale] @@ -67,7 +66,7 @@ if __name__ == '__main__': output = output.transpose(1, 2, 0) gt = gt.asnumpy() gt = gt.transpose(1, 2, 0) - + result = Image.fromarray((output * 255.0).astype(np.uint8)) y_output = rgb2ycbcr(output)[args.scale:-args.scale, args.scale:-args.scale, :1] y_gt = rgb2ycbcr(gt)[args.scale:-args.scale, args.scale:-args.scale, :1] diff --git a/research/cv/SRGAN/export.py b/research/cv/SRGAN/export.py index 1f325b4ef4d4b7010f91a7299e4bd6eff5e900fa..7001c1e3ef1a4ae60d92549a3283d5fb3d6ab642 100644 --- a/research/cv/SRGAN/export.py +++ b/research/cv/SRGAN/export.py @@ -24,9 +24,9 @@ from src.model.generator import Generator parser = argparse.ArgumentParser(description="SRGAN export") parser.add_argument('--file_name', type=str, default='SRGAN', help='output file name prefix.') -parser.add_argument('--file_format', type=str, choices=['AIR', 'ONNX', 'MINDIR'], default='AIR', \ +parser.add_argument('--file_format', type=str, choices=['AIR', 'ONNX', 'MINDIR'], default='MINDIR', \ help='file format') -parser.add_argument("--generator_path", type=str, default='./scripts/srgan0/src/ckpt/G_model_1000.ckpt') +parser.add_argument("--generator_path", type=str, default='') parser.add_argument("--device_id", type=int, default=0, help="device id, default: 0.") if __name__ == '__main__': @@ -35,8 +35,9 @@ if __name__ == '__main__': generator = Generator(4) params = load_checkpoint(args.generator_path) load_param_into_net(generator, params) - generator.set_train(True) - input_shp = [16, 3, 96, 96] + generator.set_train(False) + input_shp = [1, 3, 126, 126] input_array = Tensor(np.random.uniform(-1.0, 1.0, size=input_shp).astype(np.float32)) G_file = f"{args.file_name}_model" + generator(input_array) export(generator, input_array, file_name=G_file, file_format=args.file_format) diff --git a/research/cv/SRGAN/postprocess.py b/research/cv/SRGAN/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..af2e76a664db72897a7a2636792a56f2f23305bf --- /dev/null +++ b/research/cv/SRGAN/postprocess.py @@ -0,0 +1,77 @@ +# 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 PIL import Image +import numpy as np +from src.dataset.testdataset import create_testdataset +from mindspore import context +from skimage.color import rgb2ycbcr +from skimage.metrics import peak_signal_noise_ratio +parser = argparse.ArgumentParser(description="SRGAN eval") +parser.add_argument("--test_LR_path", type=str, default='/home/SRGANprofile/Set14/LR') +parser.add_argument("--test_GT_path", type=str, default='/home/SRGANprofile/Set14/HR') +parser.add_argument("--result_path", type=str, default='./result_Files') +parser.add_argument("--device_id", type=int, default=0, help="device id, default: 0.") +parser.add_argument("--scale", type=int, default=4) +args = parser.parse_args() +context.set_context(mode=context.GRAPH_MODE, device_id=args.device_id) + +def unpadding(img, target_shape): + a, b = target_shape[0], target_shape[1] + img_h, img_w, _ = img.shape + if img_h > a: + img = img[:a, :, :] + if img_w > b: + img = img[:, :b, :] + return img + + +if __name__ == '__main__': + i = 0 + args = parser.parse_args() + test_ds = create_testdataset(1, args.test_LR_path, args.test_GT_path) + test_data_loader = test_ds.create_dict_iterator(output_numpy=True) + sr_list = [] + psnr_list = [] + for j in range(0, 12): + f_name = os.path.join(args.result_path, "SRGAN_data_" + str(j) + "_0.bin") + sr = np.fromfile(f_name, np.float32).reshape(3, 800, 800) + sr_list.append(sr) + for data in test_data_loader: + lr = data['LR'] + sr = sr_list[i] + i = i+1 + gt = data['HR'] + bs, c, h, w = lr.shape[:4] + gt = gt[:, :, : h * 4, : w *4] + gt = gt[0] + gt = (gt + 1.0) / 2.0 + gt = gt.transpose(1, 2, 0) + output = sr.transpose(1, 2, 0) + output = unpadding(output, gt.shape) + output = (output + 1.0) / 2.0 + result = Image.fromarray((output * 255.0).astype(np.uint8)) + y_output = rgb2ycbcr(output)[args.scale:-args.scale, args.scale:-args.scale, :1] + y_gt = rgb2ycbcr(gt)[args.scale:-args.scale, args.scale:-args.scale, :1] + psnr = peak_signal_noise_ratio(y_output / 255.0, y_gt / 255.0, data_range=1.0) + psnr = float('%.2f' % psnr) + psnr_list.append(psnr) + x = np.mean(psnr_list) + x = float('%.2f' % x) + print("avg PSNR:", x) + \ No newline at end of file diff --git a/research/cv/SRGAN/preprocess.py b/research/cv/SRGAN/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..19a5557b63c35974cdea0c529a2c4b4e7ccc56e9 --- /dev/null +++ b/research/cv/SRGAN/preprocess.py @@ -0,0 +1,57 @@ +# 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 context +from src.dataset.testdataset import create_testdataset + +parser = argparse.ArgumentParser(description="SRGAN eval") +parser.add_argument("--test_LR_path", type=str, default='./Set14/LR') +parser.add_argument("--test_GT_path", type=str, default='./Set14/HR') +parser.add_argument("--result_path", type=str, default='./preprocess_path') +parser.add_argument("--device_id", type=int, default=1, help="device id, default: 0.") +args = parser.parse_args() +context.set_context(mode=context.GRAPH_MODE, device_id=args.device_id) + +def padding(_img, target_shape): + h, w = target_shape[0], target_shape[1] + img_h, img_w, _ = _img.shape + dh, dw = h - img_h, w - img_w + if dh < 0 or dw < 0: + raise RuntimeError(f"target_shape is bigger than img.shape, {target_shape} > {_img.shape}") + if dh != 0 or dw != 0: + _img = np.pad(_img, ((0, dh), (0, dw), (0, 0)), "constant") + return _img +if __name__ == '__main__': + test_ds = create_testdataset(1, args.test_LR_path, args.test_GT_path) + test_data_loader = test_ds.create_dict_iterator(output_numpy=True) + i = 0 + img_path = args.result_path + if not os.path.exists(img_path): + os.makedirs(img_path) + for data in test_data_loader: + file_name = "SRGAN_data" + "_" + str(i) + ".bin" + file_path = img_path + "/" + file_name + lr = data['LR'] + lr = lr[0] + lr = lr.transpose(1, 2, 0) + org_img = padding(lr, [200, 200]) + org_img = org_img.transpose(2, 0, 1) + img = org_img.copy() + img.tofile(file_path) + i = i + 1 diff --git a/research/cv/SRGAN/scripts/run_infer_310.sh b/research/cv/SRGAN/scripts/run_infer_310.sh new file mode 100644 index 0000000000000000000000000000000000000000..2f0d65d63c88d48220e3c86bdb128cdac00a986f --- /dev/null +++ b/research/cv/SRGAN/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 4 || $# -gt 5 ]]; then + echo "Usage: bash run_infer_310.sh [MINDIR_PATH] [TEST_LR_PATH] [TEST_GT_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) +test_LR_path=$(get_real_path $2) +test_GT_path=$(get_real_path $3) + +if [ "$4" == "y" ] || [ "$4" == "n" ];then + need_preprocess=$4 +else + echo "weather need preprocess or not, it's value must be in [y, n]" + exit 1 +fi + +device_id=0 +if [ $# == 5 ]; then + device_id=$5 +fi + +echo "mindir name: "$model +echo "test_LR_path: "$test_LR_path +echo "test_GT_path: "$test_GT_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_path ]; then + rm -rf ./preprocess_path + fi + mkdir preprocess_path + python3.7 ../preprocess.py --test_LR_path=$test_LR_path --test_GT_path=$test_GT_path --result_path=./preprocess_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_path --device_id=$device_id &> infer.log + +} + +function cal_acc() +{ + if [ -d infer_output ]; then + rm -rf ./infer_output + fi + mkdir infer_output + python3.7 ../postprocess.py --test_LR_path=$test_LR_path --test_GT_path=$test_GT_path --device_id=$device_id &> acc.log +} + +if [ $need_preprocess == "y" ]; then + preprocess_data +fi +compile_app +if [ $? -ne 0 ]; then + echo "compile app code failed" + exit 1 +fi +infer +if [ $? -ne 0 ]; then + echo " execute inference failed" + exit 1 +fi +cal_acc +if [ $? -ne 0 ]; then + echo "calculate accuracy failed" + exit 1 +fi \ No newline at end of file diff --git a/research/cv/SRGAN/src/dataset/testdataset.py b/research/cv/SRGAN/src/dataset/testdataset.py index 1fda8fe3c8296f31e37b4369624e4bf3fb819760..256d329cc93625c20a4d63565c5551199d2b01fa 100644 --- a/research/cv/SRGAN/src/dataset/testdataset.py +++ b/research/cv/SRGAN/src/dataset/testdataset.py @@ -57,8 +57,10 @@ class mydata: return img_item['LR'], img_item['GT'] def create_testdataset(batchsize, LR_path, GT_path): - """create testdataset""" + """create testdataset + # noqa: DAR201 + """ dataset = mydata(LR_path, GT_path, in_memory=False) - DS = ds.GeneratorDataset(dataset, column_names=["LR", "HR"]) - DS = DS.batch(batchsize) - return DS + dataloader = ds.GeneratorDataset(dataset, column_names=["LR", "HR"], shuffle=False) + dataloader = dataloader.batch(batchsize) + return dataloader diff --git a/research/cv/SRGAN/src/dataset/traindataset.py b/research/cv/SRGAN/src/dataset/traindataset.py index 64d02e9c1d69debf7e354d504b7965ec327d4737..4dea59e269205bb5bc7aaaa7727cb16505a7569d 100644 --- a/research/cv/SRGAN/src/dataset/traindataset.py +++ b/research/cv/SRGAN/src/dataset/traindataset.py @@ -18,6 +18,7 @@ import os import random import math +import multiprocessing import numpy as np from PIL import Image import mindspore.dataset as ds @@ -110,18 +111,26 @@ class MySampler(): def create_traindataset(batchsize, LR_path, GT_path): """"create SRGAN dataset""" + + device_num = int(os.getenv("RANK_SIZE", "1")) + rank_id = int(os.getenv("RANK_ID", "0")) + cores = multiprocessing.cpu_count() + num_parallel_workers = int(cores / device_num) parallel_mode = context.get_auto_parallel_context("parallel_mode") if parallel_mode in [ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL]: dataset = mydata(LR_path, GT_path, in_memory=True) - sampler = MySampler(dataset, local_rank=0, world_size=4) - device_num = int(os.getenv("RANK_SIZE")) - rank_id = int(os.getenv("DEVICE_ID")) - sampler = MySampler(dataset, local_rank=rank_id, world_size=4) - DS = ds.GeneratorDataset(dataset, column_names=['LR', 'HR'], shuffle=True, - num_shards=device_num, shard_id=rank_id, sampler=sampler) - DS = DS.batch(batchsize, drop_remainder=True) + sampler = MySampler(dataset, local_rank=rank_id, world_size=device_num) + dataloader = ds.GeneratorDataset(dataset, column_names=['LR', 'HR'], shuffle=True, + num_shards=device_num, shard_id=rank_id, sampler=sampler, + python_multiprocessing=True, + num_parallel_workers=min(12, num_parallel_workers) + ) + dataloader = dataloaderS.batch(batchsize, drop_remainder=True, + num_parallel_workers=min(8, num_parallel_workers)) else: dataset = mydata(LR_path, GT_path, in_memory=True) - DS = ds.GeneratorDataset(dataset, column_names=['LR', 'HR'], shuffle=True) - DS = DS.batch(batchsize) - return DS + dataloader = ds.GeneratorDataset(dataset, column_names=['LR', 'HR'], shuffle=True, + python_multiprocessing=True, + num_parallel_workers=min(12, num_parallel_workers)) + dataloader = dataloader.batch(batchsize, drop_remainder=True, num_parallel_workers=min(8, num_parallel_workers)) + return dataloader