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_callback.py 13 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 callback function."""
  16. import os
  17. import stat
  18. from unittest import mock
  19. import numpy as np
  20. import pytest
  21. import mindspore.common.dtype as mstype
  22. import mindspore.nn as nn
  23. from mindspore.common.api import ms_function
  24. from mindspore.common.tensor import Tensor
  25. from mindspore.nn import TrainOneStepCell, WithLossCell
  26. from mindspore.nn.optim import Momentum
  27. from mindspore.train.callback import ModelCheckpoint, RunContext, LossMonitor, _InternalCallbackParam, \
  28. _CallbackManager, Callback, CheckpointConfig, _set_cur_net, _checkpoint_cb_for_save_op
  29. from mindspore.train.callback._checkpoint import _check_file_name_prefix, _chg_ckpt_file_name_if_same_exist
  30. class Net(nn.Cell):
  31. """Net definition."""
  32. def __init__(self):
  33. super(Net, self).__init__()
  34. self.conv = nn.Conv2d(3, 64, 3, has_bias=False, weight_init='normal')
  35. self.bn = nn.BatchNorm2d(64)
  36. self.relu = nn.ReLU()
  37. self.flatten = nn.Flatten()
  38. self.fc = nn.Dense(64 * 222 * 222, 3)
  39. @ms_function
  40. def construct(self, x):
  41. x = self.conv(x)
  42. x = self.bn(x)
  43. x = self.relu(x)
  44. x = self.flatten(x)
  45. out = self.fc(x)
  46. return out
  47. class LossNet(nn.Cell):
  48. """ LossNet definition """
  49. def __init__(self):
  50. super(LossNet, self).__init__()
  51. self.conv = nn.Conv2d(3, 64, 3, has_bias=False, weight_init='normal', pad_mode='valid')
  52. self.bn = nn.BatchNorm2d(64)
  53. self.relu = nn.ReLU()
  54. self.flatten = nn.Flatten()
  55. self.fc = nn.Dense(64 * 222 * 222, 3) # padding=0
  56. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  57. @ms_function
  58. def construct(self, x, y):
  59. x = self.conv(x)
  60. x = self.bn(x)
  61. x = self.relu(x)
  62. x = self.flatten(x)
  63. x = self.fc(x)
  64. out = self.loss(x, y)
  65. return out
  66. def test_model_checkpoint_prefix_invalid():
  67. """Test ModelCheckpoint prefix invalid."""
  68. with pytest.raises(ValueError):
  69. ModelCheckpoint(123)
  70. ModelCheckpoint(directory="./")
  71. with pytest.raises(TypeError):
  72. ModelCheckpoint(config='type_error')
  73. ModelCheckpoint(config=CheckpointConfig())
  74. ModelCheckpoint(prefix="ckpt_2", directory="./test_files")
  75. def test_save_checkpoint():
  76. """Test save checkpoint."""
  77. train_config = CheckpointConfig(
  78. save_checkpoint_steps=16,
  79. save_checkpoint_seconds=0,
  80. keep_checkpoint_max=5,
  81. keep_checkpoint_per_n_minutes=0)
  82. cb_params = _InternalCallbackParam()
  83. net = Net()
  84. loss = nn.SoftmaxCrossEntropyWithLogits()
  85. optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  86. network_ = WithLossCell(net, loss)
  87. _train_network = TrainOneStepCell(network_, optim)
  88. cb_params.train_network = _train_network
  89. cb_params.epoch_num = 10
  90. cb_params.cur_epoch_num = 5
  91. cb_params.cur_step_num = 0
  92. cb_params.batch_num = 32
  93. ckpoint_cb = ModelCheckpoint(prefix="test_ckpt", directory='./test_files', config=train_config)
  94. run_context = RunContext(cb_params)
  95. ckpoint_cb.begin(run_context)
  96. ckpoint_cb.step_end(run_context)
  97. if os.path.exists('./test_files/test_ckpt-model.pkl'):
  98. os.chmod('./test_files/test_ckpt-model.pkl', stat.S_IWRITE)
  99. os.remove('./test_files/test_ckpt-model.pkl')
  100. def test_loss_monitor_sink_mode():
  101. """Test loss monitor sink mode."""
  102. cb_params = _InternalCallbackParam()
  103. cb_params.cur_epoch_num = 4
  104. cb_params.epoch_num = 4
  105. cb_params.cur_step_num = 2
  106. cb_params.batch_num = 2
  107. cb_params.net_outputs = Tensor(2.0)
  108. run_context = RunContext(cb_params)
  109. loss_cb = LossMonitor(1)
  110. callbacks = [loss_cb]
  111. with _CallbackManager(callbacks) as callbacklist:
  112. callbacklist.begin(run_context)
  113. callbacklist.epoch_begin(run_context)
  114. callbacklist.step_begin(run_context)
  115. callbacklist.step_end(run_context)
  116. callbacklist.epoch_end(run_context)
  117. callbacklist.end(run_context)
  118. def test_loss_monitor_normal_mode():
  119. """Test loss monitor normal(non-sink) mode."""
  120. cb_params = _InternalCallbackParam()
  121. run_context = RunContext(cb_params)
  122. loss_cb = LossMonitor(1)
  123. cb_params.cur_epoch_num = 4
  124. cb_params.epoch_num = 4
  125. cb_params.cur_step_num = 1
  126. cb_params.batch_num = 1
  127. cb_params.net_outputs = Tensor(2.0)
  128. loss_cb.begin(run_context)
  129. loss_cb.epoch_begin(run_context)
  130. loss_cb.step_begin(run_context)
  131. loss_cb.step_end(run_context)
  132. loss_cb.epoch_end(run_context)
  133. loss_cb.end(run_context)
  134. def test_check_file_name_not_str():
  135. """Test check file name not str."""
  136. ret = _check_file_name_prefix(1)
  137. assert not ret
  138. def test_check_file_name_back_err():
  139. """Test check file name back err."""
  140. ret = _check_file_name_prefix('abc.')
  141. assert ret
  142. def test_check_file_name_one_alpha():
  143. """Test check file name one alpha."""
  144. ret = _check_file_name_prefix('a')
  145. assert ret
  146. ret = _check_file_name_prefix('_')
  147. assert ret
  148. def test_check_file_name_err():
  149. """Test check file name err."""
  150. ret = _check_file_name_prefix('_123')
  151. assert ret
  152. def test_chg_ckpt_file_name_if_same_exist():
  153. """Test chg ckpt file name if same exist."""
  154. _chg_ckpt_file_name_if_same_exist(directory="./test_files", prefix="ckpt")
  155. def test_checkpoint_cb_for_save_op():
  156. """Test checkpoint cb for save op."""
  157. parameter_list = []
  158. one_param = {}
  159. one_param['name'] = "conv1.weight"
  160. one_param['data'] = Tensor(np.random.randint(0, 255, [1, 3, 224, 224]), dtype=mstype.float32)
  161. parameter_list.append(one_param)
  162. _checkpoint_cb_for_save_op(parameter_list)
  163. def test_checkpoint_cb_for_save_op_update_net():
  164. """Test checkpoint cb for save op."""
  165. parameter_list = []
  166. one_param = {}
  167. one_param['name'] = "conv.weight"
  168. one_param['data'] = Tensor(np.ones(shape=(64, 3, 3, 3)), dtype=mstype.float32)
  169. parameter_list.append(one_param)
  170. net = Net()
  171. _set_cur_net(net)
  172. _checkpoint_cb_for_save_op(parameter_list)
  173. assert net.conv.weight.default_input.asnumpy()[0][0][0][0] == 1
  174. def test_internal_callback_param():
  175. """Test Internal CallbackParam."""
  176. cb_params = _InternalCallbackParam()
  177. cb_params.member1 = 1
  178. cb_params.member2 = "abc"
  179. assert cb_params.member1 == 1
  180. assert cb_params.member2 == "abc"
  181. def test_checkpoint_save_ckpt_steps():
  182. """Test checkpoint save ckpt steps."""
  183. train_config = CheckpointConfig(
  184. save_checkpoint_steps=16,
  185. save_checkpoint_seconds=0,
  186. keep_checkpoint_max=5,
  187. keep_checkpoint_per_n_minutes=0)
  188. ckpt_cb = ModelCheckpoint(config=train_config)
  189. cb_params = _InternalCallbackParam()
  190. net = Net()
  191. loss = nn.SoftmaxCrossEntropyWithLogits()
  192. optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  193. network_ = WithLossCell(net, loss)
  194. _train_network = TrainOneStepCell(network_, optim)
  195. cb_params.train_network = _train_network
  196. cb_params.epoch_num = 10
  197. cb_params.cur_epoch_num = 5
  198. cb_params.cur_step_num = 160
  199. cb_params.batch_num = 32
  200. run_context = RunContext(cb_params)
  201. ckpt_cb.begin(run_context)
  202. ckpt_cb.step_end(run_context)
  203. ckpt_cb2 = ModelCheckpoint(config=train_config)
  204. cb_params.cur_epoch_num = 1
  205. cb_params.cur_step_num = 15
  206. ckpt_cb2.begin(run_context)
  207. ckpt_cb2.step_end(run_context)
  208. def test_checkpoint_save_ckpt_seconds():
  209. """Test checkpoint save ckpt seconds."""
  210. train_config = CheckpointConfig(
  211. save_checkpoint_steps=16,
  212. save_checkpoint_seconds=100,
  213. keep_checkpoint_max=0,
  214. keep_checkpoint_per_n_minutes=1)
  215. ckpt_cb = ModelCheckpoint(config=train_config)
  216. cb_params = _InternalCallbackParam()
  217. net = Net()
  218. loss = nn.SoftmaxCrossEntropyWithLogits()
  219. optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  220. network_ = WithLossCell(net, loss)
  221. _train_network = TrainOneStepCell(network_, optim)
  222. cb_params.train_network = _train_network
  223. cb_params.epoch_num = 10
  224. cb_params.cur_epoch_num = 4
  225. cb_params.cur_step_num = 128
  226. cb_params.batch_num = 32
  227. run_context = RunContext(cb_params)
  228. ckpt_cb.begin(run_context)
  229. ckpt_cb.step_end(run_context)
  230. ckpt_cb2 = ModelCheckpoint(config=train_config)
  231. cb_params.cur_epoch_num = 1
  232. cb_params.cur_step_num = 16
  233. ckpt_cb2.begin(run_context)
  234. ckpt_cb2.step_end(run_context)
  235. def test_CallbackManager():
  236. """TestCallbackManager."""
  237. ck_obj = ModelCheckpoint()
  238. loss_cb_1 = LossMonitor(1)
  239. callbacks = [None]
  240. with pytest.raises(TypeError):
  241. _CallbackManager(callbacks)
  242. callbacks = ['Error']
  243. with pytest.raises(TypeError):
  244. _CallbackManager(callbacks)
  245. callbacks = [ck_obj, loss_cb_1, 'Error', None]
  246. with pytest.raises(TypeError):
  247. _CallbackManager(callbacks)
  248. def test_CallbackManager_exit_called():
  249. with mock.patch.object(Callback, '__exit__', return_value=None) as mock_exit:
  250. cb1, cb2 = Callback(), Callback()
  251. with _CallbackManager([cb1, cb2]):
  252. pass
  253. for call_args in mock_exit.call_args_list:
  254. assert call_args == mock.call(mock.ANY, None, None, None)
  255. assert mock_exit.call_count == 2
  256. def test_CallbackManager_exit_called_when_raises():
  257. with mock.patch.object(Callback, '__exit__', return_value=None) as mock_exit:
  258. cb1, cb2 = Callback(), Callback()
  259. with pytest.raises(ValueError):
  260. with _CallbackManager([cb1, cb2]):
  261. raise ValueError()
  262. for call_args in mock_exit.call_args_list:
  263. assert call_args == mock.call(*[mock.ANY] * 4)
  264. assert mock_exit.call_count == 2
  265. def test_CallbackManager_begin_called():
  266. context = dict()
  267. with mock.patch.object(Callback, 'begin', return_value=None) as mock_begin:
  268. cb1, cb2 = Callback(), Callback()
  269. with _CallbackManager([cb1, cb2]) as cm:
  270. cm.begin(context)
  271. for call_args in mock_begin.call_args_list:
  272. assert call_args == mock.call(context)
  273. assert mock_begin.call_count == 2
  274. def test_RunContext():
  275. """Test RunContext."""
  276. context_err = 666
  277. with pytest.raises(TypeError):
  278. RunContext(context_err)
  279. cb_params = _InternalCallbackParam()
  280. cb_params.member1 = 1
  281. cb_params.member2 = "abc"
  282. run_context = RunContext(cb_params)
  283. run_context.original_args()
  284. assert cb_params.member1 == 1
  285. assert cb_params.member2 == "abc"
  286. run_context.request_stop()
  287. should_stop = run_context.get_stop_requested()
  288. assert should_stop
  289. def test_Checkpoint_Config():
  290. """Test CheckpointConfig all None or 0."""
  291. with pytest.raises(ValueError):
  292. CheckpointConfig(0, 0, 0, 0, True)
  293. with pytest.raises(ValueError):
  294. CheckpointConfig(0, None, 0, 0, True)
  295. def test_step_end_save_graph():
  296. """Test save checkpoint."""
  297. train_config = CheckpointConfig(
  298. save_checkpoint_steps=16,
  299. save_checkpoint_seconds=0,
  300. keep_checkpoint_max=5,
  301. keep_checkpoint_per_n_minutes=0)
  302. cb_params = _InternalCallbackParam()
  303. net = LossNet()
  304. input_data = Tensor(np.random.randint(0, 255, [1, 3, 224, 224]).astype(np.float32))
  305. input_label = Tensor(np.random.randint(0, 3, [1, 3]).astype(np.float32))
  306. net(input_data, input_label)
  307. cb_params.train_network = net
  308. cb_params.epoch_num = 10
  309. cb_params.cur_epoch_num = 5
  310. cb_params.cur_step_num = 0
  311. cb_params.batch_num = 32
  312. ckpoint_cb = ModelCheckpoint(prefix="test", directory='./test_files', config=train_config)
  313. run_context = RunContext(cb_params)
  314. ckpoint_cb.begin(run_context)
  315. # import pdb;pdb.set_trace()
  316. ckpoint_cb.step_end(run_context)
  317. assert os.path.exists('./test_files/test-graph.meta')
  318. if os.path.exists('./test_files/test-graph.meta'):
  319. os.chmod('./test_files/test-graph.meta', stat.S_IWRITE)
  320. os.remove('./test_files/test-graph.meta')
  321. ckpoint_cb.step_end(run_context)
  322. assert not os.path.exists('./test_files/test-graph.meta')