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.

callbacks.py 4.2 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. callbacks
  16. """
  17. import time
  18. from mindspore.train.callback import Callback
  19. from mindspore import context
  20. from mindspore.train import ParallelMode
  21. def add_write(file_path, out_str):
  22. """
  23. add lines to the file
  24. """
  25. with open(file_path, 'a+', encoding="utf-8") as file_out:
  26. file_out.write(out_str + "\n")
  27. class LossCallBack(Callback):
  28. """
  29. Monitor the loss in training.
  30. If the loss is NAN or INF, terminate the training.
  31. Note:
  32. If per_print_times is 0, do NOT print loss.
  33. Args:
  34. per_print_times (int): Print loss every times. Default: 1.
  35. """
  36. def __init__(self, config=None, per_print_times=1):
  37. super(LossCallBack, self).__init__()
  38. if not isinstance(per_print_times, int) or per_print_times < 0:
  39. raise ValueError("per_print_times must be in and >= 0.")
  40. self._per_print_times = per_print_times
  41. self.config = config
  42. def step_end(self, run_context):
  43. cb_params = run_context.original_args()
  44. wide_loss, deep_loss = cb_params.net_outputs[0].asnumpy(), cb_params.net_outputs[1].asnumpy()
  45. cur_step_in_epoch = (cb_params.cur_step_num - 1) % cb_params.batch_num + 1
  46. cur_num = cb_params.cur_step_num
  47. print("===loss===", cb_params.cur_epoch_num, cur_step_in_epoch, wide_loss, deep_loss)
  48. # raise ValueError
  49. if self._per_print_times != 0 and cur_num % self._per_print_times == 0 and self.config is not None:
  50. loss_file = open(self.config.loss_file_name, "a+")
  51. loss_file.write("epoch: %s, step: %s, wide_loss: %s, deep_loss: %s" %
  52. (cb_params.cur_epoch_num, cur_step_in_epoch, wide_loss, deep_loss))
  53. loss_file.write("\n")
  54. loss_file.close()
  55. print("epoch: %s, step: %s, wide_loss: %s, deep_loss: %s" %
  56. (cb_params.cur_epoch_num, cur_step_in_epoch, wide_loss, deep_loss))
  57. class EvalCallBack(Callback):
  58. """
  59. Monitor the loss in evaluating.
  60. If the loss is NAN or INF, terminate evaluating.
  61. Note:
  62. If per_print_times is 0, do NOT print loss.
  63. Args:
  64. print_per_step (int): Print loss every times. Default: 1.
  65. """
  66. def __init__(self, model, eval_dataset, auc_metric, config, print_per_step=1):
  67. super(EvalCallBack, self).__init__()
  68. if not isinstance(print_per_step, int) or print_per_step < 0:
  69. raise ValueError("print_per_step must be int and >= 0.")
  70. self.print_per_step = print_per_step
  71. self.model = model
  72. self.eval_dataset = eval_dataset
  73. self.aucMetric = auc_metric
  74. self.aucMetric.clear()
  75. self.eval_file_name = config.eval_file_name
  76. self.eval_values = []
  77. def epoch_end(self, run_context):
  78. """
  79. epoch end
  80. """
  81. self.aucMetric.clear()
  82. parallel_mode = context.get_auto_parallel_context("parallel_mode")
  83. if parallel_mode in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL):
  84. context.set_auto_parallel_context(strategy_ckpt_save_file="",
  85. strategy_ckpt_load_file="./strategy_train.ckpt")
  86. start_time = time.time()
  87. out = self.model.eval(self.eval_dataset)
  88. end_time = time.time()
  89. eval_time = int(end_time - start_time)
  90. time_str = time.strftime("%Y-%m-%d %H:%M%S", time.localtime())
  91. out_str = "{}==== EvalCallBack model.eval(): {}; eval_time: {}s".format(time_str, out.values(), eval_time)
  92. print(out_str)
  93. self.eval_values = out.values()
  94. add_write(self.eval_file_name, out_str)