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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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(output != nullptr, "Output Tensor can not be nullptr.");
  209. CHECK_FAIL_RETURN_UNEXPECTED(ValidateDevice(), "Device Type should be 'Ascend310' or 'CPU'.");
  210. // Parse TensorTransform transforms_ into TensorOperation ops_
  211. if (info_->init_with_shared_ptr_) {
  212. RETURN_IF_NOT_OK(ParseTransforms());
  213. info_->init_with_shared_ptr_ = false;
  214. }
  215. CHECK_FAIL_RETURN_UNEXPECTED(!ops_.empty(), "Input TensorOperation should be provided.");
  216. // Validate and build runtime ops
  217. std::vector<std::shared_ptr<TensorOp>> transforms; // record the transformations
  218. std::map<MapTargetDevice, std::string> env_list = {
  219. {MapTargetDevice::kCpu, "kCpu"}, {MapTargetDevice::kGpu, "kGpu"}, {MapTargetDevice::kAscend310, "kAscend310"}};
  220. for (int32_t i = 0; i < ops_.size(); i++) {
  221. if (ops_[i] == nullptr) {
  222. std::string err_msg = "Input TensorOperation[" + std::to_string(i) +
  223. "] is unsupported on your input device:" + env_list.at(device_type_);
  224. MS_LOG(ERROR) << err_msg;
  225. RETURN_STATUS_UNEXPECTED(err_msg);
  226. }
  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. if (!de_tensor->HasData()) {
  253. std::stringstream ss;
  254. ss << "Transformation returned an empty tensor with shape " << de_tensor->shape();
  255. RETURN_STATUS_UNEXPECTED(ss.str());
  256. }
  257. *output = mindspore::MSTensor(std::make_shared<DETensor>(de_tensor));
  258. } else { // Ascend310 case, where we must set Ascend resource on each operators
  259. #ifdef ENABLE_ACL
  260. CHECK_FAIL_RETURN_UNEXPECTED(device_resource_, "Device resource is nullptr which is illegal under case Ascend310.");
  261. // Sink data from host into device
  262. std::shared_ptr<mindspore::dataset::DeviceTensor> device_input;
  263. RETURN_IF_NOT_OK(device_resource_->Sink(input, &device_input));
  264. for (auto &t : transforms) {
  265. // Initialize AscendResource for each operators
  266. std::shared_ptr<DeviceTensor> device_output;
  267. RETURN_IF_NOT_OK(t->SetAscendResource(device_resource_));
  268. RETURN_IF_NOT_OK(t->Compute(device_input, &device_output));
  269. // For next transform
  270. device_input = std::move(device_output);
  271. }
  272. CHECK_FAIL_RETURN_UNEXPECTED(device_input->HasDeviceData(), "Apply transform failed, output tensor has no data.");
  273. *output = mindspore::MSTensor(std::make_shared<DETensor>(device_input, true));
  274. #endif
  275. }
  276. return Status::OK();
  277. }
  278. Status Execute::operator()(const std::vector<MSTensor> &input_tensor_list, std::vector<MSTensor> *output_tensor_list) {
  279. // Validate input tensor
  280. CHECK_FAIL_RETURN_UNEXPECTED(!input_tensor_list.empty(), "Input Tensor is not valid.");
  281. CHECK_FAIL_RETURN_UNEXPECTED(output_tensor_list != nullptr, "Output Tensor can not be nullptr.");
  282. output_tensor_list->clear();
  283. for (auto &tensor : input_tensor_list) {
  284. CHECK_FAIL_RETURN_UNEXPECTED(tensor.DataSize() > 0, "Input Tensor has no data.");
  285. }
  286. CHECK_FAIL_RETURN_UNEXPECTED(ValidateDevice(), "Device Type should be 'Ascend310' or 'CPU'.");
  287. // Parse TensorTransform transforms_ into TensorOperation ops_
  288. if (info_->init_with_shared_ptr_) {
  289. RETURN_IF_NOT_OK(ParseTransforms());
  290. info_->init_with_shared_ptr_ = false;
  291. }
  292. CHECK_FAIL_RETURN_UNEXPECTED(!ops_.empty(), "Input TensorOperation should be provided.");
  293. std::map<MapTargetDevice, std::string> env_list = {
  294. {MapTargetDevice::kCpu, "kCpu"}, {MapTargetDevice::kGpu, "kGpu"}, {MapTargetDevice::kAscend310, "kAscend310"}};
  295. // Validate and build runtime ops
  296. std::vector<std::shared_ptr<TensorOp>> transforms;
  297. for (int32_t i = 0; i < ops_.size(); i++) {
  298. if (ops_[i] == nullptr) {
  299. std::string err_msg = "Input TensorOperation[" + std::to_string(i) +
  300. "] is unsupported on your input device:" + env_list.at(device_type_);
  301. MS_LOG(ERROR) << err_msg;
  302. RETURN_STATUS_UNEXPECTED(err_msg);
  303. }
  304. RETURN_IF_NOT_OK(ops_[i]->ValidateParams());
  305. transforms.emplace_back(ops_[i]->Build());
  306. }
  307. if (device_type_ == MapTargetDevice::kCpu) { // Case CPU
  308. TensorRow de_tensor_list;
  309. for (auto &tensor : input_tensor_list) {
  310. std::shared_ptr<dataset::Tensor> de_tensor;
  311. Status rc = dataset::Tensor::CreateFromMemory(
  312. dataset::TensorShape(tensor.Shape()), MSTypeToDEType(static_cast<TypeId>(tensor.DataType())),
  313. (const uchar *)(tensor.Data().get()), tensor.DataSize(), &de_tensor);
  314. if (rc.IsError()) {
  315. MS_LOG(ERROR) << rc;
  316. RETURN_IF_NOT_OK(rc);
  317. }
  318. de_tensor_list.emplace_back(std::move(de_tensor));
  319. }
  320. // Apply transforms on tensor
  321. for (auto &t : transforms) {
  322. TensorRow de_output_list;
  323. RETURN_IF_NOT_OK(t->Compute(de_tensor_list, &de_output_list));
  324. // For next transform
  325. de_tensor_list = std::move(de_output_list);
  326. }
  327. int32_t idx = 0;
  328. for (auto &tensor : de_tensor_list) {
  329. if (!tensor->HasData()) {
  330. std::stringstream ss;
  331. ss << "Transformation returned an empty tensor at location " << idx << ". ";
  332. ss << "The shape of the tensor is " << tensor->shape();
  333. RETURN_STATUS_UNEXPECTED(ss.str());
  334. }
  335. auto ms_tensor = mindspore::MSTensor(std::make_shared<DETensor>(tensor));
  336. output_tensor_list->emplace_back(ms_tensor);
  337. ++idx;
  338. }
  339. CHECK_FAIL_RETURN_UNEXPECTED(!output_tensor_list->empty(), "Output Tensor is not valid.");
  340. } else { // Case Ascend310
  341. #ifdef ENABLE_ACL
  342. CHECK_FAIL_RETURN_UNEXPECTED(device_resource_, "Device resource is nullptr which is illegal under case Ascend310.");
  343. for (auto &input_tensor : input_tensor_list) {
  344. // Sink each data from host into device
  345. std::shared_ptr<dataset::DeviceTensor> device_input;
  346. RETURN_IF_NOT_OK(device_resource_->Sink(input_tensor, &device_input));
  347. for (auto &t : transforms) {
  348. std::shared_ptr<DeviceTensor> device_output;
  349. RETURN_IF_NOT_OK(t->SetAscendResource(device_resource_));
  350. RETURN_IF_NOT_OK(t->Compute(device_input, &device_output));
  351. // For next transform
  352. device_input = std::move(device_output);
  353. }
  354. CHECK_FAIL_RETURN_UNEXPECTED(device_input->HasDeviceData(), "Apply transform failed, output tensor has no data");
  355. // Due to the limitation of Ascend310 memory, we have to pop every data onto host memory
  356. // So the speed of this batch method is slower than solo mode
  357. std::shared_ptr<mindspore::dataset::Tensor> host_output;
  358. RETURN_IF_NOT_OK(device_resource_->Pop(device_input, &host_output));
  359. auto ms_tensor = mindspore::MSTensor(std::make_shared<DETensor>(host_output));
  360. output_tensor_list->emplace_back(ms_tensor);
  361. // Release the data on the device because we have copied one piece onto host
  362. RETURN_IF_NOT_OK(device_resource_->DeviceDataRelease());
  363. }
  364. CHECK_FAIL_RETURN_UNEXPECTED(!output_tensor_list->empty(), "Output Tensor vector is empty.");
  365. #endif
  366. }
  367. return Status::OK();
  368. }
  369. std::vector<uint32_t> AippSizeFilter(const std::vector<uint32_t> &resize_para, const std::vector<uint32_t> &crop_para) {
  370. std::vector<uint32_t> aipp_size;
  371. // Special condition where (no Crop and no Resize) or (no Crop and resize with fixed ratio) will lead to dynamic input
  372. if ((resize_para.size() == 0 || resize_para.size() == 1) && crop_para.size() == 0) {
  373. aipp_size = {0, 0};
  374. MS_LOG(WARNING) << "Dynamic input shape is not supported, incomplete aipp config file will be generated. Please "
  375. "checkout your TensorTransform input, both src_image_size_h and src_image_size will be 0.";
  376. return aipp_size;
  377. }
  378. if (resize_para.size() == 0) { // If only Crop operator exists
  379. aipp_size = crop_para;
  380. } else if (crop_para.size() == 0) { // If only Resize operator with 2 parameters exists
  381. aipp_size = resize_para;
  382. } else { // If both of them exist
  383. if (resize_para.size() == 1) {
  384. aipp_size = crop_para;
  385. } else {
  386. aipp_size =
  387. *min_element(resize_para.begin(), resize_para.end()) < *min_element(crop_para.begin(), crop_para.end())
  388. ? resize_para
  389. : crop_para;
  390. }
  391. }
  392. #ifdef ENABLE_ACL
  393. aipp_size[0] = DVPP_ALIGN_UP(aipp_size[0], VPC_HEIGHT_ALIGN); // H
  394. aipp_size[1] = DVPP_ALIGN_UP(aipp_size[1], VPC_WIDTH_ALIGN); // W
  395. #endif
  396. return aipp_size;
  397. }
  398. std::vector<uint32_t> AippMeanFilter(const std::vector<uint32_t> &normalize_para) {
  399. std::vector<uint32_t> aipp_mean;
  400. if (normalize_para.size() == 6) { // If Normalize operator exist
  401. std::transform(normalize_para.begin(), normalize_para.begin() + 3, std::back_inserter(aipp_mean),
  402. [](uint32_t i) { return static_cast<uint32_t>(i / 10000); });
  403. } else {
  404. aipp_mean = {0, 0, 0};
  405. }
  406. return aipp_mean;
  407. }
  408. std::vector<float> AippStdFilter(const std::vector<uint32_t> &normalize_para) {
  409. std::vector<float> aipp_std;
  410. if (normalize_para.size() == 6) { // If Normalize operator exist
  411. auto zeros = std::find(std::begin(normalize_para), std::end(normalize_para), 0);
  412. if (zeros == std::end(normalize_para)) {
  413. if (std::any_of(normalize_para.begin() + 3, normalize_para.end(), [](uint32_t i) { return i == 0; })) {
  414. MS_LOG(ERROR) << "value in normalize para got 0.";
  415. return {};
  416. }
  417. std::transform(normalize_para.begin() + 3, normalize_para.end(), std::back_inserter(aipp_std),
  418. [](uint32_t i) { return 10000 / static_cast<float>(i); });
  419. } else { // If 0 occurs in std vector
  420. MS_LOG(WARNING) << "Detect 0 in std vector, please verify your input.";
  421. aipp_std = {1.0, 1.0, 1.0};
  422. }
  423. } else {
  424. aipp_std = {1.0, 1.0, 1.0};
  425. }
  426. return aipp_std;
  427. }
  428. Status AippInfoCollection(std::map<std::string, std::string> *aipp_options, const std::vector<uint32_t> &aipp_size,
  429. const std::vector<uint32_t> &aipp_mean, const std::vector<float> &aipp_std) {
  430. // Several aipp config parameters
  431. aipp_options->insert(std::make_pair("related_input_rank", "0"));
  432. aipp_options->insert(std::make_pair("src_image_size_w", std::to_string(aipp_size[1])));
  433. aipp_options->insert(std::make_pair("src_image_size_h", std::to_string(aipp_size[0])));
  434. aipp_options->insert(std::make_pair("crop", "false"));
  435. aipp_options->insert(std::make_pair("input_format", "YUV420SP_U8"));
  436. aipp_options->insert(std::make_pair("aipp_mode", "static"));
  437. aipp_options->insert(std::make_pair("csc_switch", "true"));
  438. aipp_options->insert(std::make_pair("rbuv_swap_switch", "false"));
  439. // Y = AX + b, this part is A
  440. std::vector<int32_t> color_space_matrix = {256, 0, 359, 256, -88, -183, 256, 454, 0};
  441. int count = 0;
  442. for (int i = 0; i < 3; i++) {
  443. for (int j = 0; j < 3; j++) {
  444. std::string key_word = "matrix_r" + std::to_string(i) + "c" + std::to_string(j);
  445. aipp_options->insert(std::make_pair(key_word, std::to_string(color_space_matrix[count])));
  446. ++count;
  447. }
  448. }
  449. // This part is b
  450. std::vector<uint32_t> color_space_bias = {0, 128, 128};
  451. for (int i = 0; i < 3; i++) {
  452. std::string key_word = "input_bias_" + std::to_string(i);
  453. aipp_options->insert(std::make_pair(key_word, std::to_string(color_space_bias[i])));
  454. }
  455. // Y = (X - mean - min) * [std^(-1)], this part is mean
  456. for (int i = 0; i < aipp_mean.size(); i++) {
  457. std::string key_word = "mean_chn_" + std::to_string(i);
  458. aipp_options->insert(std::make_pair(key_word, std::to_string(aipp_mean[i])));
  459. }
  460. // This part is min
  461. for (int i = 0; i < aipp_mean.size(); i++) {
  462. std::string key_word = "min_chn_" + std::to_string(i);
  463. aipp_options->insert(std::make_pair(key_word, "0.0"));
  464. }
  465. // This part is std^(-1)
  466. for (int i = 0; i < aipp_std.size(); i++) {
  467. std::string key_word = "var_reci_chn_" + std::to_string(i);
  468. aipp_options->insert(std::make_pair(key_word, std::to_string(aipp_std[i])));
  469. }
  470. return Status::OK();
  471. }
  472. std::string Execute::AippCfgGenerator() {
  473. std::string config_location = "./aipp.cfg";
  474. #ifdef ENABLE_ACL
  475. if (info_->init_with_shared_ptr_) {
  476. ParseTransforms();
  477. info_->init_with_shared_ptr_ = false;
  478. }
  479. std::vector<uint32_t> paras; // Record the parameters value of each Ascend operators
  480. for (int32_t i = 0; i < ops_.size(); i++) {
  481. // Validate operator ir
  482. json ir_info;
  483. if (ops_[i] == nullptr) {
  484. MS_LOG(ERROR) << "Input TensorOperation[" + std::to_string(i) + "] is null.";
  485. return "";
  486. }
  487. // Define map between operator name and parameter name
  488. ops_[i]->to_json(&ir_info);
  489. // Collect the information of operators
  490. for (auto pos = info_->op2para_map_.equal_range(ops_[i]->Name()); pos.first != pos.second; ++pos.first) {
  491. auto paras_key_word = pos.first->second;
  492. paras = ir_info[paras_key_word].get<std::vector<uint32_t>>();
  493. info_->aipp_cfg_.insert(std::make_pair(ops_[i]->Name(), paras));
  494. }
  495. }
  496. std::ofstream outfile;
  497. outfile.open(config_location, std::ofstream::out);
  498. if (!outfile.is_open()) {
  499. MS_LOG(ERROR) << "Fail to open Aipp config file, please verify your system config(including authority)."
  500. << "We will return empty string which represent the location of Aipp config file in this case.";
  501. std::string except = "";
  502. return except;
  503. }
  504. if (device_type_ == MapTargetDevice::kAscend310) {
  505. // Process resize parameters and crop parameters to find out the final size of input data
  506. std::vector<uint32_t> resize_paras;
  507. std::vector<uint32_t> crop_paras;
  508. // Find resize parameters
  509. std::map<std::string, std::vector<uint32_t>>::iterator iter;
  510. if (info_->aipp_cfg_.find(vision::kDvppResizeJpegOperation) != info_->aipp_cfg_.end()) {
  511. iter = info_->aipp_cfg_.find(vision::kDvppResizeJpegOperation);
  512. resize_paras = iter->second;
  513. } else if (info_->aipp_cfg_.find(vision::kDvppDecodeResizeOperation) != info_->aipp_cfg_.end()) {
  514. iter = info_->aipp_cfg_.find(vision::kDvppDecodeResizeOperation);
  515. resize_paras = iter->second;
  516. }
  517. // Find crop parameters
  518. if (info_->aipp_cfg_.find(vision::kDvppCropJpegOperation) != info_->aipp_cfg_.end()) {
  519. iter = info_->aipp_cfg_.find(vision::kDvppCropJpegOperation);
  520. crop_paras = iter->second;
  521. } else if (info_->aipp_cfg_.find(vision::kDvppDecodeResizeCropOperation) != info_->aipp_cfg_.end()) {
  522. iter = info_->aipp_cfg_.find(vision::kDvppDecodeResizeCropOperation);
  523. crop_paras = iter->second;
  524. }
  525. if (crop_paras.size() == 1) {
  526. crop_paras.emplace_back(crop_paras[0]);
  527. }
  528. std::vector<uint32_t> aipp_size = AippSizeFilter(resize_paras, crop_paras);
  529. // Process Normalization parameters to find out the final Normalization parameters for Aipp module
  530. std::vector<uint32_t> normalize_paras;
  531. if (info_->aipp_cfg_.find(vision::kDvppNormalizeOperation) != info_->aipp_cfg_.end()) {
  532. for (auto pos = info_->aipp_cfg_.equal_range(vision::kDvppNormalizeOperation); pos.first != pos.second;
  533. ++pos.first) {
  534. auto mean_or_std = pos.first->second;
  535. normalize_paras.insert(normalize_paras.end(), mean_or_std.begin(), mean_or_std.end());
  536. }
  537. }
  538. std::vector<uint32_t> aipp_mean = AippMeanFilter(normalize_paras);
  539. std::vector<float> aipp_std = AippStdFilter(normalize_paras);
  540. std::map<std::string, std::string> aipp_options;
  541. AippInfoCollection(&aipp_options, aipp_size, aipp_mean, aipp_std);
  542. std::string tab_char(4, ' ');
  543. outfile << "aipp_op {" << std::endl;
  544. for (auto &option : aipp_options) {
  545. outfile << tab_char << option.first << " : " << option.second << std::endl;
  546. }
  547. outfile << "}";
  548. outfile.close();
  549. } else { // For case GPU or CPU
  550. outfile << "aipp_op {" << std::endl << "}";
  551. outfile.close();
  552. MS_LOG(WARNING) << "Your runtime environment is not Ascend310, this config file will lead to undefined behavior on "
  553. "computing result. Please check that.";
  554. }
  555. #endif
  556. return config_location;
  557. }
  558. bool IsEmptyPtr(std::shared_ptr<TensorTransform> api_ptr) { return api_ptr == nullptr; }
  559. Status Execute::ParseTransforms() {
  560. auto iter = std::find_if(transforms_.begin(), transforms_.end(), IsEmptyPtr);
  561. if (iter != transforms_.end()) {
  562. std::string err_msg = "Your input TensorTransforms contain at least one nullptr, please check your input.";
  563. MS_LOG(ERROR) << err_msg;
  564. RETURN_STATUS_UNEXPECTED(err_msg);
  565. }
  566. if (device_type_ == MapTargetDevice::kCpu) {
  567. (void)std::transform(transforms_.begin(), transforms_.end(), std::back_inserter(ops_),
  568. [](std::shared_ptr<TensorTransform> operation) -> std::shared_ptr<TensorOperation> {
  569. return operation->Parse();
  570. });
  571. } else {
  572. for (auto &transform_ : transforms_) {
  573. ops_.emplace_back(transform_->Parse(device_type_));
  574. }
  575. }
  576. return Status::OK();
  577. }
  578. Status Execute::ValidateDevice() {
  579. if (device_type_ != MapTargetDevice::kCpu && device_type_ != MapTargetDevice::kAscend310 &&
  580. device_type_ != MapTargetDevice::kGpu) {
  581. std::string err_msg = "Your input device is not supported. (Option: CPU or GPU or Ascend310).";
  582. MS_LOG(ERROR) << err_msg;
  583. RETURN_STATUS_UNEXPECTED(err_msg);
  584. }
  585. return Status::OK();
  586. }
  587. Status Execute::DeviceMemoryRelease() {
  588. CHECK_FAIL_RETURN_UNEXPECTED(device_resource_, "Device resource is nullptr which is illegal under case Ascend310.");
  589. Status rc = device_resource_->DeviceDataRelease();
  590. if (rc.IsError()) {
  591. std::string err_msg = "Error in device data release";
  592. MS_LOG(ERROR) << err_msg;
  593. RETURN_STATUS_UNEXPECTED(err_msg);
  594. }
  595. return Status::OK();
  596. }
  597. } // namespace dataset
  598. } // namespace mindspore