Trainer
Trainer
The Trainer class provides an API for feature-complete training in PyTorch for most standard use cases. Itβs used in most of the example scripts.
Before instantiating your Trainer, create a TrainingArguments to access all the points of customization during training.
The API supports distributed training on multiple GPUs/TPUs, mixed precision through NVIDIA Apex and Native AMP for PyTorch.
The Trainer contains the basic training loop which supports the above features. To inject custom behavior you can subclass them and override the following methods:
- get_train_dataloader β Creates the training DataLoader. 
- get_eval_dataloader β Creates the evaluation DataLoader. 
- get_test_dataloader β Creates the test DataLoader. 
- log β Logs information on the various objects watching training. 
- create_optimizer_and_scheduler β Sets up the optimizer and learning rate scheduler if they were not passed at init. Note, that you can also subclass or override the - create_optimizerand- create_schedulermethods separately.
- create_optimizer β Sets up the optimizer if it wasnβt passed at init. 
- create_scheduler β Sets up the learning rate scheduler if it wasnβt passed at init. 
- compute_loss - Computes the loss on a batch of training inputs. 
- training_step β Performs a training step. 
- prediction_step β Performs an evaluation/test step. 
- evaluate β Runs an evaluation loop and returns metrics. 
- predict β Returns predictions (with metrics if labels are available) on a test set. 
The Trainer class is optimized for π Transformers models and can have surprising behaviors when you use it on other models. When using it on your own model, make sure:
- your model always return tuples or subclasses of ModelOutput. 
- your model can compute the loss if a - labelsargument is provided and that loss is returned as the first element of the tuple (if your model returns tuples)
- your model can accept multiple label arguments (use the - label_namesin your TrainingArguments to indicate their name to the Trainer) but none of them should be named- "label".
Here is an example of how to customize Trainer to use a weighted loss (useful when you have an unbalanced training set):
Copied
from torch import nn
from transformers import Trainer
class CustomTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False):
        labels = inputs.pop("labels")
        # forward pass
        outputs = model(**inputs)
        logits = outputs.get("logits")
        # compute custom loss (suppose one has 3 labels with different weights)
        loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device))
        loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
        return (loss, outputs) if return_outputs else lossAnother way to customize the training loop behavior for the PyTorch Trainer is to use callbacks that can inspect the training loop state (for progress reporting, logging on TensorBoard or other ML platformsβ¦) and take decisions (like early stopping).
Trainer
class transformers.Trainer
( model: typing.Union[transformers.modeling_utils.PreTrainedModel, torch.nn.modules.module.Module] = Noneargs: TrainingArguments = Nonedata_collator: typing.Optional[DataCollator] = Nonetrain_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = Noneeval_dataset: typing.Union[torch.utils.data.dataset.Dataset, typing.Dict[str, torch.utils.data.dataset.Dataset], NoneType] = Nonetokenizer: typing.Optional[transformers.tokenization_utils_base.PreTrainedTokenizerBase] = Nonemodel_init: typing.Union[typing.Callable[[], transformers.modeling_utils.PreTrainedModel], NoneType] = Nonecompute_metrics: typing.Union[typing.Callable[[transformers.trainer_utils.EvalPrediction], typing.Dict], NoneType] = Nonecallbacks: typing.Optional[typing.List[transformers.trainer_callback.TrainerCallback]] = Noneoptimizers: typing.Tuple[torch.optim.optimizer.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None)preprocess_logits_for_metrics: typing.Union[typing.Callable[[torch.Tensor, torch.Tensor], torch.Tensor], NoneType] = None )
Parameters
- model (PreTrainedModel or - torch.nn.Module, optional) β The model to train, evaluate or use for predictions. If not provided, a- model_initmust be passed.- Trainer is optimized to work with the PreTrainedModel provided by the library. You can still use your own models defined as - torch.nn.Moduleas long as they work the same way as the π Transformers models.
- args (TrainingArguments, optional) β The arguments to tweak for training. Will default to a basic instance of TrainingArguments with the - output_dirset to a directory named tmp_trainer in the current directory if not provided.
- data_collator ( - DataCollator, optional) β The function to use to form a batch from a list of elements of- train_datasetor- eval_dataset. Will default to default_data_collator() if no- tokenizeris provided, an instance of DataCollatorWithPadding otherwise.
- train_dataset ( - torch.utils.data.Datasetor- torch.utils.data.IterableDataset, optional) β The dataset to use for training. If it is a Dataset, columns not accepted by the- model.forward()method are automatically removed.- Note that if itβs a - torch.utils.data.IterableDatasetwith some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute- generatorthat is a- torch.Generatorfor the randomization that must be identical on all processes (and the Trainer will manually set the seed of this- generatorat each epoch) or have a- set_epoch()method that internally sets the seed of the RNGs used.
- eval_dataset (Union[ - torch.utils.data.Dataset, Dict[str,- torch.utils.data.Dataset]), optional) β The dataset to use for evaluation. If it is a Dataset, columns not accepted by the- model.forward()method are automatically removed. If it is a dictionary, it will evaluate on each dataset prepending the dictionary key to the metric name.
- tokenizer (PreTrainedTokenizerBase, optional) β The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs to the maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. 
- model_init ( - Callable[[], PreTrainedModel], optional) β A function that instantiates the model to be used. If provided, each call to train() will start from a new instance of the model as given by this function.- The function may have zero argument, or a single one containing the optuna/Ray Tune/SigOpt trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc). 
- compute_metrics ( - Callable[[EvalPrediction], Dict], optional) β The function that will be used to compute metrics at evaluation. Must take a EvalPrediction and return a dictionary string to metric values.
- callbacks (List of TrainerCallback, optional) β A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in here. - If you want to remove one of the default callbacks used, use the Trainer.remove_callback() method. 
- optimizers ( - Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR], optional) β A tuple containing the optimizer and the scheduler to use. Will default to an instance of AdamW on your model and a scheduler given by get_linear_schedule_with_warmup() controlled by- args.
- preprocess_logits_for_metrics ( - Callable[[torch.Tensor, torch.Tensor], torch.Tensor], optional) β A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by- compute_metrics.- Note that the labels (second parameter) will be - Noneif the dataset does not have them.
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for πTransformers.
Important attributes:
- model β Always points to the core model. If using a transformers model, it will be a PreTrainedModel subclass. 
- model_wrapped β Always points to the most external model in case one or more other modules wrap the original model. This is the model that should be used for the forward pass. For example, under - DeepSpeed, the inner model is wrapped in- DeepSpeedand then again in- torch.nn.DistributedDataParallel. If the inner model hasnβt been wrapped, then- self.model_wrappedis the same as- self.model.
- is_model_parallel β Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs). 
- place_model_on_device β Whether or not to automatically place the model on the device - it will be set to - Falseif model parallel or deepspeed is used, or if the default- TrainingArguments.place_model_on_deviceis overridden to return- False.
- is_in_train β Whether or not a model is currently running - train(e.g. when- evaluateis called while in- train)
add_callback
( callback )
Parameters
- callback ( - typeor- ~transformer.TrainerCallback) β A- ~transformer.TrainerCallbackclass or an instance of a- ~transformer.TrainerCallback. In the first case, will instantiate a member of that class.
Add a callback to the current list of ~transformer.TrainerCallback.
autocast_smart_context_manager
( cache_enabled: typing.Optional[bool] = True )
A helper wrapper that creates an appropriate context manager for autocast while feeding it the desired arguments, depending on the situation.
compute_loss
( modelinputsreturn_outputs = False )
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
compute_loss_context_manager
( )
A helper wrapper to group together context managers.
create_model_card
( language: typing.Optional[str] = Nonelicense: typing.Optional[str] = Nonetags: typing.Union[str, typing.List[str], NoneType] = Nonemodel_name: typing.Optional[str] = Nonefinetuned_from: typing.Optional[str] = Nonetasks: typing.Union[str, typing.List[str], NoneType] = Nonedataset_tags: typing.Union[str, typing.List[str], NoneType] = Nonedataset: typing.Union[str, typing.List[str], NoneType] = Nonedataset_args: typing.Union[str, typing.List[str], NoneType] = None )
Parameters
- language ( - str, optional) β The language of the model (if applicable)
- license ( - str, optional) β The license of the model. Will default to the license of the pretrained model used, if the original model given to the- Trainercomes from a repo on the Hub.
- tags ( - stror- List[str], optional) β Some tags to be included in the metadata of the model card.
- model_name ( - str, optional) β The name of the model.
- finetuned_from ( - str, optional) β The name of the model used to fine-tune this one (if applicable). Will default to the name of the repo of the original model given to the- Trainer(if it comes from the Hub).
- tasks ( - stror- List[str], optional) β One or several task identifiers, to be included in the metadata of the model card.
- dataset_tags ( - stror- List[str], optional) β One or several dataset tags, to be included in the metadata of the model card.
- dataset ( - stror- List[str], optional) β One or several dataset identifiers, to be included in the metadata of the model card.
- dataset_args ( - stror- List[str], optional) β One or several dataset arguments, to be included in the metadata of the model card.
Creates a draft of a model card using the information available to the Trainer.
create_optimizer
( )
Setup the optimizer.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainerβs init through optimizers, or subclass and override this method in a subclass.
create_optimizer_and_scheduler
( num_training_steps: int )
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainerβs init through optimizers, or subclass and override this method (or create_optimizer and/or create_scheduler) in a subclass.
create_scheduler
( num_training_steps: intoptimizer: Optimizer = None )
Parameters
- num_training_steps (int) β The number of training steps to do. 
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument.
evaluate
( eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = Noneignore_keys: typing.Optional[typing.List[str]] = Nonemetric_key_prefix: str = 'eval' )
Parameters
- eval_dataset ( - Dataset, optional) β Pass a dataset if you wish to override- self.eval_dataset. If it is a Dataset, columns not accepted by the- model.forward()method are automatically removed. It must implement the- __len__method.
- ignore_keys ( - List[str], optional) β A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
- metric_key_prefix ( - str, optional, defaults to- "eval") β An optional prefix to be used as the metrics key prefix. For example the metrics βbleuβ will be named βeval_bleuβ if the prefix is βevalβ (default)
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init compute_metrics argument).
You can also subclass and override this method to inject custom behavior.
evaluation_loop
( dataloader: DataLoaderdescription: strprediction_loss_only: typing.Optional[bool] = Noneignore_keys: typing.Optional[typing.List[str]] = Nonemetric_key_prefix: str = 'eval' )
Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict().
Works both with or without labels.
floating_point_ops
( inputs: typing.Dict[str, typing.Union[torch.Tensor, typing.Any]] ) β int
Parameters
- inputs ( - Dict[str, Union[torch.Tensor, Any]]) β The inputs and targets of the model.
Returns
int
The number of floating-point operations.
For models that inherit from PreTrainedModel, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method.
get_decay_parameter_names
( model )
Get all parameter names that weight decay will be applied to
Note that some models implement their own layernorm instead of calling nn.LayerNorm, weight decay could still apply to those modules since this function only filter out instance of nn.LayerNorm
get_eval_dataloader
( eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = None )
Parameters
- eval_dataset ( - torch.utils.data.Dataset, optional) β If provided, will override- self.eval_dataset. If it is a Dataset, columns not accepted by the- model.forward()method are automatically removed. It must implement- __len__.
Returns the evaluation ~torch.utils.data.DataLoader.
Subclass and override this method if you want to inject some custom behavior.
get_optimizer_cls_and_kwargs
( args: TrainingArguments )
Parameters
- args ( - transformers.training_args.TrainingArguments) β The training arguments for the training session.
Returns the optimizer class and optimizer parameters based on the training arguments.
get_test_dataloader
( test_dataset: Dataset )
Parameters
- test_dataset ( - torch.utils.data.Dataset, optional) β The test dataset to use. If it is a Dataset, columns not accepted by the- model.forward()method are automatically removed. It must implement- __len__.
Returns the test ~torch.utils.data.DataLoader.
Subclass and override this method if you want to inject some custom behavior.
get_train_dataloader
( )
Returns the training ~torch.utils.data.DataLoader.
Will use no sampler if train_dataset does not implement __len__, a random sampler (adapted to distributed training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
hyperparameter_search
( hp_space: typing.Union[typing.Callable[[ForwardRef('optuna.Trial')], typing.Dict[str, float]], NoneType] = Nonecompute_objective: typing.Union[typing.Callable[[typing.Dict[str, float]], float], NoneType] = Nonen_trials: int = 20direction: typing.Union[str, typing.List[str]] = 'minimize'backend: typing.Union[ForwardRef('str'), transformers.trainer_utils.HPSearchBackend, NoneType] = Nonehp_name: typing.Union[typing.Callable[[ForwardRef('optuna.Trial')], str], NoneType] = None**kwargs ) β [trainer_utils.BestRun or List[trainer_utils.BestRun]]
Expand 7 parameters
Parameters
- hp_space ( - Callable[["optuna.Trial"], Dict[str, float]], optional) β A function that defines the hyperparameter search space. Will default to- default_hp_space_optuna()or- default_hp_space_ray()or- default_hp_space_sigopt()depending on your backend.
- compute_objective ( - Callable[[Dict[str, float]], float], optional) β A function computing the objective to minimize or maximize from the metrics returned by the- evaluatemethod. Will default to- default_compute_objective().
- n_trials ( - int, optional, defaults to 100) β The number of trial runs to test.
- direction ( - stror- List[str], optional, defaults to- "minimize") β If itβs single objective optimization, direction is- str, can be- "minimize"or- "maximize", you should pick- "minimize"when optimizing the validation loss,- "maximize"when optimizing one or several metrics. If itβs multi objectives optimization, direction is- List[str], can be List of- "minimize"and- "maximize", you should pick- "minimize"when optimizing the validation loss,- "maximize"when optimizing one or several metrics.
- backend ( - stror- ~training_utils.HPSearchBackend, optional) β The backend to use for hyperparameter search. Will default to optuna or Ray Tune or SigOpt, depending on which one is installed. If all are installed, will default to optuna.
- hp_name ( - Callable[["optuna.Trial"], str]], optional) β A function that defines the trial/run name. Will default to None.
- kwargs ( - Dict[str, Any], optional) β Additional keyword arguments passed along to- optuna.create_studyor- ray.tune.run. For more information see:- the documentation of optuna.create_study 
- the documentation of tune.run 
- the documentation of sigopt 
 
