我们的训练中断了,一共训练50epoch,每10个epoch保存一个checkpoint,现在跑到42个epoch,然后需要恢复训练。目前的文件有:① import os…
- User
我们的训练中断了,一共训练50epoch,每10个epoch保存一个checkpoint,现在跑到42个epoch,然后需要恢复训练。目前的文件有:① import os import glob import torch import traceback from lib.train.admin import multigpu from torch.utils.data.distributed import DistributedSampler
class BaseTrainer: """Base trainer class. Contains functions for training and saving/loading checkpoints. Trainer classes should inherit from this one and overload the train_epoch function."""
def __init__(self, actor, loaders, optimizer, settings, lr_scheduler=None): """ args: actor - The actor for training the network loaders - list of dataset loaders, e.g. [train_loader, val_loader]. In each epoch, the trainer runs one epoch for each loader. optimizer - The optimizer used for training, e.g. Adam settings - Training settings lr_scheduler - Learning rate scheduler """ self.actor = actor self.optimizer = optimizer self.lr_scheduler = lr_scheduler self.loaders = loaders self.update_settings(settings) self.epoch = 0 self.stats = {} self.device = getattr(settings, 'device', None) if self.device is None: self.device = torch.device("cuda:0" if torch.cuda.is_available() and settings.use_gpu else "cpu") self.actor.to(self.device) self.settings = settings def update_settings(self, settings=None): """Updates the trainer settings. Must be called to update internal settings.""" if settings is not None: self.settings = settings if self.settings.env.workspace_dir is not None: self.settings.env.workspace_dir = os.path.expanduser(self.settings.env.workspace_dir) '''2021.1.4 New function: specify checkpoint dir''' if self.settings.save_dir is None: self._checkpoint_dir = os.path.join(self.settings.env.workspace_dir, 'checkpoints') else: self._checkpoint_dir = os.path.join(self.settings.save_dir, 'checkpoints') print("checkpoints will be saved to %s" % self._checkpoint_dir) if self.settings.local_rank in [-1, 0]: if not os.path.exists(self._checkpoint_dir): print("Training with multiple GPUs. checkpoints directory doesn't exist. " "Create checkpoints directory") os.makedirs(self._checkpoint_dir) else: self._checkpoint_dir = None def train(self, max_epochs, load_latest=False, fail_safe=True, load_previous_ckpt=False, distill=False): """Do training for the given number of epochs. args: max_epochs - Max number of training epochs, load_latest - Bool indicating whether to resume from latest epoch. fail_safe - Bool indicating whether the training to automatically restart in case of any crashes. """ epoch = -1 num_tries = 1 for i in range(num_tries): try: if load_latest: self.load_checkpoint() if load_previous_ckpt: directory = '{}/{}'.format(self._checkpoint_dir, self.settings.project_path_prv) self.load_state_dict(directory) if distill: directory_teacher = '{}/{}'.format(self._checkpoint_dir, self.settings.project_path_teacher) self.load_state_dict(directory_teacher, distill=True) for epoch in range(self.epoch+1, max_epochs+1): self.epoch = epoch self.train_epoch() if self.lr_scheduler is not None: if self.settings.scheduler_type != 'cosine': self.lr_scheduler.step() else: self.lr_scheduler.step(epoch - 1) # only save the last 10 checkpoints save_every_epoch = getattr(self.settings, "save_every_epoch", False) save_epochs = [79, 159, 239] if epoch > (max_epochs - 1) or save_every_epoch or epoch % 10 == 0 or epoch in save_epochs or epoch > (max_epochs - 3): # if epoch > (max_epochs - 10) or save_every_epoch or epoch % 100 == 0: if self._checkpoint_dir: if self.settings.local_rank in [-1, 0]: self.save_checkpoint() except: print('Training crashed at epoch {}'.format(epoch)) if fail_safe: self.epoch -= 1 load_latest = True print('Traceback for the error!') print(traceback.format_exc()) print('Restarting training from last epoch ...') else: raise print('Finished training!') def train_epoch(self): raise NotImplementedError def save_checkpoint(self): """Saves a checkpoint of the network and other variables.""" net = self.actor.net.module if multigpu.is_multi_gpu(self.actor.net) else self.actor.net actor_type = type(self.actor).__name__ net_type = type(net).__name__ state = { 'epoch': self.epoch, 'actor_type': actor_type, 'net_type': net_type, 'net': net.state_dict(), 'net_info': getattr(net, 'info', None), 'constructor': getattr(net, 'constructor', None), 'optimizer': self.optimizer.state_dict(), 'stats': self.stats, 'settings': self.settings } directory = '{}/{}'.format(self._checkpoint_dir, self.settings.project_path) print(directory) if not os.path.exists(directory): print("directory doesn't exist. creating...") os.makedirs(directory) # First save as a tmp file tmp_file_path = '{}/{}_ep{:04d}.tmp'.format(directory, net_type, self.epoch) torch.save(state, tmp_file_path) file_path = '{}/{}_ep{:04d}.pth.tar'.format(directory, net_type, self.epoch) # Now rename to actual checkpoint. os.rename seems to be atomic if files are on same filesystem. Not 100% sure os.rename(tmp_file_path, file_path) def load_checkpoint(self, checkpoint = None, fields = None, ignore_fields = None, load_constructor = False): """Loads a network checkpoint file. Can be called in three different ways: load_checkpoint(): Loads the latest epoch from the workspace. Use this to continue training. load_checkpoint(epoch_num): Loads the network at the given epoch number (int). load_checkpoint(path_to_checkpoint): Loads the file from the given absolute path (str). """ net = self.actor.net.module if multigpu.is_multi_gpu(self.actor.net) else self.actor.net actor_type = type(self.actor).__name__ net_type = type(net).__name__ if checkpoint is None: # Load most recent checkpoint checkpoint_list = sorted(glob.glob('{}/{}/{}_ep*.pth.tar'.format(self._checkpoint_dir, self.settings.project_path, net_type))) if checkpoint_list: checkpoint_path = checkpoint_list[-1] else: print('No matching checkpoint file found') return elif isinstance(checkpoint, int): # Checkpoint is the epoch number checkpoint_path = '{}/{}/{}_ep{:04d}.pth.tar'.format(self._checkpoint_dir, self.settings.project_path, net_type, checkpoint) elif isinstance(checkpoint, str): # checkpoint is the path if os.path.isdir(checkpoint): checkpoint_list = sorted(glob.glob('{}/*_ep*.pth.tar'.format(checkpoint))) if checkpoint_list: checkpoint_path = checkpoint_list[-1] else: raise Exception('No checkpoint found') else: checkpoint_path = os.path.expanduser(checkpoint) else: raise TypeError # Load network checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') assert net_type == checkpoint_dict['net_type'], 'Network is not of correct type.' if fields is None: fields = checkpoint_dict.keys() if ignore_fields is None: ignore_fields = ['settings'] # Never load the scheduler. It exists in older checkpoints. ignore_fields.extend(['lr_scheduler', 'constructor', 'net_type', 'actor_type', 'net_info']) # Load all fields for key in fields: if key in ignore_fields: continue if key == 'net': net.load_state_dict(checkpoint_dict[key]) elif key == 'optimizer': self.optimizer.load_state_dict(checkpoint_dict[key]) else: setattr(self, key, checkpoint_dict[key]) # Set the net info if load_constructor and 'constructor' in checkpoint_dict and checkpoint_dict['constructor'] is not None: net.constructor = checkpoint_dict['constructor'] if 'net_info' in checkpoint_dict and checkpoint_dict['net_info'] is not None: net.info = checkpoint_dict['net_info'] # Update the epoch in lr scheduler if 'epoch' in fields: self.lr_scheduler.last_epoch = self.epoch # 2021.1.10 Update the epoch in data_samplers for loader in self.loaders: if isinstance(loader.sampler, DistributedSampler): loader.sampler.set_epoch(self.epoch) return True def load_state_dict(self, checkpoint=None, distill=False): """Loads a network checkpoint file. Can be called in three different ways: load_checkpoint(): Loads the latest epoch from the workspace. Use this to continue training. load_checkpoint(epoch_num): Loads the network at the given epoch number (int). load_checkpoint(path_to_checkpoint): Loads the file from the given absolute path (str). """ if distill: net = self.actor.net_teacher.module if multigpu.is_multi_gpu(self.actor.net_teacher) \ else self.actor.net_teacher else: net = self.actor.net.module if multigpu.is_multi_gpu(self.actor.net) else self.actor.net net_type = type(net).__name__ if isinstance(checkpoint, str): # checkpoint is the path if os.path.isdir(checkpoint): checkpoint_list = sorted(glob.glob('{}/*_ep*.pth.tar'.format(checkpoint))) if checkpoint_list: checkpoint_path = checkpoint_list[-1] else: raise Exception('No checkpoint found') else: checkpoint_path = os.path.expanduser(checkpoint) else: raise TypeError # Load network print("Loading pretrained model from ", checkpoint_path) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') assert net_type == checkpoint_dict['net_type'], 'Network is not of correct type.' missing_k, unexpected_k = net.load_state_dict(checkpoint_dict["net"], strict=False) print("previous checkpoint is loaded.") print("missing keys: ", missing_k) print("unexpected keys:", unexpected_k) return True ② import os - Assistant
为了恢复训练,你可以采用以下步骤:
-
确保checkpoint目录和文件是存在并且可访问的。根据你提供的类
BaseTrainer中的load_checkpoint方法逻辑,该方法会自动地寻找最新的checkpoint文件并加载它。由于你提到训练到了第42个epoch,最近的checkpoint应该是第40个epoch的(因为每10个epoch保存一次)。 -
确保加载的checkpoint包含了所有必要的信息来恢复训练,例如模型的权重、优化器的状态以及已经训练了的epochs数量等。
-
根据你的代码,你可以使用
load_latest=True参数来启动train方法,这将会触发load_checkpoint方法,自动加载最新的checkpoint来继续训练。 -
根据你提供的代码框架,在
BaseTrainer类的train方法中,检查load_latest和load_checkpoint调用处是否正确配置,以确保训练可以从断点恢复。 -
如果使用分布式训练,请确保所有节点能够正确加载同一checkpoint。
-
最后,调用
trainer.train方法来恢复和继续训练过程。根据你的情况,你可能需要更改cfg.TRAIN.EPOCH值或其他相应的配置参数,以匹配实际的训练需求。
这里是一个伪代码示例来指导你如何操作:
# 假设trainer是你已经初始化的LTRTrainer的实例 # 根据你的代码示例,假设cfg.TRAIN.EPOCH是期望的总训练epoch数 # 确保cfg.TRAIN.EPOCH反映了你希望训练的总epoch数,包括已经训练的部分 cfg.TRAIN.EPOCH = 50 # 假设你希望总共训练50个epochs # 调用train方法,设置load_latest=True来自动加载最近的checkpoint # 如果你的训练设置需要其他参数(例如distill=True),请相应地调整 trainer.train(cfg.TRAIN.EPOCH, load_latest=True, fail_safe=True, distill=True)请确保根据实际情况调整和验证代码,上述示例只是基于你提供的代码片段。根据你的项目具体结构和配置,可能需要进一步的适配和调整。
-
- User
我们的代码中总共就上述三个文件有load_latest
- Assistant
既然代码中有
load_latest参数的用法,并且你要从最近的checkpoint恢复训练,那你已经设置了一个合适的起点。根据你提供的代码,以及你的目标是从第42个epoch处断点恢复训练(假定最近的checkpoint是第40个epoch),以下是一些具体的步骤和要注意的点,帮助确保你能成功地从checkpoint恢复训练:-
确认Checkpoint的位置和完整性: 首先,确认存有checkpoint文件的目录是存在的,并且在该目录下确实有第40个epoch的checkpoint文件。这些文件通常是以
.pth或者.tar等格式保存的模型权重和训练状态。 -
恢复训练的入口点: 在你的训练脚本(可能是
run函数)中设置load_latest=True,然后启动训练流程。这个参数会在训练开始时触发load_checkpoint逻辑,自动查找并加载最新的checkpoint来恢复训练。 -
验证环境: 检查你的训练环境(Python版本,PyTorch版本,CUDA版本等)是否与保存checkpoint时的环境一致。环境的不一致有时会导致加载模型时出现问题。
-
单机与分布式训练: 如果你是在分布式训练环境中,确保所有节点都能正常访问checkpoint文件,并且你已经正确地设置了所有必要的分布式训练参数(比如
local_rank)。 -
恢复其他状态: 确保除了模型权重以外的其他训练状态也被正确地恢复了,比如优化器的状态、已完成的训练轮次(epoch)等。
-
调用
train方法: 使用类似下面的代码唤醒训练进程:if __name__ == '__main__': settings = YourSettings() # 确保这包含了所有必要的配置信息 run(settings)确保
YourSettings()中包含了正确的配置,比如project_path或者其他对找到checkpoint文件夹路径有影响的参数。
-
- User
目前两个文件中的load_latest都是truth,那么是不是我直接训练即可
- Assistant
是的,如果在你的代码中
load_latest已经被设置为True,并且你确认checkpoint文件存在、可访问并且是最新的(在这个案例中是第40个epoch的checkpoint),那么你理论上可以直接继续训练,系统会自动从最近的checkpoint恢复。在继续训练之前,请确保以下几点:
-
Checkpoint目录正确: 确认你的代码中定义的checkpoint目录(
self._checkpoint_dir)指向的是包含正确checkpoint文件的目录。 -
环境配置: 确认你的运行环境(包括硬件配置、软件版本等)与训练停止时的环境兼容或一致。如果你在不同的环境中恢复训练,可能会遇到问题。
-
必要的预处理: 根据你的模型和数据集,确认在开始训练之前,所有必要的预处理步骤都已经设置好了,比如数据增强、数据加载器的初始化等。
-
验证设置: 还一次检查其他可能影响恢复过程的设置,比如
distill参数等,确定它们是否按照你的预期进行配置。
一旦上述准备工作完成,你就可以启动训练脚本,模型训练应该会从第40个epoch的checkpoint自动恢复。根据你提供的信息,这可以通过简单地运行你的训练入口函数(例如,在代码片段中可能是
run(settings))来实现。请注意,尽管
load_latest=True确实指示系统从最新的checkpoint加载模型和训练状态,但在实际操作过程中仍然建议仔细监控训练的开始阶段,以确认模型确实是从预期的checkpoint恢复的。此外,如果你的训练过程涉及到任何形式的验证过程或中间状态的检查,确保这些都按照你的预期执行。 -
- User
就是目前根据前面提到的三个文件,我们按照原来为配置,再运行训练,是否可以基于40epoch继续训练
- Assistant
基于你提供的信息和代码片段,如果
load_latest=True已经被设置为True,那么理论上你应该可以直接继续训练,系统会自动从第40个epoch的checkpoint恢复。这意味着,只要checkpoint正确保存且路径设置无误,你不需要做额外的配置,只需再次运行训练脚本即可基于第40个epoch的checkpoint继续训练过程。确保你跟随以下步骤:
-
检查Checkpoint: 确认第40epoch的checkpoint文件确实存在于
self._checkpoint_dir定义的目录下,且该文件是完整未损坏的。 -
评估训练环境: 确认你的训练环境(例如,硬件配置、软件环境等)与当初保存checkpoint时的环境相兼容。
-
复查日志和输出: 在恢复训练之前和开始训练后的初期,仔细查看训练日志,确认训练确实从第40个epoch开始重启。你可能需要检查日志文件确认是否有错误或警告需要处理。
-
运行训练脚本: 基于你的设置,直接重新运行训练脚本应该可以开始继续训练。你可能是通过一种类似下面的方式启动训练的:
if __name__ == '__main__': settings = YourSetupFunction() # 用来初始化配置的函数 run(settings) # 运行训练的函数
只要所有设定正确无误,这种方法应该允许你从上一个保存的checkpoint(第40个epoch)无缝继续训练。
请记得,持续监控训练进程,特别是在训练初期,以确保一切按照预期进行。如果出现加载checkpoint的问题或训练不如预期开始,及时回顾错误和日志信息,可能需要检查和调整配置或代码逻辑。
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.