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 30 kB

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