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 6.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. """tinybert utils"""
  16. import os
  17. import numpy as np
  18. from mindspore import Tensor
  19. from mindspore.common import dtype as mstype
  20. from mindspore.train.callback import Callback
  21. from mindspore.train.serialization import save_checkpoint
  22. from mindspore.ops import operations as P
  23. from mindspore.nn.learning_rate_schedule import LearningRateSchedule, PolynomialDecayLR, WarmUpLR
  24. from .assessment_method import Accuracy
  25. class ModelSaveCkpt(Callback):
  26. """
  27. Saves checkpoint.
  28. If the loss in NAN or INF terminating training.
  29. Args:
  30. network (Network): The train network for training.
  31. save_ckpt_num (int): The number to save checkpoint, default is 1000.
  32. max_ckpt_num (int): The max checkpoint number, default is 3.
  33. """
  34. def __init__(self, network, save_ckpt_step, max_ckpt_num, output_dir):
  35. super(ModelSaveCkpt, self).__init__()
  36. self.count = 0
  37. self.network = network
  38. self.save_ckpt_step = save_ckpt_step
  39. self.max_ckpt_num = max_ckpt_num
  40. self.output_dir = output_dir
  41. def step_end(self, run_context):
  42. """step end and save ckpt"""
  43. cb_params = run_context.original_args()
  44. if cb_params.cur_step_num % self.save_ckpt_step == 0:
  45. saved_ckpt_num = cb_params.cur_step_num / self.save_ckpt_step
  46. if saved_ckpt_num > self.max_ckpt_num:
  47. oldest_ckpt_index = saved_ckpt_num - self.max_ckpt_num
  48. path = os.path.join(self.output_dir, "tiny_bert_{}_{}.ckpt".format(int(oldest_ckpt_index),
  49. self.save_ckpt_step))
  50. if os.path.exists(path):
  51. os.remove(path)
  52. save_checkpoint(self.network, os.path.join(self.output_dir,
  53. "tiny_bert_{}_{}.ckpt".format(int(saved_ckpt_num),
  54. self.save_ckpt_step)))
  55. class LossCallBack(Callback):
  56. """
  57. Monitor the loss in training.
  58. If the loss in NAN or INF terminating training.
  59. Note:
  60. if per_print_times is 0 do not print loss.
  61. Args:
  62. per_print_times (int): Print loss every times. Default: 1.
  63. """
  64. def __init__(self, per_print_times=1):
  65. super(LossCallBack, self).__init__()
  66. if not isinstance(per_print_times, int) or per_print_times < 0:
  67. raise ValueError("print_step must be int and >= 0")
  68. self._per_print_times = per_print_times
  69. def step_end(self, run_context):
  70. """step end and print loss"""
  71. cb_params = run_context.original_args()
  72. print("epoch: {}, step: {}, outputs are {}".format(cb_params.cur_epoch_num,
  73. cb_params.cur_step_num,
  74. str(cb_params.net_outputs)))
  75. class EvalCallBack(Callback):
  76. """Evaluation callback"""
  77. def __init__(self, network, dataset):
  78. super(EvalCallBack, self).__init__()
  79. self.network = network
  80. self.global_acc = 0.0
  81. self.dataset = dataset
  82. def step_end(self, run_context):
  83. """step end and do evaluation"""
  84. cb_params = run_context.original_args()
  85. if cb_params.cur_step_num % 100 == 0:
  86. callback = Accuracy()
  87. columns_list = ["input_ids", "input_mask", "segment_ids", "label_ids"]
  88. for data in self.dataset.create_dict_iterator(num_epochs=1):
  89. input_data = []
  90. for i in columns_list:
  91. input_data.append(data[i])
  92. input_ids, input_mask, token_type_id, label_ids = input_data
  93. self.network.set_train(False)
  94. logits = self.network(input_ids, token_type_id, input_mask)
  95. callback.update(logits, label_ids)
  96. acc = callback.acc_num / callback.total_num
  97. with open("./eval.log", "a+") as f:
  98. f.write("acc_num {}, total_num{}, accuracy{:.6f}".format(callback.acc_num, callback.total_num,
  99. callback.acc_num / callback.total_num))
  100. f.write('\n')
  101. if acc > self.global_acc:
  102. self.global_acc = acc
  103. print("The best acc is {}".format(acc))
  104. eval_model_ckpt_file = "eval_model.ckpt"
  105. if os.path.exists(eval_model_ckpt_file):
  106. os.remove(eval_model_ckpt_file)
  107. save_checkpoint(self.network, eval_model_ckpt_file)
  108. class BertLearningRate(LearningRateSchedule):
  109. """
  110. Warmup-decay learning rate for Bert network.
  111. """
  112. def __init__(self, learning_rate, end_learning_rate, warmup_steps, decay_steps, power):
  113. super(BertLearningRate, self).__init__()
  114. self.warmup_flag = False
  115. if warmup_steps > 0:
  116. self.warmup_flag = True
  117. self.warmup_lr = WarmUpLR(learning_rate, warmup_steps)
  118. self.decay_lr = PolynomialDecayLR(learning_rate, end_learning_rate, decay_steps, power)
  119. self.warmup_steps = Tensor(np.array([warmup_steps]).astype(np.float32))
  120. self.greater = P.Greater()
  121. self.one = Tensor(np.array([1.0]).astype(np.float32))
  122. self.cast = P.Cast()
  123. def construct(self, global_step):
  124. decay_lr = self.decay_lr(global_step)
  125. if self.warmup_flag:
  126. is_warmup = self.cast(self.greater(self.warmup_steps, global_step), mstype.float32)
  127. warmup_lr = self.warmup_lr(global_step)
  128. lr = (self.one - is_warmup) * decay_lr + is_warmup * warmup_lr
  129. else:
  130. lr = decay_lr
  131. return lr