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