This callback enables flexible, multi-phase, scheduled fine-tuning of foundational models.
Used to implement flexible fine-tuning training schedules
- class finetuning_scheduler.fts.FinetuningScheduler(ft_schedule=None, max_depth=- 1, base_max_lr=1e-05, restore_best=True, gen_ft_sched_only=False, epoch_transitions_only=False, reinit_lr_cfg=None, allow_untested=False, apply_lambdas_new_pgs=False)¶
This callback enables flexible, multi-phase, scheduled fine-tuning of foundational models. Gradual unfreezing/thawing can help maximize foundational model knowledge retention while allowing (typically upper layers of) the model to optimally adapt to new tasks during transfer learning.
FinetuningSchedulerorchestrates the gradual unfreezing of models via a fine-tuning schedule that is either implicitly generated (the default) or explicitly provided by the user (more computationally efficient).
Fine-tuning phase transitions are driven by
FTSEarlyStoppingcriteria (a multi-phase extension of
EarlyStopping), user-specified epoch transitions or a composition of the two (the default mode). A
FinetuningSchedulertraining session completes when the final phase of the schedule has its stopping criteria met. See Early Stopping for more details on that callback’s configuration.
Schedule definition is facilitated via
gen_ft_schedule()which dumps a default fine-tuning schedule (by default using a naive, 2-parameters per level heuristic) which can be adjusted as desired by the user and subsuquently passed to the callback. Implicit fine-tuning mode generates the default schedule and proceeds to fine-tune according to the generated schedule. Implicit fine-tuning will often be less computationally efficient than explicit fine-tuning but can often serve as a good baseline for subsquent explicit schedule refinement and can marginally outperform many explicit schedules.
from pytorch_lightning import Trainer from pytorch_lightning.callbacks import FinetuningScheduler trainer = Trainer(callbacks=[FinetuningScheduler()])
Define and configure a scheduled fine-tuning training session.
None]) – The fine-tuning schedule to be executed. Usually will be a .yaml file path but can also be a properly structured Dict. See Specifying a Fine-Tuning Schedule for the basic schedule format. See LR Scheduler Reinitialization for more complex schedule configurations (including per-phase LR scheduler reinitialization). If a schedule is not provided, will generate and execute a default fine-tuning schedule using the provided
LightningModule. See the default schedule. Defaults to
int) – Maximum schedule depth to which the defined fine-tuning schedule should be executed. Specifying -1 or an integer > (number of defined schedule layers) will result in the entire fine-tuning schedule being executed. Defaults to -1.
float) – The default maximum learning rate to use for the parameter groups associated with each scheduled fine-tuning depth if not explicitly specified in the fine-tuning schedule. If overridden to
None, will be set to the
lrof the first scheduled fine-tuning depth scaled by 1e-1. Defaults to 1e-5.
bool) – If
True, generate the default fine-tuning schedule to
Trainer.log_dir(it will be named after your
LightningModulesubclass with the suffix
_ft_schedule.yaml) and exit without training. Typically used to generate a default schedule that will be adjusted by the user before training. Defaults to
bool) – If
True, use epoch-driven stopping criteria exclusively (rather than composing
FTSEarlyStoppingand epoch-driven criteria which is the default). If using this mode, an epoch-driven transition (
max_transition_epoch>= 0) must be specified for each phase. If unspecified,
max_transition_epochdefaults to -1 for each phase which signals the application of
FTSEarlyStoppingcriteria only. epoch_transitions_only defaults to
A lr scheduler reinitialization configuration dictionary consisting of at minimum a nested
lr_scheduler_initdictionary with a
class_pathkey specifying the class of the lr scheduler to be instantiated. Optionally, an
init_argsdictionary of arguments to initialize the lr scheduler with may be included. Additionally, one may optionally include arguments to pass to PyTorch Lightning’s lr scheduler configuration
pl_lrs_cfgdictionary. By way of example, one could configure this dictionary via the
LightningCLIwith the following:
reinit_lr_cfg: lr_scheduler_init: class_path: torch.optim.lr_scheduler.StepLR init_args: step_size: 1 gamma: 0.7 pl_lrs_cfg: interval: epoch frequency: 1 name: Implicit_Reinit_LR_Scheduler
True, allows the use of custom or unsupported training strategies and lr schedulers (e.g.
MyCustomLRScheduler) . Defaults to
Custom or officially unsupported strategies and lr schedulers can be used by setting
Some officially unsupported strategies may work unaltered and are only unsupported due to the
Fine-Tuning Schedulerproject’s lack of CI/testing resources for that strategy (e.g.
Most unsupported strategies and schedulers, however, are currently unsupported because they require varying degrees of modification to be compatible.
For instance, with respect to strategies,
tpu_spawnan override of the current broadcast method to include python objects.
Regarding lr schedulers,
SequentialLRare examples of schedulers not currently supported due to the configuration complexity and semantic conflicts supporting them would introduce. If a supported torch lr scheduler does not meet your requirements, one can always subclass a supported lr scheduler and modify it as required (e.g.
LambdaLRis especially useful for this).
bool) – If
True, applies most recent lambda in
lr_lambdaslist to newly added optimizer groups for lr schedulers that have a
lr_lambdasattribute. Note this option only applies to phases without reinitialized lr schedulers. Phases with defined lr scheduler reinitialization configs will always apply the specified lambdas. Defaults to
Freezes all model parameters so that parameter subsets can be subsequently thawed according to the fine- tuning schedule.
After loading a checkpoint, load the saved
FinetuningSchedulercallback state and update the current callback state accordingly.
- on_before_zero_grad(trainer, pl_module, optimizer)¶
Afer the latest optimizer step, update the
_fts_state, incrementing the global fine-tuning steps taken
- on_fit_start(trainer, pl_module)¶
Before beginning training, ensure an optimizer configuration supported by
- on_train_end(trainer, pl_module)¶
_fts_stateon end of training to ensure final training state is consistent with epoch semantics.
- on_train_epoch_start(trainer, pl_module)¶
Before beginning a training epoch, configure the internal
_fts_state, prepare the next scheduled fine-tuning level and store the updated optimizer configuration before continuing training
Restore the current best model checkpoint, according to
- Return type
- setup(trainer, pl_module, stage)¶
Validate a compatible
Strategystrategy is being used and ensure all
FinetuningSchedulercallback dependencies are met. If a valid configuration is present, then either dump the default fine-tuning schedule OR 1. configure the
FTSEarlyStoppingcallback (if relevant) 2. initialize the
_fts_state3. freeze the target
LightningModuleparameters Finally, initialize the
FinetuningSchedulertraining session in the training environment.
- Return type
Phase transition logic is contingent on whether we are composing
FTSEarlyStoppingcriteria with epoch-driven transition constraints or exclusively using epoch-driven transition scheduling. (i.e.,
Before saving a checkpoint, add the
FinetuningSchedulercallback state to be saved.
Prepare and execute the next scheduled fine-tuning level 1. Restore the current best model checkpoint if appropriate 2. Thaw model parameters according the the defined schedule 3. Synchronize the states of
FinetuningSchedulercallback initially only supports single-schedule/optimizer fine-tuning configurations
- Return type
- step_pg(optimizer, depth, depth_sync=True)¶
Configure optimizer parameter groups for the next scheduled fine-tuning level, adding parameter groups beyond the restored optimizer state up to
bool) – If
True, configure optimizer parameter groups for all depth indices greater than the restored checkpoint. If
False, configure groups only for the specified depth. Defaults to
- Return type
- property curr_depth: int¶
Index of the fine-tuning schedule depth currently being trained.
The index of the current fine-tuning training depth
- Return type