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.

test_minddataset_padded.py 33 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """
  16. This is the test module for mindrecord
  17. """
  18. import collections
  19. import os
  20. import re
  21. import string
  22. import numpy as np
  23. import pytest
  24. import mindspore.dataset as ds
  25. from mindspore import log as logger
  26. from mindspore.mindrecord import FileWriter
  27. FILES_NUM = 4
  28. CV_FILE_NAME = "../data/mindrecord/imagenet.mindrecord"
  29. CV1_FILE_NAME = "../data/mindrecord/imagenet1.mindrecord"
  30. CV2_FILE_NAME = "../data/mindrecord/imagenet2.mindrecord"
  31. CV_DIR_NAME = "../data/mindrecord/testImageNetData"
  32. NLP_FILE_NAME = "../data/mindrecord/aclImdb.mindrecord"
  33. NLP_FILE_POS = "../data/mindrecord/testAclImdbData/pos"
  34. NLP_FILE_VOCAB = "../data/mindrecord/testAclImdbData/vocab.txt"
  35. @pytest.fixture
  36. def add_and_remove_cv_file():
  37. """add/remove cv file"""
  38. paths = ["{}{}".format(CV_FILE_NAME, str(x).rjust(1, '0'))
  39. for x in range(FILES_NUM)]
  40. try:
  41. for x in paths:
  42. os.remove("{}".format(x)) if os.path.exists("{}".format(x)) else None
  43. os.remove("{}.db".format(x)) if os.path.exists(
  44. "{}.db".format(x)) else None
  45. writer = FileWriter(CV_FILE_NAME, FILES_NUM)
  46. data = get_data(CV_DIR_NAME)
  47. cv_schema_json = {"id": {"type": "int32"},
  48. "file_name": {"type": "string"},
  49. "label": {"type": "int32"},
  50. "data": {"type": "bytes"}}
  51. writer.add_schema(cv_schema_json, "img_schema")
  52. writer.add_index(["file_name", "label"])
  53. writer.write_raw_data(data)
  54. writer.commit()
  55. yield "yield_cv_data"
  56. except Exception as error:
  57. for x in paths:
  58. os.remove("{}".format(x))
  59. os.remove("{}.db".format(x))
  60. raise error
  61. else:
  62. for x in paths:
  63. os.remove("{}".format(x))
  64. os.remove("{}.db".format(x))
  65. @pytest.fixture
  66. def add_and_remove_nlp_file():
  67. """add/remove nlp file"""
  68. paths = ["{}{}".format(NLP_FILE_NAME, str(x).rjust(1, '0'))
  69. for x in range(FILES_NUM)]
  70. try:
  71. for x in paths:
  72. if os.path.exists("{}".format(x)):
  73. os.remove("{}".format(x))
  74. if os.path.exists("{}.db".format(x)):
  75. os.remove("{}.db".format(x))
  76. writer = FileWriter(NLP_FILE_NAME, FILES_NUM)
  77. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  78. nlp_schema_json = {"id": {"type": "string"}, "label": {"type": "int32"},
  79. "rating": {"type": "float32"},
  80. "input_ids": {"type": "int64",
  81. "shape": [-1]},
  82. "input_mask": {"type": "int64",
  83. "shape": [1, -1]},
  84. "segment_ids": {"type": "int64",
  85. "shape": [2, -1]}
  86. }
  87. writer.set_header_size(1 << 14)
  88. writer.set_page_size(1 << 15)
  89. writer.add_schema(nlp_schema_json, "nlp_schema")
  90. writer.add_index(["id", "rating"])
  91. writer.write_raw_data(data)
  92. writer.commit()
  93. yield "yield_nlp_data"
  94. except Exception as error:
  95. for x in paths:
  96. os.remove("{}".format(x))
  97. os.remove("{}.db".format(x))
  98. raise error
  99. else:
  100. for x in paths:
  101. os.remove("{}".format(x))
  102. os.remove("{}.db".format(x))
  103. def test_cv_minddataset_reader_basic_padded_samples(add_and_remove_cv_file):
  104. """tutorial for cv minderdataset."""
  105. columns_list = ["label", "file_name", "data"]
  106. data = get_data(CV_DIR_NAME)
  107. padded_sample = data[0]
  108. padded_sample['label'] = -1
  109. padded_sample['file_name'] = 'dummy.jpg'
  110. num_readers = 4
  111. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers, padded_sample=padded_sample, num_padded=5)
  112. assert data_set.get_dataset_size() == 15
  113. num_iter = 0
  114. num_padded_iter = 0
  115. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  116. logger.info("-------------- cv reader basic: {} ------------------------".format(num_iter))
  117. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  118. logger.info("-------------- item[label]: {} ----------------------------".format(item["label"]))
  119. if item['label'] == -1:
  120. num_padded_iter += 1
  121. assert item['file_name'] == bytes(padded_sample['file_name'],
  122. encoding='utf8')
  123. assert item['label'] == padded_sample['label']
  124. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  125. num_iter += 1
  126. assert num_padded_iter == 5
  127. assert num_iter == 15
  128. def test_cv_minddataset_reader_basic_padded_samples_type_cast(add_and_remove_cv_file):
  129. """tutorial for cv minderdataset."""
  130. columns_list = ["label", "file_name", "data"]
  131. data = get_data(CV_DIR_NAME)
  132. padded_sample = data[0]
  133. padded_sample['label'] = -1
  134. padded_sample['file_name'] = 99999
  135. num_readers = 4
  136. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers, padded_sample=padded_sample, num_padded=5)
  137. assert data_set.get_dataset_size() == 15
  138. num_iter = 0
  139. num_padded_iter = 0
  140. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  141. logger.info("-------------- cv reader basic: {} ------------------------".format(num_iter))
  142. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  143. logger.info("-------------- item[label]: {} ----------------------------".format(item["label"]))
  144. if item['label'] == -1:
  145. num_padded_iter += 1
  146. assert item['file_name'] == bytes(str(padded_sample['file_name']),
  147. encoding='utf8')
  148. assert item['label'] == padded_sample['label']
  149. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  150. num_iter += 1
  151. assert num_padded_iter == 5
  152. assert num_iter == 15
  153. def test_cv_minddataset_partition_padded_samples(add_and_remove_cv_file):
  154. """tutorial for cv minddataset."""
  155. columns_list = ["data", "file_name", "label"]
  156. data = get_data(CV_DIR_NAME)
  157. padded_sample = data[0]
  158. padded_sample['label'] = -2
  159. padded_sample['file_name'] = 'dummy.jpg'
  160. num_readers = 4
  161. def partitions(num_shards, num_padded, dataset_size):
  162. num_padded_iter = 0
  163. num_iter = 0
  164. for partition_id in range(num_shards):
  165. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  166. num_shards=num_shards,
  167. shard_id=partition_id,
  168. padded_sample=padded_sample,
  169. num_padded=num_padded)
  170. assert data_set.get_dataset_size() == dataset_size
  171. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  172. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  173. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  174. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  175. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  176. logger.info("-------------- item[label]: {} -----------------------".format(item["label"]))
  177. if item['label'] == -2:
  178. num_padded_iter += 1
  179. assert item['file_name'] == bytes(padded_sample['file_name'], encoding='utf8')
  180. assert item['label'] == padded_sample['label']
  181. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  182. num_iter += 1
  183. assert num_padded_iter == num_padded
  184. return num_iter == dataset_size * num_shards
  185. partitions(4, 2, 3)
  186. partitions(5, 5, 3)
  187. partitions(9, 8, 2)
  188. def test_cv_minddataset_partition_padded_samples_multi_epoch(add_and_remove_cv_file):
  189. """tutorial for cv minddataset."""
  190. columns_list = ["data", "file_name", "label"]
  191. data = get_data(CV_DIR_NAME)
  192. padded_sample = data[0]
  193. padded_sample['label'] = -2
  194. padded_sample['file_name'] = 'dummy.jpg'
  195. num_readers = 4
  196. def partitions(num_shards, num_padded, dataset_size):
  197. repeat_size = 5
  198. num_padded_iter = 0
  199. num_iter = 0
  200. for partition_id in range(num_shards):
  201. epoch1_shuffle_result = []
  202. epoch2_shuffle_result = []
  203. epoch3_shuffle_result = []
  204. epoch4_shuffle_result = []
  205. epoch5_shuffle_result = []
  206. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  207. num_shards=num_shards,
  208. shard_id=partition_id,
  209. padded_sample=padded_sample,
  210. num_padded=num_padded)
  211. assert data_set.get_dataset_size() == dataset_size
  212. data_set = data_set.repeat(repeat_size)
  213. local_index = 0
  214. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  215. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  216. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  217. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  218. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  219. logger.info("-------------- item[label]: {} -----------------------".format(item["label"]))
  220. if item['label'] == -2:
  221. num_padded_iter += 1
  222. assert item['file_name'] == bytes(padded_sample['file_name'], encoding='utf8')
  223. assert item['label'] == padded_sample['label']
  224. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  225. if local_index < dataset_size:
  226. epoch1_shuffle_result.append(item["file_name"])
  227. elif local_index < dataset_size * 2:
  228. epoch2_shuffle_result.append(item["file_name"])
  229. elif local_index < dataset_size * 3:
  230. epoch3_shuffle_result.append(item["file_name"])
  231. elif local_index < dataset_size * 4:
  232. epoch4_shuffle_result.append(item["file_name"])
  233. elif local_index < dataset_size * 5:
  234. epoch5_shuffle_result.append(item["file_name"])
  235. local_index += 1
  236. num_iter += 1
  237. assert len(epoch1_shuffle_result) == dataset_size
  238. assert len(epoch2_shuffle_result) == dataset_size
  239. assert len(epoch3_shuffle_result) == dataset_size
  240. assert len(epoch4_shuffle_result) == dataset_size
  241. assert len(epoch5_shuffle_result) == dataset_size
  242. assert local_index == dataset_size * repeat_size
  243. # When dataset_size is equal to 2, too high probability is the same result after shuffle operation
  244. if dataset_size > 2:
  245. assert epoch1_shuffle_result != epoch2_shuffle_result
  246. assert epoch2_shuffle_result != epoch3_shuffle_result
  247. assert epoch3_shuffle_result != epoch4_shuffle_result
  248. assert epoch4_shuffle_result != epoch5_shuffle_result
  249. assert num_padded_iter == num_padded * repeat_size
  250. assert num_iter == dataset_size * num_shards * repeat_size
  251. partitions(4, 2, 3)
  252. partitions(5, 5, 3)
  253. partitions(9, 8, 2)
  254. def test_cv_minddataset_partition_padded_samples_no_dividsible(add_and_remove_cv_file):
  255. """tutorial for cv minddataset."""
  256. columns_list = ["data", "file_name", "label"]
  257. data = get_data(CV_DIR_NAME)
  258. padded_sample = data[0]
  259. padded_sample['label'] = -2
  260. padded_sample['file_name'] = 'dummy.jpg'
  261. num_readers = 4
  262. def partitions(num_shards, num_padded):
  263. for partition_id in range(num_shards):
  264. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  265. num_shards=num_shards,
  266. shard_id=partition_id,
  267. padded_sample=padded_sample,
  268. num_padded=num_padded)
  269. num_iter = 0
  270. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  271. num_iter += 1
  272. return num_iter
  273. with pytest.raises(RuntimeError):
  274. partitions(4, 1)
  275. def test_cv_minddataset_partition_padded_samples_dataset_size_no_divisible(add_and_remove_cv_file):
  276. columns_list = ["data", "file_name", "label"]
  277. data = get_data(CV_DIR_NAME)
  278. padded_sample = data[0]
  279. padded_sample['label'] = -2
  280. padded_sample['file_name'] = 'dummy.jpg'
  281. num_readers = 4
  282. def partitions(num_shards, num_padded):
  283. for partition_id in range(num_shards):
  284. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  285. num_shards=num_shards,
  286. shard_id=partition_id,
  287. padded_sample=padded_sample,
  288. num_padded=num_padded)
  289. with pytest.raises(RuntimeError):
  290. data_set.get_dataset_size() == 3
  291. partitions(4, 1)
  292. def test_cv_minddataset_partition_padded_samples_no_equal_column_list(add_and_remove_cv_file):
  293. columns_list = ["data", "file_name", "label"]
  294. data = get_data(CV_DIR_NAME)
  295. padded_sample = data[0]
  296. padded_sample.pop('label', None)
  297. padded_sample['file_name'] = 'dummy.jpg'
  298. num_readers = 4
  299. def partitions(num_shards, num_padded):
  300. for partition_id in range(num_shards):
  301. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  302. num_shards=num_shards,
  303. shard_id=partition_id,
  304. padded_sample=padded_sample,
  305. num_padded=num_padded)
  306. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  307. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  308. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  309. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  310. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  311. with pytest.raises(Exception, match="padded_sample cannot match columns_list."):
  312. partitions(4, 2)
  313. def test_cv_minddataset_partition_padded_samples_no_column_list(add_and_remove_cv_file):
  314. data = get_data(CV_DIR_NAME)
  315. padded_sample = data[0]
  316. padded_sample['label'] = -2
  317. padded_sample['file_name'] = 'dummy.jpg'
  318. num_readers = 4
  319. def partitions(num_shards, num_padded):
  320. for partition_id in range(num_shards):
  321. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  322. num_shards=num_shards,
  323. shard_id=partition_id,
  324. padded_sample=padded_sample,
  325. num_padded=num_padded)
  326. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  327. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  328. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  329. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  330. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  331. with pytest.raises(Exception, match="padded_sample is specified and requires columns_list as well."):
  332. partitions(4, 2)
  333. def test_cv_minddataset_partition_padded_samples_no_num_padded(add_and_remove_cv_file):
  334. columns_list = ["data", "file_name", "label"]
  335. data = get_data(CV_DIR_NAME)
  336. padded_sample = data[0]
  337. padded_sample['file_name'] = 'dummy.jpg'
  338. num_readers = 4
  339. def partitions(num_shards, num_padded):
  340. for partition_id in range(num_shards):
  341. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  342. num_shards=num_shards,
  343. shard_id=partition_id,
  344. padded_sample=padded_sample)
  345. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  346. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  347. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  348. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  349. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  350. with pytest.raises(Exception, match="padded_sample is specified and requires num_padded as well."):
  351. partitions(4, 2)
  352. def test_cv_minddataset_partition_padded_samples_no_padded_samples(add_and_remove_cv_file):
  353. columns_list = ["data", "file_name", "label"]
  354. data = get_data(CV_DIR_NAME)
  355. padded_sample = data[0]
  356. padded_sample['file_name'] = 'dummy.jpg'
  357. num_readers = 4
  358. def partitions(num_shards, num_padded):
  359. for partition_id in range(num_shards):
  360. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  361. num_shards=num_shards,
  362. shard_id=partition_id,
  363. num_padded=num_padded)
  364. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  365. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  366. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  367. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  368. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  369. with pytest.raises(Exception, match="num_padded is specified but padded_sample is not."):
  370. partitions(4, 2)
  371. def test_nlp_minddataset_reader_basic_padded_samples(add_and_remove_nlp_file):
  372. columns_list = ["input_ids", "id", "rating"]
  373. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  374. padded_sample = data[0]
  375. padded_sample['id'] = "-1"
  376. padded_sample['input_ids'] = np.array([-1, -1, -1, -1], dtype=np.int64)
  377. padded_sample['rating'] = 1.0
  378. num_readers = 4
  379. def partitions(num_shards, num_padded, dataset_size):
  380. num_padded_iter = 0
  381. num_iter = 0
  382. for partition_id in range(num_shards):
  383. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  384. num_shards=num_shards,
  385. shard_id=partition_id,
  386. padded_sample=padded_sample,
  387. num_padded=num_padded)
  388. assert data_set.get_dataset_size() == dataset_size
  389. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  390. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  391. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  392. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------".format(
  393. item["input_ids"],
  394. item["input_ids"].shape))
  395. if item['id'] == bytes('-1', encoding='utf-8'):
  396. num_padded_iter += 1
  397. assert item['id'] == bytes(padded_sample['id'], encoding='utf-8')
  398. assert (item['input_ids'] == padded_sample['input_ids']).all()
  399. assert (item['rating'] == padded_sample['rating']).all()
  400. num_iter += 1
  401. assert num_padded_iter == num_padded
  402. assert num_iter == dataset_size * num_shards
  403. partitions(4, 6, 4)
  404. partitions(5, 5, 3)
  405. partitions(9, 8, 2)
  406. def test_nlp_minddataset_reader_basic_padded_samples_multi_epoch(add_and_remove_nlp_file):
  407. columns_list = ["input_ids", "id", "rating"]
  408. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  409. padded_sample = data[0]
  410. padded_sample['id'] = "-1"
  411. padded_sample['input_ids'] = np.array([-1, -1, -1, -1], dtype=np.int64)
  412. padded_sample['rating'] = 1.0
  413. num_readers = 4
  414. repeat_size = 3
  415. def partitions(num_shards, num_padded, dataset_size):
  416. num_padded_iter = 0
  417. num_iter = 0
  418. for partition_id in range(num_shards):
  419. epoch1_shuffle_result = []
  420. epoch2_shuffle_result = []
  421. epoch3_shuffle_result = []
  422. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  423. num_shards=num_shards,
  424. shard_id=partition_id,
  425. padded_sample=padded_sample,
  426. num_padded=num_padded)
  427. assert data_set.get_dataset_size() == dataset_size
  428. data_set = data_set.repeat(repeat_size)
  429. local_index = 0
  430. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  431. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  432. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  433. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------".format(
  434. item["input_ids"],
  435. item["input_ids"].shape))
  436. if item['id'] == bytes('-1', encoding='utf-8'):
  437. num_padded_iter += 1
  438. assert item['id'] == bytes(padded_sample['id'], encoding='utf-8')
  439. assert (item['input_ids'] == padded_sample['input_ids']).all()
  440. assert (item['rating'] == padded_sample['rating']).all()
  441. if local_index < dataset_size:
  442. epoch1_shuffle_result.append(item['id'])
  443. elif local_index < dataset_size * 2:
  444. epoch2_shuffle_result.append(item['id'])
  445. elif local_index < dataset_size * 3:
  446. epoch3_shuffle_result.append(item['id'])
  447. local_index += 1
  448. num_iter += 1
  449. assert len(epoch1_shuffle_result) == dataset_size
  450. assert len(epoch2_shuffle_result) == dataset_size
  451. assert len(epoch3_shuffle_result) == dataset_size
  452. assert local_index == dataset_size * repeat_size
  453. # When dataset_size is equal to 2, too high probability is the same result after shuffle operation
  454. if dataset_size > 2:
  455. assert epoch1_shuffle_result != epoch2_shuffle_result
  456. assert epoch2_shuffle_result != epoch3_shuffle_result
  457. assert num_padded_iter == num_padded * repeat_size
  458. assert num_iter == dataset_size * num_shards * repeat_size
  459. partitions(4, 6, 4)
  460. partitions(5, 5, 3)
  461. partitions(9, 8, 2)
  462. def test_nlp_minddataset_reader_basic_padded_samples_check_whole_reshuffle_result_per_epoch(add_and_remove_nlp_file):
  463. columns_list = ["input_ids", "id", "rating"]
  464. padded_sample = {}
  465. padded_sample['id'] = "-1"
  466. padded_sample['input_ids'] = np.array([-1, -1, -1, -1], dtype=np.int64)
  467. padded_sample['rating'] = 1.0
  468. num_readers = 4
  469. repeat_size = 3
  470. def partitions(num_shards, num_padded, dataset_size):
  471. num_padded_iter = 0
  472. num_iter = 0
  473. epoch_result = [[["" for i in range(dataset_size)] for i in range(repeat_size)] for i in range(num_shards)]
  474. for partition_id in range(num_shards):
  475. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  476. num_shards=num_shards,
  477. shard_id=partition_id,
  478. padded_sample=padded_sample,
  479. num_padded=num_padded)
  480. assert data_set.get_dataset_size() == dataset_size
  481. data_set = data_set.repeat(repeat_size)
  482. inner_num_iter = 0
  483. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  484. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  485. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  486. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------"
  487. .format(item["input_ids"], item["input_ids"].shape))
  488. if item['id'] == bytes('-1', encoding='utf-8'):
  489. num_padded_iter += 1
  490. assert item['id'] == bytes(padded_sample['id'], encoding='utf-8')
  491. assert (item['input_ids'] == padded_sample['input_ids']).all()
  492. assert (item['rating'] == padded_sample['rating']).all()
  493. # save epoch result
  494. epoch_result[partition_id][int(inner_num_iter / dataset_size)][inner_num_iter % dataset_size] = item[
  495. "id"]
  496. num_iter += 1
  497. inner_num_iter += 1
  498. assert epoch_result[partition_id][0] not in (epoch_result[partition_id][1], epoch_result[partition_id][2])
  499. assert epoch_result[partition_id][1] not in (epoch_result[partition_id][0], epoch_result[partition_id][2])
  500. assert epoch_result[partition_id][2] not in (epoch_result[partition_id][1], epoch_result[partition_id][0])
  501. if dataset_size > 2:
  502. epoch_result[partition_id][0].sort()
  503. epoch_result[partition_id][1].sort()
  504. epoch_result[partition_id][2].sort()
  505. assert epoch_result[partition_id][0] != epoch_result[partition_id][1]
  506. assert epoch_result[partition_id][1] != epoch_result[partition_id][2]
  507. assert epoch_result[partition_id][2] != epoch_result[partition_id][0]
  508. assert num_padded_iter == num_padded * repeat_size
  509. assert num_iter == dataset_size * num_shards * repeat_size
  510. partitions(4, 6, 4)
  511. partitions(5, 5, 3)
  512. partitions(9, 8, 2)
  513. def get_data(dir_name):
  514. """
  515. usage: get data from imagenet dataset
  516. params:
  517. dir_name: directory containing folder images and annotation information
  518. """
  519. if not os.path.isdir(dir_name):
  520. raise IOError("Directory {} not exists".format(dir_name))
  521. img_dir = os.path.join(dir_name, "images")
  522. ann_file = os.path.join(dir_name, "annotation.txt")
  523. with open(ann_file, "r") as file_reader:
  524. lines = file_reader.readlines()
  525. data_list = []
  526. for i, line in enumerate(lines):
  527. try:
  528. filename, label = line.split(",")
  529. label = label.strip("\n")
  530. with open(os.path.join(img_dir, filename), "rb") as file_reader:
  531. img = file_reader.read()
  532. data_json = {"id": i,
  533. "file_name": filename,
  534. "data": img,
  535. "label": int(label)}
  536. data_list.append(data_json)
  537. except FileNotFoundError:
  538. continue
  539. return data_list
  540. def get_nlp_data(dir_name, vocab_file, num):
  541. """
  542. Return raw data of aclImdb dataset.
  543. Args:
  544. dir_name (str): String of aclImdb dataset's path.
  545. vocab_file (str): String of dictionary's path.
  546. num (int): Number of sample.
  547. Returns:
  548. List
  549. """
  550. if not os.path.isdir(dir_name):
  551. raise IOError("Directory {} not exists".format(dir_name))
  552. for root, dirs, files in os.walk(dir_name):
  553. for index, file_name_extension in enumerate(files):
  554. if index < num:
  555. file_path = os.path.join(root, file_name_extension)
  556. file_name, _ = file_name_extension.split('.', 1)
  557. id_, rating = file_name.split('_', 1)
  558. with open(file_path, 'r') as f:
  559. raw_content = f.read()
  560. dictionary = load_vocab(vocab_file)
  561. vectors = [dictionary.get('[CLS]')]
  562. vectors += [dictionary.get(i) if i in dictionary
  563. else dictionary.get('[UNK]')
  564. for i in re.findall(r"[\w']+|[{}]"
  565. .format(string.punctuation),
  566. raw_content)]
  567. vectors += [dictionary.get('[SEP]')]
  568. input_, mask, segment = inputs(vectors)
  569. input_ids = np.reshape(np.array(input_), [-1])
  570. input_mask = np.reshape(np.array(mask), [1, -1])
  571. segment_ids = np.reshape(np.array(segment), [2, -1])
  572. data = {
  573. "label": 1,
  574. "id": id_,
  575. "rating": float(rating),
  576. "input_ids": input_ids,
  577. "input_mask": input_mask,
  578. "segment_ids": segment_ids
  579. }
  580. yield data
  581. def convert_to_uni(text):
  582. if isinstance(text, str):
  583. return text
  584. if isinstance(text, bytes):
  585. return text.decode('utf-8', 'ignore')
  586. raise Exception("The type %s does not convert!" % type(text))
  587. def load_vocab(vocab_file):
  588. """load vocabulary to translate statement."""
  589. vocab = collections.OrderedDict()
  590. vocab.setdefault('blank', 2)
  591. index = 0
  592. with open(vocab_file) as reader:
  593. while True:
  594. tmp = reader.readline()
  595. if not tmp:
  596. break
  597. token = convert_to_uni(tmp)
  598. token = token.strip()
  599. vocab[token] = index
  600. index += 1
  601. return vocab
  602. def inputs(vectors, maxlen=50):
  603. length = len(vectors)
  604. if length > maxlen:
  605. return vectors[0:maxlen], [1] * maxlen, [0] * maxlen
  606. input_ = vectors + [0] * (maxlen - length)
  607. mask = [1] * length + [0] * (maxlen - length)
  608. segment = [0] * maxlen
  609. return input_, mask, segment
  610. if __name__ == '__main__':
  611. test_cv_minddataset_reader_basic_padded_samples(add_and_remove_cv_file)
  612. test_cv_minddataset_partition_padded_samples(add_and_remove_cv_file)
  613. test_cv_minddataset_partition_padded_samples_multi_epoch(add_and_remove_cv_file)
  614. test_cv_minddataset_partition_padded_samples_no_dividsible(add_and_remove_cv_file)
  615. test_cv_minddataset_partition_padded_samples_dataset_size_no_divisible(add_and_remove_cv_file)
  616. test_cv_minddataset_partition_padded_samples_no_equal_column_list(add_and_remove_cv_file)
  617. test_cv_minddataset_partition_padded_samples_no_column_list(add_and_remove_cv_file)
  618. test_cv_minddataset_partition_padded_samples_no_num_padded(add_and_remove_cv_file)
  619. test_cv_minddataset_partition_padded_samples_no_padded_samples(add_and_remove_cv_file)
  620. test_nlp_minddataset_reader_basic_padded_samples(add_and_remove_nlp_file)
  621. test_nlp_minddataset_reader_basic_padded_samples_multi_epoch(add_and_remove_nlp_file)
  622. test_nlp_minddataset_reader_basic_padded_samples_check_whole_reshuffle_result_per_epoch(add_and_remove_nlp_file)