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.

de_pipeline.cc 55 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. /**
  2. * Copyright 2019 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 "dataset/api/de_pipeline.h"
  17. #include <algorithm>
  18. #include <set>
  19. #include <map>
  20. #include "common/utils.h"
  21. #include "dataset/core/tensor.h"
  22. #include "dataset/engine/dataset_iterator.h"
  23. #include "dataset/engine/datasetops/bucket_batch_by_length_op.h"
  24. #include "dataset/engine/datasetops/filter_op.h"
  25. #include "dataset/engine/datasetops/source/celeba_op.h"
  26. #include "dataset/engine/datasetops/source/cifar_op.h"
  27. #include "dataset/engine/datasetops/source/clue_op.h"
  28. #include "dataset/engine/datasetops/source/coco_op.h"
  29. #include "dataset/engine/datasetops/source/image_folder_op.h"
  30. #include "dataset/engine/datasetops/source/manifest_op.h"
  31. #include "dataset/engine/datasetops/source/mnist_op.h"
  32. #include "dataset/engine/datasetops/source/random_data_op.h"
  33. #include "dataset/engine/datasetops/source/text_file_op.h"
  34. #include "dataset/engine/datasetops/source/voc_op.h"
  35. #include "dataset/kernels/py_func_op.h"
  36. #include "dataset/util/random.h"
  37. #include "dataset/util/status.h"
  38. #include "mindrecord/include/shard_category.h"
  39. #include "mindrecord/include/shard_distributed_sample.h"
  40. #include "mindrecord/include/shard_sample.h"
  41. #include "mindrecord/include/shard_shuffle.h"
  42. #include "pybind11/stl.h"
  43. #include "utils/log_adapter.h"
  44. namespace mindspore {
  45. namespace dataset {
  46. using pFunction = Status (DEPipeline::*)(const py::dict &, std::shared_ptr<DatasetOp> *, std::shared_ptr<DatasetOp> *);
  47. static std::unordered_map<uint32_t, pFunction> g_parse_op_func_ = {
  48. {kShuffle, &DEPipeline::ParseShuffleOp},
  49. {kMindrecord, &DEPipeline::ParseMindRecordOp},
  50. {kMap, &DEPipeline::ParseMapOp},
  51. {kFilter, &DEPipeline::ParseFilterOp},
  52. {kBatch, &DEPipeline::ParseBatchOp},
  53. {kBucketBatch, &DEPipeline::ParseBucketBatchByLengthOp},
  54. {kBarrier, &DEPipeline::ParseBarrierOp},
  55. {kRepeat, &DEPipeline::ParseRepeatOp},
  56. {kSkip, &DEPipeline::ParseSkipOp},
  57. {kZip, &DEPipeline::ParseZipOp},
  58. {kConcat, &DEPipeline::ParseConcatOp},
  59. {kRename, &DEPipeline::ParseRenameOp},
  60. {kDeviceQueue, &DEPipeline::ParseDeviceQueueOp},
  61. {kGenerator, &DEPipeline::ParseGeneratorOp},
  62. {kTfReader, &DEPipeline::ParseTFReaderOp},
  63. {kProject, &DEPipeline::ParseProjectOp},
  64. {kTake, &DEPipeline::ParseTakeOp},
  65. {kImageFolder, &DEPipeline::ParseImageFolderOp},
  66. {kMnist, &DEPipeline::ParseMnistOp},
  67. {kManifest, &DEPipeline::ParseManifestOp},
  68. {kVoc, &DEPipeline::ParseVOCOp},
  69. {kCoco, &DEPipeline::ParseCocoOp},
  70. {kCifar10, &DEPipeline::ParseCifar10Op},
  71. {kCifar100, &DEPipeline::ParseCifar100Op},
  72. {kCelebA, &DEPipeline::ParseCelebAOp},
  73. {kRandomData, &DEPipeline::ParseRandomDataOp},
  74. {kTextFile, &DEPipeline::ParseTextFileOp},
  75. {kBuildVocab, &DEPipeline::ParseBuildVocabOp},
  76. {kClue, &DEPipeline::ParseClueOp}};
  77. DEPipeline::DEPipeline() : iterator_(nullptr) {
  78. try {
  79. // One time init
  80. (void)GlobalInit();
  81. // Instantiate the execution tree
  82. tree_ = std::make_shared<ExecutionTree>();
  83. repeat_num_ = 1;
  84. batch_size_ = 1;
  85. num_rows_ = 0;
  86. num_classes_ = 0;
  87. temp_batch_size_ = 1;
  88. temp_drop_remainder_ = false;
  89. } catch (const std::exception &err) {
  90. MS_LOG(ERROR) << "Dataset pipeline exception caught on init: " << err.what() << ".";
  91. return;
  92. }
  93. }
  94. DEPipeline::~DEPipeline() {
  95. {
  96. // Release GIL before joining all threads
  97. py::gil_scoped_release gil_release;
  98. // Release tree
  99. tree_.reset();
  100. }
  101. }
  102. // Function to add a Node to the Execution Tree.
  103. Status DEPipeline::AddNodeToTree(const OpName &op_name, const py::dict &args, py::dict *output) {
  104. // For each operator, Parse through the list of arguments, then call the respective builder/constructor.
  105. // Note that each call to the parse function may result in building more than one dataset operator.
  106. // For example, one call to ParseNNNOp may result in multiple internal C nodes:
  107. // nodeA
  108. // |
  109. // nodeB
  110. // |
  111. // nodeC
  112. // However, the python side dataset is more abstract, and it does not know about the potential subtree that
  113. // is being built here. Since the python api is hooking tree nodes together (parent/child hookups), the
  114. // python side needs to know about nodeA and NodeC to be able to appropriately hook up parents and child
  115. // to this subtee.
  116. // Thus, it is required that both the top-most parent and bottom-most child are returned from the parse
  117. // function.
  118. DsOpPtr top = nullptr;
  119. DsOpPtr bottom = nullptr;
  120. auto iter = g_parse_op_func_.find(op_name);
  121. if (iter != g_parse_op_func_.end()) {
  122. pFunction func = iter->second;
  123. RETURN_IF_NOT_OK((this->*func)(args, &top, &bottom));
  124. if (top == nullptr) {
  125. RETURN_STATUS_UNEXPECTED("An operator was parsed but it did not produce a C node.");
  126. }
  127. // It is not required that the parse function always produces the bottom pointer. If it's still null,
  128. // then set top and bottom to be the same operator
  129. if (bottom == nullptr) bottom = top;
  130. // Pack these pointers into a py dict so that we can return both back to python.
  131. (*output)["top"] = top;
  132. (*output)["bottom"] = bottom;
  133. } else {
  134. RETURN_STATUS_UNEXPECTED("No such Op");
  135. }
  136. // Associate current dataset op node with the tree.
  137. RETURN_IF_NOT_OK(tree_->AssociateNode(top));
  138. return Status::OK();
  139. }
  140. // Function to add a child and parent relationship.
  141. Status DEPipeline::AddChildToParentNode(const DsOpPtr &child_op, const DsOpPtr &parent_op) {
  142. // Link this relationship.
  143. // Note parent node takes ownership of the child
  144. return (parent_op->AddChild(child_op));
  145. }
  146. // Function to assign the node as root.
  147. Status DEPipeline::AssignRootNode(const DsOpPtr &dataset_op) { return (tree_->AssignRoot(dataset_op)); }
  148. // Function to launch the tree execution.
  149. Status DEPipeline::LaunchTreeExec() {
  150. RETURN_IF_NOT_OK(tree_->Prepare());
  151. RETURN_IF_NOT_OK(tree_->Launch());
  152. iterator_ = std::make_unique<DatasetIterator>(tree_);
  153. if (iterator_ == nullptr) RETURN_STATUS_UNEXPECTED("Cannot create an Iterator.");
  154. return Status::OK();
  155. }
  156. void DEPipeline::PrintTree() {
  157. for (auto itr = tree_->begin(); itr != tree_->end(); ++itr) {
  158. std::stringstream ss;
  159. ss << *itr;
  160. MS_LOG(DEBUG) << "Operator ID is " << itr->id() << ". Details: " << ss.str().c_str() << ".";
  161. }
  162. }
  163. Status DEPipeline::GetNextAsMap(py::dict *output) {
  164. TensorMap row;
  165. Status s;
  166. {
  167. py::gil_scoped_release gil_release;
  168. s = iterator_->GetNextAsMap(&row);
  169. }
  170. RETURN_IF_NOT_OK(s);
  171. // Generate Python dict as return
  172. for (auto el : row) {
  173. (*output)[common::SafeCStr(el.first)] = el.second;
  174. }
  175. return Status::OK();
  176. }
  177. Status DEPipeline::GetNextAsList(py::list *output) {
  178. TensorRow row;
  179. Status s;
  180. {
  181. py::gil_scoped_release gil_release;
  182. s = iterator_->FetchNextTensorRow(&row);
  183. }
  184. RETURN_IF_NOT_OK(s);
  185. // Generate Python list as return
  186. for (auto el : row) {
  187. output->append(el);
  188. }
  189. return Status::OK();
  190. }
  191. Status DEPipeline::GetOutputShapes(py::list *output) {
  192. std::vector<TensorShape> shapes;
  193. Status s;
  194. {
  195. py::gil_scoped_release gil_release;
  196. s = iterator_->GetOutputShapes(&shapes);
  197. }
  198. RETURN_IF_NOT_OK(s);
  199. for (auto el : shapes) {
  200. py::list shape;
  201. for (auto dim : el.AsVector()) {
  202. shape.append(dim);
  203. }
  204. output->append(shape);
  205. }
  206. return Status::OK();
  207. }
  208. Status DEPipeline::GetOutputTypes(py::list *output) {
  209. std::vector<DataType> types;
  210. Status s;
  211. {
  212. py::gil_scoped_release gil_release;
  213. s = iterator_->GetOutputTypes(&types);
  214. }
  215. RETURN_IF_NOT_OK(s);
  216. for (auto el : types) {
  217. output->append(el.AsNumpyType());
  218. }
  219. return Status::OK();
  220. }
  221. int DEPipeline::GetDatasetSize() const { return num_rows_ / batch_size_; }
  222. int DEPipeline::GetBatchSize() const { return batch_size_; }
  223. int DEPipeline::GetRepeatCount() const { return repeat_num_; }
  224. float ToFloat(const py::handle &handle) { return py::reinterpret_borrow<py::float_>(handle); }
  225. int ToInt(const py::handle &handle) { return py::reinterpret_borrow<py::int_>(handle); }
  226. bool ToBool(const py::handle &handle) { return py::reinterpret_borrow<py::bool_>(handle); }
  227. std::string ToString(const py::handle &handle) { return py::reinterpret_borrow<py::str>(handle); }
  228. std::vector<std::string> ToStringVector(const py::handle handle) {
  229. py::list list = py::reinterpret_borrow<py::list>(handle);
  230. std::vector<std::string> vector;
  231. for (auto l : list) {
  232. if (!l.is_none())
  233. vector.push_back(py::str(l));
  234. else
  235. vector.emplace_back("");
  236. }
  237. return vector;
  238. }
  239. std::set<std::string> ToStringSet(const py::handle handle) {
  240. py::list list = py::reinterpret_borrow<py::list>(handle);
  241. std::set<std::string> set;
  242. for (auto l : list) {
  243. if (!l.is_none()) {
  244. (void)set.insert(py::str(l));
  245. }
  246. }
  247. return set;
  248. }
  249. std::map<std::string, int32_t> ToStringMap(const py::handle handle) {
  250. py::dict dict = py::reinterpret_borrow<py::dict>(handle);
  251. std::map<std::string, int32_t> map;
  252. for (auto p : dict) {
  253. (void)map.insert(std::make_pair(ToString(p.first), ToInt(p.second)));
  254. }
  255. return map;
  256. }
  257. std::vector<int> ToIntVector(const py::handle handle) {
  258. py::list list = py::reinterpret_borrow<py::list>(handle);
  259. std::vector<int> vector;
  260. for (auto l : list) {
  261. if (!l.is_none()) {
  262. vector.push_back(ToInt(l));
  263. }
  264. }
  265. return vector;
  266. }
  267. std::vector<DataType> ToTypeVector(const py::handle handle) {
  268. py::list list = py::reinterpret_borrow<py::list>(handle);
  269. std::vector<DataType> vector;
  270. for (auto l : list) {
  271. if (l.is_none()) {
  272. vector.emplace_back(DataType());
  273. } else {
  274. vector.push_back(l.cast<DataType>());
  275. }
  276. }
  277. return vector;
  278. }
  279. Status DEPipeline::SetBatchParameters(const py::dict &args) {
  280. if (args["batch_size"].is_none()) {
  281. std::string err_msg = "Error: batchSize is invalid or not set.";
  282. RETURN_STATUS_UNEXPECTED(err_msg);
  283. }
  284. temp_batch_size_ = ToInt(args["batch_size"]);
  285. CHECK_FAIL_RETURN_UNEXPECTED(temp_batch_size_ > 0, "Error: batchSize is invalid.");
  286. for (auto arg : args) {
  287. std::string key = py::str(arg.first);
  288. py::handle value = arg.second;
  289. if (!value.is_none()) {
  290. if (key == "drop_remainder") {
  291. temp_drop_remainder_ = ToBool(value);
  292. }
  293. }
  294. }
  295. return Status::OK();
  296. }
  297. Status DEPipeline::ParseShuffleOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  298. std::shared_ptr<DatasetOp> *bottom) {
  299. std::shared_ptr<ShuffleOp::Builder> builder = std::make_shared<ShuffleOp::Builder>();
  300. if (!args["buffer_size"].is_none()) {
  301. (void)builder->SetShuffleSize(ToInt(args["buffer_size"]));
  302. } else {
  303. std::string err_msg = "Error: Shuffle buffer size is missing";
  304. RETURN_STATUS_UNEXPECTED(err_msg);
  305. }
  306. // Optional arguments
  307. for (auto arg : args) {
  308. std::string key = py::str(arg.first);
  309. py::handle value = arg.second;
  310. if (!value.is_none()) {
  311. if (key == "reshuffle_each_epoch") {
  312. (void)builder->SetReshuffleEachEpoch(ToBool(args["reshuffle_each_epoch"]));
  313. }
  314. }
  315. }
  316. std::shared_ptr<ShuffleOp> op;
  317. RETURN_IF_NOT_OK(builder->Build(&op));
  318. *top = op;
  319. return Status::OK();
  320. }
  321. Status DEPipeline::BuildMindrecordSamplerChain(const py::handle &handle,
  322. std::vector<std::shared_ptr<mindrecord::ShardOperator>> *operators,
  323. int num_padded) {
  324. auto sampler = py::reinterpret_borrow<py::object>(handle);
  325. auto create = sampler.attr("create_for_minddataset");
  326. auto op = create().cast<std::shared_ptr<mindrecord::ShardOperator>>();
  327. std::stack<std::shared_ptr<mindrecord::ShardOperator>> stack_ops;
  328. while (op != nullptr) {
  329. auto sampler_op = std::dynamic_pointer_cast<mindrecord::ShardDistributedSample>(op);
  330. if (sampler_op && num_padded > 0) {
  331. sampler_op->SetNumPaddedSamples(num_padded);
  332. stack_ops.push(sampler_op);
  333. } else {
  334. stack_ops.push(op);
  335. }
  336. op = op->GetChildOp();
  337. }
  338. while (!stack_ops.empty()) {
  339. operators->push_back(stack_ops.top());
  340. stack_ops.pop();
  341. }
  342. return Status::OK();
  343. }
  344. Status DEPipeline::ParseMindRecordOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  345. std::shared_ptr<DatasetOp> *bottom) {
  346. if (args["dataset_file"].is_none()) {
  347. std::string err_msg = "Error: at least one of dataset_files is missing";
  348. RETURN_STATUS_UNEXPECTED(err_msg);
  349. }
  350. std::shared_ptr<MindRecordOp::Builder> builder = std::make_shared<MindRecordOp::Builder>();
  351. bool load_dataset = ToBool(args["load_dataset"]);
  352. if (load_dataset == true) {
  353. (void)builder->SetDatasetFile({ToString(args["dataset_file"])});
  354. } else {
  355. (void)builder->SetDatasetFile(ToStringVector(args["dataset_file"]));
  356. }
  357. (void)builder->SetLoadDataset(load_dataset);
  358. std::vector<std::string> in_col_names;
  359. if (!args["columns_list"].is_none()) {
  360. in_col_names = ToStringVector(args["columns_list"]);
  361. if (in_col_names.empty() || in_col_names[0].empty()) {
  362. std::string err_msg = "Error: columns_list is invalid or not set.";
  363. RETURN_STATUS_UNEXPECTED(err_msg);
  364. }
  365. (void)builder->SetColumnsToLoad(in_col_names);
  366. }
  367. if (!args["padded_sample"].is_none()) {
  368. (void)builder->SetPaddedSample(args["padded_sample"]);
  369. (void)builder->SetNumToPadSamples(ToInt(args["num_padded"]));
  370. }
  371. std::vector<std::shared_ptr<mindrecord::ShardOperator>> operators;
  372. for (auto arg : args) {
  373. std::string key = py::str(arg.first);
  374. py::handle value = arg.second;
  375. if (!value.is_none()) {
  376. if (key == "num_parallel_workers") {
  377. (void)builder->SetNumMindRecordWorkers(ToInt(value));
  378. } else if (key == "block_reader" && ToBool(value) == true) {
  379. (void)builder->SetBlockReader();
  380. } else if (key == "sampler") {
  381. int num_padded = 0;
  382. if (!args["num_padded"].is_none()) {
  383. num_padded = ToInt(args["num_padded"]);
  384. }
  385. RETURN_IF_NOT_OK(BuildMindrecordSamplerChain(value, &operators, num_padded));
  386. }
  387. }
  388. }
  389. if (!operators.empty()) {
  390. (void)builder->SetOperators(operators);
  391. }
  392. std::shared_ptr<MindRecordOp> op;
  393. RETURN_IF_NOT_OK(builder->Build(&op));
  394. num_rows_ = op->num_rows();
  395. *top = op;
  396. return Status::OK();
  397. }
  398. Status DEPipeline::ParseMapOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  399. std::shared_ptr<DatasetOp> *bottom) {
  400. MapOp::Builder map_builder;
  401. std::vector<std::shared_ptr<TensorOp>> tensor_op_list;
  402. std::vector<std::string> project_columns;
  403. if (args["operations"].is_none()) RETURN_STATUS_UNEXPECTED("Error: 'operations' is not set. \n");
  404. for (auto arg : args) {
  405. std::string key = py::str(arg.first);
  406. py::handle value = arg.second;
  407. if (!value.is_none()) {
  408. if (key == "input_columns") {
  409. std::vector<std::string> in_col_names = ToStringVector(args["input_columns"]);
  410. (void)map_builder.SetInColNames(in_col_names);
  411. } else if (key == "output_columns") {
  412. (void)map_builder.SetOutColNames(ToStringVector(value));
  413. } else if (key == "columns_order") {
  414. project_columns = ToStringVector(value);
  415. } else if (key == "num_parallel_workers") {
  416. (void)map_builder.SetNumWorkers(ToInt(value));
  417. } else if (key == "prefetch_size") {
  418. (void)map_builder.SetOpConnectorSize(ToInt(value));
  419. } else if (key == "operations") {
  420. py::handle tensor_ops = args["operations"];
  421. // operation can be a list of TensorOps or a single TensorOp.
  422. if (py::isinstance<py::list>(tensor_ops)) {
  423. for (auto op : tensor_ops) {
  424. std::shared_ptr<TensorOp> tensor_op;
  425. if (py::isinstance<TensorOp>(op)) {
  426. tensor_op = op.cast<std::shared_ptr<TensorOp>>();
  427. } else if (py::isinstance<py::function>(op)) {
  428. tensor_op = std::make_shared<PyFuncOp>(op.cast<py::function>());
  429. } else {
  430. RETURN_STATUS_UNEXPECTED("Error: tensor_op is not recognised (not TensorOp and not pyfunc).");
  431. }
  432. tensor_op_list.push_back(tensor_op);
  433. }
  434. }
  435. if (tensor_op_list.empty()) RETURN_STATUS_UNEXPECTED("Error: tensor_op is invalid or not set.");
  436. (void)map_builder.SetTensorFuncs(std::move(tensor_op_list));
  437. } else {
  438. RETURN_STATUS_UNEXPECTED("Error: Unhandled key: " + key);
  439. }
  440. }
  441. }
  442. std::shared_ptr<MapOp> map_op;
  443. RETURN_IF_NOT_OK(map_builder.Build(&map_op));
  444. RETURN_IF_NOT_OK(tree_->AssociateNode(map_op));
  445. *top = map_op;
  446. // Add a project op over top of the map if the user wanted to reposition the columns
  447. if (!project_columns.empty()) {
  448. ProjectOp::Builder proj_builder(project_columns);
  449. std::shared_ptr<ProjectOp> proj_op;
  450. RETURN_IF_NOT_OK(proj_builder.Build(&proj_op));
  451. RETURN_IF_NOT_OK(tree_->AssociateNode(proj_op));
  452. RETURN_IF_NOT_OK(proj_op->AddChild(map_op));
  453. *top = proj_op;
  454. *bottom = map_op;
  455. }
  456. return Status::OK();
  457. }
  458. Status DEPipeline::ParseFilterOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  459. std::shared_ptr<DatasetOp> *bottom) {
  460. std::shared_ptr<FilterOp::Builder> builder = std::make_shared<FilterOp::Builder>();
  461. if (args["predicate"].is_none()) {
  462. RETURN_STATUS_UNEXPECTED("Error: 'predicate' is not set. \n");
  463. }
  464. for (auto arg : args) {
  465. std::string key = py::str(arg.first);
  466. py::handle value = arg.second;
  467. if (!value.is_none()) {
  468. if (key == "num_parallel_workers") {
  469. (void)builder->SetNumWorkers(ToInt(value));
  470. } else if (key == "predicate") {
  471. py::handle op = args["predicate"];
  472. if (!py::isinstance<py::function>(op)) {
  473. RETURN_STATUS_UNEXPECTED("Error: predicate is not recognised (not pyfunc).");
  474. }
  475. py::function predicate_func = op.cast<py::function>();
  476. (void)builder->SetPredicateFunc(std::move(predicate_func));
  477. } else if (key == "input_columns") {
  478. std::vector<std::string> in_col_names = ToStringVector(args["input_columns"]);
  479. (void)builder->SetInColNames(in_col_names);
  480. } else {
  481. RETURN_STATUS_UNEXPECTED("Error: Unhandled key: " + key);
  482. }
  483. }
  484. }
  485. std::shared_ptr<FilterOp> op;
  486. RETURN_IF_NOT_OK(builder->Build(&op));
  487. *top = op;
  488. return Status::OK();
  489. }
  490. Status DEPipeline::ParseRepeatOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  491. std::shared_ptr<DatasetOp> *bottom) {
  492. if (args["count"].is_none()) {
  493. std::string err_msg = "Error: count is invalid or not set.";
  494. RETURN_STATUS_UNEXPECTED(err_msg);
  495. }
  496. repeat_num_ = ToInt(args["count"]);
  497. std::shared_ptr<RepeatOp> op;
  498. RETURN_IF_NOT_OK(RepeatOp::Builder(ToInt(args["count"])).Build(&op));
  499. *top = op;
  500. return Status::OK();
  501. }
  502. Status DEPipeline::ParseSkipOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  503. std::shared_ptr<DatasetOp> *bottom) {
  504. if (args["count"].is_none()) {
  505. std::string err_msg = "Error: count is invalid or not set.";
  506. RETURN_STATUS_UNEXPECTED(err_msg);
  507. }
  508. std::shared_ptr<SkipOp> op;
  509. RETURN_IF_NOT_OK(SkipOp::Builder(ToInt(args["count"])).Build(&op));
  510. *top = op;
  511. return Status::OK();
  512. }
  513. Status DEPipeline::ParseGeneratorOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  514. std::shared_ptr<DatasetOp> *bottom) {
  515. std::shared_ptr<GeneratorOp::Builder> builder = std::make_shared<GeneratorOp::Builder>();
  516. for (auto arg : args) {
  517. std::string key = py::str(arg.first);
  518. py::handle value = arg.second;
  519. if (!value.is_none()) {
  520. if (key == "source") {
  521. py::object obj = py::cast(&value);
  522. if (!py::isinstance<py::function>(obj)) {
  523. std::string err_msg = "Error: generator is invalid or not set.";
  524. RETURN_STATUS_UNEXPECTED(err_msg);
  525. }
  526. (void)builder->SetGeneratorFunction(obj.cast<py::function>());
  527. } else if (key == "column_names") {
  528. (void)builder->SetColumnNames(ToStringVector(value));
  529. } else if (key == "column_types") {
  530. (void)builder->SetColumnTypes(ToTypeVector(value));
  531. }
  532. }
  533. }
  534. std::shared_ptr<GeneratorOp> op;
  535. RETURN_IF_NOT_OK(builder->Build(&op));
  536. *top = op;
  537. return Status::OK();
  538. }
  539. Status DEPipeline::ParseBatchOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  540. std::shared_ptr<DatasetOp> *bottom) {
  541. std::shared_ptr<BatchOp::Builder> builder;
  542. if (py::isinstance<py::int_>(args["batch_size"])) {
  543. batch_size_ = ToInt(args["batch_size"]);
  544. CHECK_FAIL_RETURN_UNEXPECTED(batch_size_ > 0, "Error: batch_size is invalid.");
  545. builder = std::make_shared<BatchOp::Builder>(ToInt(args["batch_size"]));
  546. } else if (py::isinstance<py::function>(args["batch_size"])) {
  547. builder = std::make_shared<BatchOp::Builder>(1);
  548. (void)builder->SetBatchSizeFunc(args["batch_size"].cast<py::function>());
  549. } else {
  550. std::string err_msg = "Error: batch_size is neither an Integer nor a python function";
  551. RETURN_STATUS_UNEXPECTED(err_msg);
  552. }
  553. for (auto arg : args) {
  554. std::string key = py::str(arg.first);
  555. py::handle value = arg.second;
  556. if (!value.is_none()) {
  557. if (key == "drop_remainder") {
  558. (void)builder->SetDrop(ToBool(value));
  559. }
  560. if (key == "num_parallel_workers") {
  561. (void)builder->SetNumWorkers(ToInt(value));
  562. }
  563. if (key == "per_batch_map") {
  564. (void)builder->SetBatchMapFunc(value.cast<py::function>());
  565. }
  566. if (key == "input_columns") {
  567. (void)builder->SetColumnsToMap(ToStringVector(value));
  568. }
  569. if (key == "pad_info") {
  570. PadInfo pad_info;
  571. RETURN_IF_NOT_OK(ParsePadInfo(value, &pad_info));
  572. (void)builder->SetPaddingMap(pad_info, true);
  573. }
  574. }
  575. }
  576. std::shared_ptr<BatchOp> op;
  577. RETURN_IF_NOT_OK(builder->Build(&op));
  578. *top = op;
  579. return Status::OK();
  580. }
  581. Status DEPipeline::ParseBucketBatchByLengthOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  582. std::shared_ptr<DatasetOp> *bottom) {
  583. std::vector<std::string> mandatory_arguments = {"length_dependent_columns", "bucket_boundaries",
  584. "bucket_batch_sizes"};
  585. for (auto name : mandatory_arguments) {
  586. if (args[name.c_str()].is_none()) {
  587. std::string err_msg = "Error: " + name + " is not set.";
  588. RETURN_STATUS_UNEXPECTED(err_msg);
  589. }
  590. }
  591. std::shared_ptr<BucketBatchByLengthOp::Builder> builder = std::make_shared<BucketBatchByLengthOp::Builder>(
  592. ToStringVector(args[mandatory_arguments[0].c_str()]), ToIntVector(args[mandatory_arguments[1].c_str()]),
  593. ToIntVector(args[mandatory_arguments[2].c_str()]));
  594. for (auto arg : args) {
  595. std::string key = py::str(arg.first);
  596. py::handle value = arg.second;
  597. if (!value.is_none()) {
  598. if (key == "length_dependent_columns") {
  599. (void)builder->SetLengthDependentColumns(ToStringVector(value));
  600. }
  601. if (key == "bucket_boundaries") {
  602. (void)builder->SetBucketBoundaries(ToIntVector(value));
  603. }
  604. if (key == "bucket_batch_sizes") {
  605. (void)builder->SetBucketBatchSizes(ToIntVector(value));
  606. }
  607. if (key == "element_length_function") {
  608. (void)builder->SetElementLengthFunction(value.cast<py::function>());
  609. }
  610. if (key == "pad_info") {
  611. PadInfo pad_info;
  612. RETURN_IF_NOT_OK(ParsePadInfo(value, &pad_info));
  613. (void)builder->SetPadInfo(pad_info);
  614. }
  615. if (key == "pad_to_bucket_boundary") {
  616. (void)builder->SetPadToBucketBoundary(ToBool(value));
  617. }
  618. if (key == "drop_remainder") {
  619. (void)builder->SetDropRemainder(ToBool(value));
  620. }
  621. }
  622. }
  623. std::shared_ptr<BucketBatchByLengthOp> op;
  624. RETURN_IF_NOT_OK(builder->Build(&op));
  625. *top = op;
  626. return Status::OK();
  627. }
  628. Status DEPipeline::ParseBarrierOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  629. std::shared_ptr<DatasetOp> *bottom) {
  630. std::shared_ptr<BarrierOp::Builder> builder = std::make_shared<BarrierOp::Builder>();
  631. // Right now barrier should only take num_rows_per_buffer = 1
  632. // The reason for this is because having it otherwise can lead to blocking issues
  633. // See barrier_op.h for more details
  634. (void)builder->SetRowsPerBuffer(1);
  635. for (auto arg : args) {
  636. std::string key = py::str(arg.first);
  637. py::handle value = arg.second;
  638. if (!value.is_none()) {
  639. if (key == "condition_name") {
  640. (void)builder->SetConditionName(ToString(value));
  641. } else if (key == "condition_func") {
  642. (void)builder->SetConditionFunc(value.cast<py::function>());
  643. }
  644. }
  645. }
  646. std::shared_ptr<BarrierOp> op;
  647. RETURN_IF_NOT_OK(builder->Build(&op));
  648. *top = op;
  649. return Status::OK();
  650. }
  651. Status DEPipeline::ParseDeviceQueueOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  652. std::shared_ptr<DatasetOp> *bottom) {
  653. int32_t prefetch_size = 0;
  654. if (args.contains("prefetch_size")) {
  655. if (args["prefetch_size"].is_none()) {
  656. prefetch_size = 16;
  657. } else {
  658. prefetch_size = ToInt(args["prefetch_size"]);
  659. }
  660. }
  661. std::shared_ptr<DeviceQueueOp::Builder> builder = std::make_shared<DeviceQueueOp::Builder>(prefetch_size);
  662. for (auto arg : args) {
  663. std::string key = py::str(arg.first);
  664. py::handle value = arg.second;
  665. if (!value.is_none()) {
  666. if (key == "queue_name") {
  667. (void)builder->SetChannelName(ToString(value));
  668. } else if (key == "device_type") {
  669. (void)builder->SetDeviceType(ToString(value));
  670. } else if (key == "device_id") {
  671. (void)builder->SetDeviceId(ToInt(value));
  672. } else if (key == "num_batch") {
  673. (void)builder->SetNumBatch(ToInt(value));
  674. }
  675. }
  676. }
  677. std::shared_ptr<DeviceQueueOp> op;
  678. RETURN_IF_NOT_OK(builder->Build(&op));
  679. *top = op;
  680. return Status::OK();
  681. }
  682. Status DEPipeline::ParseRenameOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  683. std::shared_ptr<DatasetOp> *bottom) {
  684. std::vector<std::string> in_col_names;
  685. std::vector<std::string> out_col_names;
  686. std::shared_ptr<RenameOp::Builder> builder = std::make_shared<RenameOp::Builder>();
  687. for (auto arg : args) {
  688. std::string key = py::str(arg.first);
  689. py::handle value = arg.second;
  690. if (!value.is_none()) {
  691. if (key == "input_columns") {
  692. in_col_names = ToStringVector(value);
  693. } else if (key == "output_columns") {
  694. out_col_names = ToStringVector(value);
  695. }
  696. }
  697. }
  698. if (in_col_names.empty() || in_col_names[0].empty()) {
  699. std::string err_msg = "Error: input_column_names is invalid or not set.";
  700. RETURN_STATUS_UNEXPECTED(err_msg);
  701. }
  702. if (out_col_names.empty() || out_col_names[0].empty()) {
  703. std::string err_msg = "Error: output_column_names is invalid or not set.";
  704. RETURN_STATUS_UNEXPECTED(err_msg);
  705. }
  706. (void)builder->SetInColNames(in_col_names);
  707. (void)builder->SetOutColNames(out_col_names);
  708. std::shared_ptr<RenameOp> op;
  709. RETURN_IF_NOT_OK(builder->Build(&op));
  710. *top = op;
  711. return Status::OK();
  712. }
  713. Status DEPipeline::ParseTakeOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  714. std::shared_ptr<DatasetOp> *bottom) {
  715. if (args["count"].is_none()) {
  716. std::string err_msg = "Error: count is invalid or not set.";
  717. RETURN_STATUS_UNEXPECTED(err_msg);
  718. }
  719. std::shared_ptr<TakeOp> op;
  720. RETURN_IF_NOT_OK(TakeOp::Builder(ToInt(args["count"])).Build(&op));
  721. *top = op;
  722. return Status::OK();
  723. }
  724. Status DEPipeline::ParseZipOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  725. std::shared_ptr<DatasetOp> *bottom) {
  726. std::shared_ptr<ZipOp::Builder> builder = std::make_shared<ZipOp::Builder>();
  727. std::shared_ptr<ZipOp> op;
  728. RETURN_IF_NOT_OK(builder->Build(&op));
  729. *top = op;
  730. return Status::OK();
  731. }
  732. Status DEPipeline::ParseConcatOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  733. std::shared_ptr<DatasetOp> *bottom) {
  734. std::shared_ptr<ConcatOp::Builder> builder = std::make_shared<ConcatOp::Builder>();
  735. std::shared_ptr<ConcatOp> op;
  736. RETURN_IF_NOT_OK(builder->Build(&op));
  737. *top = op;
  738. return Status::OK();
  739. }
  740. Status DEPipeline::ParseTFReaderOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  741. std::shared_ptr<DatasetOp> *bottom) {
  742. // Required arguments
  743. std::vector<std::string> files_list;
  744. std::shared_ptr<TFReaderOp::Builder> builder = std::make_shared<TFReaderOp::Builder>();
  745. if (!args["dataset_files"].is_none()) {
  746. files_list = ToStringVector(args["dataset_files"]);
  747. (void)builder->SetDatasetFilesList(files_list);
  748. } else {
  749. std::string err_msg = "Error: at least one of dataset_files or schema_file is missing";
  750. RETURN_STATUS_UNEXPECTED(err_msg);
  751. }
  752. std::vector<std::string> columns_to_load;
  753. bool schema_exists = false;
  754. bool shuffle_required = false;
  755. int64_t num_devices = 0;
  756. int64_t total_rows = 0;
  757. // Optional arguments
  758. for (auto arg : args) {
  759. std::string key = py::str(arg.first);
  760. py::handle value = arg.second;
  761. if (!value.is_none()) {
  762. if (key == "num_parallel_workers") {
  763. (void)builder->SetNumWorkers(ToInt(value));
  764. } else if (key == "columns_list") {
  765. columns_to_load = ToStringVector(value);
  766. (void)builder->SetColumnsToLoad(columns_to_load);
  767. } else if (key == "shuffle_files") {
  768. (void)builder->SetShuffleFiles(ToBool(value));
  769. } else if (key == "shuffle_global") {
  770. shuffle_required = ToBool(value);
  771. } else if (key == "schema_file_path" || key == "schema_json_string") {
  772. schema_exists = true;
  773. } else if (key == "num_samples") {
  774. total_rows = ToInt(value);
  775. (void)builder->setTotalRows(total_rows);
  776. } else if (key == "num_shards") {
  777. num_devices = ToInt(value);
  778. (void)builder->SetNumDevices(num_devices);
  779. } else if (key == "shard_id") {
  780. (void)builder->SetDeviceId(ToInt(value));
  781. } else if (key == "shard_equal_rows") {
  782. (void)builder->SetShardEqualRows(ToBool(value));
  783. }
  784. }
  785. }
  786. if (schema_exists) {
  787. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  788. if (args.contains("schema_file_path")) {
  789. RETURN_IF_NOT_OK(schema->LoadSchemaFile(ToString(args["schema_file_path"]), columns_to_load));
  790. } else {
  791. RETURN_IF_NOT_OK(schema->LoadSchemaString(ToString(args["schema_json_string"]), columns_to_load));
  792. }
  793. (void)builder->SetDataSchema(std::move(schema));
  794. }
  795. std::shared_ptr<TFReaderOp> tf_op;
  796. RETURN_IF_NOT_OK(builder->Build(&tf_op));
  797. RETURN_IF_NOT_OK(tree_->AssociateNode(tf_op));
  798. *top = tf_op;
  799. if (shuffle_required) {
  800. const boolean estimate = true;
  801. const int64_t workers = 8;
  802. std::shared_ptr<DatasetOp> shuffle_op = nullptr;
  803. int64_t shuffle_size = 0;
  804. int64_t num_rows = 0;
  805. // First, get the number of rows in the dataset via estimate and then compute the shuffle size
  806. RETURN_IF_NOT_OK(TFReaderOp::CountTotalRows(&num_rows, files_list, workers, estimate));
  807. RETURN_IF_NOT_OK(ComputeShuffleSize(files_list.size(), num_devices, num_rows, total_rows, &shuffle_size));
  808. // Add the shuffle op over top of this op and return the subtree (top/bottom) to caller
  809. RETURN_IF_NOT_OK(AddShuffleOp(shuffle_size, tf_op, &shuffle_op));
  810. *top = shuffle_op;
  811. *bottom = tf_op;
  812. }
  813. return Status::OK();
  814. }
  815. Status DEPipeline::ParseProjectOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  816. std::shared_ptr<DatasetOp> *bottom) {
  817. if (args["columns"].is_none()) {
  818. std::string err_msg = "Error: columns is missing";
  819. RETURN_STATUS_UNEXPECTED(err_msg);
  820. }
  821. std::vector<std::string> columns_to_project = ToStringVector(args["columns"]);
  822. std::shared_ptr<ProjectOp::Builder> builder = std::make_shared<ProjectOp::Builder>(columns_to_project);
  823. std::shared_ptr<ProjectOp> op;
  824. RETURN_IF_NOT_OK(builder->Build(&op));
  825. *top = op;
  826. return Status::OK();
  827. }
  828. Status DEPipeline::ParseImageFolderOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  829. std::shared_ptr<DatasetOp> *bottom) {
  830. // Required arguments
  831. if (args["dataset_dir"].is_none()) {
  832. std::string err_msg = "Error: No dataset path specified";
  833. RETURN_STATUS_UNEXPECTED(err_msg);
  834. }
  835. std::shared_ptr<ImageFolderOp::Builder> builder = std::make_shared<ImageFolderOp::Builder>();
  836. (void)builder->SetImageFolderDir(ToString(args["dataset_dir"]));
  837. // Optional arguments
  838. for (auto arg : args) {
  839. std::string key = py::str(arg.first);
  840. py::handle value = arg.second;
  841. if (!value.is_none()) {
  842. if (key == "num_parallel_workers") {
  843. (void)builder->SetNumWorkers(ToInt(value));
  844. } else if (key == "sampler") {
  845. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  846. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  847. (void)builder->SetSampler(std::move(sampler));
  848. } else if (key == "extensions") {
  849. (void)builder->SetExtensions(ToStringSet(value));
  850. } else if (key == "class_indexing") {
  851. (void)builder->SetClassIndex(ToStringMap(value));
  852. } else if (key == "decode") {
  853. (void)builder->SetDecode(ToBool(value));
  854. }
  855. }
  856. }
  857. std::shared_ptr<ImageFolderOp> op;
  858. RETURN_IF_NOT_OK(builder->Build(&op));
  859. *top = op;
  860. return Status::OK();
  861. }
  862. Status DEPipeline::ParseManifestOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  863. std::shared_ptr<DatasetOp> *bottom) {
  864. // Required arguments
  865. if (args["dataset_file"].is_none()) {
  866. std::string err_msg = "Error: No dataset files specified for manifest";
  867. RETURN_STATUS_UNEXPECTED(err_msg);
  868. }
  869. std::shared_ptr<ManifestOp::Builder> builder = std::make_shared<ManifestOp::Builder>();
  870. (void)builder->SetManifestFile(ToString(args["dataset_file"]));
  871. // Optional arguments
  872. for (auto arg : args) {
  873. std::string key = py::str(arg.first);
  874. py::handle value = arg.second;
  875. if (!value.is_none()) {
  876. if (key == "num_parallel_workers") {
  877. (void)builder->SetNumWorkers(ToInt(value));
  878. } else if (key == "sampler") {
  879. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  880. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  881. (void)builder->SetSampler(std::move(sampler));
  882. } else if (key == "class_indexing") {
  883. (void)builder->SetClassIndex(ToStringMap(value));
  884. } else if (key == "decode") {
  885. (void)builder->SetDecode(ToBool(value));
  886. } else if (key == "usage") {
  887. (void)builder->SetUsage(ToString(value));
  888. }
  889. }
  890. }
  891. std::shared_ptr<ManifestOp> op;
  892. RETURN_IF_NOT_OK(builder->Build(&op));
  893. *top = op;
  894. return Status::OK();
  895. }
  896. Status DEPipeline::ParseVOCOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  897. std::shared_ptr<DatasetOp> *bottom) {
  898. if (args["dataset_dir"].is_none()) {
  899. std::string err_msg = "Error: No dataset path specified";
  900. RETURN_STATUS_UNEXPECTED(err_msg);
  901. }
  902. if (args["task"].is_none()) {
  903. std::string err_msg = "Error: No task specified";
  904. RETURN_STATUS_UNEXPECTED(err_msg);
  905. }
  906. if (args["mode"].is_none()) {
  907. std::string err_msg = "Error: No mode specified";
  908. RETURN_STATUS_UNEXPECTED(err_msg);
  909. }
  910. std::shared_ptr<VOCOp::Builder> builder = std::make_shared<VOCOp::Builder>();
  911. (void)builder->SetDir(ToString(args["dataset_dir"]));
  912. (void)builder->SetTask(ToString(args["task"]));
  913. (void)builder->SetMode(ToString(args["mode"]));
  914. for (auto arg : args) {
  915. std::string key = py::str(arg.first);
  916. py::handle value = arg.second;
  917. if (!value.is_none()) {
  918. if (key == "num_parallel_workers") {
  919. (void)builder->SetNumWorkers(ToInt(value));
  920. } else if (key == "sampler") {
  921. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  922. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  923. (void)builder->SetSampler(std::move(sampler));
  924. } else if (key == "decode") {
  925. (void)builder->SetDecode(ToBool(value));
  926. } else if (key == "class_indexing") {
  927. (void)builder->SetClassIndex(ToStringMap(value));
  928. }
  929. }
  930. }
  931. std::shared_ptr<VOCOp> op;
  932. RETURN_IF_NOT_OK(builder->Build(&op));
  933. *top = op;
  934. return Status::OK();
  935. }
  936. Status DEPipeline::ParseCocoOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  937. std::shared_ptr<DatasetOp> *bottom) {
  938. if (args["dataset_dir"].is_none()) {
  939. std::string err_msg = "Error: No dataset path specified";
  940. RETURN_STATUS_UNEXPECTED(err_msg);
  941. }
  942. if (args["annotation_file"].is_none()) {
  943. std::string err_msg = "Error: No annotation_file specified";
  944. RETURN_STATUS_UNEXPECTED(err_msg);
  945. }
  946. if (args["task"].is_none()) {
  947. std::string err_msg = "Error: No task specified";
  948. RETURN_STATUS_UNEXPECTED(err_msg);
  949. }
  950. std::shared_ptr<CocoOp::Builder> builder = std::make_shared<CocoOp::Builder>();
  951. (void)builder->SetDir(ToString(args["dataset_dir"]));
  952. (void)builder->SetFile(ToString(args["annotation_file"]));
  953. (void)builder->SetTask(ToString(args["task"]));
  954. for (auto arg : args) {
  955. std::string key = py::str(arg.first);
  956. py::handle value = arg.second;
  957. if (!value.is_none()) {
  958. if (key == "num_parallel_workers") {
  959. (void)builder->SetNumWorkers(ToInt(value));
  960. } else if (key == "sampler") {
  961. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  962. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  963. (void)builder->SetSampler(std::move(sampler));
  964. } else if (key == "decode") {
  965. (void)builder->SetDecode(ToBool(value));
  966. }
  967. }
  968. }
  969. std::shared_ptr<CocoOp> op;
  970. RETURN_IF_NOT_OK(builder->Build(&op));
  971. *top = op;
  972. return Status::OK();
  973. }
  974. Status DEPipeline::ParseCifar10Op(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  975. std::shared_ptr<DatasetOp> *bottom) {
  976. // Required arguments
  977. if (args["dataset_dir"].is_none()) {
  978. std::string err_msg = "Error: No dataset path specified";
  979. RETURN_STATUS_UNEXPECTED(err_msg);
  980. }
  981. std::shared_ptr<CifarOp::Builder> builder = std::make_shared<CifarOp::Builder>();
  982. (void)builder->SetCifarDir(ToString(args["dataset_dir"]));
  983. // Optional arguments
  984. for (auto arg : args) {
  985. std::string key = py::str(arg.first);
  986. py::handle value = arg.second;
  987. if (!value.is_none()) {
  988. if (key == "num_parallel_workers") {
  989. (void)builder->SetNumWorkers(ToInt(value));
  990. } else if (key == "sampler") {
  991. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  992. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  993. (void)builder->SetSampler(std::move(sampler));
  994. }
  995. }
  996. }
  997. (void)builder->SetCifarType(true);
  998. std::shared_ptr<CifarOp> op;
  999. RETURN_IF_NOT_OK(builder->Build(&op));
  1000. *top = op;
  1001. return Status::OK();
  1002. }
  1003. Status DEPipeline::ParseCifar100Op(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1004. std::shared_ptr<DatasetOp> *bottom) {
  1005. // Required arguments
  1006. if (args["dataset_dir"].is_none()) {
  1007. std::string err_msg = "Error: No dataset path specified";
  1008. RETURN_STATUS_UNEXPECTED(err_msg);
  1009. }
  1010. std::shared_ptr<CifarOp::Builder> builder = std::make_shared<CifarOp::Builder>();
  1011. (void)builder->SetCifarDir(ToString(args["dataset_dir"]));
  1012. // Optional arguments
  1013. for (auto arg : args) {
  1014. std::string key = py::str(arg.first);
  1015. py::handle value = arg.second;
  1016. if (!value.is_none()) {
  1017. if (key == "num_parallel_workers") {
  1018. (void)builder->SetNumWorkers(ToInt(value));
  1019. } else if (key == "sampler") {
  1020. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  1021. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  1022. (void)builder->SetSampler(std::move(sampler));
  1023. }
  1024. }
  1025. }
  1026. (void)builder->SetCifarType(false);
  1027. std::shared_ptr<CifarOp> op;
  1028. RETURN_IF_NOT_OK(builder->Build(&op));
  1029. *top = op;
  1030. return Status::OK();
  1031. }
  1032. Status DEPipeline::ParseRandomDataOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1033. std::shared_ptr<DatasetOp> *bottom) {
  1034. // Required arguments
  1035. RandomDataOp::Builder builder;
  1036. if (args["num_samples"].is_none()) {
  1037. std::string err_msg = "Error: num_samples is a required argument";
  1038. RETURN_STATUS_UNEXPECTED(err_msg);
  1039. }
  1040. std::vector<std::string> columns_to_load;
  1041. bool schema_exists = false;
  1042. // Optional arguments
  1043. for (auto arg : args) {
  1044. std::string key = py::str(arg.first);
  1045. py::handle value = arg.second;
  1046. if (key == "num_parallel_workers") {
  1047. (void)builder.SetNumWorkers(ToInt(value));
  1048. } else if (key == "schema_file_path" || key == "schema_json_string") {
  1049. schema_exists = true;
  1050. } else if (key == "columns_list") {
  1051. columns_to_load = ToStringVector(value);
  1052. } else if (key == "num_samples") {
  1053. // This is not sampling here. The random data op needs to know how much data to
  1054. // generate. It does not currently support sampling.
  1055. (void)builder.SetTotalRows(ToInt(value));
  1056. }
  1057. }
  1058. if (schema_exists) {
  1059. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  1060. if (args.contains("schema_file_path")) {
  1061. RETURN_IF_NOT_OK(schema->LoadSchemaFile(ToString(args["schema_file_path"]), columns_to_load));
  1062. } else {
  1063. RETURN_IF_NOT_OK(schema->LoadSchemaString(ToString(args["schema_json_string"]), columns_to_load));
  1064. }
  1065. (void)builder.SetDataSchema(std::move(schema));
  1066. }
  1067. std::shared_ptr<RandomDataOp> op;
  1068. RETURN_IF_NOT_OK(builder.Build(&op));
  1069. *top = op;
  1070. return Status::OK();
  1071. }
  1072. int32_t DEPipeline::GetNumClasses() const { return num_classes_; }
  1073. Status DEPipeline::ParseMnistOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1074. std::shared_ptr<DatasetOp> *bottom) {
  1075. // Required arguments
  1076. if (args["dataset_dir"].is_none()) {
  1077. std::string err_msg = "Error: No dataset path specified";
  1078. RETURN_STATUS_UNEXPECTED(err_msg);
  1079. }
  1080. std::shared_ptr<MnistOp::Builder> builder = std::make_shared<MnistOp::Builder>();
  1081. (void)builder->SetDir(ToString(args["dataset_dir"]));
  1082. // Optional arguments
  1083. for (auto arg : args) {
  1084. std::string key = py::str(arg.first);
  1085. py::handle value = arg.second;
  1086. if (!value.is_none()) {
  1087. if (key == "num_parallel_workers") {
  1088. (void)builder->SetNumWorkers(ToInt(value));
  1089. } else if (key == "sampler") {
  1090. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  1091. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  1092. (void)builder->SetSampler(std::move(sampler));
  1093. }
  1094. }
  1095. }
  1096. std::shared_ptr<MnistOp> op;
  1097. RETURN_IF_NOT_OK(builder->Build(&op));
  1098. *top = op;
  1099. return Status::OK();
  1100. }
  1101. Status DEPipeline::ParseCelebAOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1102. std::shared_ptr<DatasetOp> *bottom) {
  1103. // Required arguments
  1104. if (args["dataset_dir"].is_none()) {
  1105. std::string err_msg = "Error: No dataset path specified";
  1106. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, err_msg);
  1107. }
  1108. std::shared_ptr<CelebAOp::Builder> builder = std::make_shared<CelebAOp::Builder>();
  1109. if (builder == nullptr) {
  1110. std::string err_msg = "Create celebaop builder failed";
  1111. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, err_msg);
  1112. }
  1113. (void)builder->SetCelebADir(ToString(args["dataset_dir"]));
  1114. for (const auto &arg : args) {
  1115. std::string key = py::str(arg.first);
  1116. py::handle value = arg.second;
  1117. if (!value.is_none()) {
  1118. if (key == "num_parallel_workers") {
  1119. (void)builder->SetNumWorkers(ToInt(value));
  1120. } else if (key == "sampler") {
  1121. auto create = py::reinterpret_borrow<py::object>(value).attr("create");
  1122. std::shared_ptr<Sampler> sampler = create().cast<std::shared_ptr<Sampler>>();
  1123. (void)builder->SetSampler(std::move(sampler));
  1124. } else if (key == "decode") {
  1125. (void)builder->SetDecode(ToBool(value));
  1126. } else if (key == "extensions") {
  1127. (void)builder->SetExtensions(ToStringSet(value));
  1128. } else if (key == "dataset_type") {
  1129. (void)builder->SetDatasetType(ToString(value));
  1130. }
  1131. }
  1132. }
  1133. std::shared_ptr<CelebAOp> op;
  1134. RETURN_IF_NOT_OK(builder->Build(&op));
  1135. *top = op;
  1136. return Status::OK();
  1137. }
  1138. Status DEPipeline::ParseTextFileOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1139. std::shared_ptr<DatasetOp> *bottom) {
  1140. // Required arguments
  1141. std::vector<std::string> files_list;
  1142. std::shared_ptr<TextFileOp::Builder> builder = std::make_shared<TextFileOp::Builder>();
  1143. if (!args["dataset_files"].is_none()) {
  1144. files_list = ToStringVector(args["dataset_files"]);
  1145. (void)builder->SetTextFilesList(files_list);
  1146. } else {
  1147. RETURN_STATUS_UNEXPECTED("Error: dataset_files is missing");
  1148. }
  1149. // Optional arguments
  1150. bool shuffle_required = false;
  1151. int64_t num_devices = 0;
  1152. for (auto arg : args) {
  1153. std::string key = py::str(arg.first);
  1154. py::handle value = arg.second;
  1155. if (!value.is_none()) {
  1156. if (key == "num_parallel_workers") {
  1157. (void)builder->SetNumWorkers(ToInt(value));
  1158. } else if (key == "shuffle_files") {
  1159. (void)builder->SetShuffleFiles(ToBool(value));
  1160. } else if (key == "shuffle_global") {
  1161. shuffle_required = ToBool(value);
  1162. } else if (key == "num_samples") {
  1163. (void)builder->SetTotalRows(ToInt(value));
  1164. } else if (key == "num_shards") {
  1165. num_devices = ToInt(value);
  1166. (void)builder->SetNumDevices(num_devices);
  1167. } else if (key == "shard_id") {
  1168. (void)builder->SetDeviceId(ToInt(value));
  1169. }
  1170. }
  1171. }
  1172. std::shared_ptr<TextFileOp> txt_op;
  1173. RETURN_IF_NOT_OK(builder->Build(&txt_op));
  1174. RETURN_IF_NOT_OK(tree_->AssociateNode(txt_op));
  1175. *top = txt_op;
  1176. if (shuffle_required) {
  1177. std::shared_ptr<DatasetOp> shuffle_op = nullptr;
  1178. int64_t shuffle_size = 0;
  1179. int64_t num_rows = 0;
  1180. // First, get the number of rows in the dataset and then compute the shuffle size
  1181. RETURN_IF_NOT_OK(TextFileOp::CountAllFileRows(files_list, &num_rows));
  1182. RETURN_IF_NOT_OK(ComputeShuffleSize(files_list.size(), num_devices, num_rows, 0, &shuffle_size));
  1183. // Add the shuffle op over top of this op and return the subtree (top/bottom) to caller
  1184. RETURN_IF_NOT_OK(AddShuffleOp(shuffle_size, txt_op, &shuffle_op));
  1185. *top = shuffle_op;
  1186. *bottom = txt_op;
  1187. }
  1188. return Status::OK();
  1189. }
  1190. Status DEPipeline::ParsePadInfo(py::handle value, PadInfo *pad_info) {
  1191. for (auto p : py::reinterpret_borrow<py::dict>(value)) {
  1192. if (!p.second.is_none()) {
  1193. auto tp = py::reinterpret_borrow<py::tuple>(p.second);
  1194. CHECK_FAIL_RETURN_UNEXPECTED(tp.size() == 2, "tuple in pad_info must be (list,int) or (list,float)");
  1195. TensorShape shape = tp[0].is_none() ? TensorShape::CreateUnknownRankShape() : TensorShape(tp[0]);
  1196. std::shared_ptr<Tensor> pad_val = nullptr;
  1197. if (py::isinstance<py::str>(tp[1])) {
  1198. std::string pad_val_string = tp[1].is_none() ? "" : ToString(tp[1]);
  1199. CHECK_FAIL_RETURN_UNEXPECTED(
  1200. Tensor::CreateTensor(&pad_val, std::vector<std::string>{pad_val_string}, TensorShape::CreateScalar()),
  1201. "Cannot create pad_value Tensor");
  1202. } else {
  1203. float pad_val_float = tp[1].is_none() ? 0 : ToFloat(tp[1]);
  1204. CHECK_FAIL_RETURN_UNEXPECTED(Tensor::CreateTensor(&pad_val, TensorImpl::kFlexible, TensorShape::CreateScalar(),
  1205. DataType(DataType::DE_FLOAT32)),
  1206. "Cannot create pad_value Tensor");
  1207. pad_val->SetItemAt<float>({}, pad_val_float);
  1208. }
  1209. (void)pad_info->insert({ToString(p.first), {shape, pad_val}});
  1210. } else { // tuple is None
  1211. (void)pad_info->insert({ToString(p.first), {TensorShape({}), nullptr}});
  1212. }
  1213. }
  1214. return Status::OK();
  1215. }
  1216. Status DEPipeline::ParseBuildVocabOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1217. std::shared_ptr<DatasetOp> *bottom) {
  1218. std::shared_ptr<BuildVocabOp::Builder> builder = std::make_shared<BuildVocabOp::Builder>();
  1219. for (auto arg : args) {
  1220. std::string key = py::str(arg.first);
  1221. py::handle value = arg.second;
  1222. if (!value.is_none()) {
  1223. if (key == "freq_range") {
  1224. py::tuple tp = py::reinterpret_borrow<py::tuple>(value);
  1225. if (!tp[0].is_none()) (void)builder->SetMinFreq(py::reinterpret_borrow<py::int_>(tp[0]));
  1226. if (!tp[1].is_none()) (void)builder->SetMaxFreq(py::reinterpret_borrow<py::int_>(tp[1]));
  1227. } else if (key == "top_k") {
  1228. builder->SetTopK(py::reinterpret_borrow<py::int_>(value));
  1229. } else if (key == "columns") {
  1230. (void)builder->SetColumnNames(ToStringVector(value));
  1231. } else if (key == "vocab") {
  1232. (void)builder->SetVocab(value.cast<std::shared_ptr<Vocab>>());
  1233. } else if (key == "num_parallel_workers") {
  1234. (void)builder->SetNumWorkers(ToInt(value));
  1235. } else if (key == "special_first") {
  1236. (void)builder->SetSpecialFirst(ToBool(value));
  1237. } else if (key == "special_tokens") {
  1238. (void)builder->SetSpecialTokens(ToStringVector(value));
  1239. }
  1240. }
  1241. }
  1242. std::shared_ptr<BuildVocabOp> op;
  1243. RETURN_IF_NOT_OK(builder->Build(&op));
  1244. *top = op;
  1245. return Status::OK();
  1246. }
  1247. Status DEPipeline::ParseClueOp(const py::dict &args, std::shared_ptr<DatasetOp> *top,
  1248. std::shared_ptr<DatasetOp> *bottom) {
  1249. std::vector<std::string> files_list;
  1250. std::shared_ptr<ClueOp::Builder> builder = std::make_shared<ClueOp::Builder>();
  1251. if (!args["dataset_files"].is_none()) {
  1252. files_list = ToStringVector(args["dataset_files"]);
  1253. (void)builder->SetClueFilesList(files_list);
  1254. } else {
  1255. RETURN_STATUS_UNEXPECTED("Error: dataset_files is missing");
  1256. }
  1257. // Optional arguments
  1258. bool shuffle_required = false;
  1259. int64_t num_devices = 0;
  1260. for (auto arg : args) {
  1261. std::string key = py::str(arg.first);
  1262. py::handle value = arg.second;
  1263. if (!value.is_none()) {
  1264. if (key == "num_parallel_workers") {
  1265. (void)builder->SetNumWorkers(ToInt(value));
  1266. } else if (key == "shuffle_files") {
  1267. (void)builder->SetShuffleFiles(ToBool(value));
  1268. } else if (key == "shuffle_global") {
  1269. shuffle_required = ToBool(value);
  1270. } else if (key == "num_samples") {
  1271. (void)builder->SetNumSamples(ToInt(value));
  1272. } else if (key == "num_shards") {
  1273. num_devices = ToInt(value);
  1274. (void)builder->SetNumDevices(num_devices);
  1275. } else if (key == "shard_id") {
  1276. (void)builder->SetDeviceId(ToInt(value));
  1277. } else if (key == "cols_to_keyword") {
  1278. std::map<std::string, std::string> map_dict;
  1279. for (auto p : py::reinterpret_borrow<py::dict>(value)) {
  1280. if (!p.second.is_none()) {
  1281. map_dict.insert({ToString(p.first), ToString(p.second)});
  1282. } else {
  1283. map_dict.insert({ToString(p.first), ToString(p.first)});
  1284. }
  1285. }
  1286. (void)builder->SetColsKeyMap(map_dict);
  1287. }
  1288. }
  1289. }
  1290. std::shared_ptr<ClueOp> clue_op;
  1291. RETURN_IF_NOT_OK(builder->Build(&clue_op));
  1292. RETURN_IF_NOT_OK(tree_->AssociateNode(clue_op));
  1293. *top = clue_op;
  1294. if (shuffle_required) {
  1295. std::shared_ptr<DatasetOp> shuffle_op = nullptr;
  1296. int64_t shuffle_size = 0;
  1297. int64_t num_rows = 0;
  1298. // First, get the number of rows in the dataset and then compute the shuffle size
  1299. RETURN_IF_NOT_OK(ClueOp::CountAllFileRows(files_list, &num_rows));
  1300. RETURN_IF_NOT_OK(ComputeShuffleSize(files_list.size(), num_devices, num_rows, 0, &shuffle_size));
  1301. // Add the shuffle op over top of this op and return the subtree (top/bottom) to caller
  1302. RETURN_IF_NOT_OK(AddShuffleOp(shuffle_size, clue_op, &shuffle_op));
  1303. *top = shuffle_op;
  1304. *bottom = clue_op;
  1305. }
  1306. return Status::OK();
  1307. }
  1308. // Helper function to inject a shuffle operator over top of the current operation being built.
  1309. Status DEPipeline::AddShuffleOp(int64_t shuffle_size, std::shared_ptr<DatasetOp> input_op,
  1310. std::shared_ptr<DatasetOp> *shuffle_op) {
  1311. std::shared_ptr<ShuffleOp> new_shuffle_op = nullptr;
  1312. ShuffleOp::Builder shuffle_builder;
  1313. (void)shuffle_builder.SetShuffleSize(shuffle_size);
  1314. RETURN_IF_NOT_OK(shuffle_builder.Build(&new_shuffle_op));
  1315. RETURN_IF_NOT_OK(tree_->AssociateNode(new_shuffle_op));
  1316. RETURN_IF_NOT_OK(new_shuffle_op->AddChild(input_op));
  1317. // We have now created:
  1318. //
  1319. // ShuffleOp
  1320. // |
  1321. // input_op
  1322. //
  1323. *shuffle_op = new_shuffle_op;
  1324. return Status::OK();
  1325. }
  1326. // Common code for computing a default shuffle size
  1327. Status DEPipeline::ComputeShuffleSize(int64_t num_files, int64_t num_devices, int64_t num_rows, int64_t total_rows,
  1328. int64_t *shuffle_size) {
  1329. const int64_t average_files_multiplier = 4;
  1330. const int64_t shuffle_max = 10000;
  1331. int64_t avg_rows_per_file = 0;
  1332. // Adjust the num rows per shard if sharding was given
  1333. if (num_devices > 0) {
  1334. if (num_rows % num_devices == 0) {
  1335. num_rows = num_rows / num_devices;
  1336. } else {
  1337. num_rows = (num_rows / num_devices) + 1;
  1338. }
  1339. }
  1340. // Cap based on total rows directive. Some ops do not have this and give value of 0.
  1341. if (total_rows > 0) {
  1342. num_rows = std::min(num_rows, total_rows);
  1343. }
  1344. // get the average per file
  1345. avg_rows_per_file = num_rows / num_files;
  1346. *shuffle_size = std::max(avg_rows_per_file * average_files_multiplier, shuffle_max);
  1347. return Status::OK();
  1348. }
  1349. } // namespace dataset
  1350. } // namespace mindspore