|
| 1 | +from abc import abstractmethod |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import torch |
| 5 | +import wandb |
| 6 | +from numpy import inf |
| 7 | + |
| 8 | +from logger import Loggers |
| 9 | + |
| 10 | + |
| 11 | +class BaseTrainer: |
| 12 | + """ |
| 13 | + Base class for all trainers |
| 14 | + """ |
| 15 | + |
| 16 | + def __init__(self, model, criterion, metric_ftns, optimizer, config): |
| 17 | + self.config = config |
| 18 | + self.logger = Loggers.get_logger('trainer') |
| 19 | + self.model = model |
| 20 | + self.model_id = config.model_id |
| 21 | + self.criterion = criterion |
| 22 | + self.metric_ftns = metric_ftns |
| 23 | + self.optimizer = optimizer |
| 24 | + |
| 25 | + cfg_trainer = config['trainer'] |
| 26 | + self.epochs = cfg_trainer['epochs'] |
| 27 | + self.save_period = cfg_trainer['save_period'] |
| 28 | + self.monitor = cfg_trainer.get('monitor', 'off') |
| 29 | + |
| 30 | + # configuration to monitor model performance and save best |
| 31 | + if self.monitor == 'off': |
| 32 | + self.mnt_mode = 'off' |
| 33 | + self.mnt_best = 0 |
| 34 | + else: |
| 35 | + self.mnt_mode, self.mnt_metric = self.monitor.split() |
| 36 | + self.mnt_mode = self.mnt_mode.lower() |
| 37 | + assert self.mnt_mode in ['min', 'max'] |
| 38 | + |
| 39 | + self.mnt_best = inf if self.mnt_mode == 'min' else -inf |
| 40 | + self.early_stop = cfg_trainer.get('early_stop', inf) |
| 41 | + if self.early_stop <= 0: |
| 42 | + self.early_stop = inf |
| 43 | + |
| 44 | + self.start_epoch = 1 |
| 45 | + |
| 46 | + self.checkpoint_dir = Path(config['PATHS']['CP_DIR']) |
| 47 | + |
| 48 | + if config.resume_path is not None: |
| 49 | + self._resume_checkpoint(config.resume_path) |
| 50 | + |
| 51 | + @abstractmethod |
| 52 | + def _train_epoch(self, epoch): |
| 53 | + """ |
| 54 | + Training logic for an epoch |
| 55 | +
|
| 56 | + :param epoch: Current epoch number |
| 57 | + """ |
| 58 | + raise NotImplementedError |
| 59 | + |
| 60 | + def train(self): |
| 61 | + """ |
| 62 | + Full training logic |
| 63 | + """ |
| 64 | + |
| 65 | + not_improved_count = 0 |
| 66 | + for epoch in range(self.start_epoch, self.epochs + 1): |
| 67 | + # train epoch |
| 68 | + # return metrics that may or may not be logged |
| 69 | + # TODO find how to config the mnt_metric |
| 70 | + result = self._train_epoch(epoch) |
| 71 | + |
| 72 | + # save logged information into log dict |
| 73 | + log = {'epoch': epoch} |
| 74 | + log.update(result) |
| 75 | + |
| 76 | + # print logged information to the screen |
| 77 | + for key, value in log.items(): |
| 78 | + # self.logger.info(' {:15s}: {}'.format(str(key), value)) |
| 79 | + self.logger.info(f" {key:15s}: {value}") |
| 80 | + |
| 81 | + # evaluate model performance according to configured metric, save the best checkpoint as model_best |
| 82 | + best = False |
| 83 | + if self.mnt_mode != 'off': |
| 84 | + try: |
| 85 | + # check whether model performance improved or not, according to specified metric(mnt_metric) |
| 86 | + improved = (self.mnt_mode == 'min' and log[self.mnt_metric] <= self.mnt_best) or \ |
| 87 | + (self.mnt_mode == 'max' and log[self.mnt_metric] >= self.mnt_best) |
| 88 | + except KeyError: |
| 89 | + self.logger.warning("Warning: Metric '{}' is not found. " |
| 90 | + "Model performance monitoring is disabled.".format(self.mnt_metric)) |
| 91 | + self.mnt_mode = 'off' |
| 92 | + improved = False |
| 93 | + |
| 94 | + if improved: |
| 95 | + self.mnt_best = log[self.mnt_metric] |
| 96 | + not_improved_count = 0 |
| 97 | + best = True |
| 98 | + else: |
| 99 | + not_improved_count += 1 |
| 100 | + self.logger.info("Early stop count: {}".format(not_improved_count)) |
| 101 | + |
| 102 | + if not_improved_count > self.early_stop: |
| 103 | + self.logger.info("Validation performance didn\'t improve for {} epochs. " |
| 104 | + "Training stops.".format(self.early_stop)) |
| 105 | + wandb.run.summary["early_stop"] = True |
| 106 | + |
| 107 | + break |
| 108 | + |
| 109 | + if epoch % self.save_period == 0: |
| 110 | + self._save_checkpoint(epoch, save_best=best) |
| 111 | + |
| 112 | + wandb.save(str(self.checkpoint_dir / f'{self.model_id}_best.pth')) |
| 113 | + wandb.finish() |
| 114 | + |
| 115 | + def _save_checkpoint(self, epoch, save_best=False): |
| 116 | + """ |
| 117 | + Saving checkpoints |
| 118 | +
|
| 119 | + :param epoch: current epoch number |
| 120 | + :param log: logging information of the epoch |
| 121 | + :param save_best: if True, rename the saved checkpoint to 'model_best.pth' |
| 122 | + """ |
| 123 | + arch = type(self.model).__name__ |
| 124 | + state = { |
| 125 | + 'arch': arch, |
| 126 | + 'epoch': epoch, |
| 127 | + 'model': self.model.state_dict(), |
| 128 | + 'optimizer': self.optimizer.state_dict(), |
| 129 | + 'monitor_best': self.mnt_best, |
| 130 | + # 'config': self.config |
| 131 | + 'config': { |
| 132 | + k: v for k, v in self.config.items() if k in ['model', 'optimizer', 'trainer'] |
| 133 | + } |
| 134 | + } |
| 135 | + filename = str(self.checkpoint_dir / f'{self.model_id}_checkpoints.pth') |
| 136 | + torch.save(state, filename) |
| 137 | + self.logger.info("Saving checkpoint: {} ...".format(filename)) |
| 138 | + if save_best: |
| 139 | + best_path = str(self.checkpoint_dir / f'{self.model_id}_best.pth') |
| 140 | + torch.save(state, best_path) |
| 141 | + self.logger.info("Saving current best: model_best.pth ...") |
| 142 | + |
| 143 | + def _resume_checkpoint(self, resume_path): |
| 144 | + """ |
| 145 | + Resume from saved checkpoints |
| 146 | +
|
| 147 | + :param resume_path: Checkpoint path to be resumed |
| 148 | + """ |
| 149 | + resume_path = str(resume_path) |
| 150 | + self.logger.info("Loading checkpoint: {} ...".format(resume_path)) |
| 151 | + checkpoint = torch.load(resume_path) |
| 152 | + self.start_epoch = checkpoint['epoch'] + 1 |
| 153 | + self.mnt_best = checkpoint['monitor_best'] |
| 154 | + |
| 155 | + # load architecture params from checkpoint. |
| 156 | + if checkpoint['config']['model'] != self.config['arch']: |
| 157 | + self.logger.warning("Warning: Architecture configuration given in config file is different from that of " |
| 158 | + "checkpoint. This may yield an exception while state_dict is being loaded.") |
| 159 | + self.model.load_state_dict(checkpoint['model']) |
| 160 | + |
| 161 | + # load optimizer state from checkpoint only when optimizer type is not changed. |
| 162 | + if checkpoint['config']['optimizer']['type'] != self.config['optimizer']['type']: |
| 163 | + self.logger.warning("Warning: Optimizer type given in config file is different from that of checkpoint. " |
| 164 | + "Optimizer parameters not being resumed.") |
| 165 | + else: |
| 166 | + self.optimizer.load_state_dict(checkpoint['optimizer']) |
| 167 | + |
| 168 | + self.logger.info("Checkpoint loaded. Resume training from epoch {}".format(self.start_epoch)) |
0 commit comments