Returns
[trainer_utils.BestRun or List[trainer_utils.BestRun]]
All the information about the best run or best runs for multi-objective optimization. Experiment summary can be found in run_summary attribute for Ray backend.
Launch an hyperparameter search using optuna or Ray Tune or SigOpt. The optimized quantity is determined by compute_objective, which defaults to a function returning the evaluation loss when no metric is provided, the sum of all metrics otherwise.
To use this method, you need to have provided a model_init when initializing your Trainer: we need to reinitialize the model at each new run. This is incompatible with the optimizers argument, so you need to subclass Trainer and override the method create_optimizer_and_scheduler() for custom optimizer/scheduler.
init_git_repo
( at_init: bool = False )
Parameters
- at_init ( - bool, optional, defaults to- False) β Whether this function is called before any training or not. If- self.args.overwrite_output_diris- Trueand- at_initis- True, the path to the repo (which is- self.args.output_dir) might be wiped out.
Initializes a git repo in self.args.hub_model_id.
This function is deprecated and will be removed in v4.34.0 of Transformers.
init_hf_repo
( )
Initializes a git repo in self.args.hub_model_id.
is_local_process_zero
( )
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process.
is_world_process_zero
( )
Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be True for one process).
log
( logs: typing.Dict[str, float] )
Parameters
- logs ( - Dict[str, float]) β The values to log.
Log logs on the various objects watching training.
Subclass and override this method to inject custom behavior.
log_metrics
( splitmetrics )
Parameters
- split ( - str) β Mode/split name: one of- train,- eval,- test
- metrics ( - Dict[str, float]) β The metrics returned from train/evaluate/predictmetrics: metrics dict
Log metrics in a specially formatted way
Under distributed environment this is done only for a process with rank 0.
Notes on memory reports:
In order to get memory usage report you need to install psutil. You can do that with pip install psutil.
Now when this method is run, you will see a report that will include: :
Copied
init_mem_cpu_alloc_delta   =     1301MB
init_mem_cpu_peaked_delta  =      154MB
init_mem_gpu_alloc_delta   =      230MB
init_mem_gpu_peaked_delta  =        0MB
train_mem_cpu_alloc_delta  =     1345MB
train_mem_cpu_peaked_delta =        0MB
train_mem_gpu_alloc_delta  =      693MB
train_mem_gpu_peaked_delta =        7MBUnderstanding the reports:
- the first segment, e.g., - train__, tells you which stage the metrics are for. Reports starting with- init_will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the- __init__will be reported along with the- eval_metrics.
- the third segment, is either - cpuor- gpu, tells you whether itβs the general RAM or the gpu0 memory metric.
- *_alloc_delta- is the difference in the used/allocated memory counter between the end and the start of the stage - it can be negative if a function released more memory than it allocated.
- *_peaked_delta- is any extra memory that was consumed and then freed - relative to the current allocated memory counter - it is never negative. When you look at the metrics of any stage you add up- alloc_delta+- peaked_deltaand you know how much memory was needed to complete that stage.
The reporting happens only for process of rank 0 and gpu 0 (if there is a gpu). Typically this is enough since the main process does the bulk of work, but it could be not quite so if model parallel is used and then other GPUs may use a different amount of gpu memory. This is also not the same under DataParallel where gpu0 may require much more memory than the rest since it stores the gradient and optimizer states for all participating GPUS. Perhaps in the future these reports will evolve to measure those too.
The CPU RAM metric measures RSS (Resident Set Size) includes both the memory which is unique to the process and the memory shared with other processes. It is important to note that it does not include swapped out memory, so the reports could be imprecise.
The CPU peak memory is measured using a sampling thread. Due to pythonβs GIL it may miss some of the peak memory if that thread didnβt get a chance to run when the highest memory was used. Therefore this report can be less than reality. Using tracemalloc would have reported the exact peak memory, but it doesnβt report memory allocations outside of python. So if some C++ CUDA extension allocated its own memory it wonβt be reported. And therefore it was dropped in favor of the memory sampling approach, which reads the current process memory usage.
The GPU allocated and peak memory reporting is done with torch.cuda.memory_allocated() and torch.cuda.max_memory_allocated(). This metric reports only βdeltasβ for pytorch-specific allocations, as torch.cuda memory management system doesnβt track any memory allocated outside of pytorch. For example, the very first cuda call typically loads CUDA kernels, which may take from 0.5 to 2GB of GPU memory.
Note that this tracker doesnβt account for memory allocations outside of Trainerβs __init__, train, evaluate and predict calls.
Because evaluation calls may happen during train, we canβt handle nested invocations because torch.cuda.max_memory_allocated is a single counter, so if it gets reset by a nested eval call, trainβs tracker will report incorrect info. If this pytorch issue gets resolved it will be possible to change this class to be re-entrant. Until then we will only track the outer level of train, evaluate and predict methods. Which means that if eval is called during train, itβs the latter that will account for its memory usage and that of the former.
This also means that if any other tool that is used along the Trainer calls torch.cuda.reset_peak_memory_stats, the gpu peak memory stats could be invalid. And the Trainer will disrupt the normal behavior of any such tools that rely on calling torch.cuda.reset_peak_memory_stats themselves.
For best performance you may want to consider turning the memory profiling off for production runs.
metrics_format
( metrics: typing.Dict[str, float] ) β metrics (Dict[str, float])
Parameters
- metrics ( - Dict[str, float]) β The metrics returned from train/evaluate/predict
Returns
metrics (Dict[str, float])
The reformatted metrics
Reformat Trainer metrics values to a human-readable format
num_examples
( dataloader: DataLoader )
Helper to get number of samples in a ~torch.utils.data.DataLoader by accessing its dataset. When dataloader.dataset does not exist or has no length, estimates as best it can
num_tokens
( train_dl: DataLoadermax_steps: typing.Optional[int] = None )
Helper to get number of tokens in a ~torch.utils.data.DataLoader by enumerating dataloader.
pop_callback
( callback ) β ~transformer.TrainerCallback
Parameters
- callback ( - typeor- ~transformer.TrainerCallback) β A- ~transformer.TrainerCallbackclass or an instance of a- ~transformer.TrainerCallback. In the first case, will pop the first member of that class found in the list of callbacks.
Returns
~transformer.TrainerCallback
The callback removed, if found.
Remove a callback from the current list of ~transformer.TrainerCallback and returns it.
If the callback is not found, returns None (and no error is raised).
predict
( test_dataset: Datasetignore_keys: typing.Optional[typing.List[str]] = Nonemetric_key_prefix: str = 'test' )
Parameters
- test_dataset ( - Dataset) β Dataset to run the predictions on. If it is an- datasets.Dataset, columns not accepted by the- model.forward()method are automatically removed. Has to implement the method- __len__
- ignore_keys ( - List[str], optional) β A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
- metric_key_prefix ( - str, optional, defaults to- "test") β An optional prefix to be used as the metrics key prefix. For example the metrics βbleuβ will be named βtest_bleuβ if the prefix is βtestβ (default)
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in evaluate().
If your predictions or labels have different sequence length (for instance because youβre doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100.
Returns: NamedTuple A namedtuple with the following keys:
- predictions ( - np.ndarray): The predictions on- test_dataset.
- label_ids ( - np.ndarray, optional): The labels (if the dataset contained some).
- metrics ( - Dict[str, float], optional): The potential dictionary of metrics (if the dataset contained labels).
prediction_loop
( dataloader: DataLoaderdescription: strprediction_loss_only: typing.Optional[bool] = Noneignore_keys: typing.Optional[typing.List[str]] = Nonemetric_key_prefix: str = 'eval' )
Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict().
Works both with or without labels.
prediction_step
( model: Moduleinputs: typing.Dict[str, typing.Union[torch.Tensor, typing.Any]]prediction_loss_only: boolignore_keys: typing.Optional[typing.List[str]] = None ) β Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]
Parameters
- model ( - nn.Module) β The model to evaluate.
- inputs ( - Dict[str, Union[torch.Tensor, Any]]) β The inputs and targets of the model.- The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument - labels. Check your modelβs documentation for all accepted arguments.
- prediction_loss_only ( - bool) β Whether or not to return the loss only.
- ignore_keys ( - List[str], optional) β A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
Returns
Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]
A tuple with the loss, logits and labels (each being optional).
Perform an evaluation step on model using inputs.
Subclass and override to inject custom behavior.
push_to_hub
( commit_message: typing.Optional[str] = 'End of training'blocking: bool = True**kwargs )
Parameters
- commit_message ( - str, optional, defaults to- "End of training") β Message to commit while pushing.
- blocking ( - bool, optional, defaults to- True) β Whether the function should return only when the- git pushhas finished.
- kwargs ( - Dict[str, Any], optional) β Additional keyword arguments passed along to create_model_card().
Upload self.model and self.tokenizer to the π model hub on the repo self.args.hub_model_id.
remove_callback
( callback )
Parameters
- callback ( - typeor- ~transformer.TrainerCallback) β A- ~transformer.TrainerCallbackclass or an instance of a- ~transformer.TrainerCallback. In the first case, will remove the first member of that class found in the list of callbacks.
Remove a callback from the current list of ~transformer.TrainerCallback.
save_metrics
( splitmetricscombined = True )
Parameters
- split ( - str) β Mode/split name: one of- train,- eval,- test,- all
- metrics ( - Dict[str, float]) β The metrics returned from train/evaluate/predict
- combined ( - bool, optional, defaults to- True) β Creates combined metrics by updating- all_results.jsonwith metrics of this call
Save metrics into a json file for that split, e.g. train_results.json.
Under distributed environment this is done only for a process with rank 0.
To understand the metrics please read the docstring of log_metrics(). The only difference is that raw unformatted numbers are saved in the current method.
save_model
( output_dir: typing.Optional[str] = None_internal_call: bool = False )
Will save the model, so you can reload it using from_pretrained().
Will only save from the main process.
save_state
( )
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model
Under distributed environment this is done only for a process with rank 0.
train
( resume_from_checkpoint: typing.Union[bool, str, NoneType] = Nonetrial: typing.Union[ForwardRef('optuna.Trial'), typing.Dict[str, typing.Any]] = Noneignore_keys_for_eval: typing.Optional[typing.List[str]] = None**kwargs )
Parameters
- resume_from_checkpoint ( - stror- bool, optional) β If a- str, local path to a saved checkpoint as saved by a previous instance of Trainer. If a- booland equals- True, load the last checkpoint in args.output_dir as saved by a previous instance of Trainer. If present, training will resume from the model/optimizer/scheduler states loaded here.
- trial ( - optuna.Trialor- Dict[str, Any], optional) β The trial run or the hyperparameter dictionary for hyperparameter search.
- ignore_keys_for_eval ( - List[str], optional) β A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training.
- kwargs ( - Dict[str, Any], optional) β Additional keyword arguments used to hide deprecated arguments
Main training entry point.
training_step
( model: Moduleinputs: typing.Dict[str, typing.Union[torch.Tensor, typing.Any]] ) β torch.Tensor
Parameters
- model ( - nn.Module) β The model to train.
- inputs ( - Dict[str, Union[torch.Tensor, Any]]) β The inputs and targets of the model.- The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument - labels. Check your modelβs documentation for all accepted arguments.
Returns
torch.Tensor
The tensor with training loss on this batch.
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Seq2SeqTrainer
class transformers.Seq2SeqTrainer
( model: typing.Union[ForwardRef('PreTrainedModel'), torch.nn.modules.module.Module] = Noneargs: TrainingArguments = Nonedata_collator: typing.Optional[ForwardRef('DataCollator')] = Nonetrain_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = Noneeval_dataset: typing.Union[torch.utils.data.dataset.Dataset, typing.Dict[str, torch.utils.data.dataset.Dataset], NoneType] = Nonetokenizer: typing.Optional[ForwardRef('PreTrainedTokenizerBase')] = Nonemodel_init: typing.Union[typing.Callable[[], ForwardRef('PreTrainedModel')], NoneType] = Nonecompute_metrics: typing.Union[typing.Callable[[ForwardRef('EvalPrediction')], typing.Dict], NoneType] = Nonecallbacks: typing.Optional[typing.List[ForwardRef('TrainerCallback')]] = Noneoptimizers: typing.Tuple[torch.optim.optimizer.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None)preprocess_logits_for_metrics: typing.Union[typing.Callable[[torch.Tensor, torch.Tensor], torch.Tensor], NoneType] = None )
evaluate
( eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = Noneignore_keys: typing.Optional[typing.List[str]] = Nonemetric_key_prefix: str = 'eval'**gen_kwargs )
Parameters
- eval_dataset ( - Dataset, optional) β Pass a dataset if you wish to override- self.eval_dataset. If it is an Dataset, columns not accepted by the- model.forward()method are automatically removed. It must implement the- __len__method.
- ignore_keys ( - List[str], optional) β A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
- metric_key_prefix ( - str, optional, defaults to- "eval") β An optional prefix to be used as the metrics key prefix. For example the metrics βbleuβ will be named βeval_bleuβ if the prefix is- "eval"(default)
- max_length ( - int, optional) β The maximum target length to use when predicting with the generate method.
- num_beams ( - int, optional) β Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. gen_kwargs β Additional- generatespecific kwargs.
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init compute_metrics argument).
You can also subclass and override this method to inject custom behavior.
predict
( test_dataset: Datasetignore_keys: typing.Optional[typing.List[str]] = Nonemetric_key_prefix: str = 'test'**gen_kwargs )
Parameters
- test_dataset ( - Dataset) β Dataset to run the predictions on. If it is a Dataset, columns not accepted by the- model.forward()method are automatically removed. Has to implement the method- __len__
- ignore_keys ( - List[str], optional) β A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
- metric_key_prefix ( - str, optional, defaults to- "eval") β An optional prefix to be used as the metrics key prefix. For example the metrics βbleuβ will be named βeval_bleuβ if the prefix is- "eval"(default)
- max_length ( - int, optional) β The maximum target length to use when predicting with the generate method.
- num_beams ( - int, optional) β Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. gen_kwargs β Additional- generatespecific kwargs.
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in evaluate().
If your predictions or labels have different sequence lengths (for instance because youβre doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100.
Returns: NamedTuple A namedtuple with the following keys:
- predictions ( - np.ndarray): The predictions on- test_dataset.
- label_ids ( - np.ndarray, optional): The labels (if the dataset contained some).
- metrics ( - Dict[str, float], optional): The potential dictionary of metrics (if the dataset contained labels).
TrainingArguments
class transformers.TrainingArguments
( output_dir: stroverwrite_output_dir: bool = Falsedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseevaluation_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'no'prediction_loss_only: bool = Falseper_device_train_batch_size: int = 8per_device_eval_batch_size: int = 8per_gpu_train_batch_size: typing.Optional[int] = Noneper_gpu_eval_batch_size: typing.Optional[int] = Nonegradient_accumulation_steps: int = 1eval_accumulation_steps: typing.Optional[int] = Noneeval_delay: typing.Optional[float] = 0learning_rate: float = 5e-05weight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08max_grad_norm: float = 1.0num_train_epochs: float = 3.0max_steps: int = -1lr_scheduler_type: typing.Union[transformers.trainer_utils.SchedulerType, str] = 'linear'warmup_ratio: float = 0.0warmup_steps: int = 0log_level: typing.Optional[str] = 'passive'log_level_replica: typing.Optional[str] = 'warning'log_on_each_node: bool = Truelogging_dir: typing.Optional[str] = Nonelogging_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'steps'logging_first_step: bool = Falselogging_steps: float = 500logging_nan_inf_filter: bool = Truesave_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'steps'save_steps: float = 500save_total_limit: typing.Optional[int] = Nonesave_safetensors: typing.Optional[bool] = Falsesave_on_each_node: bool = Falseno_cuda: bool = Falseuse_cpu: bool = Falseuse_mps_device: bool = Falseseed: int = 42data_seed: typing.Optional[int] = Nonejit_mode_eval: bool = Falseuse_ipex: bool = Falsebf16: bool = Falsefp16: bool = Falsefp16_opt_level: str = 'O1'half_precision_backend: str = 'auto'bf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: typing.Optional[bool] = Nonelocal_rank: int = -1ddp_backend: typing.Optional[str] = Nonetpu_num_cores: typing.Optional[int] = Nonetpu_metrics_debug: bool = Falsedebug: typing.Union[str, typing.List[transformers.debug_utils.DebugOption]] = ''dataloader_drop_last: bool = Falseeval_steps: typing.Optional[float] = Nonedataloader_num_workers: int = 0past_index: int = -1run_name: typing.Optional[str] = Nonedisable_tqdm: typing.Optional[bool] = Noneremove_unused_columns: typing.Optional[bool] = Truelabel_names: typing.Optional[typing.List[str]] = Noneload_best_model_at_end: typing.Optional[bool] = Falsemetric_for_best_model: typing.Optional[str] = Nonegreater_is_better: typing.Optional[bool] = Noneignore_data_skip: bool = Falsesharded_ddp: typing.Union[typing.List[transformers.trainer_utils.ShardedDDPOption], str, NoneType] = ''fsdp: typing.Union[typing.List[transformers.trainer_utils.FSDPOption], str, NoneType] = ''fsdp_min_num_params: int = 0fsdp_config: typing.Optional[str] = Nonefsdp_transformer_layer_cls_to_wrap: typing.Optional[str] = Nonedeepspeed: typing.Optional[str] = Nonelabel_smoothing_factor: float = 0.0optim: typing.Union[transformers.training_args.OptimizerNames, str] = 'adamw_torch'optim_args: typing.Optional[str] = Noneadafactor: bool = Falsegroup_by_length: bool = Falselength_column_name: typing.Optional[str] = 'length'report_to: typing.Optional[typing.List[str]] = Noneddp_find_unused_parameters: typing.Optional[bool] = Noneddp_bucket_cap_mb: typing.Optional[int] = Noneddp_broadcast_buffers: typing.Optional[bool] = Nonedataloader_pin_memory: bool = Trueskip_memory_metrics: bool = Trueuse_legacy_prediction_loop: bool = Falsepush_to_hub: bool = Falseresume_from_checkpoint: typing.Optional[str] = Nonehub_model_id: typing.Optional[str] = Nonehub_strategy: typing.Union[transformers.trainer_utils.HubStrategy, str] = 'every_save'hub_token: typing.Optional[str] = Nonehub_private_repo: bool = Falsehub_always_push: bool = Falsegradient_checkpointing: bool = Falseinclude_inputs_for_metrics: bool = Falsefp16_backend: str = 'auto'push_to_hub_model_id: typing.Optional[str] = Nonepush_to_hub_organization: typing.Optional[str] = Nonepush_to_hub_token: typing.Optional[str] = Nonemp_parameters: str = ''auto_find_batch_size: bool = Falsefull_determinism: bool = Falsetorchdynamo: typing.Optional[str] = Noneray_scope: typing.Optional[str] = 'last'ddp_timeout: typing.Optional[int] = 1800torch_compile: bool = Falsetorch_compile_backend: typing.Optional[str] = Nonetorch_compile_mode: typing.Optional[str] = Nonedispatch_batches: typing.Optional[bool] = Noneinclude_tokens_per_second: typing.Optional[bool] = False )
Parameters
- output_dir ( - str) β The output directory where the model predictions and checkpoints will be written.
- overwrite_output_dir ( - bool, optional, defaults to- False) β If- True, overwrite the content of the output directory. Use this to continue training if- output_dirpoints to a checkpoint directory.
- do_train ( - bool, optional, defaults to- False) β Whether to run training or not. This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- do_eval ( - bool, optional) β Whether to run evaluation on the validation set or not. Will be set to- Trueif- evaluation_strategyis different from- "no". This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- do_predict ( - bool, optional, defaults to- False) β Whether to run predictions on the test set or not. This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- evaluation_strategy ( - stror IntervalStrategy, optional, defaults to- "no") β The evaluation strategy to adopt during training. Possible values are:- "no": No evaluation is done during training.
- "steps": Evaluation is done (and logged) every- eval_steps.
- "epoch": Evaluation is done at the end of each epoch.
 
- prediction_loss_only ( - bool, optional, defaults to- False) β When performing evaluation and generating predictions, only returns the loss.
- per_device_train_batch_size ( - int, optional, defaults to 8) β The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training.
- per_device_eval_batch_size ( - int, optional, defaults to 8) β The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation.
- gradient_accumulation_steps ( - int, optional, defaults to 1) β Number of updates steps to accumulate the gradients for, before performing a backward/update pass.- When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every - gradient_accumulation_steps * xxx_steptraining examples.
- eval_accumulation_steps ( - int, optional) β Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but requires more memory).
- eval_delay ( - float, optional) β Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy.
- learning_rate ( - float, optional, defaults to 5e-5) β The initial learning rate for AdamW optimizer.
- weight_decay ( - float, optional, defaults to 0) β The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in AdamW optimizer.
- adam_beta1 ( - float, optional, defaults to 0.9) β The beta1 hyperparameter for the AdamW optimizer.
- adam_beta2 ( - float, optional, defaults to 0.999) β The beta2 hyperparameter for the AdamW optimizer.
- adam_epsilon ( - float, optional, defaults to 1e-8) β The epsilon hyperparameter for the AdamW optimizer.
- max_grad_norm ( - float, optional, defaults to 1.0) β Maximum gradient norm (for gradient clipping).
- num_train_epochs( - float, optional, defaults to 3.0) β Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).
- max_steps ( - int, optional, defaults to -1) β If set to a positive number, the total number of training steps to perform. Overrides- num_train_epochs. In case of using a finite iterable dataset the training may stop before reaching the set number of steps when all data is exhausted
- lr_scheduler_type ( - stror SchedulerType, optional, defaults to- "linear") β The scheduler type to use. See the documentation of SchedulerType for all possible values.
- warmup_ratio ( - float, optional, defaults to 0.0) β Ratio of total training steps used for a linear warmup from 0 to- learning_rate.
- warmup_steps ( - int, optional, defaults to 0) β Number of steps used for a linear warmup from 0 to- learning_rate. Overrides any effect of- warmup_ratio.
- log_level ( - str, optional, defaults to- passive) β Logger log level to use on the main process. Possible choices are the log levels as strings: βdebugβ, βinfoβ, βwarningβ, βerrorβ and βcriticalβ, plus a βpassiveβ level which doesnβt set anything and keeps the current log level for the Transformers library (which will be- "warning"by default).
- log_level_replica ( - str, optional, defaults to- "warning") β Logger log level to use on replicas. Same choices as- log_levelβ
- log_on_each_node ( - bool, optional, defaults to- True) β In multinode distributed training, whether to log using- log_levelonce per node, or only on the main node.
- logging_dir ( - str, optional) β TensorBoard log directory. Will default to *output_dir/runs/CURRENT_DATETIME_HOSTNAME*.
- logging_strategy ( - stror IntervalStrategy, optional, defaults to- "steps") β The logging strategy to adopt during training. Possible values are:- "no": No logging is done during training.
- "epoch": Logging is done at the end of each epoch.
- "steps": Logging is done every- logging_steps.
 
