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