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 26 kB

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