- logging_first_step ( - bool, optional, defaults to- False) β Whether to log and evaluate the first- global_stepor not.
- logging_steps ( - intor- float, optional, defaults to 500) β Number of update steps between two logs if- logging_strategy="steps". Should be an integer or a float in range- [0,1). If smaller than 1, will be interpreted as ratio of total training steps.
- logging_nan_inf_filter ( - bool, optional, defaults to- True) β Whether to filter- nanand- inflosses for logging. If set to- Truethe loss of every step that is- nanor- infis filtered and the average loss of the current logging window is taken instead.- logging_nan_inf_filteronly influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model.
- save_strategy ( - stror IntervalStrategy, optional, defaults to- "steps") β The checkpoint save strategy to adopt during training. Possible values are:- "no": No save is done during training.
- "epoch": Save is done at the end of each epoch.
- "steps": Save is done every- save_steps.
 
- save_steps ( - intor- float, optional, defaults to 500) β Number of updates steps before two checkpoint saves if- save_strategy="steps". Should be an integer or a float in range- [0,1). If smaller than 1, will be interpreted as ratio of total training steps.
- save_total_limit ( - int, optional) β If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in- output_dir. When- load_best_model_at_endis enabled, the βbestβ checkpoint according to- metric_for_best_modelwill always be retained in addition to the most recent ones. For example, for- save_total_limit=5and- load_best_model_at_end, the four last checkpoints will always be retained alongside the best model. When- save_total_limit=1and- load_best_model_at_end, it is possible that two checkpoints are saved: the last one and the best one (if they are different).
- save_safetensors ( - bool, optional, defaults to- False) β Use safetensors saving and loading for state dicts instead of default- torch.loadand- torch.save.
- save_on_each_node ( - bool, optional, defaults to- False) β When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one.- This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. 
- use_cpu ( - bool, optional, defaults to- False) β Whether or not to use cpu. If set to False, we will use cuda or mps device if available.
- seed ( - int, optional, defaults to 42) β Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the- ~Trainer.model_initfunction to instantiate the model if it has some randomly initialized parameters.
- data_seed ( - int, optional) β Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as- seed. This can be used to ensure reproducibility of data sampling, independent of the model seed.
- jit_mode_eval ( - bool, optional, defaults to- False) β Whether or not to use PyTorch jit trace for inference.
- use_ipex ( - bool, optional, defaults to- False) β Use Intel extension for PyTorch when it is available. IPEX installation.
- bf16 ( - bool, optional, defaults to- False) β Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change.
- fp16 ( - bool, optional, defaults to- False) β Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
- fp16_opt_level ( - str, optional, defaults to βO1β) β For- fp16training, Apex AMP optimization level selected in [βO0β, βO1β, βO2β, and βO3β]. See details on the Apex documentation.
- fp16_backend ( - str, optional, defaults to- "auto") β This argument is deprecated. Use- half_precision_backendinstead.
- half_precision_backend ( - str, optional, defaults to- "auto") β The backend to use for mixed precision training. Must be one of- "auto", "cuda_amp", "apex", "cpu_amp".- "auto"will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend.
- bf16_full_eval ( - bool, optional, defaults to- False) β Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. This is an experimental API and it may change.
- fp16_full_eval ( - bool, optional, defaults to- False) β Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values.
- tf32 ( - bool, optional) β Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorchβs version default of- torch.backends.cuda.matmul.allow_tf32. For more details please refer to the TF32 documentation. This is an experimental API and it may change.
- local_rank ( - int, optional, defaults to -1) β Rank of the process during distributed training.
- ddp_backend ( - str, optional) β The backend to use for distributed training. Must be one of- "nccl",- "mpi",- "ccl",- "gloo",- "hccl".
- tpu_num_cores ( - int, optional) β When training on TPU, the number of TPU cores (automatically passed by launcher script).
- dataloader_drop_last ( - bool, optional, defaults to- False) β Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.
- eval_steps ( - intor- float, optional) β Number of update steps between two evaluations if- evaluation_strategy="steps". Will default to the same value as- logging_stepsif not set. Should be an integer or a float in range- [0,1). If smaller than 1, will be interpreted as ratio of total training steps.
- dataloader_num_workers ( - int, optional, defaults to 0) β Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.
- past_index ( - int, optional, defaults to -1) β Some models like TransformerXL or XLNet can make use of the past hidden states for their predictions. If this argument is set to a positive int, the- Trainerwill use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument- mems.
- disable_tqdm ( - bool, optional) β Whether or not to disable the tqdm progress bars and table of metrics produced by- ~notebook.NotebookTrainingTrackerin Jupyter Notebooks. Will default to- Trueif the logging level is set to warn or lower (default),- Falseotherwise.
- remove_unused_columns ( - bool, optional, defaults to- True) β Whether or not to automatically remove the columns unused by the model forward method.- (Note that this behavior is not implemented for - TFTraineryet.)
- label_names ( - List[str], optional) β The list of keys in your dictionary of inputs that correspond to the labels.- Will eventually default to the list of argument names accepted by the model that contain the word βlabelβ, except if the model used is one of the - XxxForQuestionAnsweringin which case it will also include the- ["start_positions", "end_positions"]keys.
- load_best_model_at_end ( - bool, optional, defaults to- False) β Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See- save_total_limitfor more.- When set to - True, the parameters- save_strategyneeds to be the same as- evaluation_strategy, and in the case it is βstepsβ,- save_stepsmust be a round multiple of- eval_steps.
- metric_for_best_model ( - str, optional) β Use in conjunction with- load_best_model_at_endto specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix- "eval_". Will default to- "loss"if unspecified and- load_best_model_at_end=True(to use the evaluation loss).- If you set this value, - greater_is_betterwill default to- True. Donβt forget to set it to- Falseif your metric is better when lower.
- greater_is_better ( - bool, optional) β Use in conjunction with- load_best_model_at_endand- metric_for_best_modelto specify if better models should have a greater metric or not. Will default to:- Trueif- metric_for_best_modelis set to a value that isnβt- "loss"or- "eval_loss".
- Falseif- metric_for_best_modelis not set, or set to- "loss"or- "eval_loss".
 
