|
| 1 | +import time |
| 2 | +import torch |
| 3 | +from abc import abstractmethod |
| 4 | +from numpy import inf |
| 5 | +from tqdm.auto import tqdm |
| 6 | +from ..logger import TensorboardWriter |
| 7 | + |
| 8 | + |
| 9 | +class BaseTrainer: |
| 10 | + """ |
| 11 | + Base class for all trainers |
| 12 | + """ |
| 13 | + |
| 14 | + def __init__(self, model, criterion, metric_ftns, optimizer, config): |
| 15 | + self.config = config |
| 16 | + self.logger = config.get_logger("trainer", config["trainer"]["verbosity"]) |
| 17 | + |
| 18 | + # setup GPU device if available, move model into configured device |
| 19 | + self.device, device_ids = self._prepare_device(config["n_gpu"]) |
| 20 | + self.model = model.to(self.device) |
| 21 | + if len(device_ids) > 1: |
| 22 | + self.model = torch.nn.DataParallel(model, device_ids=device_ids) |
| 23 | + |
| 24 | + self.criterion = criterion |
| 25 | + self.metric_ftns = metric_ftns |
| 26 | + self.optimizer = optimizer |
| 27 | + |
| 28 | + cfg_trainer = config["trainer"] |
| 29 | + self.epochs = cfg_trainer["epochs"] |
| 30 | + self.save_period = cfg_trainer["save_period"] |
| 31 | + self.monitor = cfg_trainer.get("monitor", "off") |
| 32 | + |
| 33 | + # configuration to monitor model performance and save best |
| 34 | + if self.monitor == "off": |
| 35 | + self.mnt_mode = "off" |
| 36 | + self.mnt_best = 0 |
| 37 | + else: |
| 38 | + self.mnt_mode, self.mnt_metric = self.monitor.split() |
| 39 | + assert self.mnt_mode in ["min", "max"] |
| 40 | + |
| 41 | + self.mnt_best = inf if self.mnt_mode == "min" else -inf |
| 42 | + self.early_stop = cfg_trainer.get("early_stop", inf) |
| 43 | + |
| 44 | + self.start_epoch = 1 |
| 45 | + |
| 46 | + self.checkpoint_dir = config.save_dir |
| 47 | + |
| 48 | + # setup visualization writer instance |
| 49 | + self.writer = TensorboardWriter( |
| 50 | + config.log_dir, self.logger, cfg_trainer["tensorboard"] |
| 51 | + ) |
| 52 | + |
| 53 | + if config.resume is not None: |
| 54 | + self._resume_checkpoint(config.resume) |
| 55 | + |
| 56 | + @abstractmethod |
| 57 | + def _train_epoch(self, epoch): |
| 58 | + """ |
| 59 | + Training logic for an epoch |
| 60 | +
|
| 61 | + :param epoch: Current epoch number |
| 62 | + """ |
| 63 | + raise NotImplementedError |
| 64 | + |
| 65 | + def train(self, callback=None, callback_freq=1): |
| 66 | + """ |
| 67 | + Full training logic |
| 68 | + """ |
| 69 | + not_improved_count = 0 |
| 70 | + tik = time.time() |
| 71 | + if "mle" in self.config["loss"]["type"]: |
| 72 | + if self.config["arch"]["args"]["pred_unspliced"]: |
| 73 | + self.candidate_states = torch.cat( |
| 74 | + [ |
| 75 | + self.data_loader.dataset.Sx_sz, |
| 76 | + self.data_loader.dataset.Ux_sz, |
| 77 | + ], |
| 78 | + dim=1, |
| 79 | + ).to(self.device) |
| 80 | + else: |
| 81 | + self.candidate_states = self.data_loader.dataset.Sx_sz.to(self.device) |
| 82 | + |
| 83 | + # Create progress bar for epochs |
| 84 | + use_pbar = self.config["trainer"].get("use_progress_bar", True) |
| 85 | + if use_pbar: |
| 86 | + pbar = tqdm(range(self.start_epoch, self.epochs + 1), |
| 87 | + desc="Training", |
| 88 | + dynamic_ncols=True, |
| 89 | + leave=True, |
| 90 | + position=0) |
| 91 | + else: |
| 92 | + pbar = range(self.start_epoch, self.epochs + 1) |
| 93 | + |
| 94 | + for epoch in pbar: |
| 95 | + result = self._train_epoch(epoch) |
| 96 | + |
| 97 | + # save logged informations into log dict |
| 98 | + log = {"epoch": epoch, "time:": time.time() - tik} |
| 99 | + log.update(result) |
| 100 | + tik = time.time() |
| 101 | + |
| 102 | + # Update progress bar with metrics or print to logger |
| 103 | + if use_pbar: |
| 104 | + postfix_dict = {k: f'{v:.4f}' if isinstance(v, float) else v |
| 105 | + for k, v in log.items() if k not in ['epoch', 'time:']} |
| 106 | + pbar.set_postfix(postfix_dict) |
| 107 | + pbar.refresh() |
| 108 | + else: |
| 109 | + # print logged informations to the screen |
| 110 | + for key, value in log.items(): |
| 111 | + self.logger.info(" {:15s}: {}".format(str(key), value)) |
| 112 | + |
| 113 | + if callback is not None: |
| 114 | + if epoch % callback_freq == 0: |
| 115 | + callback(epoch) |
| 116 | + |
| 117 | + # evaluate model performance according to configured metric, save best checkpoint as model_best |
| 118 | + best = False |
| 119 | + if self.mnt_mode != "off": |
| 120 | + try: |
| 121 | + # check whether model performance improved or not, according to specified metric(mnt_metric) |
| 122 | + improved = ( |
| 123 | + self.mnt_mode == "min" and log[self.mnt_metric] <= self.mnt_best |
| 124 | + ) or ( |
| 125 | + self.mnt_mode == "max" and log[self.mnt_metric] >= self.mnt_best |
| 126 | + ) |
| 127 | + except KeyError: |
| 128 | + self.logger.warning( |
| 129 | + "Warning: Metric '{}' is not found. " |
| 130 | + "Model performance monitoring is disabled.".format( |
| 131 | + self.mnt_metric |
| 132 | + ) |
| 133 | + ) |
| 134 | + self.mnt_mode = "off" |
| 135 | + improved = False |
| 136 | + |
| 137 | + if improved: |
| 138 | + self.mnt_best = log[self.mnt_metric] |
| 139 | + not_improved_count = 0 |
| 140 | + best = True |
| 141 | + else: |
| 142 | + not_improved_count += 1 |
| 143 | + |
| 144 | + if not_improved_count > self.early_stop: |
| 145 | + if use_pbar: |
| 146 | + pbar.close() |
| 147 | + self.logger.info( |
| 148 | + "Validation performance didn't improve for {} epochs. " |
| 149 | + "Training stops.".format(self.early_stop) |
| 150 | + ) |
| 151 | + break |
| 152 | + |
| 153 | + if epoch % self.save_period == 0: |
| 154 | + self._save_checkpoint(epoch, save_best=best) |
| 155 | + |
| 156 | + if use_pbar: |
| 157 | + pbar.close() |
| 158 | + |
| 159 | + def train_with_epoch_callback(self, callback, freq): |
| 160 | + self.train(callback, freq) |
| 161 | + |
| 162 | + def _prepare_device(self, n_gpu_use): |
| 163 | + """ |
| 164 | + setup GPU device if available, move model into configured device |
| 165 | + """ |
| 166 | + n_gpu = torch.cuda.device_count() |
| 167 | + if n_gpu_use > 0 and n_gpu == 0: |
| 168 | + self.logger.warning( |
| 169 | + "Warning: There's no GPU available on this machine," |
| 170 | + "training will be performed on CPU." |
| 171 | + ) |
| 172 | + n_gpu_use = 0 |
| 173 | + if n_gpu_use > n_gpu: |
| 174 | + self.logger.warning( |
| 175 | + "Warning: The number of GPU's configured to use is {}, but only {} are available " |
| 176 | + "on this machine.".format(n_gpu_use, n_gpu) |
| 177 | + ) |
| 178 | + n_gpu_use = n_gpu |
| 179 | + device = torch.device("cuda:0" if n_gpu_use > 0 else "cpu") |
| 180 | + list_ids = list(range(n_gpu_use)) |
| 181 | + return device, list_ids |
| 182 | + |
| 183 | + def _save_checkpoint(self, epoch, save_best=False): |
| 184 | + """ |
| 185 | + Saving checkpoints |
| 186 | +
|
| 187 | + :param epoch: current epoch number |
| 188 | + :param log: logging information of the epoch |
| 189 | + :param save_best: if True, rename the saved checkpoint to 'model_best.pth' |
| 190 | + """ |
| 191 | + arch = type(self.model).__name__ |
| 192 | + state = { |
| 193 | + "arch": arch, |
| 194 | + "epoch": epoch, |
| 195 | + "state_dict": self.model.state_dict(), |
| 196 | + "optimizer": self.optimizer.state_dict(), |
| 197 | + "monitor_best": self.mnt_best, |
| 198 | + "config": self.config, |
| 199 | + } |
| 200 | + filename = str(self.checkpoint_dir / "checkpoint-epoch{}.pth".format(epoch)) |
| 201 | + torch.save(state, filename) |
| 202 | + self.logger.info("Saving checkpoint: {} ...".format(filename)) |
| 203 | + if save_best: |
| 204 | + best_path = str(self.checkpoint_dir / "model_best.pth") |
| 205 | + torch.save(state, best_path) |
| 206 | + self.logger.info("Saving current best: model_best.pth ...") |
| 207 | + |
| 208 | + def _resume_checkpoint(self, resume_path): |
| 209 | + """ |
| 210 | + Resume from saved checkpoints |
| 211 | +
|
| 212 | + :param resume_path: Checkpoint path to be resumed |
| 213 | + """ |
| 214 | + resume_path = str(resume_path) |
| 215 | + self.logger.info("Loading checkpoint: {} ...".format(resume_path)) |
| 216 | + checkpoint = torch.load(resume_path) |
| 217 | + self.start_epoch = checkpoint["epoch"] + 1 |
| 218 | + self.mnt_best = checkpoint["monitor_best"] |
| 219 | + |
| 220 | + # load architecture params from checkpoint. |
| 221 | + if checkpoint["config"]["arch"] != self.config["arch"]: |
| 222 | + self.logger.warning( |
| 223 | + "Warning: Architecture configuration given in config file is different from that of " |
| 224 | + "checkpoint. This may yield an exception while state_dict is being loaded." |
| 225 | + ) |
| 226 | + self.model.load_state_dict(checkpoint["state_dict"]) |
| 227 | + |
| 228 | + # load optimizer state from checkpoint only when optimizer type is not changed. |
| 229 | + if ( |
| 230 | + checkpoint["config"]["optimizer"]["type"] |
| 231 | + != self.config["optimizer"]["type"] |
| 232 | + ): |
| 233 | + self.logger.warning( |
| 234 | + "Warning: Optimizer type given in config file is different from that of checkpoint. " |
| 235 | + "Optimizer parameters not being resumed." |
| 236 | + ) |
| 237 | + else: |
| 238 | + self.optimizer.load_state_dict(checkpoint["optimizer"]) |
| 239 | + |
| 240 | + self.logger.info( |
| 241 | + "Checkpoint loaded. Resume training from epoch {}".format(self.start_epoch) |
| 242 | + ) |
0 commit comments