Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

训练时,基于训练好的checkpoint继续训练,应该在代码中如何设置?

  1. User

    训练时,基于训练好的checkpoint继续训练,应该在代码中如何设置?

  2. Assistant

    基于已经训练好的模型(checkpoint)继续训练主要涉及到加载模型参数的步骤,具体的实现方式可能会因所使用的框架(如TensorFlow, PyTorch等)而异。下面我会分别以PyTorch和TensorFlow为例,简单描述如何设置。

    PyTorch

    在PyTorch中,您可以使用torch.load函数加载已保存的模型参数,然后通过load_state_dict方法将这些参数载入模型中。假设您已经有一个模型的实例model和优化器optimizer,可以这样做:

    # 导入需要的库
    import torch
    
    # 假设模型定义为 model,优化器定义为 optimizer
    
    # 加载模型参数
    checkpoint = torch.load("path_to_your_checkpoint.pth")
    model.load_state_dict(checkpoint['model_state_dict'])
    
    # 如果你还需要加载优化器的状态
    optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
    
    # 如果训练时使用了epoch记录,也可以从checkpoint加载
    epoch = checkpoint['epoch']
    
    # 可选:如果使用到了学习率调度器
    scheduler.load_state_dict(checkpoint['scheduler'])
    
    # 然后可以继续训练模型
    

    TensorFlow/Keras

    在使用TensorFlow或Keras时,可以通过load_model来加载整个模型,或者通过load_weights仅加载模型的权重。以下是仅加载模型权重的一个示例:

    from tensorflow.keras.models import load_model
    
    # 假设你的模型定义在 model 变量中
    
    # 加载权重
    model.load_weights('path_to_your_checkpoint.h5')
    
    # 继续训练模型
    

    如果你使用的是tf.train.Checkpoint管理模型和优化器等的状态,那么可以这样加载:

    import tensorflow as tf
    
    # 假设模型和优化器的定义
    model = ...  # Your model definition
    optimizer = ...  # Your optimizer definition
    
    ckpt = tf.train.Checkpoint(model=model, optimizer=optimizer)
    ckpt_manager = tf.train.CheckpointManager(ckpt, directory='your_checkpoint_dir', max_to_keep=5)
    
    # 恢复最新的checkpoint
    ckpt.restore(ckpt_manager.latest_checkpoint)
    
    # 如果检查点存在,可以继续训练
    if ckpt_manager.latest_checkpoint:
        print("Restored from {}".format(ckpt_manager.latest_checkpoint))
    else:
        print("Initializing from scratch.")
    
    # 继续训练模型
    

    保证代码中已适当配置模型定义和训练循环后,通过以上方法可以从特定的checkpoint继续训练。记得保存模型时也要同时保存训练的相关状态(如epoch,优化器状态等),以便完整地恢复训练状态。

  3. User

    解读: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
    
  4. Assistant

    这个BaseTrainer类提供了一个基本的深度学习模型训练框架,包括训练过程、保存/加载检查点(checkpoints)、更新设置等功能。它主要用于简化训练循环的实现,同时提供了一些高级功能,如从最新或特定的检查点恢复训练,多GPU训练支持,以及分布式采样。以下是对这个类中一些关键部分的解释:

    初始化 (__init__)

    • 初始化一个BaseTrainer实例,需要传入模型(actor)、数据加载器(loaders)、优化器(optimizer)、训练设置(settings)以及可选的学习率调度器(lr_scheduler)。
    • 设置中的device决定了模型要在CPU还是GPU上训练,这取决于是否有可用的GPU以及设置中的use_gpu标志。
    • 初始化时还将设置相关的工作目录和检查点存储位置。

    训练 (train)

    • train方法控制整个训练过程,包括选择是否从最近的或特定的检查点恢复训练、异常处理和自动重启训练(如果启用了fail_safe)。
    • 在每个epoch结束后,根据设置,它可以保存当前模型的检查点。保存策略可以是保存最后10个检查点,指定特定epoch保存,或者每隔10个epoch保存一次。

    训练每个周期 (train_epoch)

    • 这是一个抽象的方法,需要在继承BaseTrainer的子类中实现。它定义了在每个训练周期(epoch)中完成的具体训练步骤。

    保存检查点 (save_checkpoint)

    • 这个方法用于保存当前训练状态的检查点。它包括了模型状态、优化器状态、当前训练epoch和其他相关设置信息。
    • 为了防止在写入文件时发生中断导致的文件损坏,它先将状态保存到一个临时文件中,然后再将这个临时文件重命名为最终的检查点文件。这一步操作在大多数文件系统上被认为是原子性的。

    加载检查点 (load_checkpoint)

    • 这个方法用于从已保存的检查点中恢复模型的状态。这个方法非常灵活,可以根据提供的参数恢复最新的检查点、特定epoch的检查点或从指定路径的检查点恢复。
    • 首先检查提供的检查点类型,然后加载对应的检查点文件。在加载过程中,它会确认检查点中的模型类型与当前模型是否匹配,然后恢复模型状态和其他相关信息。

    加载状态字典 (load_state_dict)

    • 这个方法用于从指定路径的检查点中加载模型权重,支持普通模型和蒸馏(distill)中的教师模型的检查点加载。
    • 在加载检查点之前会确定要加载到的目标网络(标准网络或教师网络),然后按路径加载检查点字典,并从中恢复网络权重。该方法还会报告遗漏和非预期的键。

    整个类设计得既灵活又健壮,支持多种深度学习实验的常见需求,包括高效地保存和恢复训练进度,使得实验过程更加顺畅、可控。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.