- ignore_data_skip ( - bool, optional, defaults to- False) β When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to- True, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.
- sharded_ddp ( - bool,- stror list of- ShardedDDPOption, optional, defaults to- '') β Use Sharded DDP training from FairScale (in distributed training only). This is an experimental feature.- A list of options along the following: - "simple": to use first instance of sharded DDP released by fairscale (- ShardedDDP) similar to ZeRO-2.
- "zero_dp_2": to use the second instance of sharded DPP released by fairscale (- FullyShardedDDP) in Zero-2 mode (with- reshard_after_forward=False).
- "zero_dp_3": to use the second instance of sharded DPP released by fairscale (- FullyShardedDDP) in Zero-3 mode (with- reshard_after_forward=True).
- "offload": to add ZeRO-offload (only compatible with- "zero_dp_2"and- "zero_dp_3").
 - If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty list for - Falseand- ["simple"]for- True.
- fsdp ( - bool,- stror list of- FSDPOption, optional, defaults to- '') β Use PyTorch Distributed Parallel Training (in distributed training only).- A list of options along the following: - "full_shard": Shard parameters, gradients and optimizer states.
- "shard_grad_op": Shard optimizer states and gradients.
- "offload": Offload parameters and gradients to CPUs (only compatible with- "full_shard"and- "shard_grad_op").
- "auto_wrap": Automatically recursively wrap layers with FSDP using- default_auto_wrap_policy.
 
- fsdp_config ( - stror- dict, optional) β Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of deepspeed json config file (e.g.,- ds_config.json) or an already loaded json file as- dict.- A List of config and its options: - min_num_params ( - int, optional, defaults to- 0): FSDPβs minimum number of parameters for Default Auto Wrapping. (useful only when- fsdpfield is passed).
- transformer_layer_cls_to_wrap ( - List[str], optional): List of transformer layer class names (case-sensitive) to wrap, e.g,- BertLayer,- GPTJBlock,- T5Block⦠(useful only when- fsdpflag is passed).
- backward_prefetch ( - str, optional) FSDPβs backward prefetch mode. Controls when to prefetch next set of parameters (useful only when- fsdpfield is passed).- A list of options along the following: - "backward_pre": Prefetches the next set of parameters before the current set of parameterβs gradient computation.
- "backward_post": This prefetches the next set of parameters after the current set of parameterβs gradient computation.
 
- forward_prefetch ( - bool, optional, defaults to- False) FSDPβs forward prefetch mode (useful only when- fsdpfield is passed). If- "True", then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass.
- limit_all_gathers ( - bool, optional, defaults to- False) FSDPβs limit_all_gathers (useful only when- fsdpfield is passed). If- "True", FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers.
- use_orig_params ( - bool, optional, defaults to- False) If- "True", allows non-uniform- requires_gradduring init, which means support for interspersed frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019
- sync_module_states ( - bool, optional, defaults to- True) If- "True", each individually wrapped FSDP unit will broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization
- xla ( - bool, optional, defaults to- False): Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future.
- xla_fsdp_settings ( - dict, optional) The value is a dictionary which stores the XLA FSDP wrapping parameters.- For a complete list of options, please see here. 
- xla_fsdp_grad_ckpt ( - bool, optional, defaults to- False): Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.
- activation_checkpointing ( - bool, optional, defaults to- False): If True, activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage.
 
- deepspeed ( - stror- dict, optional) β Use Deepspeed. This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,- ds_config.json) or an already loaded json file as a- dictβ
- label_smoothing_factor ( - float, optional, defaults to 0.0) β The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded labels are changed from 0s and 1s to- label_smoothing_factor/num_labelsand- 1 - label_smoothing_factor + label_smoothing_factor/num_labelsrespectively.
- debug ( - stror list of- DebugOption, optional, defaults to- "") β Enable one or more debug features. This is an experimental feature.- Possible options are: - "underflow_overflow": detects overflow in modelβs input/outputs and reports the last frames that led to the event
- "tpu_metrics_debug": print debug metrics on TPU
 - The options should be separated by whitespaces. 
- optim ( - stror- training_args.OptimizerNames, optional, defaults to- "adamw_torch") β The optimizer to use: adamw_hf, adamw_torch, adamw_torch_fused, adamw_apex_fused, adamw_anyprecision or adafactor.
- optim_args ( - str, optional) β Optional arguments that are supplied to AnyPrecisionAdamW.
- group_by_length ( - bool, optional, defaults to- False) β Whether or not to group together samples of roughly the same length in the training dataset (to minimize padding applied and be more efficient). Only useful if applying dynamic padding.
- length_column_name ( - str, optional, defaults to- "length") β Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unless- group_by_lengthis- Trueand the dataset is an instance of- Dataset.
- report_to ( - stror- List[str], optional, defaults to- "all") β The list of integrations to report the results and logs to. Supported platforms are- "azure_ml",- "clearml",- "codecarbon",- "comet_ml",- "dagshub",- "flyte",- "mlflow",- "neptune",- "tensorboard", and- "wandb". Use- "all"to report to all integrations installed,- "none"for no integrations.
- ddp_find_unused_parameters ( - bool, optional) β When using distributed training, the value of the flag- find_unused_parameterspassed to- DistributedDataParallel. Will default to- Falseif gradient checkpointing is used,- Trueotherwise.
- ddp_bucket_cap_mb ( - int, optional) β When using distributed training, the value of the flag- bucket_cap_mbpassed to- DistributedDataParallel.
- ddp_broadcast_buffers ( - bool, optional) β When using distributed training, the value of the flag- broadcast_bufferspassed to- DistributedDataParallel. Will default to- Falseif gradient checkpointing is used,- Trueotherwise.
- dataloader_pin_memory ( - bool, optional, defaults to- True) β Whether you want to pin memory in data loaders or not. Will default to- True.
- skip_memory_metrics ( - bool, optional, defaults to- True) β Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows down the training and evaluation speed.
- push_to_hub ( - bool, optional, defaults to- False) β Whether or not to push the model to the Hub every time the model is saved. If this is activated,- output_dirwill begin a git directory synced with the repo (determined by- hub_model_id) and the content will be pushed each time a save is triggered (depending on your- save_strategy). Calling save_model() will also trigger a push.- If - output_direxists, it needs to be a local clone of the repository to which the Trainer will be pushed.
- resume_from_checkpoint ( - str, optional) β The path to a folder with a valid checkpoint for your model. This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- hub_model_id ( - str, optional) β The name of the repository to keep in sync with the local output_dir. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance- "user_name/model", which allows you to push to an organization you are a member of with- "organization_name/model". Will default to- user_name/output_dir_namewith output_dir_name being the name of- output_dir.- Will default to the name of - output_dir.
- hub_strategy ( - stror- HubStrategy, optional, defaults to- "every_save") β Defines the scope of what is pushed to the Hub and when. Possible values are:- "end": push the model, its configuration, the tokenizer (if passed along to the Trainer) and a draft of a model card when the save_model() method is called.
- "every_save": push the model, its configuration, the tokenizer (if passed along to the Trainer) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training.
- "checkpoint": like- "every_save"but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with- trainer.train(resume_from_checkpoint="last-checkpoint").
- "all_checkpoints": like- "checkpoint"but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)
 
- hub_token ( - str, optional) β The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with- boincai-cli login.
- hub_private_repo ( - bool, optional, defaults to- False) β If True, the Hub repo will be set to private.
- hub_always_push ( - bool, optional, defaults to- False) β Unless this is- True, the- Trainerwill skip pushing a checkpoint when the previous push is not finished.
- gradient_checkpointing ( - bool, optional, defaults to- False) β If True, use gradient checkpointing to save memory at the expense of slower backward pass.
- include_inputs_for_metrics ( - bool, optional, defaults to- False) β Whether or not the inputs will be passed to the- compute_metricsfunction. This is intended for metrics that need inputs, predictions and references for scoring calculation in Metric class.
- auto_find_batch_size ( - bool, optional, defaults to- False) β Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (- pip install accelerate)
- full_determinism ( - bool, optional, defaults to- False) β If- True, enable_full_determinism() is called instead of set_seed() to ensure reproducible results in distributed training. Important: this will negatively impact the performance, so only use it for debugging.
- torchdynamo ( - str, optional) β If set, the backend compiler for TorchDynamo. Possible choices are- "eager",- "aot_eager",- "inductor",- "nvfuser",- "aot_nvfuser",- "aot_cudagraphs",- "ofi",- "fx2trt",- "onnxrt"and- "ipex".
- ray_scope ( - str, optional, defaults to- "last") β The scope to use when doing hyperparameter search with Ray. By default,- "last"will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the Ray documentation for more options.
- ddp_timeout ( - int, optional, defaults to 1800) β The timeout for- torch.distributed.init_process_groupcalls, used to avoid GPU socket timeouts when performing slow operations in distributed runnings. Please refer the [PyTorch documentation] (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information.
- use_mps_device ( - bool, optional, defaults to- False) β This argument is deprecated.- mpsdevice will be used if it is available similar to- cudadevice.
- torch_compile ( - bool, optional, defaults to- False) β Whether or not to compile the model using PyTorch 2.0- torch.compile.- This will use the best defaults for the - torch.compileAPI. You can customize the defaults with the argument- torch_compile_backendand- torch_compile_modebut we donβt guarantee any of them will work as the support is progressively rolled in in PyTorch.- This flag and the whole compile API is experimental and subject to change in future releases. 
- torch_compile_backend ( - str, optional) β The backend to use in- torch.compile. If set to any value,- torch_compilewill be set to- True.- Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions. - This flag is experimental and subject to change in future releases. 
- torch_compile_mode ( - str, optional) β The mode to use in- torch.compile. If set to any value,- torch_compilewill be set to- True.- Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions. - This flag is experimental and subject to change in future releases. 
- include_tokens_per_second ( - bool, optional) β Whether or not to compute the number of tokens per second per device for training speed metrics.- This will iterate over the entire training dataloader once beforehand, - and will slow down the entire process. 
TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
get_process_log_level
( )
Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process.
For the main process the log level defaults to the logging level set (logging.WARNING if you didnβt do anything) unless overridden by log_level argument.
For the replica processes the log level defaults to logging.WARNING unless overridden by log_level_replica argument.
The choice between the main and replica process settings is made according to the return value of should_log.
get_warmup_steps
( num_training_steps: int )
Get number of steps used for a linear warmup.
main_process_first
( local = Truedesc = 'work' )
Parameters
- local ( - bool, optional, defaults to- True) β if- Truefirst means process of rank 0 of each node if- Falsefirst means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to use- local=Falseso that only the main process of the first node will do the processing. If however, the filesystem is not shared, then the main process of each node will need to do the processing, which is the default behavior.
- desc ( - str, optional, defaults to- "work") β a work description to be used in debug logs
A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when itβs finished releasing the replicas.
One such use is for datasetsβs map feature which to be efficient should be run once on the main process, which upon completion saves a cached version of results and which then automatically gets loaded by the replicas.
set_dataloader
( train_batch_size: int = 8eval_batch_size: int = 8drop_last: bool = Falsenum_workers: int = 0pin_memory: bool = Trueauto_find_batch_size: bool = Falseignore_data_skip: bool = Falsesampler_seed: typing.Optional[int] = None )
Parameters
- drop_last ( - bool, optional, defaults to- False) β Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.
- num_workers ( - int, optional, defaults to 0) β Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.
- pin_memory ( - bool, optional, defaults to- True) β Whether you want to pin memory in data loaders or not. Will default to- True.
- auto_find_batch_size ( - bool, optional, defaults to- False) β Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (- pip install accelerate)
- ignore_data_skip ( - bool, optional, defaults to- False) β When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to- True, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.
- sampler_seed ( - int, optional) β Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as- self.seed. This can be used to ensure reproducibility of data sampling, independent of the model seed.
A method that regroups all arguments linked to the dataloaders creation.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64)
>>> args.per_device_train_batch_size
16set_evaluate
( strategy: typing.Union[str, transformers.trainer_utils.IntervalStrategy] = 'no'steps: int = 500batch_size: int = 8accumulation_steps: typing.Optional[int] = Nonedelay: typing.Optional[float] = Noneloss_only: bool = Falsejit_mode: bool = False )
Parameters
- strategy ( - stror IntervalStrategy, optional, defaults to- "no") β The evaluation strategy to adopt during training. Possible values are:- "no": No evaluation is done during training.
- "steps": Evaluation is done (and logged) every- steps.
- "epoch": Evaluation is done at the end of each epoch.
 - Setting a - strategydifferent from- "no"will set- self.do_evalto- True.
- steps ( - int, optional, defaults to 500) β Number of update steps between two evaluations if- strategy="steps".
- batch_size ( - intoptional, defaults to 8) β The batch size per device (GPU/TPU core/CPUβ¦) used for evaluation.
- accumulation_steps ( - int, optional) β Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but requires more memory).
- delay ( - float, optional) β Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy.
- loss_only ( - bool, optional, defaults to- False) β Ignores all outputs except the loss.
- jit_mode ( - bool, optional) β Whether or not to use PyTorch jit trace for inference.
A method that regroups all arguments linked to the evaluation.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_evaluate(strategy="steps", steps=100)
>>> args.eval_steps
100set_logging
( strategy: typing.Union[str, transformers.trainer_utils.IntervalStrategy] = 'steps'steps: int = 500report_to: typing.Union[str, typing.List[str]] = 'none'level: str = 'passive'first_step: bool = Falsenan_inf_filter: bool = Falseon_each_node: bool = Falsereplica_level: str = 'passive' )
Parameters
- strategy ( - stror IntervalStrategy, optional, defaults to- "steps") β The logging strategy to adopt during training. Possible values are:- "no": No save is done during training.
- "epoch": Save is done at the end of each epoch.
- "steps": Save is done every- save_steps.
 
