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_training.py 8.7 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. """ test_training """
  16. import logging
  17. import numpy as np
  18. import pytest
  19. import mindspore.nn as nn
  20. from mindspore import Model, context
  21. from mindspore import Tensor
  22. from mindspore.train.callback import Callback
  23. from mindspore.nn.optim import Momentum
  24. from ..ut_filter import non_graph_engine
  25. from ....dataset_mock import MindData
  26. class Net(nn.Cell):
  27. """ Net definition """
  28. def __init__(self):
  29. super(Net, self).__init__()
  30. self.conv = nn.Conv2d(3, 64, 3, has_bias=False, weight_init='normal', pad_mode='valid')
  31. self.bn = nn.BatchNorm2d(64)
  32. self.relu = nn.ReLU()
  33. self.flatten = nn.Flatten()
  34. self.fc = nn.Dense(64 * 222 * 222, 3) # padding=0
  35. def construct(self, x):
  36. x = self.conv(x)
  37. x = self.bn(x)
  38. x = self.relu(x)
  39. x = self.flatten(x)
  40. out = self.fc(x)
  41. return out
  42. class LossNet(nn.Cell):
  43. """ LossNet definition """
  44. def __init__(self):
  45. super(LossNet, self).__init__()
  46. self.conv = nn.Conv2d(3, 64, 3, has_bias=False, weight_init='normal', pad_mode='valid')
  47. self.bn = nn.BatchNorm2d(64)
  48. self.relu = nn.ReLU()
  49. self.flatten = nn.Flatten()
  50. self.fc = nn.Dense(64 * 222 * 222, 3) # padding=0
  51. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  52. def construct(self, x, y):
  53. x = self.conv(x)
  54. x = self.bn(x)
  55. x = self.relu(x)
  56. x = self.flatten(x)
  57. x = self.fc(x)
  58. out = self.loss(x, y)
  59. return out
  60. def get_model(metrics=None):
  61. """ get_model """
  62. net = Net()
  63. loss = nn.SoftmaxCrossEntropyWithLogits()
  64. optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  65. model = Model(net, loss_fn=loss, optimizer=optim, metrics=metrics)
  66. return model
  67. def get_dataset():
  68. """ get_dataset """
  69. dataset_types = (np.float32, np.float32)
  70. dataset_shapes = ((32, 3, 224, 224), (32, 3))
  71. dataset = MindData(size=2, batch_size=32,
  72. np_types=dataset_types,
  73. output_shapes=dataset_shapes,
  74. input_indexs=(0, 1))
  75. return dataset
  76. @non_graph_engine
  77. def test_single_input():
  78. """ test_single_input """
  79. input_data = Tensor(np.random.randint(0, 255, [1, 3, 224, 224]).astype(np.float32))
  80. context.set_context(mode=context.GRAPH_MODE)
  81. model = Model(Net())
  82. out = model.predict(input_data)
  83. assert out is not None
  84. @non_graph_engine
  85. def test_multiple_argument():
  86. """ test_multiple_argument """
  87. input_data = Tensor(np.random.randint(0, 255, [1, 3, 224, 224]).astype(np.float32))
  88. input_label = Tensor(np.random.randint(0, 3, [1, 3]).astype(np.float32))
  89. context.set_context(mode=context.GRAPH_MODE)
  90. model = Model(LossNet())
  91. out = model.predict(input_data, input_label)
  92. assert out is not None
  93. def test_train_feed_mode(test_with_simu):
  94. """ test_train_feed_mode """
  95. dataset = get_dataset()
  96. model = get_model()
  97. if test_with_simu:
  98. return
  99. model.train(2, dataset)
  100. def test_dataset_sink_mode_args_check():
  101. """ test_dataset_sink_mode_args_check """
  102. dataset = get_dataset()
  103. model = get_model()
  104. with pytest.raises(TypeError):
  105. model.train(2, dataset, dataset_sink_mode="True")
  106. with pytest.raises(TypeError):
  107. model.train(2, dataset, dataset_sink_mode=1)
  108. @non_graph_engine
  109. def test_eval():
  110. """ test_eval """
  111. dataset_types = (np.float32, np.float32)
  112. dataset_shapes = ((32, 3, 224, 224), (32, 3))
  113. dataset = MindData(size=2, batch_size=32,
  114. np_types=dataset_types,
  115. output_shapes=dataset_shapes,
  116. input_indexs=(0, 1))
  117. net = Net()
  118. context.set_context(mode=context.GRAPH_MODE)
  119. model = Model(net, loss_fn=nn.SoftmaxCrossEntropyWithLogits(), metrics={"loss"})
  120. with pytest.raises(ValueError):
  121. model.eval(dataset)
  122. net2 = LossNet()
  123. model2 = Model(net2, eval_network=net2, eval_indexes=[0, 1, 2], metrics={"loss"})
  124. with pytest.raises(ValueError):
  125. model2.eval(dataset)
  126. _ = LossNet()
  127. model3 = Model(net2, eval_network=net2, metrics={"loss"})
  128. with pytest.raises(ValueError):
  129. model3.eval(dataset)
  130. class TestGraphMode:
  131. """ TestGraphMode definition """
  132. def test_train_minddata_graph_mode(self, test_with_simu):
  133. """ test_train_minddata_graph_mode """
  134. # pylint: disable=unused-argument
  135. dataset_types = (np.float32, np.float32)
  136. dataset_shapes = ((32, 3, 224, 224), (32, 3))
  137. dataset = MindData(size=2, batch_size=32,
  138. np_types=dataset_types,
  139. output_shapes=dataset_shapes,
  140. input_indexs=())
  141. model = get_model()
  142. model.train(1, dataset)
  143. class CallbackTest(Callback):
  144. """ CallbackTest definition """
  145. def __init__(self):
  146. pass
  147. def __enter__(self):
  148. return self
  149. def __exit__(self, *err):
  150. pass
  151. def step_end(self, run_context):
  152. cb_params = run_context.original_args()
  153. print(cb_params.cur_epoch_num, cb_params.cur_step_num)
  154. def test_train_callback(test_with_simu):
  155. """ test_train_callback """
  156. dataset = get_dataset()
  157. model = get_model()
  158. callback = CallbackTest()
  159. if test_with_simu:
  160. return
  161. model.train(2, dataset, callbacks=callback)
  162. log = logging.getLogger("test")
  163. log.setLevel(level=logging.ERROR)
  164. # Test the invalid args and trigger RuntimeError
  165. def test_model_build_abnormal_string():
  166. """ test_model_build_abnormal_string """
  167. net = nn.ReLU()
  168. context.set_context(mode=context.GRAPH_MODE)
  169. model = Model(net)
  170. err = False
  171. try:
  172. model.predict('aaa')
  173. except ValueError as e:
  174. log.error("Find value error: %r ", e)
  175. err = True
  176. finally:
  177. assert err
  178. def test_model_init():
  179. """ test_model_init_error """
  180. train_dataset = get_dataset()
  181. eval_dataset = get_dataset()
  182. with pytest.raises(RuntimeError):
  183. context.set_context(mode=context.PYNATIVE_MODE)
  184. get_model().init(train_dataset)
  185. context.set_context(mode=context.GRAPH_MODE)
  186. get_model().init(train_dataset)
  187. get_model(metrics={'acc'}).init(eval_dataset)
  188. with pytest.raises(RuntimeError):
  189. get_model().init(train_dataset, eval_dataset)
  190. with pytest.raises(ValueError):
  191. get_model().init()
  192. def test_init_model_error():
  193. """ test_init_model_error """
  194. net = nn.ReLU()
  195. loss = nn.SoftmaxCrossEntropyWithLogits()
  196. with pytest.raises(KeyError):
  197. Model(net, loss, metrics={"top1"})
  198. with pytest.raises(ValueError):
  199. Model(net, metrics={"top_1_accuracy"})
  200. with pytest.raises(TypeError):
  201. Model(net, metrics={"top5": None})
  202. with pytest.raises(ValueError):
  203. Model(net, eval_network=net, eval_indexes=[], metrics={"top_1_accuracy"})
  204. with pytest.raises(ValueError):
  205. Model(net, eval_network=net, eval_indexes=(1, 2, 3), metrics={"top_1_accuracy"})
  206. with pytest.raises(TypeError):
  207. Model(net, loss, metrics=("top_1_accuracy"))
  208. with pytest.raises(TypeError):
  209. Model(net, loss, metrics=())
  210. with pytest.raises(TypeError):
  211. Model(net, loss, metrics=["top_1_accuracy"])
  212. def test_model_eval_error():
  213. """ test_model_eval_error """
  214. dataset_types = (np.float32, np.float32)
  215. dataset_shapes = ((32, 3, 224, 224), (32, 3))
  216. dataset = MindData(size=2, batch_size=32,
  217. np_types=dataset_types,
  218. output_shapes=dataset_shapes,
  219. input_indexs=())
  220. net = nn.ReLU()
  221. loss = nn.SoftmaxCrossEntropyWithLogits()
  222. context.set_context(mode=context.GRAPH_MODE)
  223. model_nometrics = Model(net, loss)
  224. with pytest.raises(ValueError):
  225. model_nometrics.eval(dataset)
  226. model_metrics_empty = Model(net, loss, metrics={})
  227. with pytest.raises(ValueError):
  228. model_metrics_empty.eval(dataset)