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_exception.py 14 kB

6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #!/usr/bin/env python
  2. # Copyright 2019-2021 Huawei Technologies Co., Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # ==============================================================================
  16. import os
  17. import pytest
  18. import mindspore.dataset as ds
  19. from mindspore.mindrecord import FileWriter
  20. CV_FILE_NAME = "./imagenet.mindrecord"
  21. CV1_FILE_NAME = "./imagenet1.mindrecord"
  22. def create_cv_mindrecord(files_num):
  23. """tutorial for cv dataset writer."""
  24. if os.path.exists(CV_FILE_NAME):
  25. os.remove(CV_FILE_NAME)
  26. if os.path.exists("{}.db".format(CV_FILE_NAME)):
  27. os.remove("{}.db".format(CV_FILE_NAME))
  28. writer = FileWriter(CV_FILE_NAME, files_num)
  29. cv_schema_json = {"file_name": {"type": "string"},
  30. "label": {"type": "int32"}, "data": {"type": "bytes"}}
  31. data = [{"file_name": "001.jpg", "label": 43,
  32. "data": bytes('0xffsafdafda', encoding='utf-8')}]
  33. writer.add_schema(cv_schema_json, "img_schema")
  34. writer.add_index(["file_name", "label"])
  35. writer.write_raw_data(data)
  36. writer.commit()
  37. def create_diff_schema_cv_mindrecord(files_num):
  38. """tutorial for cv dataset writer."""
  39. if os.path.exists(CV1_FILE_NAME):
  40. os.remove(CV1_FILE_NAME)
  41. if os.path.exists("{}.db".format(CV1_FILE_NAME)):
  42. os.remove("{}.db".format(CV1_FILE_NAME))
  43. writer = FileWriter(CV1_FILE_NAME, files_num)
  44. cv_schema_json = {"file_name_1": {"type": "string"},
  45. "label": {"type": "int32"}, "data": {"type": "bytes"}}
  46. data = [{"file_name_1": "001.jpg", "label": 43,
  47. "data": bytes('0xffsafdafda', encoding='utf-8')}]
  48. writer.add_schema(cv_schema_json, "img_schema")
  49. writer.add_index(["file_name_1", "label"])
  50. writer.write_raw_data(data)
  51. writer.commit()
  52. def create_diff_page_size_cv_mindrecord(files_num):
  53. """tutorial for cv dataset writer."""
  54. if os.path.exists(CV1_FILE_NAME):
  55. os.remove(CV1_FILE_NAME)
  56. if os.path.exists("{}.db".format(CV1_FILE_NAME)):
  57. os.remove("{}.db".format(CV1_FILE_NAME))
  58. writer = FileWriter(CV1_FILE_NAME, files_num)
  59. writer.set_page_size(1 << 26) # 64MB
  60. cv_schema_json = {"file_name": {"type": "string"},
  61. "label": {"type": "int32"}, "data": {"type": "bytes"}}
  62. data = [{"file_name": "001.jpg", "label": 43,
  63. "data": bytes('0xffsafdafda', encoding='utf-8')}]
  64. writer.add_schema(cv_schema_json, "img_schema")
  65. writer.add_index(["file_name", "label"])
  66. writer.write_raw_data(data)
  67. writer.commit()
  68. def test_cv_lack_json():
  69. """tutorial for cv minderdataset."""
  70. create_cv_mindrecord(1)
  71. columns_list = ["data", "file_name", "label"]
  72. num_readers = 4
  73. with pytest.raises(Exception):
  74. ds.MindDataset(CV_FILE_NAME, "no_exist.json",
  75. columns_list, num_readers)
  76. os.remove(CV_FILE_NAME)
  77. os.remove("{}.db".format(CV_FILE_NAME))
  78. def test_cv_lack_mindrecord():
  79. """tutorial for cv minderdataset."""
  80. columns_list = ["data", "file_name", "label"]
  81. num_readers = 4
  82. with pytest.raises(Exception, match="does not exist or permission denied"):
  83. _ = ds.MindDataset("no_exist.mindrecord", columns_list, num_readers)
  84. def test_invalid_mindrecord():
  85. with open('dummy.mindrecord', 'w') as f:
  86. f.write('just for test')
  87. columns_list = ["data", "file_name", "label"]
  88. num_readers = 4
  89. with pytest.raises(RuntimeError, match="Unexpected error. Invalid file "
  90. "content, incorrect file or file header is exceeds the upper limit."):
  91. data_set = ds.MindDataset(
  92. 'dummy.mindrecord', columns_list, num_readers)
  93. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  94. pass
  95. os.remove('dummy.mindrecord')
  96. def test_minddataset_lack_db():
  97. create_cv_mindrecord(1)
  98. os.remove("{}.db".format(CV_FILE_NAME))
  99. columns_list = ["data", "file_name", "label"]
  100. num_readers = 4
  101. with pytest.raises(RuntimeError, match="Unexpected error. Invalid database file, path:"):
  102. data_set = ds.MindDataset(CV_FILE_NAME, columns_list, num_readers)
  103. num_iter = 0
  104. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  105. num_iter += 1
  106. try:
  107. assert num_iter == 0
  108. except Exception as error:
  109. os.remove(CV_FILE_NAME)
  110. raise error
  111. else:
  112. os.remove(CV_FILE_NAME)
  113. def test_cv_minddataset_pk_sample_error_class_column():
  114. create_cv_mindrecord(1)
  115. columns_list = ["data", "file_name", "label"]
  116. num_readers = 4
  117. sampler = ds.PKSampler(5, None, True, 'no_exist_column')
  118. with pytest.raises(RuntimeError, match="Unexpected error. Failed to launch read threads."):
  119. data_set = ds.MindDataset(
  120. CV_FILE_NAME, columns_list, num_readers, sampler=sampler)
  121. num_iter = 0
  122. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  123. num_iter += 1
  124. os.remove(CV_FILE_NAME)
  125. os.remove("{}.db".format(CV_FILE_NAME))
  126. def test_cv_minddataset_pk_sample_exclusive_shuffle():
  127. create_cv_mindrecord(1)
  128. columns_list = ["data", "file_name", "label"]
  129. num_readers = 4
  130. sampler = ds.PKSampler(2)
  131. with pytest.raises(Exception, match="sampler and shuffle cannot be specified at the same time."):
  132. data_set = ds.MindDataset(CV_FILE_NAME, columns_list, num_readers,
  133. sampler=sampler, shuffle=False)
  134. num_iter = 0
  135. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  136. num_iter += 1
  137. os.remove(CV_FILE_NAME)
  138. os.remove("{}.db".format(CV_FILE_NAME))
  139. def test_cv_minddataset_reader_different_schema():
  140. create_cv_mindrecord(1)
  141. create_diff_schema_cv_mindrecord(1)
  142. columns_list = ["data", "label"]
  143. num_readers = 4
  144. with pytest.raises(RuntimeError, match="Unexpected error. Invalid data, "
  145. "MindRecord files meta data is not consistent."):
  146. data_set = ds.MindDataset([CV_FILE_NAME, CV1_FILE_NAME], columns_list,
  147. num_readers)
  148. num_iter = 0
  149. for _ in data_set.create_dict_iterator(num_epochs=1):
  150. num_iter += 1
  151. os.remove(CV_FILE_NAME)
  152. os.remove("{}.db".format(CV_FILE_NAME))
  153. os.remove(CV1_FILE_NAME)
  154. os.remove("{}.db".format(CV1_FILE_NAME))
  155. def test_cv_minddataset_reader_different_page_size():
  156. create_cv_mindrecord(1)
  157. create_diff_page_size_cv_mindrecord(1)
  158. columns_list = ["data", "label"]
  159. num_readers = 4
  160. with pytest.raises(RuntimeError, match="Unexpected error. Invalid data, "
  161. "MindRecord files meta data is not consistent."):
  162. data_set = ds.MindDataset([CV_FILE_NAME, CV1_FILE_NAME], columns_list,
  163. num_readers)
  164. num_iter = 0
  165. for _ in data_set.create_dict_iterator(num_epochs=1):
  166. num_iter += 1
  167. os.remove(CV_FILE_NAME)
  168. os.remove("{}.db".format(CV_FILE_NAME))
  169. os.remove(CV1_FILE_NAME)
  170. os.remove("{}.db".format(CV1_FILE_NAME))
  171. def test_minddataset_invalidate_num_shards():
  172. create_cv_mindrecord(1)
  173. columns_list = ["data", "label"]
  174. num_readers = 4
  175. with pytest.raises(Exception) as error_info:
  176. data_set = ds.MindDataset(
  177. CV_FILE_NAME, columns_list, num_readers, True, 1, 2)
  178. num_iter = 0
  179. for _ in data_set.create_dict_iterator(num_epochs=1):
  180. num_iter += 1
  181. try:
  182. assert 'Input shard_id is not within the required interval of [0, 0].' in str(
  183. error_info.value)
  184. except Exception as error:
  185. os.remove(CV_FILE_NAME)
  186. os.remove("{}.db".format(CV_FILE_NAME))
  187. raise error
  188. else:
  189. os.remove(CV_FILE_NAME)
  190. os.remove("{}.db".format(CV_FILE_NAME))
  191. def test_minddataset_invalidate_shard_id():
  192. create_cv_mindrecord(1)
  193. columns_list = ["data", "label"]
  194. num_readers = 4
  195. with pytest.raises(Exception) as error_info:
  196. data_set = ds.MindDataset(
  197. CV_FILE_NAME, columns_list, num_readers, True, 1, -1)
  198. num_iter = 0
  199. for _ in data_set.create_dict_iterator(num_epochs=1):
  200. num_iter += 1
  201. try:
  202. assert 'Input shard_id is not within the required interval of [0, 0].' in str(
  203. error_info.value)
  204. except Exception as error:
  205. os.remove(CV_FILE_NAME)
  206. os.remove("{}.db".format(CV_FILE_NAME))
  207. raise error
  208. else:
  209. os.remove(CV_FILE_NAME)
  210. os.remove("{}.db".format(CV_FILE_NAME))
  211. def test_minddataset_shard_id_bigger_than_num_shard():
  212. create_cv_mindrecord(1)
  213. columns_list = ["data", "label"]
  214. num_readers = 4
  215. with pytest.raises(Exception) as error_info:
  216. data_set = ds.MindDataset(
  217. CV_FILE_NAME, columns_list, num_readers, True, 2, 2)
  218. num_iter = 0
  219. for _ in data_set.create_dict_iterator(num_epochs=1):
  220. num_iter += 1
  221. try:
  222. assert 'Input shard_id is not within the required interval of [0, 1].' in str(
  223. error_info.value)
  224. except Exception as error:
  225. os.remove(CV_FILE_NAME)
  226. os.remove("{}.db".format(CV_FILE_NAME))
  227. raise error
  228. with pytest.raises(Exception) as error_info:
  229. data_set = ds.MindDataset(
  230. CV_FILE_NAME, columns_list, num_readers, True, 2, 5)
  231. num_iter = 0
  232. for _ in data_set.create_dict_iterator(num_epochs=1):
  233. num_iter += 1
  234. try:
  235. assert 'Input shard_id is not within the required interval of [0, 1].' in str(
  236. error_info.value)
  237. except Exception as error:
  238. os.remove(CV_FILE_NAME)
  239. os.remove("{}.db".format(CV_FILE_NAME))
  240. raise error
  241. else:
  242. os.remove(CV_FILE_NAME)
  243. os.remove("{}.db".format(CV_FILE_NAME))
  244. def test_cv_minddataset_partition_num_samples_equals_0():
  245. """tutorial for cv minddataset."""
  246. create_cv_mindrecord(1)
  247. columns_list = ["data", "label"]
  248. num_readers = 4
  249. def partitions(num_shards):
  250. for partition_id in range(num_shards):
  251. data_set = ds.MindDataset(CV_FILE_NAME, columns_list, num_readers,
  252. num_shards=num_shards,
  253. shard_id=partition_id, num_samples=-1)
  254. num_iter = 0
  255. for _ in data_set.create_dict_iterator(num_epochs=1):
  256. num_iter += 1
  257. with pytest.raises(ValueError) as error_info:
  258. partitions(5)
  259. try:
  260. assert 'num_samples exceeds the boundary between 0 and 9223372036854775807(INT64_MAX)' in str(
  261. error_info.value)
  262. except Exception as error:
  263. os.remove(CV_FILE_NAME)
  264. os.remove("{}.db".format(CV_FILE_NAME))
  265. raise error
  266. else:
  267. os.remove(CV_FILE_NAME)
  268. os.remove("{}.db".format(CV_FILE_NAME))
  269. def test_mindrecord_exception():
  270. """tutorial for exception scenario of minderdataset + map would print error info."""
  271. def exception_func(item):
  272. raise Exception("Error occur!")
  273. create_cv_mindrecord(1)
  274. columns_list = ["data", "file_name", "label"]
  275. with pytest.raises(RuntimeError, match="The corresponding data files"):
  276. data_set = ds.MindDataset(CV_FILE_NAME, columns_list, shuffle=False)
  277. data_set = data_set.map(operations=exception_func, input_columns=["data"],
  278. num_parallel_workers=1)
  279. num_iter = 0
  280. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  281. num_iter += 1
  282. with pytest.raises(RuntimeError, match="The corresponding data files"):
  283. data_set = ds.MindDataset(CV_FILE_NAME, columns_list, shuffle=False)
  284. data_set = data_set.map(operations=exception_func, input_columns=["file_name"],
  285. num_parallel_workers=1)
  286. num_iter = 0
  287. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  288. num_iter += 1
  289. with pytest.raises(RuntimeError, match="The corresponding data files"):
  290. data_set = ds.MindDataset(CV_FILE_NAME, columns_list, shuffle=False)
  291. data_set = data_set.map(operations=exception_func, input_columns=["label"],
  292. num_parallel_workers=1)
  293. num_iter = 0
  294. for _ in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  295. num_iter += 1
  296. os.remove(CV_FILE_NAME)
  297. os.remove("{}.db".format(CV_FILE_NAME))
  298. if __name__ == '__main__':
  299. test_cv_lack_json()
  300. test_cv_lack_mindrecord()
  301. test_invalid_mindrecord()
  302. test_minddataset_lack_db()
  303. test_cv_minddataset_pk_sample_error_class_column()
  304. test_cv_minddataset_pk_sample_exclusive_shuffle()
  305. test_cv_minddataset_reader_different_schema()
  306. test_cv_minddataset_reader_different_page_size()
  307. test_minddataset_invalidate_num_shards()
  308. test_minddataset_invalidate_shard_id()
  309. test_minddataset_shard_id_bigger_than_num_shard()
  310. test_cv_minddataset_partition_num_samples_equals_0()
  311. test_mindrecord_exception()