- steps ( - int, optional, defaults to 500) β Number of update steps between two logs if- strategy="steps".
- level ( - str, optional, defaults to- "passive") β Logger log level to use on the main process. Possible choices are the log levels as strings:- "debug",- "info",- "warning",- "error"and- "critical", plus a- "passive"level which doesnβt set anything and lets the application set the level.
- report_to ( - stror- List[str], optional, defaults to- "none") β The list of integrations to report the results and logs to. Supported platforms are- "azure_ml",- "comet_ml",- "mlflow",- "neptune",- "tensorboard",- "clearml"and- "wandb". Use- "all"to report to all integrations installed,- "none"for no integrations.
- first_step ( - bool, optional, defaults to- False) β Whether to log and evaluate the first- global_stepor not.
- nan_inf_filter ( - bool, optional, defaults to- True) β Whether to filter- nanand- inflosses for logging. If set to- Truethe loss of every step that is- nanor- infis filtered and the average loss of the current logging window is taken instead.- nan_inf_filteronly influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model.
- on_each_node ( - bool, optional, defaults to- True) β In multinode distributed training, whether to log using- log_levelonce per node, or only on the main node.
- replica_level ( - str, optional, defaults to- "passive") β Logger log level to use on replicas. Same choices as- log_level
A method that regroups all arguments linked to the evaluation.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_logging(strategy="steps", steps=100)
>>> args.logging_steps
100set_lr_scheduler
( name: typing.Union[str, transformers.trainer_utils.SchedulerType] = 'linear'num_epochs: float = 3.0max_steps: int = -1warmup_ratio: float = 0warmup_steps: int = 0 )
Parameters
- name ( - stror SchedulerType, optional, defaults to- "linear") β The scheduler type to use. See the documentation of SchedulerType for all possible values.
- num_epochs( - float, optional, defaults to 3.0) β Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).
- max_steps ( - int, optional, defaults to -1) β If set to a positive number, the total number of training steps to perform. Overrides- num_train_epochs. In case of using a finite iterable dataset the training may stop before reaching the set number of steps when all data is exhausted.
- warmup_ratio ( - float, optional, defaults to 0.0) β Ratio of total training steps used for a linear warmup from 0 to- learning_rate.
- warmup_steps ( - int, optional, defaults to 0) β Number of steps used for a linear warmup from 0 to- learning_rate. Overrides any effect of- warmup_ratio.
A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_lr_scheduler(name="cosine", warmup_ratio=0.05)
>>> args.warmup_ratio
0.05set_optimizer
( name: typing.Union[str, transformers.training_args.OptimizerNames] = 'adamw_torch'learning_rate: float = 5e-05weight_decay: float = 0beta1: float = 0.9beta2: float = 0.999epsilon: float = 1e-08args: typing.Optional[str] = None )
Parameters
- name ( - stror- training_args.OptimizerNames, optional, defaults to- "adamw_torch") β The optimizer to use:- "adamw_hf",- "adamw_torch",- "adamw_torch_fused",- "adamw_apex_fused",- "adamw_anyprecision"or- "adafactor".
- learning_rate ( - float, optional, defaults to 5e-5) β The initial learning rate.
- weight_decay ( - float, optional, defaults to 0) β The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.
- beta1 ( - float, optional, defaults to 0.9) β The beta1 hyperparameter for the adam optimizer or its variants.
- beta2 ( - float, optional, defaults to 0.999) β The beta2 hyperparameter for the adam optimizer or its variants.
- epsilon ( - float, optional, defaults to 1e-8) β The epsilon hyperparameter for the adam optimizer or its variants.
- args ( - str, optional) β Optional arguments that are supplied to AnyPrecisionAdamW (only useful when- optim="adamw_anyprecision").
A method that regroups all arguments linked to the optimizer and its hyperparameters.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_optimizer(name="adamw_torch", beta1=0.8)
>>> args.optim
'adamw_torch'set_push_to_hub
( model_id: strstrategy: typing.Union[str, transformers.trainer_utils.HubStrategy] = 'every_save'token: typing.Optional[str] = Noneprivate_repo: bool = Falsealways_push: bool = False )
Parameters
- model_id ( - str) β The name of the repository to keep in sync with the local output_dir. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance- "user_name/model", which allows you to push to an organization you are a member of with- "organization_name/model".
- strategy ( - stror- HubStrategy, optional, defaults to- "every_save") β Defines the scope of what is pushed to the Hub and when. Possible values are:- "end": push the model, its configuration, the tokenizer (if passed along to the Trainer) and a draft of a model card when the save_model() method is called.
- "every_save": push the model, its configuration, the tokenizer (if passed along to the Trainer) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training.
- "checkpoint": like- "every_save"but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with- trainer.train(resume_from_checkpoint="last-checkpoint").
- "all_checkpoints": like- "checkpoint"but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)
 
- token ( - str, optional) β The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with- boincai-cli login.
- private_repo ( - bool, optional, defaults to- False) β If True, the Hub repo will be set to private.
- always_push ( - bool, optional, defaults to- False) β Unless this is- True, the- Trainerwill skip pushing a checkpoint when the previous push is not finished.
A method that regroups all arguments linked to synchronizing checkpoints with the Hub.
Calling this method will set self.push_to_hub to True, which means the output_dir will begin a git directory synced with the repo (determined by model_id) and the content will be pushed each time a save is triggered (depending onself.save_strategy). Calling save_model() will also trigger a push.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_push_to_hub("me/awesome-model")
>>> args.hub_model_id
'me/awesome-model'set_save
( strategy: typing.Union[str, transformers.trainer_utils.IntervalStrategy] = 'steps'steps: int = 500total_limit: typing.Optional[int] = Noneon_each_node: bool = False )
Parameters
- strategy ( - stror IntervalStrategy, optional, defaults to- "steps") β The checkpoint save strategy to adopt during training. Possible values are:- "no": No save is done during training.
- "epoch": Save is done at the end of each epoch.
- "steps": Save is done every- save_steps.
 
- steps ( - int, optional, defaults to 500) β Number of updates steps before two checkpoint saves if- strategy="steps".
- total_limit ( - int, optional) β If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in- output_dir.
- on_each_node ( - bool, optional, defaults to- False) β When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one.- This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. 
A method that regroups all arguments linked to the evaluation.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_save(strategy="steps", steps=100)
>>> args.save_steps
100set_testing
( batch_size: int = 8loss_only: bool = Falsejit_mode: bool = False )
Parameters
- batch_size ( - intoptional, defaults to 8) β The batch size per device (GPU/TPU core/CPUβ¦) used for testing.
- loss_only ( - bool, optional, defaults to- False) β Ignores all outputs except the loss.
- jit_mode ( - bool, optional) β Whether or not to use PyTorch jit trace for inference.
A method that regroups all basic arguments linked to testing on a held-out dataset.
Calling this method will automatically set self.do_predict to True.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_testing(batch_size=32)
>>> args.per_device_eval_batch_size
32set_training
( learning_rate: float = 5e-05batch_size: int = 8weight_decay: float = 0num_epochs: float = 3max_steps: int = -1gradient_accumulation_steps: int = 1seed: int = 42gradient_checkpointing: bool = False )
Parameters
- learning_rate ( - float, optional, defaults to 5e-5) β The initial learning rate for the optimizer.
- batch_size ( - intoptional, defaults to 8) β The batch size per device (GPU/TPU core/CPUβ¦) used for training.
- weight_decay ( - float, optional, defaults to 0) β The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the optimizer.
- num_train_epochs( - float, optional, defaults to 3.0) β Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).
- max_steps ( - int, optional, defaults to -1) β If set to a positive number, the total number of training steps to perform. Overrides- num_train_epochs. In case of using a finite iterable dataset the training may stop before reaching the set number of steps when all data is exhausted.
- gradient_accumulation_steps ( - int, optional, defaults to 1) β Number of updates steps to accumulate the gradients for, before performing a backward/update pass.- When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every - gradient_accumulation_steps * xxx_steptraining examples.
- seed ( - int, optional, defaults to 42) β Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the- ~Trainer.model_initfunction to instantiate the model if it has some randomly initialized parameters.
- gradient_checkpointing ( - bool, optional, defaults to- False) β If True, use gradient checkpointing to save memory at the expense of slower backward pass.
A method that regroups all basic arguments linked to the training.
Calling this method will automatically set self.do_train to True.
Example:
Copied
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_training(learning_rate=1e-4, batch_size=32)
>>> args.learning_rate
1e-4to_dict
( )
Serializes this instance while replace Enum by their values (for JSON serialization support). It obfuscates the token values by removing their value.
to_json_string
( )
Serializes this instance to a JSON string.
to_sanitized_dict
( )
Sanitized serialization to use with TensorBoardβs hparams
Seq2SeqTrainingArguments
class transformers.Seq2SeqTrainingArguments
( output_dir: stroverwrite_output_dir: bool = Falsedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseevaluation_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'no'prediction_loss_only: bool = Falseper_device_train_batch_size: int = 8per_device_eval_batch_size: int = 8per_gpu_train_batch_size: typing.Optional[int] = Noneper_gpu_eval_batch_size: typing.Optional[int] = Nonegradient_accumulation_steps: int = 1eval_accumulation_steps: typing.Optional[int] = Noneeval_delay: typing.Optional[float] = 0learning_rate: float = 5e-05weight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08max_grad_norm: float = 1.0num_train_epochs: float = 3.0max_steps: int = -1lr_scheduler_type: typing.Union[transformers.trainer_utils.SchedulerType, str] = 'linear'warmup_ratio: float = 0.0warmup_steps: int = 0log_level: typing.Optional[str] = 'passive'log_level_replica: typing.Optional[str] = 'warning'log_on_each_node: bool = Truelogging_dir: typing.Optional[str] = Nonelogging_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'steps'logging_first_step: bool = Falselogging_steps: float = 500logging_nan_inf_filter: bool = Truesave_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'steps'save_steps: float = 500save_total_limit: typing.Optional[int] = Nonesave_safetensors: typing.Optional[bool] = Falsesave_on_each_node: bool = Falseno_cuda: bool = Falseuse_cpu: bool = Falseuse_mps_device: bool = Falseseed: int = 42data_seed: typing.Optional[int] = Nonejit_mode_eval: bool = Falseuse_ipex: bool = Falsebf16: bool = Falsefp16: bool = Falsefp16_opt_level: str = 'O1'half_precision_backend: str = 'auto'bf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: typing.Optional[bool] = Nonelocal_rank: int = -1ddp_backend: typing.Optional[str] = Nonetpu_num_cores: typing.Optional[int] = Nonetpu_metrics_debug: bool = Falsedebug: typing.Union[str, typing.List[transformers.debug_utils.DebugOption]] = ''dataloader_drop_last: bool = Falseeval_steps: typing.Optional[float] = Nonedataloader_num_workers: int = 0past_index: int = -1run_name: typing.Optional[str] = Nonedisable_tqdm: typing.Optional[bool] = Noneremove_unused_columns: typing.Optional[bool] = Truelabel_names: typing.Optional[typing.List[str]] = Noneload_best_model_at_end: typing.Optional[bool] = Falsemetric_for_best_model: typing.Optional[str] = Nonegreater_is_better: typing.Optional[bool] = Noneignore_data_skip: bool = Falsesharded_ddp: typing.Union[typing.List[transformers.trainer_utils.ShardedDDPOption], str, NoneType] = ''fsdp: typing.Union[typing.List[transformers.trainer_utils.FSDPOption], str, NoneType] = ''fsdp_min_num_params: int = 0fsdp_config: typing.Optional[str] = Nonefsdp_transformer_layer_cls_to_wrap: typing.Optional[str] = Nonedeepspeed: typing.Optional[str] = Nonelabel_smoothing_factor: float = 0.0optim: typing.Union[transformers.training_args.OptimizerNames, str] = 'adamw_torch'optim_args: typing.Optional[str] = Noneadafactor: bool = Falsegroup_by_length: bool = Falselength_column_name: typing.Optional[str] = 'length'report_to: typing.Optional[typing.List[str]] = Noneddp_find_unused_parameters: typing.Optional[bool] = Noneddp_bucket_cap_mb: typing.Optional[int] = Noneddp_broadcast_buffers: typing.Optional[bool] = Nonedataloader_pin_memory: bool = Trueskip_memory_metrics: bool = Trueuse_legacy_prediction_loop: bool = Falsepush_to_hub: bool = Falseresume_from_checkpoint: typing.Optional[str] = Nonehub_model_id: typing.Optional[str] = Nonehub_strategy: typing.Union[transformers.trainer_utils.HubStrategy, str] = 'every_save'hub_token: typing.Optional[str] = Nonehub_private_repo: bool = Falsehub_always_push: bool = Falsegradient_checkpointing: bool = Falseinclude_inputs_for_metrics: bool = Falsefp16_backend: str = 'auto'push_to_hub_model_id: typing.Optional[str] = Nonepush_to_hub_organization: typing.Optional[str] = Nonepush_to_hub_token: typing.Optional[str] = Nonemp_parameters: str = ''auto_find_batch_size: bool = Falsefull_determinism: bool = Falsetorchdynamo: typing.Optional[str] = Noneray_scope: typing.Optional[str] = 'last'ddp_timeout: typing.Optional[int] = 1800torch_compile: bool = Falsetorch_compile_backend: typing.Optional[str] = Nonetorch_compile_mode: typing.Optional[str] = Nonedispatch_batches: typing.Optional[bool] = Noneinclude_tokens_per_second: typing.Optional[bool] = Falsesortish_sampler: bool = Falsepredict_with_generate: bool = Falsegeneration_max_length: typing.Optional[int] = Nonegeneration_num_beams: typing.Optional[int] = Nonegeneration_config: typing.Union[str, pathlib.Path, transformers.generation.configuration_utils.GenerationConfig, NoneType] = None )
Parameters
- output_dir ( - str) β The output directory where the model predictions and checkpoints will be written.
- overwrite_output_dir ( - bool, optional, defaults to- False) β If- True, overwrite the content of the output directory. Use this to continue training if- output_dirpoints to a checkpoint directory.
- do_train ( - bool, optional, defaults to- False) β Whether to run training or not. This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- do_eval ( - bool, optional) β Whether to run evaluation on the validation set or not. Will be set to- Trueif- evaluation_strategyis different from- "no". This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- do_predict ( - bool, optional, defaults to- False) β Whether to run predictions on the test set or not. This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- evaluation_strategy ( - stror IntervalStrategy, optional, defaults to- "no") β The evaluation strategy to adopt during training. Possible values are:- "no": No evaluation is done during training.
- "steps": Evaluation is done (and logged) every- eval_steps.
- "epoch": Evaluation is done at the end of each epoch.
 
