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.

utils.py 2.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. # less 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 time
  16. import numpy as np
  17. from mindspore.train.callback import Callback
  18. from mindspore.common.tensor import Tensor
  19. class StepLossTimeMonitor(Callback):
  20. def __init__(self, batch_size, per_print_times=1):
  21. super(StepLossTimeMonitor, self).__init__()
  22. if not isinstance(per_print_times, int) or per_print_times < 0:
  23. raise ValueError("print_step must be int and >= 0.")
  24. self._per_print_times = per_print_times
  25. self.batch_size = batch_size
  26. def step_begin(self, run_context):
  27. self.step_time = time.time()
  28. def step_end(self, run_context):
  29. step_seconds = time.time() - self.step_time
  30. step_fps = self.batch_size*1.0/step_seconds
  31. cb_params = run_context.original_args()
  32. loss = cb_params.net_outputs
  33. if isinstance(loss, (tuple, list)):
  34. if isinstance(loss[0], Tensor) and isinstance(loss[0].asnumpy(), np.ndarray):
  35. loss = loss[0]
  36. if isinstance(loss, Tensor) and isinstance(loss.asnumpy(), np.ndarray):
  37. loss = np.mean(loss.asnumpy())
  38. cur_step_in_epoch = (cb_params.cur_step_num - 1) % cb_params.batch_num + 1
  39. if isinstance(loss, float) and (np.isnan(loss) or np.isinf(loss)):
  40. raise ValueError("epoch: {} step: {}. Invalid loss, terminating training.".format(
  41. cb_params.cur_epoch_num, cur_step_in_epoch))
  42. if self._per_print_times != 0 and cb_params.cur_step_num % self._per_print_times == 0:
  43. # TEST
  44. print("step: %s, loss is %s, fps is %s" % (cur_step_in_epoch, loss, step_fps), flush=True)