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.

datasets.cc 69 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  1. /**
  2. * Copyright 2020 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 <fstream>
  17. #include "minddata/dataset/include/datasets.h"
  18. #include "minddata/dataset/include/samplers.h"
  19. #include "minddata/dataset/include/transforms.h"
  20. #include "minddata/dataset/engine/dataset_iterator.h"
  21. // Source dataset headers (in alphabetical order)
  22. #include "minddata/dataset/engine/datasetops/source/album_op.h"
  23. #include "minddata/dataset/engine/datasetops/source/celeba_op.h"
  24. #include "minddata/dataset/engine/datasetops/source/cifar_op.h"
  25. #include "minddata/dataset/engine/datasetops/source/clue_op.h"
  26. #include "minddata/dataset/engine/datasetops/source/coco_op.h"
  27. #include "minddata/dataset/engine/datasetops/source/csv_op.h"
  28. #include "minddata/dataset/engine/datasetops/source/image_folder_op.h"
  29. #include "minddata/dataset/engine/datasetops/source/manifest_op.h"
  30. #include "minddata/dataset/engine/datasetops/source/mnist_op.h"
  31. #include "minddata/dataset/engine/datasetops/source/random_data_op.h"
  32. #include "minddata/dataset/engine/datasetops/source/text_file_op.h"
  33. #include "minddata/dataset/engine/datasetops/source/voc_op.h"
  34. // Dataset operator headers (in alphabetical order)
  35. #include "minddata/dataset/engine/datasetops/batch_op.h"
  36. #include "minddata/dataset/engine/datasetops/build_vocab_op.h"
  37. #include "minddata/dataset/engine/datasetops/concat_op.h"
  38. #include "minddata/dataset/engine/datasetops/map_op/map_op.h"
  39. #include "minddata/dataset/engine/datasetops/project_op.h"
  40. #include "minddata/dataset/engine/datasetops/rename_op.h"
  41. #include "minddata/dataset/engine/datasetops/repeat_op.h"
  42. #include "minddata/dataset/engine/datasetops/shuffle_op.h"
  43. #include "minddata/dataset/engine/datasetops/skip_op.h"
  44. #include "minddata/dataset/engine/datasetops/take_op.h"
  45. #include "minddata/dataset/engine/datasetops/zip_op.h"
  46. // Sampler headers (in alphabetical order)
  47. #include "minddata/dataset/engine/datasetops/source/sampler/sampler.h"
  48. #include "minddata/dataset/engine/datasetops/source/sampler/random_sampler.h"
  49. #include "minddata/dataset/engine/datasetops/source/sampler/sequential_sampler.h"
  50. #include "minddata/dataset/core/config_manager.h"
  51. #include "minddata/dataset/util/random.h"
  52. #include "minddata/dataset/util/path.h"
  53. namespace mindspore {
  54. namespace dataset {
  55. namespace api {
  56. #define RETURN_EMPTY_IF_ERROR(_s) \
  57. do { \
  58. Status __rc = (_s); \
  59. if (__rc.IsError()) { \
  60. MS_LOG(ERROR) << __rc; \
  61. return {}; \
  62. } \
  63. } while (false)
  64. // Function to create the iterator, which will build and launch the execution tree.
  65. std::shared_ptr<Iterator> Dataset::CreateIterator(std::vector<std::string> columns) {
  66. std::shared_ptr<Iterator> iter;
  67. try {
  68. auto ds = shared_from_this();
  69. // The specified columns will be selected from the dataset and passed down the pipeline
  70. // in the order specified, other columns will be discarded.
  71. if (!columns.empty()) {
  72. ds = ds->Project(columns);
  73. }
  74. iter = std::make_shared<Iterator>();
  75. Status rc = iter->BuildAndLaunchTree(ds);
  76. if (rc.IsError()) {
  77. MS_LOG(ERROR) << "CreateIterator failed." << rc;
  78. return nullptr;
  79. }
  80. return iter;
  81. } catch (const std::exception &err) {
  82. MS_LOG(ERROR) << "CreateIterator: Iterator exception caught: " << err.what();
  83. return nullptr;
  84. }
  85. return iter;
  86. }
  87. // Constructor
  88. Dataset::Dataset() {
  89. // Fetch some default value from config manager
  90. std::shared_ptr<ConfigManager> cfg = GlobalContext::config_manager();
  91. num_workers_ = cfg->num_parallel_workers();
  92. rows_per_buffer_ = cfg->rows_per_buffer();
  93. connector_que_size_ = cfg->op_connector_size();
  94. worker_connector_size_ = cfg->worker_connector_size();
  95. }
  96. /// \brief Function to create a SchemaObj
  97. /// \param[in] schema_file Path of schema file
  98. /// \return Shared pointer to the current schema
  99. std::shared_ptr<SchemaObj> Schema(const std::string &schema_file) {
  100. auto schema = std::make_shared<SchemaObj>(schema_file);
  101. return schema->init() ? schema : nullptr;
  102. }
  103. // FUNCTIONS TO CREATE DATASETS FOR LEAF-NODE DATASETS
  104. // (In alphabetical order)
  105. // Function to create a AlbumDataset.
  106. std::shared_ptr<AlbumDataset> Album(const std::string &dataset_dir, const std::string &data_schema,
  107. const std::vector<std::string> &column_names, bool decode,
  108. const std::shared_ptr<SamplerObj> &sampler) {
  109. auto ds = std::make_shared<AlbumDataset>(dataset_dir, data_schema, column_names, decode, sampler);
  110. return ds->ValidateParams() ? ds : nullptr;
  111. }
  112. // Function to create a CelebADataset.
  113. std::shared_ptr<CelebADataset> CelebA(const std::string &dataset_dir, const std::string &dataset_type,
  114. const std::shared_ptr<SamplerObj> &sampler, bool decode,
  115. const std::set<std::string> &extensions) {
  116. auto ds = std::make_shared<CelebADataset>(dataset_dir, dataset_type, sampler, decode, extensions);
  117. // Call derived class validation method.
  118. return ds->ValidateParams() ? ds : nullptr;
  119. }
  120. // Function to create a Cifar10Dataset.
  121. std::shared_ptr<Cifar10Dataset> Cifar10(const std::string &dataset_dir, const std::shared_ptr<SamplerObj> &sampler) {
  122. auto ds = std::make_shared<Cifar10Dataset>(dataset_dir, sampler);
  123. // Call derived class validation method.
  124. return ds->ValidateParams() ? ds : nullptr;
  125. }
  126. // Function to create a Cifar100Dataset.
  127. std::shared_ptr<Cifar100Dataset> Cifar100(const std::string &dataset_dir, const std::shared_ptr<SamplerObj> &sampler) {
  128. auto ds = std::make_shared<Cifar100Dataset>(dataset_dir, sampler);
  129. // Call derived class validation method.
  130. return ds->ValidateParams() ? ds : nullptr;
  131. }
  132. // Function to create a CLUEDataset.
  133. std::shared_ptr<CLUEDataset> CLUE(const std::vector<std::string> &clue_files, const std::string &task,
  134. const std::string &usage, int64_t num_samples, ShuffleMode shuffle,
  135. int32_t num_shards, int32_t shard_id) {
  136. auto ds = std::make_shared<CLUEDataset>(clue_files, task, usage, num_samples, shuffle, num_shards, shard_id);
  137. // Call derived class validation method.
  138. return ds->ValidateParams() ? ds : nullptr;
  139. }
  140. // Function to create a CocoDataset.
  141. std::shared_ptr<CocoDataset> Coco(const std::string &dataset_dir, const std::string &annotation_file,
  142. const std::string &task, const bool &decode,
  143. const std::shared_ptr<SamplerObj> &sampler) {
  144. auto ds = std::make_shared<CocoDataset>(dataset_dir, annotation_file, task, decode, sampler);
  145. // Call derived class validation method.
  146. return ds->ValidateParams() ? ds : nullptr;
  147. }
  148. // Function to create a CSVDataset.
  149. std::shared_ptr<CSVDataset> CSV(const std::vector<std::string> &dataset_files, char field_delim,
  150. const std::vector<std::shared_ptr<CsvBase>> &column_defaults,
  151. const std::vector<std::string> &column_names, int64_t num_samples, ShuffleMode shuffle,
  152. int32_t num_shards, int32_t shard_id) {
  153. auto ds = std::make_shared<CSVDataset>(dataset_files, field_delim, column_defaults, column_names, num_samples,
  154. shuffle, num_shards, shard_id);
  155. // Call derived class validation method.
  156. return ds->ValidateParams() ? ds : nullptr;
  157. }
  158. // Function to create a ImageFolderDataset.
  159. std::shared_ptr<ImageFolderDataset> ImageFolder(const std::string &dataset_dir, bool decode,
  160. const std::shared_ptr<SamplerObj> &sampler,
  161. const std::set<std::string> &extensions,
  162. const std::map<std::string, int32_t> &class_indexing) {
  163. // This arg exists in ImageFolderOp, but not externalized (in Python API). The default value is false.
  164. bool recursive = false;
  165. // Create logical representation of ImageFolderDataset.
  166. auto ds = std::make_shared<ImageFolderDataset>(dataset_dir, decode, sampler, recursive, extensions, class_indexing);
  167. // Call derived class validation method.
  168. return ds->ValidateParams() ? ds : nullptr;
  169. }
  170. // Function to create a ManifestDataset.
  171. std::shared_ptr<ManifestDataset> Manifest(std::string dataset_file, std::string usage,
  172. std::shared_ptr<SamplerObj> sampler,
  173. const std::map<std::string, int32_t> &class_indexing, bool decode) {
  174. auto ds = std::make_shared<ManifestDataset>(dataset_file, usage, sampler, class_indexing, decode);
  175. // Call derived class validation method.
  176. return ds->ValidateParams() ? ds : nullptr;
  177. }
  178. // Function to create a MnistDataset.
  179. std::shared_ptr<MnistDataset> Mnist(const std::string &dataset_dir, const std::shared_ptr<SamplerObj> &sampler) {
  180. auto ds = std::make_shared<MnistDataset>(dataset_dir, sampler);
  181. // Call derived class validation method.
  182. return ds->ValidateParams() ? ds : nullptr;
  183. }
  184. // Function to overload "+" operator to concat two datasets
  185. std::shared_ptr<ConcatDataset> operator+(const std::shared_ptr<Dataset> &datasets1,
  186. const std::shared_ptr<Dataset> &datasets2) {
  187. std::shared_ptr<ConcatDataset> ds = std::make_shared<ConcatDataset>(std::vector({datasets2, datasets1}));
  188. // Call derived class validation method.
  189. return ds->ValidateParams() ? ds : nullptr;
  190. }
  191. // Function to create a TextFileDataset.
  192. std::shared_ptr<TextFileDataset> TextFile(const std::vector<std::string> &dataset_files, int64_t num_samples,
  193. ShuffleMode shuffle, int32_t num_shards, int32_t shard_id) {
  194. auto ds = std::make_shared<TextFileDataset>(dataset_files, num_samples, shuffle, num_shards, shard_id);
  195. // Call derived class validation method.
  196. return ds->ValidateParams() ? ds : nullptr;
  197. }
  198. // Function to create a VOCDataset.
  199. std::shared_ptr<VOCDataset> VOC(const std::string &dataset_dir, const std::string &task, const std::string &mode,
  200. const std::map<std::string, int32_t> &class_indexing, bool decode,
  201. const std::shared_ptr<SamplerObj> &sampler) {
  202. auto ds = std::make_shared<VOCDataset>(dataset_dir, task, mode, class_indexing, decode, sampler);
  203. // Call derived class validation method.
  204. return ds->ValidateParams() ? ds : nullptr;
  205. }
  206. // Function to create a ZipDataset.
  207. std::shared_ptr<ZipDataset> Zip(const std::vector<std::shared_ptr<Dataset>> &datasets) {
  208. auto ds = std::make_shared<ZipDataset>(datasets);
  209. // Call derived class validation method.
  210. return ds->ValidateParams() ? ds : nullptr;
  211. }
  212. // FUNCTIONS TO CREATE DATASETS FOR DATASET OPS
  213. // (In alphabetical order)
  214. // Function to create a Batch dataset
  215. std::shared_ptr<BatchDataset> Dataset::Batch(int32_t batch_size, bool drop_remainder) {
  216. // Default values
  217. std::vector<std::string> cols_to_map = {};
  218. std::map<std::string, std::pair<TensorShape, std::shared_ptr<Tensor>>> pad_map;
  219. bool pad = false;
  220. auto ds = std::make_shared<BatchDataset>(batch_size, drop_remainder, pad, cols_to_map, pad_map);
  221. if (!ds->ValidateParams()) {
  222. return nullptr;
  223. }
  224. ds->children.push_back(shared_from_this());
  225. return ds;
  226. }
  227. // Function to create a Vocab from dataset
  228. std::shared_ptr<Vocab> Dataset::BuildVocab(const std::vector<std::string> &columns,
  229. const std::pair<int64_t, int64_t> &freq_range, int64_t top_k,
  230. const std::vector<std::string> &special_tokens, bool special_first) {
  231. auto vocab = std::make_shared<Vocab>();
  232. auto ds = std::make_shared<BuildVocabDataset>(vocab, columns, freq_range, top_k, special_tokens, special_first);
  233. if (!ds->ValidateParams()) {
  234. return nullptr;
  235. }
  236. ds->children.push_back(shared_from_this());
  237. // Run tree here to starting building vocab
  238. std::shared_ptr<Iterator> iter = ds->CreateIterator();
  239. if (iter == nullptr) {
  240. MS_LOG(ERROR) << "Fail to run iterator in BuildVocab.";
  241. return nullptr;
  242. }
  243. // Finish building vocab by triggering GetNextRow
  244. std::unordered_map<std::string, std::shared_ptr<Tensor>> row;
  245. iter->GetNextRow(&row);
  246. if (vocab == nullptr) {
  247. MS_LOG(ERROR) << "Fail to build vocab.";
  248. return nullptr;
  249. }
  250. return vocab;
  251. }
  252. // Function to create a Concat dataset
  253. std::shared_ptr<ConcatDataset> Dataset::Concat(const std::vector<std::shared_ptr<Dataset>> &datasets) {
  254. auto ds = std::make_shared<ConcatDataset>(datasets);
  255. ds->children.push_back(shared_from_this());
  256. return ds->ValidateParams() ? ds : nullptr;
  257. }
  258. // Function to create a Map dataset.
  259. std::shared_ptr<MapDataset> Dataset::Map(std::vector<std::shared_ptr<TensorOperation>> operations,
  260. std::vector<std::string> input_columns,
  261. std::vector<std::string> output_columns,
  262. const std::vector<std::string> &project_columns) {
  263. auto ds = std::make_shared<MapDataset>(operations, input_columns, output_columns, project_columns);
  264. if (!ds->ValidateParams()) {
  265. return nullptr;
  266. }
  267. ds->children.push_back(shared_from_this());
  268. return ds;
  269. }
  270. // Function to create a ProjectDataset.
  271. std::shared_ptr<ProjectDataset> Dataset::Project(const std::vector<std::string> &columns) {
  272. auto ds = std::make_shared<ProjectDataset>(columns);
  273. // Call derived class validation method.
  274. if (!ds->ValidateParams()) {
  275. return nullptr;
  276. }
  277. ds->children.push_back(shared_from_this());
  278. return ds;
  279. }
  280. // Function to create a RenameDataset.
  281. std::shared_ptr<RenameDataset> Dataset::Rename(const std::vector<std::string> &input_columns,
  282. const std::vector<std::string> &output_columns) {
  283. auto ds = std::make_shared<RenameDataset>(input_columns, output_columns);
  284. // Call derived class validation method.
  285. if (!ds->ValidateParams()) {
  286. return nullptr;
  287. }
  288. ds->children.push_back(shared_from_this());
  289. return ds;
  290. }
  291. // Function to create Repeat dataset.
  292. std::shared_ptr<Dataset> Dataset::Repeat(int32_t count) {
  293. // Workaround for repeat == 1, do not inject repeat.
  294. if (count == 1) {
  295. return shared_from_this();
  296. }
  297. auto ds = std::make_shared<RepeatDataset>(count);
  298. if (!ds->ValidateParams()) {
  299. return nullptr;
  300. }
  301. ds->children.push_back(shared_from_this());
  302. return ds;
  303. }
  304. // Function to create a ShuffleOp
  305. std::shared_ptr<ShuffleDataset> Dataset::Shuffle(int32_t buffer_size) {
  306. // Pass in reshuffle_each_epoch with true
  307. auto ds = std::make_shared<ShuffleDataset>(buffer_size, true);
  308. if (!ds->ValidateParams()) {
  309. return nullptr;
  310. }
  311. ds->children.push_back(shared_from_this());
  312. return ds;
  313. }
  314. // Function to create a SkipDataset.
  315. std::shared_ptr<SkipDataset> Dataset::Skip(int32_t count) {
  316. auto ds = std::make_shared<SkipDataset>(count);
  317. // Call derived class validation method.
  318. if (!ds->ValidateParams()) {
  319. return nullptr;
  320. }
  321. ds->children.push_back(shared_from_this());
  322. return ds;
  323. }
  324. // Function to create a TakeDataset.
  325. std::shared_ptr<Dataset> Dataset::Take(int32_t count) {
  326. // If count is greater than the number of element in dataset or equal to -1,
  327. // all the element in dataset will be taken
  328. if (count == -1) {
  329. return shared_from_this();
  330. }
  331. auto ds = std::make_shared<TakeDataset>(count);
  332. // Call derived class validation method.
  333. if (!ds->ValidateParams()) {
  334. return nullptr;
  335. }
  336. ds->children.push_back(shared_from_this());
  337. return ds;
  338. }
  339. // Function to create a Zip dataset
  340. std::shared_ptr<ZipDataset> Dataset::Zip(const std::vector<std::shared_ptr<Dataset>> &datasets) {
  341. // Default values
  342. auto ds = std::make_shared<ZipDataset>(datasets);
  343. ds->children.push_back(shared_from_this());
  344. return ds->ValidateParams() ? ds : nullptr;
  345. }
  346. SchemaObj::SchemaObj(const std::string &schema_file) : schema_file_(schema_file), num_rows_(0), dataset_type_("") {}
  347. // SchemaObj init function
  348. bool SchemaObj::init() {
  349. if (schema_file_ != "") {
  350. Path schema_file(schema_file_);
  351. if (!schema_file.Exists()) {
  352. MS_LOG(ERROR) << "The file " << schema_file << " does not exist or permission denied!";
  353. return false;
  354. }
  355. nlohmann::json js;
  356. try {
  357. std::ifstream in(schema_file_);
  358. in >> js;
  359. } catch (const std::exception &err) {
  360. MS_LOG(ERROR) << "Schema file failed to load";
  361. return false;
  362. }
  363. return from_json(js);
  364. }
  365. return true;
  366. }
  367. // Function to add a column to schema with a mstype de_type
  368. bool SchemaObj::add_column(std::string name, TypeId de_type, std::vector<int32_t> shape) {
  369. nlohmann::json new_column;
  370. new_column["name"] = name;
  371. // if de_type is mstype
  372. DataType data_type = dataset::MSTypeToDEType(de_type);
  373. new_column["type"] = data_type.ToString();
  374. if (shape.size() > 0) {
  375. new_column["shape"] = shape;
  376. new_column["rank"] = shape.size();
  377. } else {
  378. new_column["rank"] = 1;
  379. }
  380. columns_.push_back(new_column);
  381. return true;
  382. }
  383. // Function to add a column to schema with a string de_type
  384. bool SchemaObj::add_column(std::string name, std::string de_type, std::vector<int32_t> shape) {
  385. nlohmann::json new_column;
  386. new_column["name"] = name;
  387. DataType data_type(de_type);
  388. new_column["type"] = data_type.ToString();
  389. if (shape.size() > 0) {
  390. new_column["shape"] = shape;
  391. new_column["rank"] = shape.size();
  392. } else {
  393. new_column["rank"] = 1;
  394. }
  395. columns_.push_back(new_column);
  396. return true;
  397. }
  398. std::string SchemaObj::to_json() {
  399. nlohmann::json json_file;
  400. json_file["columns"] = columns_;
  401. if (dataset_type_ != "") {
  402. json_file["datasetType"] = dataset_type_;
  403. }
  404. if (num_rows_ > 0) {
  405. json_file["numRows"] = num_rows_;
  406. }
  407. return json_file.dump(2);
  408. }
  409. bool SchemaObj::parse_column(nlohmann::json columns) {
  410. std::string name, de_type;
  411. std::vector<int32_t> shape;
  412. columns_.clear();
  413. if (columns.type() == nlohmann::json::value_t::array) {
  414. // reference to python list
  415. for (auto column : columns) {
  416. auto key_name = column.find("name");
  417. if (key_name == column.end()) {
  418. MS_LOG(ERROR) << "Column's name is missing";
  419. return false;
  420. }
  421. name = *key_name;
  422. auto key_type = column.find("type");
  423. if (key_type == column.end()) {
  424. MS_LOG(ERROR) << "Column's type is missing";
  425. return false;
  426. }
  427. de_type = *key_type;
  428. shape.clear();
  429. auto key_shape = column.find("shape");
  430. if (key_shape != column.end()) {
  431. shape.insert(shape.end(), (*key_shape).begin(), (*key_shape).end());
  432. }
  433. if (!add_column(name, de_type, shape)) {
  434. return false;
  435. }
  436. }
  437. } else if (columns.type() == nlohmann::json::value_t::object) {
  438. for (const auto &it_child : columns.items()) {
  439. name = it_child.key();
  440. auto key_type = it_child.value().find("type");
  441. if (key_type == it_child.value().end()) {
  442. MS_LOG(ERROR) << "Column's type is missing";
  443. return false;
  444. }
  445. de_type = *key_type;
  446. shape.clear();
  447. auto key_shape = it_child.value().find("shape");
  448. if (key_shape != it_child.value().end()) {
  449. shape.insert(shape.end(), (*key_shape).begin(), (*key_shape).end());
  450. }
  451. if (!add_column(name, de_type, shape)) {
  452. return false;
  453. }
  454. }
  455. } else {
  456. MS_LOG(ERROR) << "columns must be dict or list, columns contain name, type, shape(optional).";
  457. return false;
  458. }
  459. return true;
  460. }
  461. bool SchemaObj::from_json(nlohmann::json json_obj) {
  462. for (const auto &it_child : json_obj.items()) {
  463. if (it_child.key() == "datasetType") {
  464. dataset_type_ = it_child.value();
  465. } else if (it_child.key() == "numRows") {
  466. num_rows_ = it_child.value();
  467. } else if (it_child.key() == "columns") {
  468. if (!parse_column(it_child.value())) {
  469. MS_LOG(ERROR) << "parse columns failed";
  470. return false;
  471. }
  472. } else {
  473. MS_LOG(ERROR) << "Unknown field " << it_child.key();
  474. return false;
  475. }
  476. }
  477. if (columns_.empty()) {
  478. MS_LOG(ERROR) << "Columns are missing.";
  479. return false;
  480. }
  481. if (num_rows_ <= 0) {
  482. MS_LOG(ERROR) << "numRows must be greater than 0";
  483. return false;
  484. }
  485. return true;
  486. }
  487. // OTHER FUNCTIONS
  488. // Helper function to create default RandomSampler.
  489. std::shared_ptr<SamplerObj> CreateDefaultSampler() {
  490. const int32_t num_samples = 0; // 0 means to sample all ids.
  491. bool replacement = false;
  492. return std::make_shared<RandomSamplerObj>(replacement, num_samples);
  493. }
  494. // Helper function to compute a default shuffle size
  495. Status ComputeShuffleSize(int64_t num_files, int64_t num_devices, int64_t num_rows, int64_t total_rows,
  496. int64_t *shuffle_size) {
  497. const int64_t average_files_multiplier = 4;
  498. const int64_t shuffle_max = 10000;
  499. int64_t avg_rows_per_file = 0;
  500. // Adjust the num rows per shard if sharding was given
  501. if (num_devices > 0) {
  502. if (num_rows % num_devices == 0) {
  503. num_rows = num_rows / num_devices;
  504. } else {
  505. num_rows = (num_rows / num_devices) + 1;
  506. }
  507. }
  508. // Cap based on total rows directive. Some ops do not have this and give value of 0.
  509. if (total_rows > 0) {
  510. num_rows = std::min(num_rows, total_rows);
  511. }
  512. // get the average per file
  513. CHECK_FAIL_RETURN_UNEXPECTED(num_files != 0, "The size of dataset_files must greater than 0.");
  514. avg_rows_per_file = num_rows / num_files;
  515. *shuffle_size = std::max(avg_rows_per_file * average_files_multiplier, shuffle_max);
  516. return Status::OK();
  517. }
  518. // Helper function to inject a shuffle operator over top of current operator being built
  519. Status AddShuffleOp(int64_t num_files, int64_t num_devices, int64_t num_rows, int64_t total_rows,
  520. int32_t connector_que_size, int32_t rows_per_buffer, std::shared_ptr<DatasetOp> *shuffle_op) {
  521. std::shared_ptr<ShuffleOp> new_shuffle_op = nullptr;
  522. int64_t shuffle_size = 0;
  523. RETURN_EMPTY_IF_ERROR(ComputeShuffleSize(num_files, num_devices, num_rows, total_rows, &shuffle_size));
  524. MS_LOG(INFO) << "Dataset::AddShuffleOp - num_rows: " << num_rows << ", shuffle_size: " << shuffle_size;
  525. // Add the shuffle op
  526. *shuffle_op = std::make_shared<ShuffleOp>(shuffle_size, GetSeed(), connector_que_size, true, rows_per_buffer);
  527. return Status::OK();
  528. }
  529. // Helper function to validate dataset directory parameter
  530. bool ValidateDatasetDirParam(const std::string &dataset_name, std::string dataset_dir) {
  531. if (dataset_dir.empty()) {
  532. MS_LOG(ERROR) << dataset_name << ": dataset_dir is not specified.";
  533. return false;
  534. }
  535. Path dir(dataset_dir);
  536. if (!dir.IsDirectory()) {
  537. MS_LOG(ERROR) << dataset_name << ": dataset_dir: [" << dataset_dir << "] is an invalid directory path.";
  538. return false;
  539. }
  540. if (access(dataset_dir.c_str(), R_OK) == -1) {
  541. MS_LOG(ERROR) << dataset_name << ": No access to specified dataset path: " << dataset_dir;
  542. return false;
  543. }
  544. return true;
  545. }
  546. // Helper function to validate dataset dataset files parameter
  547. bool ValidateDatasetFilesParam(const std::string &dataset_name, const std::vector<std::string> &dataset_files) {
  548. if (dataset_files.empty()) {
  549. MS_LOG(ERROR) << dataset_name << ": dataset_files is not specified.";
  550. return false;
  551. }
  552. for (auto f : dataset_files) {
  553. Path dataset_file(f);
  554. if (!dataset_file.Exists()) {
  555. MS_LOG(ERROR) << dataset_name << ": dataset file: [" << f << "] is invalid or does not exist.";
  556. return false;
  557. }
  558. }
  559. return true;
  560. }
  561. // Helper function to validate dataset num_shards and shard_id parameters
  562. bool ValidateDatasetShardParams(const std::string &dataset_name, int32_t num_shards, int32_t shard_id) {
  563. if (num_shards <= 0) {
  564. MS_LOG(ERROR) << dataset_name << ": Invalid num_shards: " << num_shards;
  565. return false;
  566. }
  567. if (shard_id < 0 || shard_id >= num_shards) {
  568. MS_LOG(ERROR) << dataset_name << ": Invalid input, shard_id: " << shard_id << ", num_shards: " << num_shards;
  569. return false;
  570. }
  571. return true;
  572. }
  573. /* ####################################### Derived Dataset classes ################################# */
  574. // DERIVED DATASET CLASSES LEAF-NODE DATASETS
  575. // (In alphabetical order)
  576. // Constructor for AlbumDataset
  577. AlbumDataset::AlbumDataset(const std::string &dataset_dir, const std::string &data_schema,
  578. const std::vector<std::string> &column_names, bool decode,
  579. const std::shared_ptr<SamplerObj> &sampler)
  580. : dataset_dir_(dataset_dir),
  581. schema_path_(data_schema),
  582. column_names_(column_names),
  583. decode_(decode),
  584. sampler_(sampler) {}
  585. bool AlbumDataset::ValidateParams() {
  586. if (!ValidateDatasetDirParam("AlbumDataset", dataset_dir_)) {
  587. return false;
  588. }
  589. if (!ValidateDatasetFilesParam("AlbumDataset", {schema_path_})) {
  590. return false;
  591. }
  592. return true;
  593. }
  594. // Function to build AlbumDataset
  595. std::vector<std::shared_ptr<DatasetOp>> AlbumDataset::Build() {
  596. // A vector containing shared pointer to the Dataset Ops that this object will create
  597. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  598. // If user does not specify Sampler, create a default sampler, i.e., RandomSampler.
  599. if (sampler_ == nullptr) {
  600. sampler_ = CreateDefaultSampler();
  601. }
  602. auto schema = std::make_unique<DataSchema>();
  603. RETURN_EMPTY_IF_ERROR(schema->LoadSchemaFile(schema_path_, column_names_));
  604. // Argument that is not exposed to user in the API.
  605. std::set<std::string> extensions = {};
  606. node_ops.push_back(std::make_shared<AlbumOp>(num_workers_, rows_per_buffer_, dataset_dir_, connector_que_size_,
  607. decode_, extensions, std::move(schema), std::move(sampler_->Build())));
  608. return node_ops;
  609. }
  610. // Constructor for CelebADataset
  611. CelebADataset::CelebADataset(const std::string &dataset_dir, const std::string &dataset_type,
  612. const std::shared_ptr<SamplerObj> &sampler, const bool &decode,
  613. const std::set<std::string> &extensions)
  614. : dataset_dir_(dataset_dir),
  615. dataset_type_(dataset_type),
  616. sampler_(sampler),
  617. decode_(decode),
  618. extensions_(extensions) {}
  619. bool CelebADataset::ValidateParams() {
  620. if (!ValidateDatasetDirParam("CelebADataset", dataset_dir_)) {
  621. return false;
  622. }
  623. std::set<std::string> dataset_type_list = {"all", "train", "valid", "test"};
  624. auto iter = dataset_type_list.find(dataset_type_);
  625. if (iter == dataset_type_list.end()) {
  626. MS_LOG(ERROR) << "dataset_type should be one of 'all', 'train', 'valid' or 'test'.";
  627. return false;
  628. }
  629. return true;
  630. }
  631. // Function to build CelebADataset
  632. std::vector<std::shared_ptr<DatasetOp>> CelebADataset::Build() {
  633. // A vector containing shared pointer to the Dataset Ops that this object will create
  634. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  635. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  636. if (sampler_ == nullptr) {
  637. sampler_ = CreateDefaultSampler();
  638. }
  639. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  640. RETURN_EMPTY_IF_ERROR(
  641. schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  642. // label is like this:0 1 0 0 1......
  643. RETURN_EMPTY_IF_ERROR(
  644. schema->AddColumn(ColDescriptor("attr", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  645. node_ops.push_back(std::make_shared<CelebAOp>(num_workers_, rows_per_buffer_, dataset_dir_, connector_que_size_,
  646. decode_, dataset_type_, extensions_, std::move(schema),
  647. std::move(sampler_->Build())));
  648. return node_ops;
  649. }
  650. // Constructor for Cifar10Dataset
  651. Cifar10Dataset::Cifar10Dataset(const std::string &dataset_dir, std::shared_ptr<SamplerObj> sampler)
  652. : dataset_dir_(dataset_dir), sampler_(sampler) {}
  653. bool Cifar10Dataset::ValidateParams() { return ValidateDatasetDirParam("Cifar10Dataset", dataset_dir_); }
  654. // Function to build CifarOp for Cifar10
  655. std::vector<std::shared_ptr<DatasetOp>> Cifar10Dataset::Build() {
  656. // A vector containing shared pointer to the Dataset Ops that this object will create
  657. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  658. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  659. if (sampler_ == nullptr) {
  660. sampler_ = CreateDefaultSampler();
  661. }
  662. // Do internal Schema generation.
  663. auto schema = std::make_unique<DataSchema>();
  664. RETURN_EMPTY_IF_ERROR(schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kCv, 1)));
  665. TensorShape scalar = TensorShape::CreateScalar();
  666. RETURN_EMPTY_IF_ERROR(
  667. schema->AddColumn(ColDescriptor("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar)));
  668. node_ops.push_back(std::make_shared<CifarOp>(CifarOp::CifarType::kCifar10, num_workers_, rows_per_buffer_,
  669. dataset_dir_, connector_que_size_, std::move(schema),
  670. std::move(sampler_->Build())));
  671. return node_ops;
  672. }
  673. // Constructor for Cifar100Dataset
  674. Cifar100Dataset::Cifar100Dataset(const std::string &dataset_dir, std::shared_ptr<SamplerObj> sampler)
  675. : dataset_dir_(dataset_dir), sampler_(sampler) {}
  676. bool Cifar100Dataset::ValidateParams() { return ValidateDatasetDirParam("Cifar100Dataset", dataset_dir_); }
  677. // Function to build CifarOp for Cifar100
  678. std::vector<std::shared_ptr<DatasetOp>> Cifar100Dataset::Build() {
  679. // A vector containing shared pointer to the Dataset Ops that this object will create
  680. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  681. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  682. if (sampler_ == nullptr) {
  683. sampler_ = CreateDefaultSampler();
  684. }
  685. // Do internal Schema generation.
  686. auto schema = std::make_unique<DataSchema>();
  687. RETURN_EMPTY_IF_ERROR(schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kCv, 1)));
  688. TensorShape scalar = TensorShape::CreateScalar();
  689. RETURN_EMPTY_IF_ERROR(
  690. schema->AddColumn(ColDescriptor("coarse_label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar)));
  691. RETURN_EMPTY_IF_ERROR(
  692. schema->AddColumn(ColDescriptor("fine_label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar)));
  693. node_ops.push_back(std::make_shared<CifarOp>(CifarOp::CifarType::kCifar100, num_workers_, rows_per_buffer_,
  694. dataset_dir_, connector_que_size_, std::move(schema),
  695. std::move(sampler_->Build())));
  696. return node_ops;
  697. }
  698. // Constructor for CLUEDataset
  699. CLUEDataset::CLUEDataset(const std::vector<std::string> clue_files, std::string task, std::string usage,
  700. int64_t num_samples, ShuffleMode shuffle, int32_t num_shards, int32_t shard_id)
  701. : dataset_files_(clue_files),
  702. task_(task),
  703. usage_(usage),
  704. num_samples_(num_samples),
  705. shuffle_(shuffle),
  706. num_shards_(num_shards),
  707. shard_id_(shard_id) {}
  708. bool CLUEDataset::ValidateParams() {
  709. if (!ValidateDatasetFilesParam("CLUEDataset", dataset_files_)) {
  710. return false;
  711. }
  712. std::vector<std::string> task_list = {"AFQMC", "TNEWS", "IFLYTEK", "CMNLI", "WSC", "CSL"};
  713. std::vector<std::string> usage_list = {"train", "test", "eval"};
  714. if (find(task_list.begin(), task_list.end(), task_) == task_list.end()) {
  715. MS_LOG(ERROR) << "task should be AFQMC, TNEWS, IFLYTEK, CMNLI, WSC or CSL.";
  716. return false;
  717. }
  718. if (find(usage_list.begin(), usage_list.end(), usage_) == usage_list.end()) {
  719. MS_LOG(ERROR) << "usage should be train, test or eval.";
  720. return false;
  721. }
  722. if (num_samples_ < 0) {
  723. MS_LOG(ERROR) << "CLUEDataset: Invalid number of samples: " << num_samples_;
  724. return false;
  725. }
  726. if (!ValidateDatasetShardParams("CLUEDataset", num_shards_, shard_id_)) {
  727. return false;
  728. }
  729. return true;
  730. }
  731. // Function to split string based on a character delimiter
  732. std::vector<std::string> CLUEDataset::split(const std::string &s, char delim) {
  733. std::vector<std::string> res;
  734. std::stringstream ss(s);
  735. std::string item;
  736. while (getline(ss, item, delim)) {
  737. res.push_back(item);
  738. }
  739. return res;
  740. }
  741. // Function to build CLUEDataset
  742. std::vector<std::shared_ptr<DatasetOp>> CLUEDataset::Build() {
  743. // A vector containing shared pointer to the Dataset Ops that this object will create
  744. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  745. std::map<std::string, std::string> key_map;
  746. if (task_ == "AFQMC") {
  747. if (usage_ == "train") {
  748. key_map["sentence1"] = "sentence1";
  749. key_map["sentence2"] = "sentence2";
  750. key_map["label"] = "label";
  751. } else if (usage_ == "test") {
  752. key_map["id"] = "id";
  753. key_map["sentence1"] = "sentence1";
  754. key_map["sentence2"] = "sentence2";
  755. } else if (usage_ == "eval") {
  756. key_map["sentence1"] = "sentence1";
  757. key_map["sentence2"] = "sentence2";
  758. key_map["label"] = "label";
  759. }
  760. } else if (task_ == "CMNLI") {
  761. if (usage_ == "train") {
  762. key_map["sentence1"] = "sentence1";
  763. key_map["sentence2"] = "sentence2";
  764. key_map["label"] = "label";
  765. } else if (usage_ == "test") {
  766. key_map["id"] = "id";
  767. key_map["sentence1"] = "sentence1";
  768. key_map["sentence2"] = "sentence2";
  769. } else if (usage_ == "eval") {
  770. key_map["sentence1"] = "sentence1";
  771. key_map["sentence2"] = "sentence2";
  772. key_map["label"] = "label";
  773. }
  774. } else if (task_ == "CSL") {
  775. if (usage_ == "train") {
  776. key_map["id"] = "id";
  777. key_map["abst"] = "abst";
  778. key_map["keyword"] = "keyword";
  779. key_map["label"] = "label";
  780. } else if (usage_ == "test") {
  781. key_map["id"] = "id";
  782. key_map["abst"] = "abst";
  783. key_map["keyword"] = "keyword";
  784. } else if (usage_ == "eval") {
  785. key_map["id"] = "id";
  786. key_map["abst"] = "abst";
  787. key_map["keyword"] = "keyword";
  788. key_map["label"] = "label";
  789. }
  790. } else if (task_ == "IFLYTEK") {
  791. if (usage_ == "train") {
  792. key_map["label"] = "label";
  793. key_map["label_des"] = "label_des";
  794. key_map["sentence"] = "sentence";
  795. } else if (usage_ == "test") {
  796. key_map["id"] = "id";
  797. key_map["sentence"] = "sentence";
  798. } else if (usage_ == "eval") {
  799. key_map["label"] = "label";
  800. key_map["label_des"] = "label_des";
  801. key_map["sentence"] = "sentence";
  802. }
  803. } else if (task_ == "TNEWS") {
  804. if (usage_ == "train") {
  805. key_map["label"] = "label";
  806. key_map["label_desc"] = "label_desc";
  807. key_map["sentence"] = "sentence";
  808. key_map["keywords"] = "keywords";
  809. } else if (usage_ == "test") {
  810. key_map["id"] = "id";
  811. key_map["sentence"] = "sentence";
  812. key_map["keywords"] = "keywords";
  813. } else if (usage_ == "eval") {
  814. key_map["label"] = "label";
  815. key_map["label_desc"] = "label_desc";
  816. key_map["sentence"] = "sentence";
  817. key_map["keywords"] = "keywords";
  818. }
  819. } else if (task_ == "WSC") {
  820. if (usage_ == "train") {
  821. key_map["span1_index"] = "target/span1_index";
  822. key_map["span2_index"] = "target/span2_index";
  823. key_map["span1_text"] = "target/span1_text";
  824. key_map["span2_text"] = "target/span2_text";
  825. key_map["idx"] = "idx";
  826. key_map["label"] = "label";
  827. key_map["text"] = "text";
  828. } else if (usage_ == "test") {
  829. key_map["span1_index"] = "target/span1_index";
  830. key_map["span2_index"] = "target/span2_index";
  831. key_map["span1_text"] = "target/span1_text";
  832. key_map["span2_text"] = "target/span2_text";
  833. key_map["idx"] = "idx";
  834. key_map["text"] = "text";
  835. } else if (usage_ == "eval") {
  836. key_map["span1_index"] = "target/span1_index";
  837. key_map["span2_index"] = "target/span2_index";
  838. key_map["span1_text"] = "target/span1_text";
  839. key_map["span2_text"] = "target/span2_text";
  840. key_map["idx"] = "idx";
  841. key_map["label"] = "label";
  842. key_map["text"] = "text";
  843. }
  844. }
  845. ColKeyMap ck_map;
  846. for (auto &p : key_map) {
  847. ck_map.insert({p.first, split(p.second, '/')});
  848. }
  849. bool shuffle_files = (shuffle_ == ShuffleMode::kGlobal || shuffle_ == ShuffleMode::kFiles);
  850. std::shared_ptr<ClueOp> clue_op =
  851. std::make_shared<ClueOp>(num_workers_, rows_per_buffer_, num_samples_, worker_connector_size_, ck_map,
  852. dataset_files_, connector_que_size_, shuffle_files, num_shards_, shard_id_);
  853. RETURN_EMPTY_IF_ERROR(clue_op->Init());
  854. if (shuffle_ == ShuffleMode::kGlobal) {
  855. // Inject ShuffleOp
  856. std::shared_ptr<DatasetOp> shuffle_op = nullptr;
  857. int64_t num_rows = 0;
  858. // First, get the number of rows in the dataset
  859. RETURN_EMPTY_IF_ERROR(ClueOp::CountAllFileRows(dataset_files_, &num_rows));
  860. // Add the shuffle op after this op
  861. RETURN_EMPTY_IF_ERROR(AddShuffleOp(dataset_files_.size(), num_shards_, num_rows, 0, connector_que_size_,
  862. rows_per_buffer_, &shuffle_op));
  863. node_ops.push_back(shuffle_op);
  864. }
  865. node_ops.push_back(clue_op);
  866. return node_ops;
  867. }
  868. // Constructor for CocoDataset
  869. CocoDataset::CocoDataset(const std::string &dataset_dir, const std::string &annotation_file, const std::string &task,
  870. const bool &decode, const std::shared_ptr<SamplerObj> &sampler)
  871. : dataset_dir_(dataset_dir), annotation_file_(annotation_file), task_(task), decode_(decode), sampler_(sampler) {}
  872. bool CocoDataset::ValidateParams() {
  873. if (!ValidateDatasetDirParam("CocoDataset", dataset_dir_)) {
  874. return false;
  875. }
  876. Path annotation_file(annotation_file_);
  877. if (!annotation_file.Exists()) {
  878. MS_LOG(ERROR) << "annotation_file is invalid or not exist";
  879. return false;
  880. }
  881. std::set<std::string> task_list = {"Detection", "Stuff", "Panoptic", "Keypoint"};
  882. auto task_iter = task_list.find(task_);
  883. if (task_iter == task_list.end()) {
  884. MS_LOG(ERROR) << "Invalid task type";
  885. return false;
  886. }
  887. return true;
  888. }
  889. // Function to build CocoDataset
  890. std::vector<std::shared_ptr<DatasetOp>> CocoDataset::Build() {
  891. // A vector containing shared pointer to the Dataset Ops that this object will create
  892. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  893. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  894. if (sampler_ == nullptr) {
  895. sampler_ = CreateDefaultSampler();
  896. }
  897. CocoOp::TaskType task_type;
  898. if (task_ == "Detection") {
  899. task_type = CocoOp::TaskType::Detection;
  900. } else if (task_ == "Stuff") {
  901. task_type = CocoOp::TaskType::Stuff;
  902. } else if (task_ == "Keypoint") {
  903. task_type = CocoOp::TaskType::Keypoint;
  904. } else if (task_ == "Panoptic") {
  905. task_type = CocoOp::TaskType::Panoptic;
  906. }
  907. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  908. RETURN_EMPTY_IF_ERROR(
  909. schema->AddColumn(ColDescriptor(std::string("image"), DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  910. switch (task_type) {
  911. case CocoOp::TaskType::Detection:
  912. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  913. ColDescriptor(std::string("bbox"), DataType(DataType::DE_FLOAT32), TensorImpl::kFlexible, 1)));
  914. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  915. ColDescriptor(std::string("category_id"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  916. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  917. ColDescriptor(std::string("iscrowd"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  918. break;
  919. case CocoOp::TaskType::Stuff:
  920. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  921. ColDescriptor(std::string("segmentation"), DataType(DataType::DE_FLOAT32), TensorImpl::kFlexible, 1)));
  922. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  923. ColDescriptor(std::string("iscrowd"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  924. break;
  925. case CocoOp::TaskType::Keypoint:
  926. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  927. ColDescriptor(std::string("keypoints"), DataType(DataType::DE_FLOAT32), TensorImpl::kFlexible, 1)));
  928. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  929. ColDescriptor(std::string("num_keypoints"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  930. break;
  931. case CocoOp::TaskType::Panoptic:
  932. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  933. ColDescriptor(std::string("bbox"), DataType(DataType::DE_FLOAT32), TensorImpl::kFlexible, 1)));
  934. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  935. ColDescriptor(std::string("category_id"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  936. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  937. ColDescriptor(std::string("iscrowd"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  938. RETURN_EMPTY_IF_ERROR(
  939. schema->AddColumn(ColDescriptor(std::string("area"), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  940. break;
  941. default:
  942. MS_LOG(ERROR) << "CocoDataset::Build : Invalid task type";
  943. return {};
  944. }
  945. std::shared_ptr<CocoOp> op =
  946. std::make_shared<CocoOp>(task_type, dataset_dir_, annotation_file_, num_workers_, rows_per_buffer_,
  947. connector_que_size_, decode_, std::move(schema), std::move(sampler_->Build()));
  948. node_ops.push_back(op);
  949. return node_ops;
  950. }
  951. // Constructor for CSVDataset
  952. CSVDataset::CSVDataset(const std::vector<std::string> &csv_files, char field_delim,
  953. const std::vector<std::shared_ptr<CsvBase>> &column_defaults,
  954. const std::vector<std::string> &column_names, int64_t num_samples, ShuffleMode shuffle,
  955. int32_t num_shards, int32_t shard_id)
  956. : dataset_files_(csv_files),
  957. field_delim_(field_delim),
  958. column_defaults_(column_defaults),
  959. column_names_(column_names),
  960. num_samples_(num_samples),
  961. shuffle_(shuffle),
  962. num_shards_(num_shards),
  963. shard_id_(shard_id) {}
  964. bool CSVDataset::ValidateParams() {
  965. if (!ValidateDatasetFilesParam("CSVDataset", dataset_files_)) {
  966. return false;
  967. }
  968. if (field_delim_ == '"' || field_delim_ == '\r' || field_delim_ == '\n') {
  969. MS_LOG(ERROR) << "CSVDataset: The field delimiter should not be \", \\r, \\n";
  970. return false;
  971. }
  972. if (num_samples_ < -1) {
  973. MS_LOG(ERROR) << "CSVDataset: Invalid number of samples: " << num_samples_;
  974. return false;
  975. }
  976. if (!ValidateDatasetShardParams("CSVDataset", num_shards_, shard_id_)) {
  977. return false;
  978. }
  979. return true;
  980. }
  981. // Function to build CSVDataset
  982. std::vector<std::shared_ptr<DatasetOp>> CSVDataset::Build() {
  983. // A vector containing shared pointer to the Dataset Ops that this object will create
  984. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  985. bool shuffle_files = (shuffle_ == ShuffleMode::kGlobal || shuffle_ == ShuffleMode::kFiles);
  986. std::vector<std::shared_ptr<CsvOp::BaseRecord>> column_default_list;
  987. for (auto v : column_defaults_) {
  988. if (v->type == CsvType::INT) {
  989. column_default_list.push_back(
  990. std::make_shared<CsvOp::Record<int>>(CsvOp::INT, std::dynamic_pointer_cast<CsvRecord<int>>(v)->value));
  991. } else if (v->type == CsvType::FLOAT) {
  992. column_default_list.push_back(
  993. std::make_shared<CsvOp::Record<float>>(CsvOp::FLOAT, std::dynamic_pointer_cast<CsvRecord<float>>(v)->value));
  994. } else if (v->type == CsvType::STRING) {
  995. column_default_list.push_back(std::make_shared<CsvOp::Record<std::string>>(
  996. CsvOp::STRING, std::dynamic_pointer_cast<CsvRecord<std::string>>(v)->value));
  997. }
  998. }
  999. std::shared_ptr<CsvOp> csv_op = std::make_shared<CsvOp>(
  1000. dataset_files_, field_delim_, column_default_list, column_names_, num_workers_, rows_per_buffer_, num_samples_,
  1001. worker_connector_size_, connector_que_size_, shuffle_files, num_shards_, shard_id_);
  1002. RETURN_EMPTY_IF_ERROR(csv_op->Init());
  1003. if (shuffle_ == ShuffleMode::kGlobal) {
  1004. // Inject ShuffleOp
  1005. std::shared_ptr<DatasetOp> shuffle_op = nullptr;
  1006. int64_t num_rows = 0;
  1007. // First, get the number of rows in the dataset
  1008. RETURN_EMPTY_IF_ERROR(CsvOp::CountAllFileRows(dataset_files_, column_names_.empty(), &num_rows));
  1009. // Add the shuffle op after this op
  1010. RETURN_EMPTY_IF_ERROR(AddShuffleOp(dataset_files_.size(), num_shards_, num_rows, 0, connector_que_size_,
  1011. rows_per_buffer_, &shuffle_op));
  1012. node_ops.push_back(shuffle_op);
  1013. }
  1014. node_ops.push_back(csv_op);
  1015. return node_ops;
  1016. }
  1017. ImageFolderDataset::ImageFolderDataset(std::string dataset_dir, bool decode, std::shared_ptr<SamplerObj> sampler,
  1018. bool recursive, std::set<std::string> extensions,
  1019. std::map<std::string, int32_t> class_indexing)
  1020. : dataset_dir_(dataset_dir),
  1021. decode_(decode),
  1022. sampler_(sampler),
  1023. recursive_(recursive),
  1024. class_indexing_(class_indexing),
  1025. exts_(extensions) {}
  1026. bool ImageFolderDataset::ValidateParams() { return ValidateDatasetDirParam("ImageFolderDataset", dataset_dir_); }
  1027. std::vector<std::shared_ptr<DatasetOp>> ImageFolderDataset::Build() {
  1028. // A vector containing shared pointer to the Dataset Ops that this object will create
  1029. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1030. // If user does not specify Sampler, create a default sampler, i.e., RandomSampler.
  1031. if (sampler_ == nullptr) {
  1032. sampler_ = CreateDefaultSampler();
  1033. }
  1034. // Do internal Schema generation.
  1035. // This arg is exist in ImageFolderOp, but not externalized (in Python API).
  1036. std::unique_ptr<DataSchema> schema = std::make_unique<DataSchema>();
  1037. TensorShape scalar = TensorShape::CreateScalar();
  1038. RETURN_EMPTY_IF_ERROR(
  1039. schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  1040. RETURN_EMPTY_IF_ERROR(
  1041. schema->AddColumn(ColDescriptor("label", DataType(DataType::DE_INT32), TensorImpl::kFlexible, 0, &scalar)));
  1042. node_ops.push_back(std::make_shared<ImageFolderOp>(num_workers_, rows_per_buffer_, dataset_dir_, connector_que_size_,
  1043. recursive_, decode_, exts_, class_indexing_, std::move(schema),
  1044. std::move(sampler_->Build())));
  1045. return node_ops;
  1046. }
  1047. ManifestDataset::ManifestDataset(std::string dataset_file, std::string usage, std::shared_ptr<SamplerObj> sampler,
  1048. const std::map<std::string, int32_t> &class_indexing, bool decode)
  1049. : dataset_file_(dataset_file), usage_(usage), decode_(decode), class_index_(class_indexing), sampler_(sampler) {}
  1050. bool ManifestDataset::ValidateParams() {
  1051. Path manifest_file(dataset_file_);
  1052. if (!manifest_file.Exists()) {
  1053. MS_LOG(ERROR) << "dataset file: [" << dataset_file_ << "] is invalid or not exist";
  1054. return false;
  1055. }
  1056. std::vector<std::string> usage_list = {"train", "eval", "inference"};
  1057. if (find(usage_list.begin(), usage_list.end(), usage_) == usage_list.end()) {
  1058. MS_LOG(ERROR) << "usage should be train, eval or inference.";
  1059. return false;
  1060. }
  1061. return true;
  1062. }
  1063. std::vector<std::shared_ptr<DatasetOp>> ManifestDataset::Build() {
  1064. // A vector containing shared pointer to the Dataset Ops that this object will create
  1065. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1066. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  1067. if (sampler_ == nullptr) {
  1068. sampler_ = CreateDefaultSampler();
  1069. }
  1070. // Do internal Schema generation.
  1071. auto schema = std::make_unique<DataSchema>();
  1072. RETURN_EMPTY_IF_ERROR(schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kCv, 1)));
  1073. TensorShape scalar = TensorShape::CreateScalar();
  1074. RETURN_EMPTY_IF_ERROR(
  1075. schema->AddColumn(ColDescriptor("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar)));
  1076. std::shared_ptr<ManifestOp> manifest_op;
  1077. manifest_op =
  1078. std::make_shared<ManifestOp>(num_workers_, rows_per_buffer_, dataset_file_, connector_que_size_, decode_,
  1079. class_index_, std::move(schema), std::move(sampler_->Build()), usage_);
  1080. node_ops.push_back(manifest_op);
  1081. return node_ops;
  1082. }
  1083. MnistDataset::MnistDataset(std::string dataset_dir, std::shared_ptr<SamplerObj> sampler)
  1084. : dataset_dir_(dataset_dir), sampler_(sampler) {}
  1085. bool MnistDataset::ValidateParams() { return ValidateDatasetDirParam("MnistDataset", dataset_dir_); }
  1086. std::vector<std::shared_ptr<DatasetOp>> MnistDataset::Build() {
  1087. // A vector containing shared pointer to the Dataset Ops that this object will create
  1088. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1089. // If user does not specify Sampler, create a default sampler, i.e., RandomSampler.
  1090. if (sampler_ == nullptr) {
  1091. sampler_ = CreateDefaultSampler();
  1092. }
  1093. // Do internal Schema generation.
  1094. auto schema = std::make_unique<DataSchema>();
  1095. RETURN_EMPTY_IF_ERROR(schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kCv, 1)));
  1096. TensorShape scalar = TensorShape::CreateScalar();
  1097. RETURN_EMPTY_IF_ERROR(
  1098. schema->AddColumn(ColDescriptor("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar)));
  1099. node_ops.push_back(std::make_shared<MnistOp>(num_workers_, rows_per_buffer_, dataset_dir_, connector_que_size_,
  1100. std::move(schema), std::move(sampler_->Build())));
  1101. return node_ops;
  1102. }
  1103. // ValideParams for RandomDataset
  1104. bool RandomDataset::ValidateParams() {
  1105. if (total_rows_ < 0) {
  1106. MS_LOG(ERROR) << "RandomDataset: total_rows must be greater than 0, now get " << total_rows_;
  1107. return false;
  1108. }
  1109. return true;
  1110. }
  1111. int32_t RandomDataset::GenRandomInt(int32_t min, int32_t max) {
  1112. std::uniform_int_distribution<int32_t> uniDist(min, max);
  1113. return uniDist(rand_gen_);
  1114. }
  1115. // Build for RandomDataset
  1116. std::vector<std::shared_ptr<DatasetOp>> RandomDataset::Build() {
  1117. // A vector containing shared pointer to the Dataset Ops that this object will create
  1118. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1119. rand_gen_.seed(GetSeed()); // seed the random generator
  1120. // If total rows was not given, then randomly pick a number
  1121. std::shared_ptr<SchemaObj> schema_obj;
  1122. if (!schema_path_.empty()) schema_obj = std::make_shared<SchemaObj>(schema_path_);
  1123. if (schema_obj != nullptr && total_rows_ == 0) {
  1124. total_rows_ = schema_obj->get_num_rows();
  1125. }
  1126. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  1127. if (sampler_ == nullptr) {
  1128. sampler_ = CreateDefaultSampler();
  1129. }
  1130. std::string schema_json_string, schema_file_path;
  1131. if (schema_ != nullptr) {
  1132. schema_->set_dataset_type("Random");
  1133. if (total_rows_ != 0) {
  1134. schema_->set_num_rows(total_rows_);
  1135. }
  1136. schema_json_string = schema_->to_json();
  1137. } else {
  1138. schema_file_path = schema_path_;
  1139. }
  1140. std::unique_ptr<DataSchema> data_schema;
  1141. std::vector<std::string> columns_to_load;
  1142. if (!schema_file_path.empty() || !schema_json_string.empty()) {
  1143. data_schema = std::make_unique<DataSchema>();
  1144. if (!schema_file_path.empty()) {
  1145. data_schema->LoadSchemaFile(schema_file_path, columns_to_load);
  1146. } else if (!schema_json_string.empty()) {
  1147. data_schema->LoadSchemaString(schema_json_string, columns_to_load);
  1148. }
  1149. }
  1150. std::shared_ptr<RandomDataOp> op;
  1151. op = std::make_shared<RandomDataOp>(num_workers_, connector_que_size_, rows_per_buffer_, total_rows_,
  1152. std::move(data_schema), std::move(sampler_->Build()));
  1153. node_ops.push_back(op);
  1154. return node_ops;
  1155. }
  1156. // Constructor for TextFileDataset
  1157. TextFileDataset::TextFileDataset(std::vector<std::string> dataset_files, int32_t num_samples, ShuffleMode shuffle,
  1158. int32_t num_shards, int32_t shard_id)
  1159. : dataset_files_(dataset_files),
  1160. num_samples_(num_samples),
  1161. shuffle_(shuffle),
  1162. num_shards_(num_shards),
  1163. shard_id_(shard_id) {}
  1164. bool TextFileDataset::ValidateParams() {
  1165. if (!ValidateDatasetFilesParam("TextFileDataset", dataset_files_)) {
  1166. return false;
  1167. }
  1168. if (num_samples_ < 0) {
  1169. MS_LOG(ERROR) << "TextFileDataset: Invalid number of samples: " << num_samples_;
  1170. return false;
  1171. }
  1172. if (!ValidateDatasetShardParams("TextFileDataset", num_shards_, shard_id_)) {
  1173. return false;
  1174. }
  1175. return true;
  1176. }
  1177. // Function to build TextFileDataset
  1178. std::vector<std::shared_ptr<DatasetOp>> TextFileDataset::Build() {
  1179. // A vector containing shared pointer to the Dataset Ops that this object will create
  1180. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1181. bool shuffle_files = (shuffle_ == ShuffleMode::kGlobal || shuffle_ == ShuffleMode::kFiles);
  1182. // Do internal Schema generation.
  1183. auto schema = std::make_unique<DataSchema>();
  1184. RETURN_EMPTY_IF_ERROR(
  1185. schema->AddColumn(ColDescriptor("text", DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  1186. // Create and initalize TextFileOp
  1187. std::shared_ptr<TextFileOp> text_file_op = std::make_shared<TextFileOp>(
  1188. num_workers_, rows_per_buffer_, num_samples_, worker_connector_size_, std::move(schema), dataset_files_,
  1189. connector_que_size_, shuffle_files, num_shards_, shard_id_, std::move(nullptr));
  1190. RETURN_EMPTY_IF_ERROR(text_file_op->Init());
  1191. if (shuffle_ == ShuffleMode::kGlobal) {
  1192. // Inject ShuffleOp
  1193. std::shared_ptr<DatasetOp> shuffle_op = nullptr;
  1194. int64_t num_rows = 0;
  1195. // First, get the number of rows in the dataset
  1196. RETURN_EMPTY_IF_ERROR(TextFileOp::CountAllFileRows(dataset_files_, &num_rows));
  1197. // Add the shuffle op after this op
  1198. RETURN_EMPTY_IF_ERROR(AddShuffleOp(dataset_files_.size(), num_shards_, num_rows, 0, connector_que_size_,
  1199. rows_per_buffer_, &shuffle_op));
  1200. node_ops.push_back(shuffle_op);
  1201. }
  1202. // Add TextFileOp
  1203. node_ops.push_back(text_file_op);
  1204. return node_ops;
  1205. }
  1206. // Constructor for VOCDataset
  1207. VOCDataset::VOCDataset(const std::string &dataset_dir, const std::string &task, const std::string &mode,
  1208. const std::map<std::string, int32_t> &class_indexing, bool decode,
  1209. std::shared_ptr<SamplerObj> sampler)
  1210. : dataset_dir_(dataset_dir),
  1211. task_(task),
  1212. mode_(mode),
  1213. class_index_(class_indexing),
  1214. decode_(decode),
  1215. sampler_(sampler) {}
  1216. bool VOCDataset::ValidateParams() {
  1217. Path dir(dataset_dir_);
  1218. if (!dir.IsDirectory()) {
  1219. MS_LOG(ERROR) << "Invalid dataset path or no dataset path is specified.";
  1220. return false;
  1221. }
  1222. if (task_ == "Segmentation") {
  1223. if (!class_index_.empty()) {
  1224. MS_LOG(ERROR) << "class_indexing is invalid in Segmentation task.";
  1225. return false;
  1226. }
  1227. Path imagesets_file = dir / "ImageSets" / "Segmentation" / mode_ + ".txt";
  1228. if (!imagesets_file.Exists()) {
  1229. MS_LOG(ERROR) << "Invalid mode: " << mode_ << ", file \"" << imagesets_file << "\" is not exists!";
  1230. return false;
  1231. }
  1232. } else if (task_ == "Detection") {
  1233. Path imagesets_file = dir / "ImageSets" / "Main" / mode_ + ".txt";
  1234. if (!imagesets_file.Exists()) {
  1235. MS_LOG(ERROR) << "Invalid mode: " << mode_ << ", file \"" << imagesets_file << "\" is not exists!";
  1236. return false;
  1237. }
  1238. } else {
  1239. MS_LOG(ERROR) << "Invalid task: " << task_;
  1240. return false;
  1241. }
  1242. return true;
  1243. }
  1244. // Function to build VOCDataset
  1245. std::vector<std::shared_ptr<DatasetOp>> VOCDataset::Build() {
  1246. // A vector containing shared pointer to the Dataset Ops that this object will create
  1247. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1248. // If user does not specify Sampler, create a default sampler based on the shuffle variable.
  1249. if (sampler_ == nullptr) {
  1250. sampler_ = CreateDefaultSampler();
  1251. }
  1252. auto schema = std::make_unique<DataSchema>();
  1253. VOCOp::TaskType task_type_;
  1254. if (task_ == "Segmentation") {
  1255. task_type_ = VOCOp::TaskType::Segmentation;
  1256. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1257. ColDescriptor(std::string(kColumnImage), DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  1258. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1259. ColDescriptor(std::string(kColumnTarget), DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  1260. } else if (task_ == "Detection") {
  1261. task_type_ = VOCOp::TaskType::Detection;
  1262. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1263. ColDescriptor(std::string(kColumnImage), DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
  1264. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1265. ColDescriptor(std::string(kColumnBbox), DataType(DataType::DE_FLOAT32), TensorImpl::kFlexible, 1)));
  1266. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1267. ColDescriptor(std::string(kColumnLabel), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  1268. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1269. ColDescriptor(std::string(kColumnDifficult), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  1270. RETURN_EMPTY_IF_ERROR(schema->AddColumn(
  1271. ColDescriptor(std::string(kColumnTruncate), DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
  1272. }
  1273. std::shared_ptr<VOCOp> voc_op;
  1274. voc_op = std::make_shared<VOCOp>(task_type_, mode_, dataset_dir_, class_index_, num_workers_, rows_per_buffer_,
  1275. connector_que_size_, decode_, std::move(schema), std::move(sampler_->Build()));
  1276. node_ops.push_back(voc_op);
  1277. return node_ops;
  1278. }
  1279. // DERIVED DATASET CLASSES LEAF-NODE DATASETS
  1280. // (In alphabetical order)
  1281. BatchDataset::BatchDataset(int32_t batch_size, bool drop_remainder, bool pad, std::vector<std::string> cols_to_map,
  1282. std::map<std::string, std::pair<TensorShape, std::shared_ptr<Tensor>>> pad_map)
  1283. : batch_size_(batch_size),
  1284. drop_remainder_(drop_remainder),
  1285. pad_(pad),
  1286. cols_to_map_(cols_to_map),
  1287. pad_map_(pad_map) {}
  1288. std::vector<std::shared_ptr<DatasetOp>> BatchDataset::Build() {
  1289. // A vector containing shared pointer to the Dataset Ops that this object will create
  1290. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1291. #ifdef ENABLE_PYTHON
  1292. py::function noop;
  1293. node_ops.push_back(std::make_shared<BatchOp>(batch_size_, drop_remainder_, pad_, connector_que_size_, num_workers_,
  1294. cols_to_map_, noop, noop, pad_map_));
  1295. #else
  1296. node_ops.push_back(std::make_shared<BatchOp>(batch_size_, drop_remainder_, pad_, connector_que_size_, num_workers_,
  1297. cols_to_map_, pad_map_));
  1298. #endif
  1299. return node_ops;
  1300. }
  1301. bool BatchDataset::ValidateParams() {
  1302. if (batch_size_ <= 0) {
  1303. MS_LOG(ERROR) << "Batch: batch_size should be positive integer, but got: " << batch_size_;
  1304. return false;
  1305. }
  1306. return true;
  1307. }
  1308. BuildVocabDataset::BuildVocabDataset(std::shared_ptr<Vocab> vocab, const std::vector<std::string> &columns,
  1309. const std::pair<int64_t, int64_t> &freq_range, int64_t top_k,
  1310. const std::vector<std::string> &special_tokens, bool special_first)
  1311. : vocab_(vocab),
  1312. columns_(columns),
  1313. freq_range_(freq_range),
  1314. top_k_(top_k),
  1315. special_tokens_(special_tokens),
  1316. special_first_(special_first) {}
  1317. // Function to build BuildVocabDataset
  1318. std::vector<std::shared_ptr<DatasetOp>> BuildVocabDataset::Build() {
  1319. // A vector containing shared pointer to the Dataset Ops that this object will create
  1320. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1321. std::shared_ptr<BuildVocabOp> build_vocab_op;
  1322. build_vocab_op = std::make_shared<BuildVocabOp>(vocab_, columns_, freq_range_, top_k_, special_tokens_,
  1323. special_first_, num_workers_, connector_que_size_);
  1324. node_ops.push_back(build_vocab_op);
  1325. return node_ops;
  1326. }
  1327. bool BuildVocabDataset::ValidateParams() {
  1328. if (vocab_ == nullptr) {
  1329. MS_LOG(ERROR) << "BuildVocab: vocab is null.";
  1330. return false;
  1331. }
  1332. if (top_k_ < 0) {
  1333. MS_LOG(ERROR) << "BuildVocab: top_k shoule be positive, but got: " << top_k_;
  1334. return false;
  1335. }
  1336. if (freq_range_.first < 0 || freq_range_.second > kDeMaxFreq || freq_range_.first > freq_range_.second) {
  1337. MS_LOG(ERROR) << "BuildVocab: requency_range [a,b] should be 0 <= a <= b (a,b are inclusive), "
  1338. << "but got [" << freq_range_.first << ", " << freq_range_.second << "]";
  1339. return false;
  1340. }
  1341. return true;
  1342. }
  1343. // Function to build ConcatOp
  1344. ConcatDataset::ConcatDataset(const std::vector<std::shared_ptr<Dataset>> &datasets) : datasets_(datasets) {
  1345. this->children = datasets_;
  1346. }
  1347. bool ConcatDataset::ValidateParams() {
  1348. if (datasets_.empty()) {
  1349. MS_LOG(ERROR) << "Concat: concatenated datasets are not specified.";
  1350. return false;
  1351. }
  1352. if (find(datasets_.begin(), datasets_.end(), nullptr) != datasets_.end()) {
  1353. MS_LOG(ERROR) << "Concat: concatenated dataset should not be null.";
  1354. return false;
  1355. }
  1356. return true;
  1357. }
  1358. std::vector<std::shared_ptr<DatasetOp>> ConcatDataset::Build() {
  1359. // A vector containing shared pointer to the Dataset Ops that this object will create
  1360. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1361. node_ops.push_back(std::make_shared<ConcatOp>(connector_que_size_));
  1362. return node_ops;
  1363. }
  1364. MapDataset::MapDataset(std::vector<std::shared_ptr<TensorOperation>> operations, std::vector<std::string> input_columns,
  1365. std::vector<std::string> output_columns, const std::vector<std::string> &project_columns)
  1366. : operations_(operations),
  1367. input_columns_(input_columns),
  1368. output_columns_(output_columns),
  1369. project_columns_(project_columns) {}
  1370. std::vector<std::shared_ptr<DatasetOp>> MapDataset::Build() {
  1371. // A vector containing shared pointer to the Dataset Ops that this object will create
  1372. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1373. std::vector<std::shared_ptr<TensorOp>> tensor_ops;
  1374. // Build tensorOp from tensorOperation vector
  1375. // This is to ensure each iterator hold its own copy of the tensorOp objects.
  1376. (void)std::transform(
  1377. operations_.begin(), operations_.end(), std::back_inserter(tensor_ops),
  1378. [](std::shared_ptr<TensorOperation> operation) -> std::shared_ptr<TensorOp> { return operation->Build(); });
  1379. // This parameter will be removed with next rebase
  1380. std::vector<std::string> col_orders;
  1381. auto map_op = std::make_shared<MapOp>(input_columns_, output_columns_, tensor_ops, num_workers_, connector_que_size_);
  1382. if (!project_columns_.empty()) {
  1383. auto project_op = std::make_shared<ProjectOp>(project_columns_);
  1384. node_ops.push_back(project_op);
  1385. }
  1386. node_ops.push_back(map_op);
  1387. return node_ops;
  1388. }
  1389. bool MapDataset::ValidateParams() {
  1390. if (operations_.empty()) {
  1391. MS_LOG(ERROR) << "Map: No operation is specified.";
  1392. return false;
  1393. }
  1394. return true;
  1395. }
  1396. // Function to build ProjectOp
  1397. ProjectDataset::ProjectDataset(const std::vector<std::string> &columns) : columns_(columns) {}
  1398. bool ProjectDataset::ValidateParams() {
  1399. if (columns_.empty()) {
  1400. MS_LOG(ERROR) << "No columns are specified.";
  1401. return false;
  1402. }
  1403. return true;
  1404. }
  1405. std::vector<std::shared_ptr<DatasetOp>> ProjectDataset::Build() {
  1406. // A vector containing shared pointer to the Dataset Ops that this object will create
  1407. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1408. node_ops.push_back(std::make_shared<ProjectOp>(columns_));
  1409. return node_ops;
  1410. }
  1411. // Function to build RenameOp
  1412. RenameDataset::RenameDataset(const std::vector<std::string> &input_columns,
  1413. const std::vector<std::string> &output_columns)
  1414. : input_columns_(input_columns), output_columns_(output_columns) {}
  1415. bool RenameDataset::ValidateParams() {
  1416. if (input_columns_.empty() || output_columns_.empty()) {
  1417. MS_LOG(ERROR) << "input and output columns must be specified";
  1418. return false;
  1419. }
  1420. if (input_columns_.size() != output_columns_.size()) {
  1421. MS_LOG(ERROR) << "input and output columns must be the same size";
  1422. return false;
  1423. }
  1424. for (uint32_t i = 0; i < input_columns_.size(); ++i) {
  1425. if (input_columns_[i].empty()) {
  1426. MS_LOG(ERROR) << "input_columns: column name should not be empty.";
  1427. return false;
  1428. }
  1429. if (output_columns_[i].empty()) {
  1430. MS_LOG(ERROR) << "output_columns: column name should not be empty.";
  1431. return false;
  1432. }
  1433. }
  1434. return true;
  1435. }
  1436. std::vector<std::shared_ptr<DatasetOp>> RenameDataset::Build() {
  1437. // A vector containing shared pointer to the Dataset Ops that this object will create
  1438. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1439. node_ops.push_back(std::make_shared<RenameOp>(input_columns_, output_columns_, connector_que_size_));
  1440. return node_ops;
  1441. }
  1442. RepeatDataset::RepeatDataset(int32_t count) : repeat_count_(count) {}
  1443. std::vector<std::shared_ptr<DatasetOp>> RepeatDataset::Build() {
  1444. // A vector containing shared pointer to the Dataset Ops that this object will create
  1445. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1446. node_ops.push_back(std::make_shared<RepeatOp>(repeat_count_));
  1447. return node_ops;
  1448. }
  1449. bool RepeatDataset::ValidateParams() {
  1450. if (repeat_count_ <= 0 && repeat_count_ != -1) {
  1451. MS_LOG(ERROR) << "Repeat: repeat_count should be either -1 or positive integer, repeat_count_: " << repeat_count_;
  1452. return false;
  1453. }
  1454. return true;
  1455. }
  1456. // Constructor for ShuffleDataset
  1457. ShuffleDataset::ShuffleDataset(int32_t shuffle_size, bool reset_every_epoch)
  1458. : shuffle_size_(shuffle_size), shuffle_seed_(GetSeed()), reset_every_epoch_(reset_every_epoch) {}
  1459. // Function to build the ShuffleOp
  1460. std::vector<std::shared_ptr<DatasetOp>> ShuffleDataset::Build() {
  1461. // A vector containing shared pointer to the Dataset Ops that this object will create
  1462. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1463. node_ops.push_back(std::make_shared<ShuffleOp>(shuffle_size_, shuffle_seed_, connector_que_size_, reset_every_epoch_,
  1464. rows_per_buffer_));
  1465. return node_ops;
  1466. }
  1467. // Function to validate the parameters for ShuffleDataset
  1468. bool ShuffleDataset::ValidateParams() {
  1469. if (shuffle_size_ <= 1) {
  1470. MS_LOG(ERROR) << "ShuffleDataset: Invalid input, shuffle_size: " << shuffle_size_;
  1471. return false;
  1472. }
  1473. return true;
  1474. }
  1475. // Constructor for SkipDataset
  1476. SkipDataset::SkipDataset(int32_t count) : skip_count_(count) {}
  1477. // Function to build the SkipOp
  1478. std::vector<std::shared_ptr<DatasetOp>> SkipDataset::Build() {
  1479. // A vector containing shared pointer to the Dataset Ops that this object will create
  1480. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1481. node_ops.push_back(std::make_shared<SkipOp>(skip_count_, connector_que_size_));
  1482. return node_ops;
  1483. }
  1484. // Function to validate the parameters for SkipDataset
  1485. bool SkipDataset::ValidateParams() {
  1486. if (skip_count_ <= -1) {
  1487. MS_LOG(ERROR) << "Skip: skip_count should not be negative, skip_count: " << skip_count_;
  1488. return false;
  1489. }
  1490. return true;
  1491. }
  1492. // Constructor for TakeDataset
  1493. TakeDataset::TakeDataset(int32_t count) : take_count_(count) {}
  1494. // Function to build the TakeOp
  1495. std::vector<std::shared_ptr<DatasetOp>> TakeDataset::Build() {
  1496. // A vector containing shared pointer to the Dataset Ops that this object will create
  1497. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1498. node_ops.push_back(std::make_shared<TakeOp>(take_count_, connector_que_size_));
  1499. return node_ops;
  1500. }
  1501. // Function to validate the parameters for TakeDataset
  1502. bool TakeDataset::ValidateParams() {
  1503. if (take_count_ <= 0 && take_count_ != -1) {
  1504. MS_LOG(ERROR) << "Take: take_count should be either -1 or positive integer, take_count: " << take_count_;
  1505. return false;
  1506. }
  1507. return true;
  1508. }
  1509. // Function to build ZipOp
  1510. ZipDataset::ZipDataset(const std::vector<std::shared_ptr<Dataset>> &datasets) : datasets_(datasets) {
  1511. for (auto dataset : datasets_) {
  1512. this->children.push_back(dataset);
  1513. }
  1514. }
  1515. bool ZipDataset::ValidateParams() {
  1516. if (datasets_.empty()) {
  1517. MS_LOG(ERROR) << "Zip: dataset to zip are not specified.";
  1518. return false;
  1519. }
  1520. return true;
  1521. }
  1522. std::vector<std::shared_ptr<DatasetOp>> ZipDataset::Build() {
  1523. // A vector containing shared pointer to the Dataset Ops that this object will create
  1524. std::vector<std::shared_ptr<DatasetOp>> node_ops;
  1525. node_ops.push_back(std::make_shared<ZipOp>(rows_per_buffer_, connector_que_size_));
  1526. return node_ops;
  1527. }
  1528. } // namespace api
  1529. } // namespace dataset
  1530. } // namespace mindspore