Monitor the ppl loss in evaluating. Note: If per_print_times is 0, do NOT print loss. Args: print_per_step (int): Print loss every times. Default: 1.
| 90 | |
| 91 | |
| 92 | class EvalCallBack(Callback): |
| 93 | """ |
| 94 | Monitor the ppl loss in evaluating. |
| 95 | Note: |
| 96 | If per_print_times is 0, do NOT print loss. |
| 97 | |
| 98 | Args: |
| 99 | print_per_step (int): Print loss every times. Default: 1. |
| 100 | """ |
| 101 | |
| 102 | def __init__(self, model, eval_dataset, ppl_metric, validation_loss, print_per_step=250, has_trained_step=0, |
| 103 | local_rank=0, rank_size=1, tb_writer=None, lang=None): |
| 104 | super(EvalCallBack, self).__init__() |
| 105 | if not isinstance(print_per_step, int) or print_per_step < 0: |
| 106 | raise ValueError("print_per_step must be int and >= 0.") |
| 107 | self.print_per_step = print_per_step |
| 108 | self.model = model |
| 109 | self.eval_dataset = eval_dataset |
| 110 | self.pplMetric = ppl_metric |
| 111 | self.validation_loss = validation_loss |
| 112 | self.has_trained_step = has_trained_step |
| 113 | self.local_rank = local_rank |
| 114 | self.rank_size = rank_size |
| 115 | self.pplMetric.clear() |
| 116 | self.validation_loss.clear() |
| 117 | self.parallel_mode = context.get_auto_parallel_context("parallel_mode") |
| 118 | self.strategy_ckpt_save_file = context.get_auto_parallel_context("strategy_ckpt_save_file") |
| 119 | self.strategy_ckpt_load_file = context.get_auto_parallel_context("strategy_ckpt_load_file") |
| 120 | self.summary_writer = tb_writer |
| 121 | self.lang = lang |
| 122 | |
| 123 | def step_end(self, run_context): |
| 124 | """ |
| 125 | step end |
| 126 | """ |
| 127 | cb_params = run_context.original_args() |
| 128 | current_step = cb_params.cur_step_num + self.has_trained_step |
| 129 | if current_step % self.print_per_step != 0: |
| 130 | return |
| 131 | self.pplMetric.clear() |
| 132 | self.validation_loss.clear() |
| 133 | if self.parallel_mode in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL): |
| 134 | context.set_auto_parallel_context(strategy_ckpt_save_file="", |
| 135 | strategy_ckpt_load_file=self.strategy_ckpt_save_file) |
| 136 | rank_id = 0 |
| 137 | if self.parallel_mode in (ParallelMode.SEMI_AUTO_PARALLEL, |
| 138 | ParallelMode.AUTO_PARALLEL, ParallelMode.DATA_PARALLEL): |
| 139 | rank_id = get_rank() |
| 140 | print("validation begin") |
| 141 | start_time = time.time() |
| 142 | out = self.model.eval(self.eval_dataset) |
| 143 | end_time = time.time() |
| 144 | eval_time = int(end_time - start_time) |
| 145 | |
| 146 | time_str = time.strftime("%Y-%m-%d %H:%M%S", time.localtime()) |
| 147 | out_str = f"{time_str} == Language {self.lang}; Rank {rank_id} Eval: {out}; eval_time: {eval_time}s" |
| 148 | print(out_str) |
| 149 | if self.summary_writer is not None: |
no outgoing calls
no test coverage detected