- prediction_loss_only ( - bool, optional, defaults to- False) β When performing evaluation and generating predictions, only returns the loss.
- per_device_train_batch_size ( - int, optional, defaults to 8) β The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training.
- per_device_eval_batch_size ( - int, optional, defaults to 8) β The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation.
- gradient_accumulation_steps ( - int, optional, defaults to 1) β Number of updates steps to accumulate the gradients for, before performing a backward/update pass.- When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every - gradient_accumulation_steps * xxx_steptraining examples.
- eval_accumulation_steps ( - int, optional) β Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but requires more memory).
- eval_delay ( - float, optional) β Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy.
- learning_rate ( - float, optional, defaults to 5e-5) β The initial learning rate for AdamW optimizer.
- weight_decay ( - float, optional, defaults to 0) β The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in AdamW optimizer.
- adam_beta1 ( - float, optional, defaults to 0.9) β The beta1 hyperparameter for the AdamW optimizer.
- adam_beta2 ( - float, optional, defaults to 0.999) β The beta2 hyperparameter for the AdamW optimizer.
- adam_epsilon ( - float, optional, defaults to 1e-8) β The epsilon hyperparameter for the AdamW optimizer.
- max_grad_norm ( - float, optional, defaults to 1.0) β Maximum gradient norm (for gradient clipping).
- num_train_epochs( - float, optional, defaults to 3.0) β Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).
- max_steps ( - int, optional, defaults to -1) β If set to a positive number, the total number of training steps to perform. Overrides- num_train_epochs. In case of using a finite iterable dataset the training may stop before reaching the set number of steps when all data is exhausted
- lr_scheduler_type ( - stror SchedulerType, optional, defaults to- "linear") β The scheduler type to use. See the documentation of SchedulerType for all possible values.
- warmup_ratio ( - float, optional, defaults to 0.0) β Ratio of total training steps used for a linear warmup from 0 to- learning_rate.
- warmup_steps ( - int, optional, defaults to 0) β Number of steps used for a linear warmup from 0 to- learning_rate. Overrides any effect of- warmup_ratio.
- log_level ( - str, optional, defaults to- passive) β Logger log level to use on the main process. Possible choices are the log levels as strings: βdebugβ, βinfoβ, βwarningβ, βerrorβ and βcriticalβ, plus a βpassiveβ level which doesnβt set anything and keeps the current log level for the Transformers library (which will be- "warning"by default).
- log_level_replica ( - str, optional, defaults to- "warning") β Logger log level to use on replicas. Same choices as- log_levelβ
- log_on_each_node ( - bool, optional, defaults to- True) β In multinode distributed training, whether to log using- log_levelonce per node, or only on the main node.
- logging_dir ( - str, optional) β TensorBoard log directory. Will default to *output_dir/runs/CURRENT_DATETIME_HOSTNAME*.
- logging_strategy ( - stror IntervalStrategy, optional, defaults to- "steps") β The logging strategy to adopt during training. Possible values are:- "no": No logging is done during training.
- "epoch": Logging is done at the end of each epoch.
- "steps": Logging is done every- logging_steps.
 
- logging_first_step ( - bool, optional, defaults to- False) β Whether to log and evaluate the first- global_stepor not.
- logging_steps ( - intor- float, optional, defaults to 500) β Number of update steps between two logs if- logging_strategy="steps". Should be an integer or a float in range- [0,1). If smaller than 1, will be interpreted as ratio of total training steps.
- logging_nan_inf_filter ( - bool, optional, defaults to- True) β Whether to filter- nanand- inflosses for logging. If set to- Truethe loss of every step that is- nanor- infis filtered and the average loss of the current logging window is taken instead.- logging_nan_inf_filteronly influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model.
- save_strategy ( - stror IntervalStrategy, optional, defaults to- "steps") β The checkpoint save strategy to adopt during training. Possible values are:- "no": No save is done during training.
- "epoch": Save is done at the end of each epoch.
- "steps": Save is done every- save_steps.
 
- save_steps ( - intor- float, optional, defaults to 500) β Number of updates steps before two checkpoint saves if- save_strategy="steps". Should be an integer or a float in range- [0,1). If smaller than 1, will be interpreted as ratio of total training steps.
- save_total_limit ( - int, optional) β If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in- output_dir. When- load_best_model_at_endis enabled, the βbestβ checkpoint according to- metric_for_best_modelwill always be retained in addition to the most recent ones. For example, for- save_total_limit=5and- load_best_model_at_end, the four last checkpoints will always be retained alongside the best model. When- save_total_limit=1and- load_best_model_at_end, it is possible that two checkpoints are saved: the last one and the best one (if they are different).
- save_safetensors ( - bool, optional, defaults to- False) β Use safetensors saving and loading for state dicts instead of default- torch.loadand- torch.save.
- save_on_each_node ( - bool, optional, defaults to- False) β When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one.- This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. 
- use_cpu ( - bool, optional, defaults to- False) β Whether or not to use cpu. If set to False, we will use cuda or mps device if available.
- seed ( - int, optional, defaults to 42) β Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the- ~Trainer.model_initfunction to instantiate the model if it has some randomly initialized parameters.
- data_seed ( - int, optional) β Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as- seed. This can be used to ensure reproducibility of data sampling, independent of the model seed.
- jit_mode_eval ( - bool, optional, defaults to- False) β Whether or not to use PyTorch jit trace for inference.
- use_ipex ( - bool, optional, defaults to- False) β Use Intel extension for PyTorch when it is available. IPEX installation.
- bf16 ( - bool, optional, defaults to- False) β Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change.
- fp16 ( - bool, optional, defaults to- False) β Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
- fp16_opt_level ( - str, optional, defaults to βO1β) β For- fp16training, Apex AMP optimization level selected in [βO0β, βO1β, βO2β, and βO3β]. See details on the Apex documentation.
- fp16_backend ( - str, optional, defaults to- "auto") β This argument is deprecated. Use- half_precision_backendinstead.
- half_precision_backend ( - str, optional, defaults to- "auto") β The backend to use for mixed precision training. Must be one of- "auto", "cuda_amp", "apex", "cpu_amp".- "auto"will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend.
- bf16_full_eval ( - bool, optional, defaults to- False) β Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. This is an experimental API and it may change.
- fp16_full_eval ( - bool, optional, defaults to- False) β Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values.
- tf32 ( - bool, optional) β Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorchβs version default of- torch.backends.cuda.matmul.allow_tf32. For more details please refer to the TF32 documentation. This is an experimental API and it may change.
- local_rank ( - int, optional, defaults to -1) β Rank of the process during distributed training.
- ddp_backend ( - str, optional) β The backend to use for distributed training. Must be one of- "nccl",- "mpi",- "ccl",- "gloo",- "hccl".
- tpu_num_cores ( - int, optional) β When training on TPU, the number of TPU cores (automatically passed by launcher script).
- dataloader_drop_last ( - bool, optional, defaults to- False) β Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.
- eval_steps ( - intor- float, optional) β Number of update steps between two evaluations if- evaluation_strategy="steps". Will default to the same value as- logging_stepsif not set. Should be an integer or a float in range- [0,1). If smaller than 1, will be interpreted as ratio of total training steps.
- dataloader_num_workers ( - int, optional, defaults to 0) β Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.
- past_index ( - int, optional, defaults to -1) β Some models like TransformerXL or XLNet can make use of the past hidden states for their predictions. If this argument is set to a positive int, the- Trainerwill use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument- mems.
- disable_tqdm ( - bool, optional) β Whether or not to disable the tqdm progress bars and table of metrics produced by- ~notebook.NotebookTrainingTrackerin Jupyter Notebooks. Will default to- Trueif the logging level is set to warn or lower (default),- Falseotherwise.
- remove_unused_columns ( - bool, optional, defaults to- True) β Whether or not to automatically remove the columns unused by the model forward method.- (Note that this behavior is not implemented for - TFTraineryet.)
- label_names ( - List[str], optional) β The list of keys in your dictionary of inputs that correspond to the labels.- Will eventually default to the list of argument names accepted by the model that contain the word βlabelβ, except if the model used is one of the - XxxForQuestionAnsweringin which case it will also include the- ["start_positions", "end_positions"]keys.
- load_best_model_at_end ( - bool, optional, defaults to- False) β Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See- save_total_limitfor more.- When set to - True, the parameters- save_strategyneeds to be the same as- evaluation_strategy, and in the case it is βstepsβ,- save_stepsmust be a round multiple of- eval_steps.
- metric_for_best_model ( - str, optional) β Use in conjunction with- load_best_model_at_endto specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix- "eval_". Will default to- "loss"if unspecified and- load_best_model_at_end=True(to use the evaluation loss).- If you set this value, - greater_is_betterwill default to- True. Donβt forget to set it to- Falseif your metric is better when lower.
- greater_is_better ( - bool, optional) β Use in conjunction with- load_best_model_at_endand- metric_for_best_modelto specify if better models should have a greater metric or not. Will default to:- Trueif- metric_for_best_modelis set to a value that isnβt- "loss"or- "eval_loss".
- Falseif- metric_for_best_modelis not set, or set to- "loss"or- "eval_loss".
 
- ignore_data_skip ( - bool, optional, defaults to- False) β When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to- True, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.
- sharded_ddp ( - bool,- stror list of- ShardedDDPOption, optional, defaults to- '') β Use Sharded DDP training from FairScale (in distributed training only). This is an experimental feature.- A list of options along the following: - "simple": to use first instance of sharded DDP released by fairscale (- ShardedDDP) similar to ZeRO-2.
- "zero_dp_2": to use the second instance of sharded DPP released by fairscale (- FullyShardedDDP) in Zero-2 mode (with- reshard_after_forward=False).
- "zero_dp_3": to use the second instance of sharded DPP released by fairscale (- FullyShardedDDP) in Zero-3 mode (with- reshard_after_forward=True).
- "offload": to add ZeRO-offload (only compatible with- "zero_dp_2"and- "zero_dp_3").
 - If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty list for - Falseand- ["simple"]for- True.
- fsdp ( - bool,- stror list of- FSDPOption, optional, defaults to- '') β Use PyTorch Distributed Parallel Training (in distributed training only).- A list of options along the following: - "full_shard": Shard parameters, gradients and optimizer states.
- "shard_grad_op": Shard optimizer states and gradients.
- "offload": Offload parameters and gradients to CPUs (only compatible with- "full_shard"and- "shard_grad_op").
- "auto_wrap": Automatically recursively wrap layers with FSDP using- default_auto_wrap_policy.
 
- fsdp_config ( - stror- dict, optional) β Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of deepspeed json config file (e.g.,- ds_config.json) or an already loaded json file as- dict.- A List of config and its options: - min_num_params ( - int, optional, defaults to- 0): FSDPβs minimum number of parameters for Default Auto Wrapping. (useful only when- fsdpfield is passed).
- transformer_layer_cls_to_wrap ( - List[str], optional): List of transformer layer class names (case-sensitive) to wrap, e.g,- BertLayer,- GPTJBlock,- T5Block⦠(useful only when- fsdpflag is passed).
- backward_prefetch ( - str, optional) FSDPβs backward prefetch mode. Controls when to prefetch next set of parameters (useful only when- fsdpfield is passed).- A list of options along the following: - "backward_pre": Prefetches the next set of parameters before the current set of parameterβs gradient computation.
- "backward_post": This prefetches the next set of parameters after the current set of parameterβs gradient computation.
 
- forward_prefetch ( - bool, optional, defaults to- False) FSDPβs forward prefetch mode (useful only when- fsdpfield is passed). If- "True", then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass.
- limit_all_gathers ( - bool, optional, defaults to- False) FSDPβs limit_all_gathers (useful only when- fsdpfield is passed). If- "True", FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers.
- use_orig_params ( - bool, optional, defaults to- False) If- "True", allows non-uniform- requires_gradduring init, which means support for interspersed frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019
- sync_module_states ( - bool, optional, defaults to- True) If- "True", each individually wrapped FSDP unit will broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization
- xla ( - bool, optional, defaults to- False): Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future.
- xla_fsdp_settings ( - dict, optional) The value is a dictionary which stores the XLA FSDP wrapping parameters.- For a complete list of options, please see here. 
- xla_fsdp_grad_ckpt ( - bool, optional, defaults to- False): Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.
- activation_checkpointing ( - bool, optional, defaults to- False): If True, activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage.
 
- deepspeed ( - stror- dict, optional) β Use Deepspeed. This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,- ds_config.json) or an already loaded json file as a- dictβ
- label_smoothing_factor ( - float, optional, defaults to 0.0) β The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded labels are changed from 0s and 1s to- label_smoothing_factor/num_labelsand- 1 - label_smoothing_factor + label_smoothing_factor/num_labelsrespectively.
- debug ( - stror list of- DebugOption, optional, defaults to- "") β Enable one or more debug features. This is an experimental feature.- Possible options are: - "underflow_overflow": detects overflow in modelβs input/outputs and reports the last frames that led to the event
- "tpu_metrics_debug": print debug metrics on TPU
 - The options should be separated by whitespaces. 
