Save training states during training, which will be used for resuming. Args: epoch (int): Current epoch. current_iter (int): Current iteration.
(self, epoch, current_iter)
| 320 | |
| 321 | @master_only |
| 322 | def save_training_state(self, epoch, current_iter): |
| 323 | """Save training states during training, which will be used for |
| 324 | resuming. |
| 325 | |
| 326 | Args: |
| 327 | epoch (int): Current epoch. |
| 328 | current_iter (int): Current iteration. |
| 329 | """ |
| 330 | if current_iter != -1: |
| 331 | state = {'epoch': epoch, 'iter': current_iter, 'optimizers': [], 'schedulers': []} |
| 332 | for o in self.optimizers: |
| 333 | state['optimizers'].append(o.state_dict()) |
| 334 | for s in self.schedulers: |
| 335 | state['schedulers'].append(s.state_dict()) |
| 336 | save_filename = f'{current_iter}.state' |
| 337 | save_path = os.path.join(self.opt['path']['training_states'], save_filename) |
| 338 | |
| 339 | # avoid occasional writing errors |
| 340 | retry = 3 |
| 341 | while retry > 0: |
| 342 | try: |
| 343 | torch.save(state, save_path) |
| 344 | except Exception as e: |
| 345 | logger = get_root_logger() |
| 346 | logger.warning(f'Save training state error: {e}, remaining retry times: {retry - 1}') |
| 347 | time.sleep(1) |
| 348 | else: |
| 349 | break |
| 350 | finally: |
| 351 | retry -= 1 |
| 352 | if retry == 0: |
| 353 | logger.warning(f'Still cannot save {save_path}. Just ignore it.') |
| 354 | # raise IOError(f'Cannot save {save_path}.') |
| 355 | |
| 356 | def resume_training(self, resume_state): |
| 357 | """Reload the optimizers and schedulers for resumed training. |