You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

execute.cc 28 kB

5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /**
  2. * Copyright 2020-2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "minddata/dataset/include/dataset/execute.h"
  17. #include <algorithm>
  18. #include <fstream>
  19. #include "minddata/dataset/core/de_tensor.h"
  20. #include "minddata/dataset/core/tensor_row.h"
  21. #include "minddata/dataset/core/tensor.h"
  22. #include "minddata/dataset/core/type_id.h"
  23. #include "minddata/dataset/kernels/ir/tensor_operation.h"
  24. #include "minddata/dataset/kernels/tensor_op.h"
  25. #ifndef ENABLE_ANDROID
  26. #include "utils/log_adapter.h"
  27. #else
  28. #include "mindspore/lite/src/common/log_adapter.h"
  29. #endif
  30. #ifdef ENABLE_ACL
  31. #include "minddata/dataset/core/ascend_resource.h"
  32. #include "minddata/dataset/kernels/image/dvpp/utils/CommonDataType.h"
  33. #include "minddata/dataset/kernels/ir/vision/ascend_vision_ir.h"
  34. #endif
  35. namespace mindspore {
  36. namespace dataset {
  37. using json = nlohmann::json;
  38. struct Execute::ExtraInfo {
  39. std::multimap<std::string, std::vector<uint32_t>> aipp_cfg_;
  40. bool init_with_shared_ptr_ = true; // Initial execute object with shared_ptr as default
  41. #ifdef ENABLE_ACL
  42. std::multimap<std::string, std::string> op2para_map_ = {{vision::kDvppCropJpegOperation, "size"},
  43. {vision::kDvppDecodeResizeOperation, "size"},
  44. {vision::kDvppDecodeResizeCropOperation, "crop_size"},
  45. {vision::kDvppDecodeResizeCropOperation, "resize_size"},
  46. {vision::kDvppNormalizeOperation, "mean"},
  47. {vision::kDvppNormalizeOperation, "std"},
  48. {vision::kDvppResizeJpegOperation, "size"}};
  49. #endif
  50. };
  51. Status Execute::InitResource(MapTargetDevice device_type, uint32_t device_id) {
  52. #ifdef ENABLE_ACL
  53. if (device_type_ == MapTargetDevice::kAscend310) {
  54. device_resource_ = std::make_shared<AscendResource>();
  55. Status rc = device_resource_->InitResource(device_id);
  56. if (!rc.IsOk()) {
  57. device_resource_ = nullptr;
  58. std::string err_msg = "Initialize Ascend310 resource fail";
  59. MS_LOG(ERROR) << err_msg;
  60. RETURN_STATUS_UNEXPECTED(err_msg);
  61. }
  62. }
  63. #endif
  64. return Status::OK();
  65. }
  66. Execute::Execute(std::shared_ptr<TensorOperation> op, MapTargetDevice device_type, uint32_t device_id) {
  67. ops_.emplace_back(std::move(op));
  68. device_type_ = device_type;
  69. info_ = std::make_shared<ExtraInfo>();
  70. (void)InitResource(device_type, device_id);
  71. }
  72. Execute::Execute(std::shared_ptr<TensorTransform> op, MapTargetDevice device_type, uint32_t device_id) {
  73. // Initialize the op and other context
  74. transforms_.emplace_back(op);
  75. info_ = std::make_shared<ExtraInfo>();
  76. device_type_ = device_type;
  77. (void)InitResource(device_type, device_id);
  78. }
  79. Execute::Execute(std::reference_wrapper<TensorTransform> op, MapTargetDevice device_type, uint32_t device_id) {
  80. // Initialize the transforms_ and other context
  81. std::shared_ptr<TensorOperation> operation = op.get().Parse();
  82. ops_.emplace_back(std::move(operation));
  83. info_ = std::make_shared<ExtraInfo>();
  84. info_->init_with_shared_ptr_ = false;
  85. device_type_ = device_type;
  86. (void)InitResource(device_type, device_id);
  87. }
  88. // Execute function for the example case: auto decode(new vision::Decode());
  89. Execute::Execute(TensorTransform *op, MapTargetDevice device_type, uint32_t device_id) {
  90. // Initialize the transforms_ and other context
  91. std::shared_ptr<TensorTransform> smart_ptr_op(op);
  92. transforms_.emplace_back(smart_ptr_op);
  93. info_ = std::make_shared<ExtraInfo>();
  94. device_type_ = device_type;
  95. (void)InitResource(device_type, device_id);
  96. }
  97. Execute::Execute(std::vector<std::shared_ptr<TensorOperation>> ops, MapTargetDevice device_type, uint32_t device_id)
  98. : ops_(std::move(ops)), device_type_(device_type) {
  99. info_ = std::make_shared<ExtraInfo>();
  100. (void)InitResource(device_type, device_id);
  101. }
  102. Execute::Execute(std::vector<std::shared_ptr<TensorTransform>> ops, MapTargetDevice device_type, uint32_t device_id) {
  103. // Initialize the transforms_ and other context
  104. transforms_ = ops;
  105. info_ = std::make_shared<ExtraInfo>();
  106. device_type_ = device_type;
  107. (void)InitResource(device_type, device_id);
  108. }
  109. Execute::Execute(const std::vector<std::reference_wrapper<TensorTransform>> ops, MapTargetDevice device_type,
  110. uint32_t device_id) {
  111. // Initialize the transforms_ and other context
  112. if (device_type == MapTargetDevice::kCpu) {
  113. (void)std::transform(
  114. ops.begin(), ops.end(), std::back_inserter(ops_),
  115. [](TensorTransform &operation) -> std::shared_ptr<TensorOperation> { return operation.Parse(); });
  116. } else {
  117. for (auto &op : ops) {
  118. ops_.emplace_back(op.get().Parse(device_type));
  119. }
  120. }
  121. info_ = std::make_shared<ExtraInfo>();
  122. info_->init_with_shared_ptr_ = false;
  123. device_type_ = device_type;
  124. (void)InitResource(device_type, device_id);
  125. }
  126. // Execute function for the example vector case: auto decode(new vision::Decode());
  127. Execute::Execute(const std::vector<TensorTransform *> &ops, MapTargetDevice device_type, uint32_t device_id) {
  128. // Initialize the transforms_ and other context
  129. for (auto &op : ops) {
  130. std::shared_ptr<TensorTransform> smart_ptr_op(op);
  131. transforms_.emplace_back(smart_ptr_op);
  132. }
  133. info_ = std::make_shared<ExtraInfo>();
  134. device_type_ = device_type;
  135. (void)InitResource(device_type, device_id);
  136. }
  137. Execute::~Execute() {
  138. #ifdef ENABLE_ACL
  139. if (device_type_ == MapTargetDevice::kAscend310) {
  140. if (device_resource_) {
  141. auto rc = device_resource_->FinalizeResource();
  142. if (rc.IsError()) {
  143. MS_LOG(ERROR) << "Device resource release failed, error msg is " << rc;
  144. }
  145. } else {
  146. MS_LOG(ERROR) << "Device resource is nullptr which is illegal under case Ascend310";
  147. }
  148. }
  149. #endif
  150. }
  151. Status Execute::operator()(const mindspore::MSTensor &input, mindspore::MSTensor *output) {
  152. // Validate input tensor
  153. RETURN_UNEXPECTED_IF_NULL(output);
  154. CHECK_FAIL_RETURN_UNEXPECTED(input.DataSize() > 0, "Input Tensor has no data.");
  155. CHECK_FAIL_RETURN_UNEXPECTED(output != nullptr, "Output Tensor can not be nullptr.");
  156. CHECK_FAIL_RETURN_UNEXPECTED(ValidateDevice(), "Device Type should be 'Ascend310' or 'CPU'.");
  157. // Parse TensorTransform transforms_ into TensorOperation ops_
  158. if (info_->init_with_shared_ptr_) {
  159. RETURN_IF_NOT_OK(ParseTransforms());
  160. info_->init_with_shared_ptr_ = false;
  161. }
  162. CHECK_FAIL_RETURN_UNEXPECTED(!ops_.empty(), "Input TensorOperation should be provided.");
  163. // Validate and build runtime ops
  164. std::vector<std::shared_ptr<TensorOp>> transforms; // record the transformations
  165. std::map<MapTargetDevice, std::string> env_list = {
  166. {MapTargetDevice::kCpu, "kCpu"}, {MapTargetDevice::kGpu, "kGpu"}, {MapTargetDevice::kAscend310, "kAscend310"}};
  167. for (int32_t i = 0; i < ops_.size(); i++) {
  168. if (ops_[i] == nullptr) {
  169. std::string err_msg = "Input TensorOperation[" + std::to_string(i) +
  170. "] is unsupported on your input device:" + env_list.at(device_type_);
  171. MS_LOG(ERROR) << err_msg;
  172. RETURN_STATUS_UNEXPECTED(err_msg);
  173. }
  174. RETURN_IF_NOT_OK(ops_[i]->ValidateParams());
  175. transforms.emplace_back(ops_[i]->Build());
  176. }
  177. if (device_type_ == MapTargetDevice::kCpu) {
  178. // Convert mindspore::Tensor to dataset::Tensor
  179. std::shared_ptr<dataset::Tensor> de_tensor;
  180. Status rc = dataset::Tensor::CreateFromMemory(dataset::TensorShape(input.Shape()),
  181. MSTypeToDEType(static_cast<TypeId>(input.DataType())),
  182. (const uchar *)(input.Data().get()), input.DataSize(), &de_tensor);
  183. if (rc.IsError()) {
  184. MS_LOG(ERROR) << rc;
  185. return rc;
  186. }
  187. // Apply transforms on tensor
  188. for (auto &t : transforms) {
  189. TensorRow de_tensor_row;
  190. TensorRow de_output_row;
  191. de_tensor_row.push_back(de_tensor);
  192. de_output_row.resize(1);
  193. Status rc_ = t->Compute(de_tensor_row, &de_output_row);
  194. if (rc_.IsError()) {
  195. MS_LOG(ERROR) << rc_;
  196. return rc_;
  197. }
  198. // For next transform
  199. de_tensor = std::move(de_output_row[0]);
  200. }
  201. // Convert dataset::Tensor to mindspore::Tensor
  202. if (!de_tensor->HasData()) {
  203. std::stringstream ss;
  204. ss << "Transformation returned an empty tensor with shape " << de_tensor->shape();
  205. RETURN_STATUS_UNEXPECTED(ss.str());
  206. }
  207. *output = mindspore::MSTensor(std::make_shared<DETensor>(de_tensor));
  208. } else if (device_type_ ==
  209. MapTargetDevice::kAscend310) { // Ascend310 case, where we must set Ascend resource on each operators
  210. #ifdef ENABLE_ACL
  211. CHECK_FAIL_RETURN_UNEXPECTED(device_resource_, "Device resource is nullptr which is illegal under case Ascend310.");
  212. // Sink data from host into device
  213. std::shared_ptr<mindspore::dataset::DeviceTensor> device_input;
  214. RETURN_IF_NOT_OK(device_resource_->Sink(input, &device_input));
  215. for (auto &t : transforms) {
  216. // Initialize AscendResource for each operators
  217. std::shared_ptr<DeviceTensor> device_output;
  218. RETURN_IF_NOT_OK(t->SetAscendResource(device_resource_));
  219. RETURN_IF_NOT_OK(t->Compute(device_input, &device_output));
  220. // For next transform
  221. device_input = std::move(device_output);
  222. }
  223. CHECK_FAIL_RETURN_UNEXPECTED(device_input->HasDeviceData(), "Apply transform failed, output tensor has no data.");
  224. *output = mindspore::MSTensor(std::make_shared<DETensor>(device_input, true));
  225. #endif
  226. } else {
  227. std::string err_msg = "Your input device is not supported. (Option: CPU or Ascend310)";
  228. MS_LOG(ERROR) << err_msg;
  229. RETURN_STATUS_UNEXPECTED(err_msg);
  230. }
  231. return Status::OK();
  232. }
  233. Status Execute::operator()(const std::vector<MSTensor> &input_tensor_list, std::vector<MSTensor> *output_tensor_list) {
  234. // Validate input tensor
  235. RETURN_UNEXPECTED_IF_NULL(output_tensor_list);
  236. CHECK_FAIL_RETURN_UNEXPECTED(!input_tensor_list.empty(), "Input Tensor is not valid.");
  237. CHECK_FAIL_RETURN_UNEXPECTED(output_tensor_list != nullptr, "Output Tensor can not be nullptr.");
  238. output_tensor_list->clear();
  239. for (auto &tensor : input_tensor_list) {
  240. CHECK_FAIL_RETURN_UNEXPECTED(tensor.DataSize() > 0, "Input Tensor has no data.");
  241. }
  242. CHECK_FAIL_RETURN_UNEXPECTED(ValidateDevice(), "Device Type should be 'Ascend310' or 'CPU'.");
  243. // Parse TensorTransform transforms_ into TensorOperation ops_
  244. if (info_->init_with_shared_ptr_) {
  245. RETURN_IF_NOT_OK(ParseTransforms());
  246. info_->init_with_shared_ptr_ = false;
  247. }
  248. CHECK_FAIL_RETURN_UNEXPECTED(!ops_.empty(), "Input TensorOperation should be provided.");
  249. std::map<MapTargetDevice, std::string> env_list = {
  250. {MapTargetDevice::kCpu, "kCpu"}, {MapTargetDevice::kGpu, "kGpu"}, {MapTargetDevice::kAscend310, "kAscend310"}};
  251. // Validate and build runtime ops
  252. std::vector<std::shared_ptr<TensorOp>> transforms;
  253. for (int32_t i = 0; i < ops_.size(); i++) {
  254. if (ops_[i] == nullptr) {
  255. std::string err_msg = "Input TensorOperation[" + std::to_string(i) +
  256. "] is unsupported on your input device:" + env_list.at(device_type_);
  257. MS_LOG(ERROR) << err_msg;
  258. RETURN_STATUS_UNEXPECTED(err_msg);
  259. }
  260. RETURN_IF_NOT_OK(ops_[i]->ValidateParams());
  261. transforms.emplace_back(ops_[i]->Build());
  262. }
  263. if (device_type_ == MapTargetDevice::kCpu) { // Case CPU
  264. TensorRow de_tensor_list;
  265. for (auto &tensor : input_tensor_list) {
  266. std::shared_ptr<dataset::Tensor> de_tensor;
  267. Status rc = dataset::Tensor::CreateFromMemory(
  268. dataset::TensorShape(tensor.Shape()), MSTypeToDEType(static_cast<TypeId>(tensor.DataType())),
  269. (const uchar *)(tensor.Data().get()), tensor.DataSize(), &de_tensor);
  270. if (rc.IsError()) {
  271. MS_LOG(ERROR) << rc;
  272. RETURN_IF_NOT_OK(rc);
  273. }
  274. de_tensor_list.emplace_back(std::move(de_tensor));
  275. }
  276. // Apply transforms on tensor
  277. for (auto &t : transforms) {
  278. TensorRow de_output_list;
  279. RETURN_IF_NOT_OK(t->Compute(de_tensor_list, &de_output_list));
  280. // For next transform
  281. de_tensor_list = std::move(de_output_list);
  282. }
  283. int32_t idx = 0;
  284. for (auto &tensor : de_tensor_list) {
  285. if (!tensor->HasData()) {
  286. std::stringstream ss;
  287. ss << "Transformation returned an empty tensor at location " << idx << ". ";
  288. ss << "The shape of the tensor is " << tensor->shape();
  289. RETURN_STATUS_UNEXPECTED(ss.str());
  290. }
  291. auto ms_tensor = mindspore::MSTensor(std::make_shared<DETensor>(tensor));
  292. output_tensor_list->emplace_back(ms_tensor);
  293. ++idx;
  294. }
  295. CHECK_FAIL_RETURN_UNEXPECTED(!output_tensor_list->empty(), "Output Tensor is not valid.");
  296. } else if (device_type_ ==
  297. MapTargetDevice::kAscend310) { // Ascend310 case, where we must set Ascend resource on each operators
  298. #ifdef ENABLE_ACL
  299. CHECK_FAIL_RETURN_UNEXPECTED(device_resource_, "Device resource is nullptr which is illegal under case Ascend310.");
  300. for (auto &input_tensor : input_tensor_list) {
  301. // Sink each data from host into device
  302. std::shared_ptr<dataset::DeviceTensor> device_input;
  303. RETURN_IF_NOT_OK(device_resource_->Sink(input_tensor, &device_input));
  304. for (auto &t : transforms) {
  305. std::shared_ptr<DeviceTensor> device_output;
  306. RETURN_IF_NOT_OK(t->SetAscendResource(device_resource_));
  307. RETURN_IF_NOT_OK(t->Compute(device_input, &device_output));
  308. // For next transform
  309. device_input = std::move(device_output);
  310. }
  311. CHECK_FAIL_RETURN_UNEXPECTED(device_input->HasDeviceData(), "Apply transform failed, output tensor has no data");
  312. // Due to the limitation of Ascend310 memory, we have to pop every data onto host memory
  313. // So the speed of this batch method is slower than solo mode
  314. std::shared_ptr<mindspore::dataset::Tensor> host_output;
  315. RETURN_IF_NOT_OK(device_resource_->Pop(device_input, &host_output));
  316. auto ms_tensor = mindspore::MSTensor(std::make_shared<DETensor>(host_output));
  317. output_tensor_list->emplace_back(ms_tensor);
  318. // Release the data on the device because we have copied one piece onto host
  319. RETURN_IF_NOT_OK(device_resource_->DeviceDataRelease());
  320. }
  321. CHECK_FAIL_RETURN_UNEXPECTED(!output_tensor_list->empty(), "Output Tensor vector is empty.");
  322. #endif
  323. } else {
  324. std::string err_msg = "Your input device is not supported. (Option: CPU or Ascend310)";
  325. MS_LOG(ERROR) << err_msg;
  326. RETURN_STATUS_UNEXPECTED(err_msg);
  327. }
  328. return Status::OK();
  329. }
  330. std::vector<uint32_t> AippSizeFilter(const std::vector<uint32_t> &resize_para, const std::vector<uint32_t> &crop_para) {
  331. std::vector<uint32_t> aipp_size;
  332. // Special condition where (no Crop and no Resize) or (no Crop and resize with fixed ratio) will lead to dynamic input
  333. if ((resize_para.size() == 0 || resize_para.size() == 1) && crop_para.size() == 0) {
  334. aipp_size = {0, 0};
  335. MS_LOG(WARNING) << "Dynamic input shape is not supported, incomplete aipp config file will be generated. Please "
  336. "checkout your TensorTransform input, both src_image_size_h and src_image_size will be 0.";
  337. return aipp_size;
  338. }
  339. if (resize_para.size() == 0) { // If only Crop operator exists
  340. aipp_size = crop_para;
  341. } else if (crop_para.size() == 0) { // If only Resize operator with 2 parameters exists
  342. aipp_size = resize_para;
  343. } else { // If both of them exist
  344. if (resize_para.size() == 1) {
  345. aipp_size = crop_para;
  346. } else {
  347. aipp_size =
  348. *min_element(resize_para.begin(), resize_para.end()) < *min_element(crop_para.begin(), crop_para.end())
  349. ? resize_para
  350. : crop_para;
  351. }
  352. }
  353. #ifdef ENABLE_ACL
  354. aipp_size[0] = DVPP_ALIGN_UP(aipp_size[0], VPC_HEIGHT_ALIGN); // H
  355. aipp_size[1] = DVPP_ALIGN_UP(aipp_size[1], VPC_WIDTH_ALIGN); // W
  356. #endif
  357. return aipp_size;
  358. }
  359. std::vector<uint32_t> AippMeanFilter(const std::vector<uint32_t> &normalize_para) {
  360. std::vector<uint32_t> aipp_mean;
  361. if (normalize_para.size() == 6) { // If Normalize operator exist
  362. std::transform(normalize_para.begin(), normalize_para.begin() + 3, std::back_inserter(aipp_mean),
  363. [](uint32_t i) { return static_cast<uint32_t>(i / 10000); });
  364. } else {
  365. aipp_mean = {0, 0, 0};
  366. }
  367. return aipp_mean;
  368. }
  369. std::vector<float> AippStdFilter(const std::vector<uint32_t> &normalize_para) {
  370. std::vector<float> aipp_std;
  371. if (normalize_para.size() == 6) { // If Normalize operator exist
  372. auto zeros = std::find(std::begin(normalize_para), std::end(normalize_para), 0);
  373. if (zeros == std::end(normalize_para)) {
  374. if (std::any_of(normalize_para.begin() + 3, normalize_para.end(), [](uint32_t i) { return i == 0; })) {
  375. MS_LOG(ERROR) << "value in normalize para got 0.";
  376. return {};
  377. }
  378. std::transform(normalize_para.begin() + 3, normalize_para.end(), std::back_inserter(aipp_std),
  379. [](uint32_t i) { return 10000 / static_cast<float>(i); });
  380. } else { // If 0 occurs in std vector
  381. MS_LOG(WARNING) << "Detect 0 in std vector, please verify your input.";
  382. aipp_std = {1.0, 1.0, 1.0};
  383. }
  384. } else {
  385. aipp_std = {1.0, 1.0, 1.0};
  386. }
  387. return aipp_std;
  388. }
  389. Status AippInfoCollection(std::map<std::string, std::string> *aipp_options, const std::vector<uint32_t> &aipp_size,
  390. const std::vector<uint32_t> &aipp_mean, const std::vector<float> &aipp_std) {
  391. // Several aipp config parameters
  392. aipp_options->insert(std::make_pair("related_input_rank", "0"));
  393. aipp_options->insert(std::make_pair("src_image_size_w", std::to_string(aipp_size[1])));
  394. aipp_options->insert(std::make_pair("src_image_size_h", std::to_string(aipp_size[0])));
  395. aipp_options->insert(std::make_pair("crop", "false"));
  396. aipp_options->insert(std::make_pair("input_format", "YUV420SP_U8"));
  397. aipp_options->insert(std::make_pair("aipp_mode", "static"));
  398. aipp_options->insert(std::make_pair("csc_switch", "true"));
  399. aipp_options->insert(std::make_pair("rbuv_swap_switch", "false"));
  400. // Y = AX + b, this part is A
  401. std::vector<int32_t> color_space_matrix = {256, 0, 359, 256, -88, -183, 256, 454, 0};
  402. int count = 0;
  403. for (int i = 0; i < 3; i++) {
  404. for (int j = 0; j < 3; j++) {
  405. std::string key_word = "matrix_r" + std::to_string(i) + "c" + std::to_string(j);
  406. aipp_options->insert(std::make_pair(key_word, std::to_string(color_space_matrix[count])));
  407. ++count;
  408. }
  409. }
  410. // This part is b
  411. std::vector<uint32_t> color_space_bias = {0, 128, 128};
  412. for (int i = 0; i < 3; i++) {
  413. std::string key_word = "input_bias_" + std::to_string(i);
  414. aipp_options->insert(std::make_pair(key_word, std::to_string(color_space_bias[i])));
  415. }
  416. // Y = (X - mean - min) * [std^(-1)], this part is mean
  417. for (int i = 0; i < aipp_mean.size(); i++) {
  418. std::string key_word = "mean_chn_" + std::to_string(i);
  419. aipp_options->insert(std::make_pair(key_word, std::to_string(aipp_mean[i])));
  420. }
  421. // This part is min
  422. for (int i = 0; i < aipp_mean.size(); i++) {
  423. std::string key_word = "min_chn_" + std::to_string(i);
  424. aipp_options->insert(std::make_pair(key_word, "0.0"));
  425. }
  426. // This part is std^(-1)
  427. for (int i = 0; i < aipp_std.size(); i++) {
  428. std::string key_word = "var_reci_chn_" + std::to_string(i);
  429. aipp_options->insert(std::make_pair(key_word, std::to_string(aipp_std[i])));
  430. }
  431. return Status::OK();
  432. }
  433. std::string Execute::AippCfgGenerator() {
  434. std::string config_location = "./aipp.cfg";
  435. if (info_ == nullptr) {
  436. MS_LOG(ERROR) << "info_ is null";
  437. return "";
  438. }
  439. #ifdef ENABLE_ACL
  440. if (info_->init_with_shared_ptr_) {
  441. auto rc = ParseTransforms();
  442. if (rc.IsError()) {
  443. MS_LOG(ERROR) << "Parse transforms failed, error msg is " << rc;
  444. return "";
  445. }
  446. info_->init_with_shared_ptr_ = false;
  447. }
  448. std::vector<uint32_t> paras; // Record the parameters value of each Ascend operators
  449. for (int32_t i = 0; i < ops_.size(); i++) {
  450. // Validate operator ir
  451. json ir_info;
  452. if (ops_[i] == nullptr) {
  453. MS_LOG(ERROR) << "Input TensorOperation[" + std::to_string(i) + "] is null.";
  454. return "";
  455. }
  456. // Define map between operator name and parameter name
  457. auto rc = ops_[i]->to_json(&ir_info);
  458. if (rc.IsError()) {
  459. MS_LOG(ERROR) << "IR information serialize to json failed, error msg is " << rc;
  460. return "";
  461. }
  462. // Collect the information of operators
  463. for (auto pos = info_->op2para_map_.equal_range(ops_[i]->Name()); pos.first != pos.second; ++pos.first) {
  464. auto paras_key_word = pos.first->second;
  465. paras = ir_info[paras_key_word].get<std::vector<uint32_t>>();
  466. info_->aipp_cfg_.insert(std::make_pair(ops_[i]->Name(), paras));
  467. }
  468. }
  469. std::ofstream outfile;
  470. outfile.open(config_location, std::ofstream::out);
  471. if (!outfile.is_open()) {
  472. MS_LOG(ERROR) << "Fail to open Aipp config file, please verify your system config(including authority)."
  473. << "We will return empty string which represent the location of Aipp config file in this case.";
  474. return "";
  475. }
  476. if (device_type_ == MapTargetDevice::kAscend310) {
  477. // Process resize parameters and crop parameters to find out the final size of input data
  478. std::vector<uint32_t> resize_paras;
  479. std::vector<uint32_t> crop_paras;
  480. // Find resize parameters
  481. std::map<std::string, std::vector<uint32_t>>::iterator iter;
  482. if (info_->aipp_cfg_.find(vision::kDvppResizeJpegOperation) != info_->aipp_cfg_.end()) {
  483. iter = info_->aipp_cfg_.find(vision::kDvppResizeJpegOperation);
  484. resize_paras = iter->second;
  485. } else if (info_->aipp_cfg_.find(vision::kDvppDecodeResizeOperation) != info_->aipp_cfg_.end()) {
  486. iter = info_->aipp_cfg_.find(vision::kDvppDecodeResizeOperation);
  487. resize_paras = iter->second;
  488. }
  489. // Find crop parameters
  490. if (info_->aipp_cfg_.find(vision::kDvppCropJpegOperation) != info_->aipp_cfg_.end()) {
  491. iter = info_->aipp_cfg_.find(vision::kDvppCropJpegOperation);
  492. crop_paras = iter->second;
  493. } else if (info_->aipp_cfg_.find(vision::kDvppDecodeResizeCropOperation) != info_->aipp_cfg_.end()) {
  494. iter = info_->aipp_cfg_.find(vision::kDvppDecodeResizeCropOperation);
  495. crop_paras = iter->second;
  496. }
  497. if (crop_paras.size() == 1) {
  498. crop_paras.emplace_back(crop_paras[0]);
  499. }
  500. std::vector<uint32_t> aipp_size = AippSizeFilter(resize_paras, crop_paras);
  501. // Process Normalization parameters to find out the final Normalization parameters for Aipp module
  502. std::vector<uint32_t> normalize_paras;
  503. if (info_->aipp_cfg_.find(vision::kDvppNormalizeOperation) != info_->aipp_cfg_.end()) {
  504. for (auto pos = info_->aipp_cfg_.equal_range(vision::kDvppNormalizeOperation); pos.first != pos.second;
  505. ++pos.first) {
  506. auto mean_or_std = pos.first->second;
  507. normalize_paras.insert(normalize_paras.end(), mean_or_std.begin(), mean_or_std.end());
  508. }
  509. }
  510. std::vector<uint32_t> aipp_mean = AippMeanFilter(normalize_paras);
  511. std::vector<float> aipp_std = AippStdFilter(normalize_paras);
  512. std::map<std::string, std::string> aipp_options;
  513. auto rc = AippInfoCollection(&aipp_options, aipp_size, aipp_mean, aipp_std);
  514. if (rc.IsError()) {
  515. MS_LOG(ERROR) << "Aipp information initialization failed, error msg is " << rc;
  516. return "";
  517. }
  518. std::string tab_char(4, ' ');
  519. outfile << "aipp_op {" << std::endl;
  520. for (auto &option : aipp_options) {
  521. outfile << tab_char << option.first << " : " << option.second << std::endl;
  522. }
  523. outfile << "}";
  524. outfile.close();
  525. } else { // For case GPU or CPU
  526. outfile << "aipp_op {" << std::endl << "}";
  527. outfile.close();
  528. MS_LOG(WARNING) << "Your runtime environment is not Ascend310, this config file will lead to undefined behavior on "
  529. "computing result. Please check that.";
  530. }
  531. #endif
  532. return config_location;
  533. }
  534. bool IsEmptyPtr(std::shared_ptr<TensorTransform> api_ptr) { return api_ptr == nullptr; }
  535. Status Execute::ParseTransforms() {
  536. auto iter = std::find_if(transforms_.begin(), transforms_.end(), IsEmptyPtr);
  537. if (iter != transforms_.end()) {
  538. std::string err_msg = "Your input TensorTransforms contain at least one nullptr, please check your input.";
  539. MS_LOG(ERROR) << err_msg;
  540. RETURN_STATUS_UNEXPECTED(err_msg);
  541. }
  542. if (device_type_ == MapTargetDevice::kCpu) {
  543. (void)std::transform(transforms_.begin(), transforms_.end(), std::back_inserter(ops_),
  544. [](std::shared_ptr<TensorTransform> operation) -> std::shared_ptr<TensorOperation> {
  545. return operation->Parse();
  546. });
  547. } else if (device_type_ == MapTargetDevice::kAscend310) {
  548. for (auto &transform_ : transforms_) {
  549. ops_.emplace_back(transform_->Parse(device_type_));
  550. }
  551. } else {
  552. std::string err_msg = "Your input device is not supported. (Option: CPU or Ascend310)";
  553. MS_LOG(ERROR) << err_msg;
  554. RETURN_STATUS_UNEXPECTED(err_msg);
  555. }
  556. return Status::OK();
  557. }
  558. Status Execute::ValidateDevice() {
  559. if (device_type_ != MapTargetDevice::kCpu && device_type_ != MapTargetDevice::kAscend310 &&
  560. device_type_ != MapTargetDevice::kGpu) {
  561. std::string err_msg = "Your input device is not supported. (Option: CPU or GPU or Ascend310).";
  562. MS_LOG(ERROR) << err_msg;
  563. RETURN_STATUS_UNEXPECTED(err_msg);
  564. }
  565. return Status::OK();
  566. }
  567. Status Execute::DeviceMemoryRelease() {
  568. CHECK_FAIL_RETURN_UNEXPECTED(device_resource_, "Device resource is nullptr which is illegal under case Ascend310.");
  569. Status rc = device_resource_->DeviceDataRelease();
  570. if (rc.IsError()) {
  571. std::string err_msg = "Error in device data release";
  572. MS_LOG(ERROR) << err_msg;
  573. RETURN_STATUS_UNEXPECTED(err_msg);
  574. }
  575. return Status::OK();
  576. }
  577. Status Execute::Run(const std::vector<std::shared_ptr<dataset::Execute>> &data_graph,
  578. const std::vector<mindspore::MSTensor> &inputs, std::vector<mindspore::MSTensor> *outputs) {
  579. std::vector<MSTensor> transform_inputs = inputs;
  580. std::vector<MSTensor> transform_outputs;
  581. if (!data_graph.empty()) {
  582. for (auto exes : data_graph) {
  583. CHECK_FAIL_RETURN_UNEXPECTED(exes != nullptr, "Given execute object is null.");
  584. Status ret = exes->operator()(transform_inputs, &transform_outputs);
  585. if (ret != kSuccess) {
  586. MS_LOG(ERROR) << "Run preprocess failed:" << ret.GetErrDescription();
  587. return ret;
  588. }
  589. MS_LOG(DEBUG) << "transform_outputs[0].Shape: " << transform_outputs[0].Shape();
  590. transform_inputs = transform_outputs;
  591. }
  592. *outputs = std::move(transform_outputs);
  593. } else {
  594. std::string msg = "The set of Executors can not be empty.";
  595. MS_LOG(ERROR) << msg;
  596. RETURN_STATUS_UNEXPECTED(msg);
  597. }
  598. return Status::OK();
  599. }
  600. // In the current stage, there is a cyclic dependency between libmindspore.so and c_dataengine.so,
  601. // we make a C function here and dlopen by libminspore.so to avoid linking explicitly,
  602. // will be fix after decouling libminspore.so into multi submodules
  603. extern "C" {
  604. // ExecuteRun_C has C-linkage specified, but returns user-defined type 'mindspore::Status' which is incompatible with C
  605. void ExecuteRun_C(const std::vector<std::shared_ptr<dataset::Execute>> &data_graph,
  606. std::vector<mindspore::MSTensor> &inputs, std::vector<mindspore::MSTensor> *outputs, Status *s) {
  607. Status ret = Execute::Run(data_graph, inputs, outputs);
  608. *s = Status(ret);
  609. }
  610. }
  611. } // namespace dataset
  612. } // namespace mindspore