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

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