- optim ( - stror- training_args.OptimizerNames, optional, defaults to- "adamw_torch") β The optimizer to use: adamw_hf, adamw_torch, adamw_torch_fused, adamw_apex_fused, adamw_anyprecision or adafactor.
- optim_args ( - str, optional) β Optional arguments that are supplied to AnyPrecisionAdamW.
- group_by_length ( - bool, optional, defaults to- False) β Whether or not to group together samples of roughly the same length in the training dataset (to minimize padding applied and be more efficient). Only useful if applying dynamic padding.
- length_column_name ( - str, optional, defaults to- "length") β Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unless- group_by_lengthis- Trueand the dataset is an instance of- Dataset.
- report_to ( - stror- List[str], optional, defaults to- "all") β The list of integrations to report the results and logs to. Supported platforms are- "azure_ml",- "clearml",- "codecarbon",- "comet_ml",- "dagshub",- "flyte",- "mlflow",- "neptune",- "tensorboard", and- "wandb". Use- "all"to report to all integrations installed,- "none"for no integrations.
- ddp_find_unused_parameters ( - bool, optional) β When using distributed training, the value of the flag- find_unused_parameterspassed to- DistributedDataParallel. Will default to- Falseif gradient checkpointing is used,- Trueotherwise.
- ddp_bucket_cap_mb ( - int, optional) β When using distributed training, the value of the flag- bucket_cap_mbpassed to- DistributedDataParallel.
- ddp_broadcast_buffers ( - bool, optional) β When using distributed training, the value of the flag- broadcast_bufferspassed to- DistributedDataParallel. Will default to- Falseif gradient checkpointing is used,- Trueotherwise.
- dataloader_pin_memory ( - bool, optional, defaults to- True) β Whether you want to pin memory in data loaders or not. Will default to- True.
- skip_memory_metrics ( - bool, optional, defaults to- True) β Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows down the training and evaluation speed.
- push_to_hub ( - bool, optional, defaults to- False) β Whether or not to push the model to the Hub every time the model is saved. If this is activated,- output_dirwill begin a git directory synced with the repo (determined by- hub_model_id) and the content will be pushed each time a save is triggered (depending on your- save_strategy). Calling save_model() will also trigger a push.- If - output_direxists, it needs to be a local clone of the repository to which the Trainer will be pushed.
- resume_from_checkpoint ( - str, optional) β The path to a folder with a valid checkpoint for your model. This argument is not directly used by Trainer, itβs intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
- hub_model_id ( - str, optional) β The name of the repository to keep in sync with the local output_dir. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance- "user_name/model", which allows you to push to an organization you are a member of with- "organization_name/model". Will default to- user_name/output_dir_namewith output_dir_name being the name of- output_dir.- Will default to the name of - output_dir.
- hub_strategy ( - stror- HubStrategy, optional, defaults to- "every_save") β Defines the scope of what is pushed to the Hub and when. Possible values are:- "end": push the model, its configuration, the tokenizer (if passed along to the Trainer) and a draft of a model card when the save_model() method is called.
- "every_save": push the model, its configuration, the tokenizer (if passed along to the Trainer) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training.
- "checkpoint": like- "every_save"but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with- trainer.train(resume_from_checkpoint="last-checkpoint").
- "all_checkpoints": like- "checkpoint"but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)
 
- hub_token ( - str, optional) β The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with- boincai-cli login.
- hub_private_repo ( - bool, optional, defaults to- False) β If True, the Hub repo will be set to private.
- hub_always_push ( - bool, optional, defaults to- False) β Unless this is- True, the- Trainerwill skip pushing a checkpoint when the previous push is not finished.
- gradient_checkpointing ( - bool, optional, defaults to- False) β If True, use gradient checkpointing to save memory at the expense of slower backward pass.
- include_inputs_for_metrics ( - bool, optional, defaults to- False) β Whether or not the inputs will be passed to the- compute_metricsfunction. This is intended for metrics that need inputs, predictions and references for scoring calculation in Metric class.
- auto_find_batch_size ( - bool, optional, defaults to- False) β Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (- pip install accelerate)
- full_determinism ( - bool, optional, defaults to- False) β If- True, enable_full_determinism() is called instead of set_seed() to ensure reproducible results in distributed training. Important: this will negatively impact the performance, so only use it for debugging.
- torchdynamo ( - str, optional) β If set, the backend compiler for TorchDynamo. Possible choices are- "eager",- "aot_eager",- "inductor",- "nvfuser",- "aot_nvfuser",- "aot_cudagraphs",- "ofi",- "fx2trt",- "onnxrt"and- "ipex".
- ray_scope ( - str, optional, defaults to- "last") β The scope to use when doing hyperparameter search with Ray. By default,- "last"will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the Ray documentation for more options.
- ddp_timeout ( - int, optional, defaults to 1800) β The timeout for- torch.distributed.init_process_groupcalls, used to avoid GPU socket timeouts when performing slow operations in distributed runnings. Please refer the [PyTorch documentation] (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information.
- use_mps_device ( - bool, optional, defaults to- False) β This argument is deprecated.- mpsdevice will be used if it is available similar to- cudadevice.
- torch_compile ( - bool, optional, defaults to- False) β Whether or not to compile the model using PyTorch 2.0- torch.compile.- This will use the best defaults for the - torch.compileAPI. You can customize the defaults with the argument- torch_compile_backendand- torch_compile_modebut we donβt guarantee any of them will work as the support is progressively rolled in in PyTorch.- This flag and the whole compile API is experimental and subject to change in future releases. 
- torch_compile_backend ( - str, optional) β The backend to use in- torch.compile. If set to any value,- torch_compilewill be set to- True.- Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions. - This flag is experimental and subject to change in future releases. 
- torch_compile_mode ( - str, optional) β The mode to use in- torch.compile. If set to any value,- torch_compilewill be set to- True.- Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions. - This flag is experimental and subject to change in future releases. 
- include_tokens_per_second ( - bool, optional) β Whether or not to compute the number of tokens per second per device for training speed metrics.- This will iterate over the entire training dataloader once beforehand, - and will slow down the entire process. 
- sortish_sampler ( - bool, optional, defaults to- False) β Whether to use a sortish sampler or not. Only possible if the underlying datasets are Seq2SeqDataset for now but will become generally available in the near future.- It sorts the inputs according to lengths in order to minimize the padding size, with a bit of randomness for the training set. 
- predict_with_generate ( - bool, optional, defaults to- False) β Whether to use generate to calculate generative metrics (ROUGE, BLEU).
- generation_max_length ( - int, optional) β The- max_lengthto use on each evaluation loop when- predict_with_generate=True. Will default to the- max_lengthvalue of the model configuration.
- generation_num_beams ( - int, optional) β The- num_beamsto use on each evaluation loop when- predict_with_generate=True. Will default to the- num_beamsvalue of the model configuration.
- generation_config ( - stror- Pathor GenerationConfig, optional) β Allows to load a GenerationConfig from the- from_pretrainedmethod. This can be either:- a string, the model id of a pretrained model configuration hosted inside a model repo on boincai.com. Valid model ids can be located at the root-level, like - bert-base-uncased, or namespaced under a user or organization name, like- dbmdz/bert-base-german-cased.
- a path to a directory containing a configuration file saved using the save_pretrained() method, e.g., - ./my_model_directory/.
- a GenerationConfig object. 
 
TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
to_dict
( )
Serializes this instance while replace Enum by their values and GenerationConfig by dictionaries (for JSON serialization support). It obfuscates the token values by removing their value.
Checkpoints
By default, Trainer will save all checkpoints in the output_dir you set in the TrainingArguments you are using. Those will go in subfolder named checkpoint-xxx with xxx being the step at which the training was at.
Resuming training from a checkpoint can be done when calling Trainer.train() with either:
- resume_from_checkpoint=Truewhich will resume training from the latest checkpoint
- resume_from_checkpoint=checkpoint_dirwhich will resume training from the specific checkpoint in the directory passed.
In addition, you can easily save your checkpoints on the Model Hub when using push_to_hub=True. By default, all the models saved in intermediate checkpoints are saved in different commits, but not the optimizer state. You can adapt the hub-strategy value of your TrainingArguments to either:
- "checkpoint": the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with- trainer.train(resume_from_checkpoint="output_dir/last-checkpoint").
- "all_checkpoints": all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)
Logging
By default Trainer will use logging.INFO for the main process and logging.WARNING for the replicas if any.
These defaults can be overridden to use any of the 5 logging levels with TrainingArgumentsβs arguments:
- log_level- for the main process
- log_level_replica- for the replicas
Further, if TrainingArgumentsβs log_on_each_node is set to False only the main node will use the log level settings for its main process, all other nodes will use the log level settings for replicas.
Note that Trainer is going to set transformersβs log level separately for each node in its Trainer.__init__(). So you may want to set this sooner (see the next example) if you tap into other transformers functionality before creating the Trainer object.
Here is an example of how this can be used in an application:
Copied
[...]
logger = logging.getLogger(__name__)
# Setup logging
logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    handlers=[logging.StreamHandler(sys.stdout)],
)
# set the main code and the modules it uses to the same log-level according to the node
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
trainer = Trainer(...)And then if you only want to see warnings on the main node and all other nodes to not print any most likely duplicated warnings you could run it as:
Copied
my_app.py ... --log_level warning --log_level_replica errorIn the multi-node environment if you also donβt want the logs to repeat for each nodeβs main process, you will want to change the above to:
Copied
my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0and then only the main process of the first node will log at the βwarningβ level, and all other processes on the main node and all processes on other nodes will log at the βerrorβ level.
If you need your application to be as quiet as possible you could do:
Copied
my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0(add --log_on_each_node 0 if on multi-node environment)
Randomness
When resuming from a checkpoint generated by Trainer all efforts are made to restore the python, numpy and pytorch RNG states to the same states as they were at the moment of saving that checkpoint, which should make the βstop and resumeβ style of training as close as possible to non-stop training.
However, due to various default non-deterministic pytorch settings this might not fully work. If you want full determinism please refer to Controlling sources of randomness. As explained in the document, that some of those settings that make things deterministic (.e.g., torch.backends.cudnn.deterministic) may slow things down, therefore this canβt be done by default, but you can enable those yourself if needed.
Specific GPUs Selection
Letβs discuss how you can tell your program which GPUs are to be used and in what order.
When using DistributedDataParallel to use only a subset of your GPUs, you simply specify the number of GPUs to use. For example, if you have 4 GPUs, but you wish to use the first 2 you can do:
Copied
python -m torch.distributed.launch --nproc_per_node=2  trainer-program.py ...if you have either accelerate or deepspeed installed you can also accomplish the same by using one of:
Copied
accelerate launch --num_processes 2 trainer-program.py ...Copied
deepspeed --num_gpus 2 trainer-program.py ...You donβt need to use the Accelerate or the Deepspeed integration features to use these launchers.
Until now you were able to tell the program how many GPUs to use. Now letβs discuss how to select specific GPUs and control their order.
The following environment variables help you control which GPUs to use and their order.
CUDA_VISIBLE_DEVICES
If you have multiple GPUs and youβd like to use only 1 or a few of those GPUs, set the environment variable CUDA_VISIBLE_DEVICES to a list of the GPUs to be used.
For example, letβs say you have 4 GPUs: 0, 1, 2 and 3. To run only on the physical GPUs 0 and 2, you can do:
Copied
CUDA_VISIBLE_DEVICES=0,2 python -m torch.distributed.launch trainer-program.py ...So now pytorch will see only 2 GPUs, where your physical GPUs 0 and 2 are mapped to cuda:0 and cuda:1 correspondingly.
You can even change their order:
Copied
CUDA_VISIBLE_DEVICES=2,0 python -m torch.distributed.launch trainer-program.py ...Here your physical GPUs 0 and 2 are mapped to cuda:1 and cuda:0 correspondingly.
The above examples were all for DistributedDataParallel use pattern, but the same method works for DataParallel as well:
Copied
CUDA_VISIBLE_DEVICES=2,0 python trainer-program.py ...To emulate an environment without GPUs simply set this environment variable to an empty value like so:
Copied
CUDA_VISIBLE_DEVICES= python trainer-program.py ...As with any environment variable you can, of course, export those instead of adding these to the command line, as in:
Copied
export CUDA_VISIBLE_DEVICES=0,2
python -m torch.distributed.launch trainer-program.py ...but this approach can be confusing since you may forget you set up the environment variable earlier and not understand why the wrong GPUs are used. Therefore, itβs a common practice to set the environment variable just for a specific run on the same command line as itβs shown in most examples of this section.
CUDA_DEVICE_ORDER
There is an additional environment variable CUDA_DEVICE_ORDER that controls how the physical devices are ordered. The two choices are:
- ordered by PCIe bus IDs (matches - nvidia-smiβs order) - this is the default.
Copied
export CUDA_DEVICE_ORDER=PCI_BUS_ID- ordered by GPU compute capabilities 
Copied
export CUDA_DEVICE_ORDER=FASTEST_FIRSTMost of the time you donβt need to care about this environment variable, but itβs very helpful if you have a lopsided setup where you have an old and a new GPUs physically inserted in such a way so that the slow older card appears to be first. One way to fix that is to swap the cards. But if you canβt swap the cards (e.g., if the cooling of the devices gets impacted) then setting CUDA_DEVICE_ORDER=FASTEST_FIRST will always put the newer faster card first. Itβll be somewhat confusing though since nvidia-smi will still report them in the PCIe order.
The other solution to swapping the order is to use:
Copied
export CUDA_VISIBLE_DEVICES=1,0In this example we are working with just 2 GPUs, but of course the same would apply to as many GPUs as your computer has.
Also if you do set this environment variable itβs the best to set it in your ~/.bashrc file or some other startup config file and forget about it.
Trainer Integrations
The Trainer has been extended to support libraries that may dramatically improve your training time and fit much bigger models.
Currently it supports third party solutions, DeepSpeed and PyTorch FSDP, which implement parts of the paper ZeRO: Memory Optimizations Toward Training Trillion Parameter Models, by Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He.
This provided support is new and experimental as of this writing. While the support for DeepSpeed and PyTorch FSDP is active and we welcome issues around it, we donβt support the FairScale integration anymore since it has been integrated in PyTorch main (see the PyTorch FSDP integration)
CUDA Extension Installation Notes
As of this writing, Deepspeed require compilation of CUDA C++ code, before it can be used.
While all installation issues should be dealt with through the corresponding GitHub Issues of Deepspeed, there are a few common issues that one may encounter while building any PyTorch extension that needs to build CUDA extensions.
Therefore, if you encounter a CUDA-related build issue while doing the following:
Copied
pip install deepspeedplease, read the following notes first.
In these notes we give examples for what to do when pytorch has been built with CUDA 10.2. If your situation is different remember to adjust the version number to the one you are after.
Possible problem #1
While, Pytorch comes with its own CUDA toolkit, to build these two projects you must have an identical version of CUDA installed system-wide.
For example, if you installed pytorch with cudatoolkit==10.2 in the Python environment, you also need to have CUDA 10.2 installed system-wide.
The exact location may vary from system to system, but /usr/local/cuda-10.2 is the most common location on many Unix systems. When CUDA is correctly set up and added to the PATH environment variable, one can find the installation location by doing:
Copied
which nvccIf you donβt have CUDA installed system-wide, install it first. You will find the instructions by using your favorite search engine. For example, if youβre on Ubuntu you may want to search for: ubuntu cuda 10.2 install.
Possible problem #2
Another possible common problem is that you may have more than one CUDA toolkit installed system-wide. For example you may have:
Copied
/usr/local/cuda-10.2
/usr/local/cuda-11.0Now, in this situation you need to make sure that your PATH and LD_LIBRARY_PATH environment variables contain the correct paths to the desired CUDA version. Typically, package installers will set these to contain whatever the last version was installed. If you encounter the problem, where the package build fails because it canβt find the right CUDA version despite you having it installed system-wide, it means that you need to adjust the 2 aforementioned environment variables.
First, you may look at their contents:
Copied
echo $PATH
echo $LD_LIBRARY_PATHso you get an idea of what is inside.
Itβs possible that LD_LIBRARY_PATH is empty.
PATH lists the locations of where executables can be found and LD_LIBRARY_PATH is for where shared libraries are to looked for. In both cases, earlier entries have priority over the later ones. : is used to separate multiple entries.
Now, to tell the build program where to find the specific CUDA toolkit, insert the desired paths to be listed first by doing:
Copied
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATHNote that we arenβt overwriting the existing values, but prepending instead.
Of course, adjust the version number, the full path if need be. Check that the directories you assign actually do exist. lib64 sub-directory is where the various CUDA .so objects, like libcudart.so reside, itβs unlikely that your system will have it named differently, but if it is adjust it to reflect your reality.
Possible problem #3
Some older CUDA versions may refuse to build with newer compilers. For example, you my have gcc-9 but it wants gcc-7.
There are various ways to go about it.
If you can install the latest CUDA toolkit it typically should support the newer compiler.
Alternatively, you could install the lower version of the compiler in addition to the one you already have, or you may already have it but itβs not the default one, so the build system canβt see it. If you have gcc-7 installed but the build system complains it canβt find it, the following might do the trick:
Copied
sudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++Here, we are making a symlink to gcc-7 from /usr/local/cuda-10.2/bin/gcc and since /usr/local/cuda-10.2/bin/ should be in the PATH environment variable (see the previous problemβs solution), it should find gcc-7 (and g++7) and then the build will succeed.
As always make sure to edit the paths in the example to match your situation.
PyTorch Fully Sharded Data parallel
To accelerate training huge models on larger batch sizes, we can use a fully sharded data parallel model. This type of data parallel paradigm enables fitting more data and larger models by sharding the optimizer states, gradients and parameters. To read more about it and the benefits, check out the Fully Sharded Data Parallel blog. We have integrated the latest PyTorchβs Fully Sharded Data Parallel (FSDP) training feature. All you need to do is enable it through the config.
Required PyTorch version for FSDP support: PyTorch Nightly (or 1.12.0 if you read this after it has been released) as the model saving with FSDP activated is only available with recent fixes.
Usage:
- Make sure you have added the distributed launcher - -m torch.distributed.launch --nproc_per_node=NUMBER_OF_GPUS_YOU_HAVEif you havenβt been using it already.
- Sharding Strategy: - FULL_SHARD : Shards optimizer states + gradients + model parameters across data parallel workers/GPUs. For this, add - --fsdp full_shardto the command line arguments.
- SHARD_GRAD_OP : Shards optimizer states + gradients across data parallel workers/GPUs. For this, add - --fsdp shard_grad_opto the command line arguments.
- NO_SHARD : No sharding. For this, add - --fsdp no_shardto the command line arguments.
 
