transformers documentation

Callbacks

Callbacks

Callbacks are objects that can customize the behavior of the training loop in the PyTorch Trainer (this feature is not yet implemented in TensorFlow) that can inspect the training loop state (for progress reporting, logging on TensorBoard or other ML platforms
) and take decisions (like early stopping).

Callbacks are “read only” pieces of code, apart from the TrainerControl object they return, they cannot change anything in the training loop. For customizations that require changes in the training loop, you should subclass Trainer and override the methods you need (see trainer for examples).

By default a Trainer will use the following callbacks:

The main class that implements callbacks is TrainerCallback. It gets the TrainingArguments used to instantiate the Trainer, can access that Trainer’s internal state via TrainerState, and can take some actions on the training loop via TrainerControl.

Available Callbacks

Here is the list of the available TrainerCallback in the library:

class transformers.integrations.CometCallback < > expand 

( )

A TrainerCallback that sends the logs to Comet ML.

setup < > expand 

( args state model )

Setup the optional Comet.ml integration.

Environment: COMETMODE (str, _optional): “OFFLINE”, “ONLINE”, or “DISABLED” COMETPROJECT_NAME (str, _optional): Comet.ml project name for experiments COMETOFFLINE_DIRECTORY (str, _optional): Folder to use for saving offline experiments when COMET_MODE is “OFFLINE”

For a number of configurable items in the environment, see here.

class transformers.DefaultFlowCallback < > expand 

( )

A TrainerCallback that handles the default flow of the training loop for logs, evaluation and checkpoints.

class transformers.PrinterCallback < > expand 

( )

A bare TrainerCallback that just prints the logs.

class transformers.ProgressCallback < > expand 

( )

A TrainerCallback that displays the progress of training or evaluation.

class transformers.EarlyStoppingCallback < > expand 

( early_stopping_patience: int = 1 early_stopping_threshold: typing.Optional[float] = 0.0 )

A TrainerCallback that handles early stopping.

This callback depends on TrainingArguments argument load_best_model_at_end functionality to set best_metric in TrainerState.

class transformers.integrations.TensorBoardCallback < > expand 

( tb_writer = None )

A TrainerCallback that sends the logs to TensorBoard.

class transformers.integrations.WandbCallback < > expand 

( )

A TrainerCallback that sends the logs to Weight and Biases.

setup < > expand 

( args state model **kwargs )

Setup the optional Weights & Biases (wandb) integration.

One can subclass and override this method to customize the setup if needed. Find more information here. You can also override the following environment variables:

Environment: WANDBLOG_MODEL (bool, _optional, defaults to False): Whether or not to log model as artifact at the end of training. Use along with TrainingArguments.load_best_model_at_end to upload best model. WANDBWATCH (str, _optional defaults to "gradients"): Can be "gradients", "all" or "false". Set to "false" to disable gradient logging or "all" to log gradients and parameters. WANDBPROJECT (str, _optional, defaults to "huggingface"): Set this to a custom string to store results in a different project. WANDBDISABLED (bool, _optional, defaults to False): Whether or not to disable wandb entirely. Set WANDB_DISABLED=true to disable.

class transformers.integrations.MLflowCallback < > expand 

( )

A TrainerCallback that sends the logs to MLflow.

setup < > expand 

( args state model )

Setup the optional MLflow integration.

Environment: HFMLFLOW_LOG_ARTIFACTS (str, _optional): Whether to use MLflow .log_artifact() facility to log artifacts.

This only makes sense if logging to a remote server, e.g. s3 or GCS. If set to True or 1, will copy whatever is in TrainingArguments’s output_dir to the local or remote artifact storage. Using it without a remote storage will just copy the files to your artifact location.

class transformers.integrations.AzureMLCallback < > expand 

( azureml_run = None )

A TrainerCallback that sends the logs to AzureML.

TrainerCallback

class transformers.TrainerCallback < > expand 

( )

A class for objects that will inspect the state of the training loop at some events and take some decisions. At each of those events the following arguments are available:

The control object is the only one that can be changed by the callback, in which case the event that changes it should return the modified version.

The argument args, state and control are positionals for all events, all the others are grouped in kwargs. You can unpack the ones you need in the signature of the event using them. As an example, see the code of the simple PrinterCallback.

Example:

class PrinterCallback(TrainerCallback):

def on_log(self, args, state, control, logs=None, **kwargs):
_ = logs.pop("total_flos", None)
if state.is_local_process_zero:
print(logs)
on_epoch_begin < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the beginning of an epoch.

on_epoch_end < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the end of an epoch.

on_evaluate < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called after an evaluation phase.

on_init_end < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the end of the initialization of the Trainer.

on_log < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called after logging the last logs.

on_prediction_step < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called after a prediction step.

on_save < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called after a checkpoint save.

on_step_begin < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the beginning of a training step. If using gradient accumulation, one training step might take several inputs.

on_step_end < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the end of a training step. If using gradient accumulation, one training step might take several inputs.

on_substep_end < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the end of an substep during gradient accumulation.

on_train_begin < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the beginning of training.

on_train_end < > expand 

( args: TrainingArguments state: TrainerState control: TrainerControl **kwargs )

Event called at the end of training.

Here is an example of how to register a custom callback with the PyTorch Trainer:

class MyCallback(TrainerCallback):
    "A callback that prints a message at the beginning of training"

    def on_train_begin(self, args, state, control, **kwargs):
        print("Starting training")

trainer = Trainer(
    model,
    args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    callbacks=[MyCallback]  # We can either pass the callback class this way or an instance of it (MyCallback())
)

Another way to register a callback is to call trainer.add_callback() as follows:

trainer = Trainer(...)
trainer.add_callback(MyCallback)
# Alternatively, we can pass an instance of the callback class
trainer.add_callback(MyCallback())

TrainerState

class transformers.TrainerState < > expand 

( epoch: typing.Optional[float] = None global_step: int = 0 max_steps: int = 0 num_train_epochs: int = 0 total_flos: float = 0 log_history: typing.List[typing.Dict[str, float]] = None best_metric: typing.Optional[float] = None best_model_checkpoint: typing.Optional[str] = None is_local_process_zero: bool = True is_world_process_zero: bool = True is_hyper_param_search: bool = False trial_name: str = None trial_params: typing.Dict[str, typing.Union[str, float, int, bool]] = None )

A class containing the Trainer inner state that will be saved along the model and optimizer when checkpointing and passed to the TrainerCallback.

In all this class, one step is to be understood as one update step. When using gradient accumulation, one update step may require several forward and backward passes: if you use gradient_accumulation_steps=n, then one update step requires going through n batches.

load_from_json < > expand 

( json_path: str )

Create an instance from the content of json_path.

save_to_json < > expand 

( json_path: str )

Save the content of this instance in JSON format inside json_path.

TrainerControl

class transformers.TrainerControl < > expand 

( should_training_stop: bool = False should_epoch_stop: bool = False should_save: bool = False should_evaluate: bool = False should_log: bool = False )

A class that handles the Trainer control flow. This class is used by the TrainerCallback to activate some switches in the training loop.