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_config.py 15 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. # Copyright 2019 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. Testing configuration manager
  17. """
  18. import os
  19. import filecmp
  20. import glob
  21. import numpy as np
  22. import mindspore.dataset as ds
  23. import mindspore.dataset.transforms.vision.c_transforms as c_vision
  24. import mindspore.dataset.transforms.vision.py_transforms as py_vision
  25. from mindspore import log as logger
  26. DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  27. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  28. def test_basic():
  29. """
  30. Test basic configuration functions
  31. """
  32. # Save original configuration values
  33. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  34. prefetch_size_original = ds.config.get_prefetch_size()
  35. seed_original = ds.config.get_seed()
  36. monitor_sampling_interval_original = ds.config.get_monitor_sampling_interval()
  37. ds.config.load('../data/dataset/declient.cfg')
  38. # assert ds.config.get_rows_per_buffer() == 32
  39. assert ds.config.get_num_parallel_workers() == 4
  40. # assert ds.config.get_worker_connector_size() == 16
  41. assert ds.config.get_prefetch_size() == 16
  42. assert ds.config.get_seed() == 5489
  43. assert ds.config.get_monitor_sampling_interval() == 15
  44. # ds.config.set_rows_per_buffer(1)
  45. ds.config.set_num_parallel_workers(2)
  46. # ds.config.set_worker_connector_size(3)
  47. ds.config.set_prefetch_size(4)
  48. ds.config.set_seed(5)
  49. ds.config.set_monitor_sampling_interval(45)
  50. # assert ds.config.get_rows_per_buffer() == 1
  51. assert ds.config.get_num_parallel_workers() == 2
  52. # assert ds.config.get_worker_connector_size() == 3
  53. assert ds.config.get_prefetch_size() == 4
  54. assert ds.config.get_seed() == 5
  55. assert ds.config.get_monitor_sampling_interval() == 45
  56. # Restore original configuration values
  57. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  58. ds.config.set_prefetch_size(prefetch_size_original)
  59. ds.config.set_seed(seed_original)
  60. ds.config.set_monitor_sampling_interval(monitor_sampling_interval_original)
  61. def test_get_seed():
  62. """
  63. This gets the seed value without explicitly setting a default, expect int.
  64. """
  65. assert isinstance(ds.config.get_seed(), int)
  66. def test_pipeline():
  67. """
  68. Test that our configuration pipeline works when we set parameters at different locations in dataset code
  69. """
  70. # Save original configuration values
  71. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  72. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False)
  73. data1 = data1.map(input_columns=["image"], operations=[c_vision.Decode(True)])
  74. ds.serialize(data1, "testpipeline.json")
  75. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, num_parallel_workers=num_parallel_workers_original,
  76. shuffle=False)
  77. data2 = data2.map(input_columns=["image"], operations=[c_vision.Decode(True)])
  78. ds.serialize(data2, "testpipeline2.json")
  79. # check that the generated output is different
  80. assert filecmp.cmp('testpipeline.json', 'testpipeline2.json')
  81. # this test passes currently because our num_parallel_workers don't get updated.
  82. # remove generated jason files
  83. file_list = glob.glob('*.json')
  84. for f in file_list:
  85. try:
  86. os.remove(f)
  87. except IOError:
  88. logger.info("Error while deleting: {}".format(f))
  89. # Restore original configuration values
  90. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  91. def test_deterministic_run_fail():
  92. """
  93. Test RandomCrop with seed, expected to fail
  94. """
  95. logger.info("test_deterministic_run_fail")
  96. # Save original configuration values
  97. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  98. seed_original = ds.config.get_seed()
  99. # when we set the seed all operations within our dataset should be deterministic
  100. ds.config.set_seed(0)
  101. ds.config.set_num_parallel_workers(1)
  102. # First dataset
  103. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  104. # Assuming we get the same seed on calling constructor, if this op is re-used then result won't be
  105. # the same in between the two datasets. For example, RandomCrop constructor takes seed (0)
  106. # outputs a deterministic series of numbers, e,g "a" = [1, 2, 3, 4, 5, 6] <- pretend these are random
  107. random_crop_op = c_vision.RandomCrop([512, 512], [200, 200, 200, 200])
  108. decode_op = c_vision.Decode()
  109. data1 = data1.map(input_columns=["image"], operations=decode_op)
  110. data1 = data1.map(input_columns=["image"], operations=random_crop_op)
  111. # Second dataset
  112. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  113. data2 = data2.map(input_columns=["image"], operations=decode_op)
  114. # If seed is set up on constructor
  115. data2 = data2.map(input_columns=["image"], operations=random_crop_op)
  116. try:
  117. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  118. np.testing.assert_equal(item1["image"], item2["image"])
  119. except Exception as e:
  120. # two datasets split the number out of the sequence a
  121. logger.info("Got an exception in DE: {}".format(str(e)))
  122. assert "Array" in str(e)
  123. # Restore original configuration values
  124. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  125. ds.config.set_seed(seed_original)
  126. def test_seed_undeterministic():
  127. """
  128. Test seed with num parallel workers in c, this test is expected to fail some of the time
  129. """
  130. logger.info("test_seed_undeterministic")
  131. # Save original configuration values
  132. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  133. seed_original = ds.config.get_seed()
  134. ds.config.set_seed(0)
  135. ds.config.set_num_parallel_workers(3)
  136. # First dataset
  137. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  138. # We get the seed when constructor is called
  139. random_crop_op = c_vision.RandomCrop([512, 512], [200, 200, 200, 200])
  140. decode_op = c_vision.Decode()
  141. data1 = data1.map(input_columns=["image"], operations=decode_op)
  142. data1 = data1.map(input_columns=["image"], operations=random_crop_op)
  143. # Second dataset
  144. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  145. data2 = data2.map(input_columns=["image"], operations=decode_op)
  146. # Since seed is set up on constructor, so the two ops output deterministic sequence.
  147. # Assume the generated random sequence "a" = [1, 2, 3, 4, 5, 6] <- pretend these are random
  148. random_crop_op2 = c_vision.RandomCrop([512, 512], [200, 200, 200, 200])
  149. data2 = data2.map(input_columns=["image"], operations=random_crop_op2)
  150. try:
  151. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  152. np.testing.assert_equal(item1["image"], item2["image"])
  153. except Exception as e:
  154. # two datasets both use numbers from the generated sequence "a"
  155. logger.info("Got an exception in DE: {}".format(str(e)))
  156. assert "Array" in str(e)
  157. # Restore original configuration values
  158. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  159. ds.config.set_seed(seed_original)
  160. def test_seed_deterministic():
  161. """
  162. Test deterministic run with setting the seed, only works with num_parallel worker = 1
  163. """
  164. logger.info("test_seed_deterministic")
  165. # Save original configuration values
  166. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  167. seed_original = ds.config.get_seed()
  168. ds.config.set_seed(0)
  169. ds.config.set_num_parallel_workers(1)
  170. # First dataset
  171. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  172. # seed will be read in during constructor call
  173. random_crop_op = c_vision.RandomCrop([512, 512], [200, 200, 200, 200])
  174. decode_op = c_vision.Decode()
  175. data1 = data1.map(input_columns=["image"], operations=decode_op)
  176. data1 = data1.map(input_columns=["image"], operations=random_crop_op)
  177. # Second dataset
  178. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  179. data2 = data2.map(input_columns=["image"], operations=decode_op)
  180. # If seed is set up on constructor, so the two ops output deterministic sequence
  181. random_crop_op2 = c_vision.RandomCrop([512, 512], [200, 200, 200, 200])
  182. data2 = data2.map(input_columns=["image"], operations=random_crop_op2)
  183. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  184. np.testing.assert_equal(item1["image"], item2["image"])
  185. # Restore original configuration values
  186. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  187. ds.config.set_seed(seed_original)
  188. def test_deterministic_run_distribution():
  189. """
  190. Test deterministic run with with setting the seed being used in a distribution
  191. """
  192. logger.info("test_deterministic_run_distribution")
  193. # Save original configuration values
  194. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  195. seed_original = ds.config.get_seed()
  196. # when we set the seed all operations within our dataset should be deterministic
  197. ds.config.set_seed(0)
  198. ds.config.set_num_parallel_workers(1)
  199. # First dataset
  200. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  201. random_horizontal_flip_op = c_vision.RandomHorizontalFlip(0.1)
  202. decode_op = c_vision.Decode()
  203. data1 = data1.map(input_columns=["image"], operations=decode_op)
  204. data1 = data1.map(input_columns=["image"], operations=random_horizontal_flip_op)
  205. # Second dataset
  206. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  207. data2 = data2.map(input_columns=["image"], operations=decode_op)
  208. # If seed is set up on constructor, so the two ops output deterministic sequence
  209. random_horizontal_flip_op2 = c_vision.RandomHorizontalFlip(0.1)
  210. data2 = data2.map(input_columns=["image"], operations=random_horizontal_flip_op2)
  211. for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
  212. np.testing.assert_equal(item1["image"], item2["image"])
  213. # Restore original configuration values
  214. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  215. ds.config.set_seed(seed_original)
  216. def test_deterministic_python_seed():
  217. """
  218. Test deterministic execution with seed in python
  219. """
  220. logger.info("test_deterministic_python_seed")
  221. # Save original configuration values
  222. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  223. seed_original = ds.config.get_seed()
  224. ds.config.set_seed(0)
  225. ds.config.set_num_parallel_workers(1)
  226. # First dataset
  227. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  228. transforms = [
  229. py_vision.Decode(),
  230. py_vision.RandomCrop([512, 512], [200, 200, 200, 200]),
  231. py_vision.ToTensor(),
  232. ]
  233. transform = py_vision.ComposeOp(transforms)
  234. data1 = data1.map(input_columns=["image"], operations=transform())
  235. data1_output = []
  236. # config.set_seed() calls random.seed()
  237. for data_one in data1.create_dict_iterator():
  238. data1_output.append(data_one["image"])
  239. # Second dataset
  240. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  241. data2 = data2.map(input_columns=["image"], operations=transform())
  242. # config.set_seed() calls random.seed(), resets seed for next dataset iterator
  243. ds.config.set_seed(0)
  244. data2_output = []
  245. for data_two in data2.create_dict_iterator():
  246. data2_output.append(data_two["image"])
  247. np.testing.assert_equal(data1_output, data2_output)
  248. # Restore original configuration values
  249. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  250. ds.config.set_seed(seed_original)
  251. def test_deterministic_python_seed_multi_thread():
  252. """
  253. Test deterministic execution with seed in python, this fails with multi-thread pyfunc run
  254. """
  255. logger.info("test_deterministic_python_seed_multi_thread")
  256. # Save original configuration values
  257. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  258. seed_original = ds.config.get_seed()
  259. ds.config.set_num_parallel_workers(3)
  260. ds.config.set_seed(0)
  261. # when we set the seed all operations within our dataset should be deterministic
  262. # First dataset
  263. data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  264. transforms = [
  265. py_vision.Decode(),
  266. py_vision.RandomCrop([512, 512], [200, 200, 200, 200]),
  267. py_vision.ToTensor(),
  268. ]
  269. transform = py_vision.ComposeOp(transforms)
  270. data1 = data1.map(input_columns=["image"], operations=transform(), python_multiprocessing=True)
  271. data1_output = []
  272. # config.set_seed() calls random.seed()
  273. for data_one in data1.create_dict_iterator():
  274. data1_output.append(data_one["image"])
  275. # Second dataset
  276. data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
  277. # If seed is set up on constructor
  278. data2 = data2.map(input_columns=["image"], operations=transform(), python_multiprocessing=True)
  279. # config.set_seed() calls random.seed()
  280. ds.config.set_seed(0)
  281. data2_output = []
  282. for data_two in data2.create_dict_iterator():
  283. data2_output.append(data_two["image"])
  284. try:
  285. np.testing.assert_equal(data1_output, data2_output)
  286. except Exception as e:
  287. # expect output to not match during multi-threaded excution
  288. logger.info("Got an exception in DE: {}".format(str(e)))
  289. assert "Array" in str(e)
  290. # Restore original configuration values
  291. ds.config.set_num_parallel_workers(num_parallel_workers_original)
  292. ds.config.set_seed(seed_original)
  293. if __name__ == '__main__':
  294. test_basic()
  295. test_get_seed()
  296. test_pipeline()
  297. test_deterministic_run_fail()
  298. test_seed_undeterministic()
  299. test_seed_deterministic()
  300. test_deterministic_run_distribution()
  301. test_deterministic_python_seed()
  302. test_deterministic_python_seed_multi_thread()