- To offload the parameters and gradients to the CPU, add - --fsdp "full_shard offload"or- --fsdp "shard_grad_op offload"to the command line arguments.
- To automatically recursively wrap layers with FSDP using - default_auto_wrap_policy, add- --fsdp "full_shard auto_wrap"or- --fsdp "shard_grad_op auto_wrap"to the command line arguments.
- To enable both CPU offloading and auto wrapping, add - --fsdp "full_shard offload auto_wrap"or- --fsdp "shard_grad_op offload auto_wrap"to the command line arguments.
- Remaining FSDP config is passed via - --fsdp_config <path_to_fsdp_config.json>. It is either a location of FSDP json config file (e.g.,- fsdp_config.json) or an already loaded json file as- dict.- If auto wrapping is enabled, you can either use transformer based auto wrap policy or size based auto wrap policy. - For transformer based auto wrap policy, it is recommended to specify - fsdp_transformer_layer_cls_to_wrapin the config file. If not specified, the default value is- model._no_split_moduleswhen available. This specifies the list of transformer layer class name (case-sensitive) to wrap ,e.g,- BertLayer,- GPTJBlock,- T5Block⦠This is important because submodules that share weights (e.g., embedding layer) should not end up in different FSDP wrapped units. Using this policy, wrapping happens for each block containing Multi-Head Attention followed by couple of MLP layers. Remaining layers including the shared embeddings are conveniently wrapped in same outermost FSDP unit. Therefore, use this for transformer based models.
- For size based auto wrap policy, please add - fsdp_min_num_paramsin the config file. It specifies FSDPβs minimum number of parameters for auto wrapping.
 
- fsdp_backward_prefetchcan be specified in the config file. It controls when to prefetch next set of parameters.- backward_preand- backward_posare available options. For more information refer- torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch
- fsdp_forward_prefetchcan be specified in the config file. It controls when to prefetch next set of parameters. If- "True", FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass.
- limit_all_gatherscan be specified in the config file. If- "True", FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers.
- activation_checkpointingcan be specified in the config file. If- "True", FSDP activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage.
 
Few caveats to be aware of
- it is incompatible with - generate, thus is incompatible with- --predict_with_generatein all seq2seq/clm scripts (translation/summarization/clm etc.). Please refer issue #21667
PyTorch/XLA Fully Sharded Data parallel
For all the TPU users, great news! PyTorch/XLA now supports FSDP. All the latest Fully Sharded Data Parallel (FSDP) training are supported. For more information refer to the Scaling PyTorch models on Cloud TPUs with FSDP and PyTorch/XLA implementation of FSDP All you need to do is enable it through the config.
Required PyTorch/XLA version for FSDP support: >=2.0
Usage:
Pass --fsdp "full shard" along with following changes to be made in --fsdp_config <path_to_fsdp_config.json>:
- xlashould be set to- Trueto enable PyTorch/XLA FSDP.
- xla_fsdp_settingsThe value is a dictionary which stores the XLA FSDP wrapping parameters. For a complete list of options, please see here.
- xla_fsdp_grad_ckpt. When- True, uses gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through- fsdp_min_num_paramsor- fsdp_transformer_layer_cls_to_wrap.
- You can either use transformer based auto wrap policy or size based auto wrap policy. - For transformer based auto wrap policy, it is recommended to specify - fsdp_transformer_layer_cls_to_wrapin the config file. If not specified, the default value is- model._no_split_moduleswhen available. This specifies the list of transformer layer class name (case-sensitive) to wrap ,e.g,- BertLayer,- GPTJBlock,- T5Block⦠This is important because submodules that share weights (e.g., embedding layer) should not end up in different FSDP wrapped units. Using this policy, wrapping happens for each block containing Multi-Head Attention followed by couple of MLP layers. Remaining layers including the shared embeddings are conveniently wrapped in same outermost FSDP unit. Therefore, use this for transformer based models.
- For size based auto wrap policy, please add - fsdp_min_num_paramsin the config file. It specifies FSDPβs minimum number of parameters for auto wrapping.
 
Using Trainer for accelerated PyTorch Training on Mac
With PyTorch v1.12 release, developers and researchers can take advantage of Apple silicon GPUs for significantly faster model training. This unlocks the ability to perform machine learning workflows like prototyping and fine-tuning locally, right on Mac. Appleβs Metal Performance Shaders (MPS) as a backend for PyTorch enables this and can be used via the new "mps" device. This will map computational graphs and primitives on the MPS Graph framework and tuned kernels provided by MPS. For more information please refer official documents Introducing Accelerated PyTorch Training on Mac and MPS BACKEND.
We strongly recommend to install PyTorch >= 1.13 (nightly version at the time of writing) on your MacOS machine. It has major fixes related to model correctness and performance improvements for transformer based models. Please refer to https://github.com/pytorch/pytorch/issues/82707 for more details.
Benefits of Training and Inference using Apple Silicon Chips
- Enables users to train larger networks or batch sizes locally 
- Reduces data retrieval latency and provides the GPU with direct access to the full memory store due to unified memory architecture. Therefore, improving end-to-end performance. 
- Reduces costs associated with cloud-based development or the need for additional local GPUs. 
Pre-requisites: To install torch with mps support, please follow this nice medium article GPU-Acceleration Comes to PyTorch on M1 Macs.
Usage: mps device will be used by default if available similar to the way cuda device is used. Therefore, no action from user is required. For example, you can run the official Glue text classififcation task (from the root folder) using Apple Silicon GPU with below command:
Copied
export TASK_NAME=mrpc
python examples/pytorch/text-classification/run_glue.py \
  --model_name_or_path bert-base-cased \
  --task_name $TASK_NAME \
  --do_train \
  --do_eval \
  --max_seq_length 128 \
  --per_device_train_batch_size 32 \
  --learning_rate 2e-5 \
  --num_train_epochs 3 \
  --output_dir /tmp/$TASK_NAME/ \
  --overwrite_output_dirA few caveats to be aware of
- Some PyTorch operations have not been implemented in mps and will throw an error. One way to get around that is to set the environment variable - PYTORCH_ENABLE_MPS_FALLBACK=1, which will fallback to CPU for these operations. It still throws a UserWarning however.
- Distributed setups - glooand- ncclare not working with- mpsdevice. This means that currently only single GPU of- mpsdevice type can be used.
Finally, please, remember that, π Trainer only integrates MPS backend, therefore if you have any problems or questions with regards to MPS backend usage, please, file an issue with PyTorch GitHub.
Using Accelerate Launcher with Trainer
Accelerate now powers Trainer. In terms of what users should expect:
- They can keep using the Trainer ingterations such as FSDP, DeepSpeed vis trainer arguments without any changes on their part. 
- They can now use Accelerate Launcher with Trainer (recommended). 
Steps to use Accelerate Launcher with Trainer:
- Make sure π Accelerate is installed, you canβt use the - Trainerwithout it anyway. If not- pip install accelerate. You may also need to update your version of Accelerate:- pip install accelerate --upgrade
- Run - accelerate configand fill the questionnaire. Below are example accelerate configs: a. DDP Multi-node Multi-GPU config:- Copied - compute_environment: LOCAL_MACHINE distributed_type: MULTI_GPU downcast_bf16: 'no' gpu_ids: all machine_rank: 0 #change rank as per the node main_process_ip: 192.168.20.1 main_process_port: 9898 main_training_function: main mixed_precision: fp16 num_machines: 2 num_processes: 8 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false- b. FSDP config: - Copied - compute_environment: LOCAL_MACHINE distributed_type: FSDP downcast_bf16: 'no' fsdp_config: fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP fsdp_backward_prefetch_policy: BACKWARD_PRE fsdp_forward_prefetch: true fsdp_offload_params: false fsdp_sharding_strategy: 1 fsdp_state_dict_type: FULL_STATE_DICT fsdp_sync_module_states: true fsdp_transformer_layer_cls_to_wrap: BertLayer fsdp_use_orig_params: true machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 2 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false- c. DeepSpeed config pointing to a file: - Copied - compute_environment: LOCAL_MACHINE deepspeed_config: deepspeed_config_file: /home/user/configs/ds_zero3_config.json zero3_init_flag: true distributed_type: DEEPSPEED downcast_bf16: 'no' machine_rank: 0 main_training_function: main num_machines: 1 num_processes: 4 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false- d. DeepSpeed config using accelerate plugin: - Copied - compute_environment: LOCAL_MACHINE deepspeed_config: gradient_accumulation_steps: 1 gradient_clipping: 0.7 offload_optimizer_device: cpu offload_param_device: cpu zero3_init_flag: true zero_stage: 2 distributed_type: DEEPSPEED downcast_bf16: 'no' machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 4 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false
- Run the Trainer script with args other than the ones handled above by accelerate config or launcher args. Below is an example to run - run_glue.pyusing- accelerate launcherwith FSDP config from above.
Copied
cd transformers
accelerate launch \
./examples/pytorch/text-classification/run_glue.py \
--model_name_or_path bert-base-cased \
--task_name $TASK_NAME \
--do_train \
--do_eval \
--max_seq_length 128 \
--per_device_train_batch_size 16 \
--learning_rate 5e-5 \
--num_train_epochs 3 \
--output_dir /tmp/$TASK_NAME/ \
--overwrite_output_dir- You can also directly use the cmd args for - accelerate launch. Above example would map to:
Copied
cd transformers
accelerate launch --num_processes=2 \
--use_fsdp \
--mixed_precision=bf16 \
--fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP  \
--fsdp_transformer_layer_cls_to_wrap="BertLayer" \
--fsdp_sharding_strategy=1 \
--fsdp_state_dict_type=FULL_STATE_DICT \
./examples/pytorch/text-classification/run_glue.py
--model_name_or_path bert-base-cased \
--task_name $TASK_NAME \
--do_train \
--do_eval \
--max_seq_length 128 \
--per_device_train_batch_size 16 \
--learning_rate 5e-5 \
--num_train_epochs 3 \
--output_dir /tmp/$TASK_NAME/ \
--overwrite_output_dirFor more information, please refer the π Accelerate CLI guide: Launching your π Accelerate scripts.
Sections that were moved:
[ DeepSpeed | Installation | Deployment with multiple GPUs | Deployment with one GPU | Deployment in Notebooks | Configuration | Passing Configuration | Shared Configuration | ZeRO | ZeRO-2 Config | ZeRO-3 Config | NVMe Support | ZeRO-2 vs ZeRO-3 Performance | ZeRO-2 Example | ZeRO-3 Example | Optimizer | Scheduler | fp32 Precision | Automatic Mixed Precision | Batch Size | Gradient Accumulation | Gradient Clipping | Getting The Model Weights Out ]
Last updated
