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_var_batch_map.py 16 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. import numpy as np
  16. import mindspore.dataset as ds
  17. from mindspore import log as logger
  18. def test_batch_corner_cases():
  19. def gen(num):
  20. for i in range(num):
  21. yield (np.array([i]),)
  22. def test_repeat_batch(gen_num, repeats, batch_size, drop, res):
  23. data1 = ds.GeneratorDataset((lambda: gen(gen_num)), ["num"]).repeat(repeats).batch(batch_size, drop)
  24. for item in data1.create_dict_iterator():
  25. res.append(item["num"])
  26. def test_batch_repeat(gen_num, repeats, batch_size, drop, res):
  27. data1 = ds.GeneratorDataset((lambda: gen(gen_num)), ["num"]).batch(batch_size, drop).repeat(repeats)
  28. for item in data1.create_dict_iterator():
  29. res.append(item["num"])
  30. tst1, tst2, tst3, tst4 = [], [], [], []
  31. # case 1 & 2, where batch_size is greater than the entire epoch, with drop equals to both val
  32. test_repeat_batch(gen_num=2, repeats=4, batch_size=7, drop=False, res=tst1)
  33. assert np.array_equal(np.array([[0], [1], [0], [1], [0], [1], [0]]), tst1[0]), "\nATTENTION BATCH FAILED\n"
  34. assert np.array_equal(np.array([[1]]), tst1[1]), "\nATTENTION TEST BATCH FAILED\n"
  35. assert len(tst1) == 2, "\nATTENTION TEST BATCH FAILED\n"
  36. test_repeat_batch(gen_num=2, repeats=4, batch_size=5, drop=True, res=tst2)
  37. assert np.array_equal(np.array([[0], [1], [0], [1], [0]]), tst2[0]), "\nATTENTION BATCH FAILED\n"
  38. assert len(tst2) == 1, "\nATTENTION TEST BATCH FAILED\n"
  39. # case 3 & 4, batch before repeat with different drop
  40. test_batch_repeat(gen_num=5, repeats=2, batch_size=4, drop=True, res=tst3)
  41. assert np.array_equal(np.array([[0], [1], [2], [3]]), tst3[0]), "\nATTENTION BATCH FAILED\n"
  42. assert np.array_equal(tst3[0], tst3[1]), "\nATTENTION BATCH FAILED\n"
  43. assert len(tst3) == 2, "\nATTENTION BATCH FAILED\n"
  44. test_batch_repeat(gen_num=5, repeats=2, batch_size=4, drop=False, res=tst4)
  45. assert np.array_equal(np.array([[0], [1], [2], [3]]), tst4[0]), "\nATTENTION BATCH FAILED\n"
  46. assert np.array_equal(tst4[0], tst4[2]), "\nATTENTION BATCH FAILED\n"
  47. assert np.array_equal(tst4[1], np.array([[4]])), "\nATTENTION BATCH FAILED\n"
  48. assert np.array_equal(tst4[1], tst4[3]), "\nATTENTION BATCH FAILED\n"
  49. assert len(tst4) == 4, "\nATTENTION BATCH FAILED\n"
  50. # each sub-test in this function is tested twice with exact parameter except that the second test passes each row
  51. # to a pyfunc which makes a deep copy of the row
  52. def test_variable_size_batch():
  53. def check_res(arr1, arr2):
  54. for ind in range(len(arr1)):
  55. if not np.array_equal(arr1[ind], np.array(arr2[ind])):
  56. return False
  57. return len(arr1) == len(arr2)
  58. def gen(num):
  59. for i in range(num):
  60. yield (np.array([i]),)
  61. def add_one_by_batch_num(batchInfo):
  62. return batchInfo.get_batch_num() + 1
  63. def add_one_by_epoch(batchInfo):
  64. return batchInfo.get_epoch_num() + 1
  65. def simple_copy(colList, batchInfo):
  66. return ([np.copy(arr) for arr in colList],)
  67. def test_repeat_batch(gen_num, r, drop, func, res):
  68. data1 = ds.GeneratorDataset((lambda: gen(gen_num)), ["num"]).repeat(r).batch(batch_size=func,
  69. drop_remainder=drop)
  70. for item in data1.create_dict_iterator():
  71. res.append(item["num"])
  72. # same as test_repeat_batch except each row is passed through via a map which makes a copy of each element
  73. def test_repeat_batch_with_copy_map(gen_num, r, drop, func):
  74. res = []
  75. data1 = ds.GeneratorDataset((lambda: gen(gen_num)), ["num"]).repeat(r) \
  76. .batch(batch_size=func, drop_remainder=drop, input_columns=["num"], per_batch_map=simple_copy)
  77. for item in data1.create_dict_iterator():
  78. res.append(item["num"])
  79. return res
  80. def test_batch_repeat(gen_num, r, drop, func, res):
  81. data1 = ds.GeneratorDataset((lambda: gen(gen_num)), ["num"]).batch(batch_size=func, drop_remainder=drop).repeat(
  82. r)
  83. for item in data1.create_dict_iterator():
  84. res.append(item["num"])
  85. # same as test_batch_repeat except each row is passed through via a map which makes a copy of each element
  86. def test_batch_repeat_with_copy_map(gen_num, r, drop, func):
  87. res = []
  88. data1 = ds.GeneratorDataset((lambda: gen(gen_num)), ["num"]) \
  89. .batch(batch_size=func, drop_remainder=drop, input_columns=["num"], per_batch_map=simple_copy).repeat(r)
  90. for item in data1.create_dict_iterator():
  91. res.append(item["num"])
  92. return res
  93. tst1, tst2, tst3, tst4, tst5, tst6, tst7 = [], [], [], [], [], [], []
  94. # no repeat, simple var size, based on batch_num
  95. test_repeat_batch(7, 1, True, add_one_by_batch_num, tst1)
  96. assert check_res(tst1, [[[0]], [[1], [2]], [[3], [4], [5]]]), "\nATTENTION VAR BATCH FAILED\n"
  97. assert check_res(tst1, test_repeat_batch_with_copy_map(7, 1, True, add_one_by_batch_num)), "\nMAP FAILED\n"
  98. test_repeat_batch(9, 1, False, add_one_by_batch_num, tst2)
  99. assert check_res(tst2, [[[0]], [[1], [2]], [[3], [4], [5]], [[6], [7], [8]]]), "\nATTENTION VAR BATCH FAILED\n"
  100. assert check_res(tst2, test_repeat_batch_with_copy_map(9, 1, False, add_one_by_batch_num)), "\nMAP FAILED\n"
  101. # batch after repeat, cross epoch batch
  102. test_repeat_batch(7, 2, False, add_one_by_batch_num, tst3)
  103. assert check_res(tst3, [[[0]], [[1], [2]], [[3], [4], [5]], [[6], [0], [1], [2]],
  104. [[3], [4], [5], [6]]]), "\nATTENTION VAR BATCH FAILED\n"
  105. assert check_res(tst3, test_repeat_batch_with_copy_map(7, 2, False, add_one_by_batch_num)), "\nMAP FAILED\n"
  106. # repeat after batch, no cross epoch batch, remainder dropped
  107. test_batch_repeat(9, 7, True, add_one_by_batch_num, tst4)
  108. assert check_res(tst4, [[[0]], [[1], [2]], [[3], [4], [5]]] * 7), "\nATTENTION VAR BATCH FAILED\n"
  109. assert check_res(tst4, test_batch_repeat_with_copy_map(9, 7, True, add_one_by_batch_num)), "\nAMAP FAILED\n"
  110. # repeat after batch, no cross epoch batch, remainder kept
  111. test_batch_repeat(9, 3, False, add_one_by_batch_num, tst5)
  112. assert check_res(tst5, [[[0]], [[1], [2]], [[3], [4], [5]], [[6], [7], [8]]] * 3), "\nATTENTION VAR BATCH FAILED\n"
  113. assert check_res(tst5, test_batch_repeat_with_copy_map(9, 3, False, add_one_by_batch_num)), "\nMAP FAILED\n"
  114. # batch_size based on epoch number, drop
  115. test_batch_repeat(4, 4, True, add_one_by_epoch, tst6)
  116. assert check_res(tst6, [[[0]], [[1]], [[2]], [[3]], [[0], [1]], [[2], [3]], [[0], [1], [2]],
  117. [[0], [1], [2], [3]]]), "\nATTENTION VAR BATCH FAILED\n"
  118. assert check_res(tst6, test_batch_repeat_with_copy_map(4, 4, True, add_one_by_epoch)), "\nMAP FAILED\n"
  119. # batch_size based on epoch number, no drop
  120. test_batch_repeat(4, 4, False, add_one_by_epoch, tst7)
  121. assert check_res(tst7, [[[0]], [[1]], [[2]], [[3]], [[0], [1]], [[2], [3]], [[0], [1], [2]], [[3]],
  122. [[0], [1], [2], [3]]]), "\nATTENTION VAR BATCH FAILED\n" + str(tst7)
  123. assert check_res(tst7, test_batch_repeat_with_copy_map(4, 4, False, add_one_by_epoch)), "\nMAP FAILED\n"
  124. def test_basic_batch_map():
  125. def check_res(arr1, arr2):
  126. for ind in range(len(arr1)):
  127. if not np.array_equal(arr1[ind], np.array(arr2[ind])):
  128. return False
  129. return len(arr1) == len(arr2)
  130. def gen(num):
  131. for i in range(num):
  132. yield (np.array([i]),)
  133. def invert_sign_per_epoch(colList, batchInfo):
  134. return ([np.copy(((-1) ** batchInfo.get_epoch_num()) * arr) for arr in colList],)
  135. def invert_sign_per_batch(colList, batchInfo):
  136. return ([np.copy(((-1) ** batchInfo.get_batch_num()) * arr) for arr in colList],)
  137. def batch_map_config(num, r, batch_size, func, res):
  138. data1 = ds.GeneratorDataset((lambda: gen(num)), ["num"]) \
  139. .batch(batch_size=batch_size, input_columns=["num"], per_batch_map=func).repeat(r)
  140. for item in data1.create_dict_iterator():
  141. res.append(item["num"])
  142. tst1, tst2, = [], []
  143. batch_map_config(4, 2, 2, invert_sign_per_epoch, tst1)
  144. assert check_res(tst1, [[[0], [1]], [[2], [3]], [[0], [-1]], [[-2], [-3]]]), "\nATTENTION MAP BATCH FAILED\n" + str(
  145. tst1)
  146. # each batch, the sign of a row is changed, test map is corrected performed according to its batch_num
  147. batch_map_config(4, 2, 2, invert_sign_per_batch, tst2)
  148. assert check_res(tst2,
  149. [[[0], [1]], [[-2], [-3]], [[0], [1]], [[-2], [-3]]]), "\nATTENTION MAP BATCH FAILED\n" + str(tst2)
  150. def test_batch_multi_col_map():
  151. def check_res(arr1, arr2):
  152. for ind in range(len(arr1)):
  153. if not np.array_equal(arr1[ind], np.array(arr2[ind])):
  154. return False
  155. return len(arr1) == len(arr2)
  156. def gen(num):
  157. for i in range(num):
  158. yield (np.array([i]), np.array([i ** 2]))
  159. def col1_col2_add_num(col1, col2, batchInfo):
  160. return ([[np.copy(arr + 100) for arr in col1],
  161. [np.copy(arr + 300) for arr in col2]])
  162. def invert_sign_per_batch(colList, batchInfo):
  163. return ([np.copy(((-1) ** batchInfo.get_batch_num()) * arr) for arr in colList],)
  164. def invert_sign_per_batch_multi_col(col1, col2, batchInfo):
  165. return ([np.copy(((-1) ** batchInfo.get_batch_num()) * arr) for arr in col1],
  166. [np.copy(((-1) ** batchInfo.get_batch_num()) * arr) for arr in col2])
  167. def batch_map_config(num, r, batch_size, func, col_names, res):
  168. data1 = ds.GeneratorDataset((lambda: gen(num)), ["num", "num_square"]) \
  169. .batch(batch_size=batch_size, input_columns=col_names, per_batch_map=func).repeat(r)
  170. for item in data1.create_dict_iterator():
  171. res.append(np.array([item["num"], item["num_square"]]))
  172. tst1, tst2, tst3, tst4 = [], [], [], []
  173. batch_map_config(4, 2, 2, invert_sign_per_batch, ["num_square"], tst1)
  174. assert check_res(tst1, [[[[0], [1]], [[0], [1]]], [[[2], [3]], [[-4], [-9]]], [[[0], [1]], [[0], [1]]],
  175. [[[2], [3]], [[-4], [-9]]]]), "\nATTENTION MAP BATCH FAILED\n" + str(tst1)
  176. batch_map_config(4, 2, 2, invert_sign_per_batch_multi_col, ["num", "num_square"], tst2)
  177. assert check_res(tst2, [[[[0], [1]], [[0], [1]]], [[[-2], [-3]], [[-4], [-9]]], [[[0], [1]], [[0], [1]]],
  178. [[[-2], [-3]], [[-4], [-9]]]]), "\nATTENTION MAP BATCH FAILED\n" + str(tst2)
  179. # the two tests below verify the order of the map.
  180. # num_square column adds 100, num column adds 300.
  181. batch_map_config(4, 3, 2, col1_col2_add_num, ["num_square", "num"], tst3)
  182. assert check_res(tst3, [[[[300], [301]], [[100], [101]]],
  183. [[[302], [303]], [[104], [109]]]] * 3), "\nATTENTION MAP BATCH FAILED\n" + str(tst3)
  184. # num column adds 100, num_square column adds 300.
  185. batch_map_config(4, 3, 2, col1_col2_add_num, ["num", "num_square"], tst4)
  186. assert check_res(tst4, [[[[100], [101]], [[300], [301]]],
  187. [[[102], [103]], [[304], [309]]]] * 3), "\nATTENTION MAP BATCH FAILED\n" + str(tst4)
  188. def test_var_batch_multi_col_map():
  189. def check_res(arr1, arr2):
  190. for ind in range(len(arr1)):
  191. if not np.array_equal(arr1[ind], np.array(arr2[ind])):
  192. return False
  193. return len(arr1) == len(arr2)
  194. # gen 3 columns
  195. # first column: 0, 3, 6, 9 ... ...
  196. # second column:1, 4, 7, 10 ... ...
  197. # third column: 2, 5, 8, 11 ... ...
  198. def gen_3_cols(num):
  199. for i in range(num):
  200. yield (np.array([i * 3]), np.array([i * 3 + 1]), np.array([i * 3 + 2]))
  201. # first epoch batch_size per batch: 1, 2 ,3 ... ...
  202. # second epoch batch_size per batch: 2, 4, 6 ... ...
  203. # third epoch batch_size per batch: 3, 6 ,9 ... ...
  204. def batch_func(batchInfo):
  205. return (batchInfo.get_batch_num() + 1) * (batchInfo.get_epoch_num() + 1)
  206. # multiply first col by batch_num, multiply second col by -batch_num
  207. def map_func(col1, col2, batchInfo):
  208. return ([np.copy((1 + batchInfo.get_batch_num()) * arr) for arr in col1],
  209. [np.copy(-(1 + batchInfo.get_batch_num()) * arr) for arr in col2])
  210. def batch_map_config(num, r, fbatch, fmap, col_names, res):
  211. data1 = ds.GeneratorDataset((lambda: gen_3_cols(num)), ["col1", "col2", "col3"]) \
  212. .batch(batch_size=fbatch, input_columns=col_names, per_batch_map=fmap).repeat(r)
  213. for item in data1.create_dict_iterator():
  214. res.append(np.array([item["col1"], item["col2"], item["col3"]]))
  215. tst1 = []
  216. tst1_res = [[[[0]], [[-1]], [[2]]], [[[6], [12]], [[-8], [-14]], [[5], [8]]],
  217. [[[27], [36], [45]], [[-30], [-39], [-48]], [[11], [14], [17]]],
  218. [[[72], [84], [96], [108]], [[-76], [-88], [-100], [-112]], [[20], [23], [26], [29]]]]
  219. batch_map_config(10, 1, batch_func, map_func, ["col1", "col2"], tst1)
  220. assert check_res(tst1, tst1_res), "test_var_batch_multi_col_map FAILED"
  221. def test_var_batch_var_resize():
  222. # fake resize image according to its batch number, if it's 5-th batch, resize to (5^2, 5^2) = (25, 25)
  223. def np_psedo_resize(col, batchInfo):
  224. s = (batchInfo.get_batch_num() + 1) ** 2
  225. return ([np.copy(c[0:s, 0:s, :]) for c in col],)
  226. def add_one(batchInfo):
  227. return (batchInfo.get_batch_num() + 1)
  228. data1 = ds.ImageFolderDatasetV2("../data/dataset/testPK/data/", num_parallel_workers=4, decode=True)
  229. data1 = data1.batch(batch_size=add_one, drop_remainder=True, input_columns=["image"], per_batch_map=np_psedo_resize)
  230. # i-th batch has shape [i, i^2, i^2, 3]
  231. i = 1
  232. for item in data1.create_dict_iterator():
  233. assert item["image"].shape == (i, i ** 2, i ** 2, 3), "\ntest_var_batch_var_resize FAILED\n"
  234. i += 1
  235. def test_exception():
  236. def gen(num):
  237. for i in range(num):
  238. yield (np.array([i]),)
  239. def bad_batch_size(batchInfo):
  240. raise StopIteration
  241. return batchInfo.get_batch_num()
  242. def bad_map_func(col, batchInfo):
  243. raise StopIteration
  244. return (col,)
  245. data1 = ds.GeneratorDataset((lambda: gen(100)), ["num"]).batch(bad_batch_size)
  246. try:
  247. for _ in data1.create_dict_iterator():
  248. pass
  249. assert False
  250. except RuntimeError:
  251. pass
  252. data2 = ds.GeneratorDataset((lambda: gen(100)), ["num"]).batch(4, input_columns=["num"], per_batch_map=bad_map_func)
  253. try:
  254. for item in data2.create_dict_iterator():
  255. pass
  256. assert False
  257. except RuntimeError:
  258. pass
  259. if __name__ == '__main__':
  260. logger.info("Running test_var_batch_map.py test_batch_corner_cases() function")
  261. test_batch_corner_cases()
  262. logger.info("Running test_var_batch_map.py test_variable_size_batch() function")
  263. test_variable_size_batch()
  264. logger.info("Running test_var_batch_map.py test_basic_batch_map() function")
  265. test_basic_batch_map()
  266. logger.info("Running test_var_batch_map.py test_batch_multi_col_map() function")
  267. test_batch_multi_col_map()
  268. logger.info("Running test_var_batch_map.py tesgit t_var_batch_multi_col_map() function")
  269. test_var_batch_multi_col_map()
  270. logger.info("Running test_var_batch_map.py test_var_batch_var_resize() function")
  271. test_var_batch_var_resize()
  272. logger.info("Running test_var_batch_map.py test_exception() function")
  273. test_exception()