Trainer
Trainer 클래스는 PyTorch에서 완전한 기능(feature-complete)의 훈련을 위한 API를 제공하며, 다중 GPU/TPU에서의 분산 훈련, NVIDIA GPU, AMD GPU를 위한 혼합 정밀도, 그리고 PyTorch의 torch.amp
를 지원합니다. Trainer는 모델의 훈련 방식을 커스터마이즈할 수 있는 다양한 옵션을 제공하는 TrainingArguments 클래스와 함께 사용됩니다. 이 두 클래스는 함께 완전한 훈련 API를 제공합니다.
Seq2SeqTrainer와 Seq2SeqTrainingArguments는 Trainer와 TrainingArguments 클래스를 상속하며, 요약이나 번역과 같은 시퀀스-투-시퀀스 작업을 위한 모델 훈련에 적합하게 조정되어 있습니다.
Trainer 클래스는 🤗 Transformers 모델에 최적화되어 있으며, 다른 모델과 함께 사용될 때 예상치 못한 동작을 하게 될 수 있습니다. 자신만의 모델을 사용할 때는 다음을 확인하세요:
- 모델은 항상 튜플이나 ModelOutput의 서브클래스를 반환해야 합니다.
- 모델은
labels
인자가 제공되면 손실을 계산할 수 있고, 모델이 튜플을 반환하는 경우 그 손실이 튜플의 첫 번째 요소로 반환되어야 합니다. - 모델은 여러 개의 레이블 인자를 수용할 수 있어야 하며, Trainer에게 이름을 알리기 위해 TrainingArguments에서
label_names
를 사용하지만, 그 중 어느 것도"label"
로 명명되어서는 안 됩니다.
Trainer
class transformers.Trainer
< source >( model: Union = None args: TrainingArguments = None data_collator: Optional = None train_dataset: Union = None eval_dataset: Union = None processing_class: Union = None model_init: Optional = None compute_loss_func: Optional = None compute_metrics: Optional = None callbacks: Optional = None optimizers: Tuple = (None, None) preprocess_logits_for_metrics: Optional = None )
Parameters
- model (PreTrainedModel or
torch.nn.Module
, optional) — The model to train, evaluate or use for predictions. If not provided, amodel_init
must 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.Module
as 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_dir
set 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 oftrain_dataset
oreval_dataset
. Will default to default_data_collator() if noprocessing_class
is provided, an instance of DataCollatorWithPadding otherwise if the processing_class is a feature extractor or tokenizer. - train_dataset (Union[
torch.utils.data.Dataset
,torch.utils.data.IterableDataset
,datasets.Dataset
], optional) — The dataset to use for training. If it is aDataset
, columns not accepted by themodel.forward()
method are automatically removed.Note that if it’s a
torch.utils.data.IterableDataset
with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attributegenerator
that is atorch.Generator
for the randomization that must be identical on all processes (and the Trainer will manually set the seed of thisgenerator
at each epoch) or have aset_epoch()
method that internally sets the seed of the RNGs used. - eval_dataset (Union[
torch.utils.data.Dataset
, Dict[str,torch.utils.data.Dataset
,datasets.Dataset
]), optional) — The dataset to use for evaluation. If it is aDataset
, columns not accepted by themodel.forward()
method are automatically removed. If it is a dictionary, it will evaluate on each dataset prepending the dictionary key to the metric name. - processing_class (
PreTrainedTokenizerBase
orBaseImageProcessor
orFeatureExtractionMixin
orProcessorMixin
, optional) — Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. This supercedes thetokenizer
argument, which is now deprecated. - 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_loss_func (
Callable
, optional) — A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, here is one using the loss function fromtransformers
- 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. Note When passing TrainingArgs withbatch_eval_metrics
set toTrue
, your compute_metrics function must take a booleancompute_result
argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics - 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, defaults to(None, None)
) — A tuple containing the optimizer and the scheduler to use. Will default to an instance ofAdamW
on your model and a scheduler given byget_linear_schedule_with_warmup()
controlled byargs
. - 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 bycompute_metrics
.Note that the labels (second parameter) will be
None
if 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 inDeepSpeed
and then again intorch.nn.DistributedDataParallel
. If the inner model hasn’t been wrapped, thenself.model_wrapped
is the same asself.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
False
if model parallel or deepspeed is used, or if the defaultTrainingArguments.place_model_on_device
is overridden to returnFalse
. - is_in_train — Whether or not a model is currently running
train
(e.g. whenevaluate
is called while intrain
)
add_callback
< source >( callback )
Parameters
- callback (
type
or [`~transformers.TrainerCallback]`) — A TrainerCallback class or an instance of a TrainerCallback. In the first case, will instantiate a member of that class.
Add a callback to the current list of TrainerCallback.
A helper wrapper that creates an appropriate context manager for autocast
while feeding it the desired
arguments, depending on the situation.
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
A helper wrapper to group together context managers.
create_model_card
< source >( language: Optional = None license: Optional = None tags: Union = None model_name: Optional = None finetuned_from: Optional = None tasks: Union = None dataset_tags: Union = None dataset: Union = None dataset_args: Union = 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 theTrainer
comes from a repo on the Hub. - tags (
str
orList[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 theTrainer
(if it comes from the Hub). - tasks (
str
orList[str]
, optional) — One or several task identifiers, to be included in the metadata of the model card. - dataset_tags (
str
orList[str]
, optional) — One or several dataset tags, to be included in the metadata of the model card. - dataset (
str
orList[str]
, optional) — One or several dataset identifiers, to be included in the metadata of the model card. - dataset_args (
str
orList[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
.
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.
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
< source >( num_training_steps: int optimizer: Optimizer = None )
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
< source >( eval_dataset: Union = None ignore_keys: Optional = None metric_key_prefix: str = 'eval' )
Parameters
- eval_dataset (Union[
Dataset
, Dict[str,Dataset
]), optional) — Pass a dataset if you wish to overrideself.eval_dataset
. If it is aDataset
, columns not accepted by themodel.forward()
method are automatically removed. If it is a dictionary, it will evaluate on each dataset, prepending the dictionary key to the metric name. Datasets must implement the__len__
method.If you pass a dictionary with names of datasets as keys and datasets as values, evaluate will run separate evaluations on each dataset. This can be useful to monitor how training affects other datasets or simply to get a more fine-grained evaluation. When used with
load_best_model_at_end
, make suremetric_for_best_model
references exactly one of the datasets. If you, for example, pass in{"data1": data1, "data2": data2}
for two datasetsdata1
anddata2
, you could specifymetric_for_best_model="eval_data1_loss"
for using the loss ondata1
andmetric_for_best_model="eval_data2_loss"
for the loss ondata2
. - 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
< source >( dataloader: DataLoader description: str prediction_loss_only: Optional = None ignore_keys: Optional = None metric_key_prefix: str = 'eval' )
Prediction/evaluation loop, shared by Trainer.evaluate()
and Trainer.predict()
.
Works both with or without labels.
floating_point_ops
< source >( inputs: Dict ) → int
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 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
< source >( eval_dataset: Union = None )
Parameters
- eval_dataset (
str
ortorch.utils.data.Dataset
, optional) — If astr
, will useself.eval_dataset[eval_dataset]
as the evaluation dataset. If aDataset
, will overrideself.eval_dataset
and must implement__len__
. If it is aDataset
, columns not accepted by themodel.forward()
method are automatically removed.
Returns the evaluation ~torch.utils.data.DataLoader
.
Subclass and override this method if you want to inject some custom behavior.
Returns the learning rate of each parameter from self.optimizer.
Get the number of trainable parameters.
get_optimizer_cls_and_kwargs
< source >( args: TrainingArguments model: Optional = None )
Returns the optimizer class and optimizer parameters based on the training arguments.
get_optimizer_group
< source >( param: Union = None )
Returns optimizer group for a parameter if given, else returns all optimizer groups for params.
get_test_dataloader
< source >( test_dataset: Dataset )
Returns the test ~torch.utils.data.DataLoader
.
Subclass and override this method if you want to inject some custom behavior.
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
< source >( hp_space: Optional = None compute_objective: Optional = None n_trials: int = 20 direction: Union = 'minimize' backend: Union = None hp_name: Optional = None **kwargs ) → [trainer_utils.BestRun
or List[trainer_utils.BestRun]
]
Parameters
- hp_space (
Callable[["optuna.Trial"], Dict[str, float]]
, optional) — A function that defines the hyperparameter search space. Will default todefault_hp_space_optuna()
ordefault_hp_space_ray()
ordefault_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 theevaluate
method. Will default todefault_compute_objective()
. - n_trials (
int
, optional, defaults to 100) — The number of trial runs to test. - direction (
str
orList[str]
, optional, defaults to"minimize"
) — If it’s single objective optimization, direction isstr
, 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 isList[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 (
str
or~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 tooptuna.create_study
orray.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.
Initializes a git repo in self.args.hub_model_id
.
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process.
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
on the various objects watching training.
Subclass and override this method to inject custom behavior.
log_metrics
< source >( split metrics )
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: :
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 = 7MB
Understanding the reports:
- the first segment, e.g.,
train__
, tells you which stage the metrics are for. Reports starting withinit_
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 theeval_
metrics. - the third segment, is either
cpu
orgpu
, 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 upalloc_delta
+peaked_delta
and 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
< source >( metrics: Dict ) → metrics (Dict[str, float]
)
Reformat Trainer metrics values to a human-readable format
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
Helper to get number of tokens in a ~torch.utils.data.DataLoader
by enumerating dataloader.
pop_callback
< source >( callback ) → TrainerCallback
Parameters
- callback (
type
or [`~transformers.TrainerCallback]`) — A TrainerCallback class or an instance of a TrainerCallback. In the first case, will pop the first member of that class found in the list of callbacks.
Returns
The callback removed, if found.
Remove a callback from the current list of TrainerCallback and returns it.
If the callback is not found, returns None
(and no error is raised).
predict
< source >( test_dataset: Dataset ignore_keys: Optional = None metric_key_prefix: str = 'test' )
Parameters
- test_dataset (
Dataset
) — Dataset to run the predictions on. If it is andatasets.Dataset
, columns not accepted by themodel.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 ontest_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
< source >( dataloader: DataLoader description: str prediction_loss_only: Optional = None ignore_keys: Optional = None metric_key_prefix: str = 'eval' )
Prediction/evaluation loop, shared by Trainer.evaluate()
and Trainer.predict()
.
Works both with or without labels.
prediction_step
< source >( model: Module inputs: Dict prediction_loss_only: bool ignore_keys: Optional = 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.
Sets values in the deepspeed plugin based on the Trainer args
push_to_hub
< source >( commit_message: Optional = 'End of training' blocking: bool = True token: Optional = None revision: Optional = None **kwargs )
Parameters
- commit_message (
str
, optional, defaults to"End of training"
) — Message to commit while pushing. - blocking (
bool
, optional, defaults toTrue
) — Whether the function should return only when thegit push
has finished. - token (
str
, optional, defaults toNone
) — Token with write permission to overwrite Trainer’s original args. - revision (
str
, optional) — The git revision to commit from. Defaults to the head of the “main” branch. - kwargs (
Dict[str, Any]
, optional) — Additional keyword arguments passed along to create_model_card().
Upload self.model
and self.processing_class
to the 🤗 model hub on the repo self.args.hub_model_id
.
remove_callback
< source >( callback )
Parameters
- callback (
type
or [`~transformers.TrainerCallback]`) — A TrainerCallback class or an instance of a 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 TrainerCallback.
save_metrics
< source >( split metrics combined = True )
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.
Will save the model, so you can reload it using from_pretrained()
.
Will only save from the main process.
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
< source >( resume_from_checkpoint: Union = None trial: Union = None ignore_keys_for_eval: Optional = None **kwargs )
Parameters
- resume_from_checkpoint (
str
orbool
, optional) — If astr
, local path to a saved checkpoint as saved by a previous instance of Trainer. If abool
and equalsTrue
, 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.Trial
orDict[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
< source >( model: Module inputs: Dict num_items_in_batch = None ) → 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
< source >( model: Union = None args: TrainingArguments = None data_collator: Optional = None train_dataset: Union = None eval_dataset: Union = None processing_class: Union = None model_init: Optional = None compute_metrics: Optional = None callbacks: Optional = None optimizers: Tuple = (None, None) preprocess_logits_for_metrics: Optional = None )
evaluate
< source >( eval_dataset: Optional = None ignore_keys: Optional = None metric_key_prefix: str = 'eval' **gen_kwargs )
Parameters
- eval_dataset (
Dataset
, optional) — Pass a dataset if you wish to overrideself.eval_dataset
. If it is anDataset
, columns not accepted by themodel.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 — Additionalgenerate
specific 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
< source >( test_dataset: Dataset ignore_keys: Optional = None metric_key_prefix: str = 'test' **gen_kwargs )
Parameters
- test_dataset (
Dataset
) — Dataset to run the predictions on. If it is aDataset
, columns not accepted by themodel.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 — Additionalgenerate
specific 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 ontest_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
< source >( output_dir: str overwrite_output_dir: bool = False do_train: bool = False do_eval: bool = False do_predict: bool = False eval_strategy: Union = 'no' prediction_loss_only: bool = False per_device_train_batch_size: int = 8 per_device_eval_batch_size: int = 8 per_gpu_train_batch_size: Optional = None per_gpu_eval_batch_size: Optional = None gradient_accumulation_steps: int = 1 eval_accumulation_steps: Optional = None eval_delay: Optional = 0 torch_empty_cache_steps: Optional = None learning_rate: float = 5e-05 weight_decay: float = 0.0 adam_beta1: float = 0.9 adam_beta2: float = 0.999 adam_epsilon: float = 1e-08 max_grad_norm: float = 1.0 num_train_epochs: float = 3.0 max_steps: int = -1 lr_scheduler_type: Union = 'linear' lr_scheduler_kwargs: Union = <factory> warmup_ratio: float = 0.0 warmup_steps: int = 0 log_level: Optional = 'passive' log_level_replica: Optional = 'warning' log_on_each_node: bool = True logging_dir: Optional = None logging_strategy: Union = 'steps' logging_first_step: bool = False logging_steps: float = 500 logging_nan_inf_filter: bool = True save_strategy: Union = 'steps' save_steps: float = 500 save_total_limit: Optional = None save_safetensors: Optional = True save_on_each_node: bool = False save_only_model: bool = False restore_callback_states_from_checkpoint: bool = False no_cuda: bool = False use_cpu: bool = False use_mps_device: bool = False seed: int = 42 data_seed: Optional = None jit_mode_eval: bool = False use_ipex: bool = False bf16: bool = False fp16: bool = False fp16_opt_level: str = 'O1' half_precision_backend: str = 'auto' bf16_full_eval: bool = False fp16_full_eval: bool = False tf32: Optional = None local_rank: int = -1 ddp_backend: Optional = None tpu_num_cores: Optional = None tpu_metrics_debug: bool = False debug: Union = '' dataloader_drop_last: bool = False eval_steps: Optional = None dataloader_num_workers: int = 0 dataloader_prefetch_factor: Optional = None past_index: int = -1 run_name: Optional = None disable_tqdm: Optional = None remove_unused_columns: Optional = True label_names: Optional = None load_best_model_at_end: Optional = False metric_for_best_model: Optional = None greater_is_better: Optional = None ignore_data_skip: bool = False fsdp: Union = '' fsdp_min_num_params: int = 0 fsdp_config: Union = None fsdp_transformer_layer_cls_to_wrap: Optional = None accelerator_config: Union = None deepspeed: Union = None label_smoothing_factor: float = 0.0 optim: Union = 'adamw_torch' optim_args: Optional = None adafactor: bool = False group_by_length: bool = False length_column_name: Optional = 'length' report_to: Union = None ddp_find_unused_parameters: Optional = None ddp_bucket_cap_mb: Optional = None ddp_broadcast_buffers: Optional = None dataloader_pin_memory: bool = True dataloader_persistent_workers: bool = False skip_memory_metrics: bool = True use_legacy_prediction_loop: bool = False push_to_hub: bool = False resume_from_checkpoint: Optional = None hub_model_id: Optional = None hub_strategy: Union = 'every_save' hub_token: Optional = None hub_private_repo: bool = False hub_always_push: bool = False gradient_checkpointing: bool = False gradient_checkpointing_kwargs: Union = None include_inputs_for_metrics: bool = False include_for_metrics: List = <factory> eval_do_concat_batches: bool = True fp16_backend: str = 'auto' evaluation_strategy: Union = None push_to_hub_model_id: Optional = None push_to_hub_organization: Optional = None push_to_hub_token: Optional = None mp_parameters: str = '' auto_find_batch_size: bool = False full_determinism: bool = False torchdynamo: Optional = None ray_scope: Optional = 'last' ddp_timeout: Optional = 1800 torch_compile: bool = False torch_compile_backend: Optional = None torch_compile_mode: Optional = None dispatch_batches: Optional = None split_batches: Optional = None include_tokens_per_second: Optional = False include_num_input_tokens_seen: Optional = False neftune_noise_alpha: Optional = None optim_target_modules: Union = None batch_eval_metrics: bool = False eval_on_start: bool = False use_liger_kernel: Optional = False eval_use_gather_object: Optional = False average_tokens_across_devices: Optional = False )
Parameters
- output_dir (
str
) — The output directory where the model predictions and checkpoints will be written. - overwrite_output_dir (
bool
, optional, defaults toFalse
) — IfTrue
, overwrite the content of the output directory. Use this to continue training ifoutput_dir
points to a checkpoint directory. - do_train (
bool
, optional, defaults toFalse
) — 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 toTrue
ifeval_strategy
is 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 toFalse
) — 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. - eval_strategy (
str
or 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) everyeval_steps
."epoch"
: Evaluation is done at the end of each epoch.
- prediction_loss_only (
bool
, optional, defaults toFalse
) — 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_step
training 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 eval_strategy. - torch_empty_cache_steps (
int
, optional) — Number of steps to wait before callingtorch.<device>.empty_cache()
. If left unset or set to None, cache will not be emptied.This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about 10% slower performance.
- learning_rate (
float
, optional, defaults to 5e-5) — The initial learning rate forAdamW
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 inAdamW
optimizer. - adam_beta1 (
float
, optional, defaults to 0.9) — The beta1 hyperparameter for theAdamW
optimizer. - adam_beta2 (
float
, optional, defaults to 0.999) — The beta2 hyperparameter for theAdamW
optimizer. - adam_epsilon (
float
, optional, defaults to 1e-8) — The epsilon hyperparameter for theAdamW
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. Overridesnum_train_epochs
. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) untilmax_steps
is reached. - lr_scheduler_type (
str
orSchedulerType
, optional, defaults to"linear"
) — The scheduler type to use. See the documentation ofSchedulerType
for all possible values. - lr_scheduler_kwargs (‘dict’, optional, defaults to {}) — The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.
- warmup_ratio (
float
, optional, defaults to 0.0) — Ratio of total training steps used for a linear warmup from 0 tolearning_rate
. - warmup_steps (
int
, optional, defaults to 0) — Number of steps used for a linear warmup from 0 tolearning_rate
. Overrides any effect ofwarmup_ratio
. - log_level (
str
, optional, defaults topassive
) — 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 aslog_level
” - log_on_each_node (
bool
, optional, defaults toTrue
) — In multinode distributed training, whether to log usinglog_level
once 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 (
str
or 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 everylogging_steps
.
- logging_first_step (
bool
, optional, defaults toFalse
) — Whether to log the firstglobal_step
or not. - logging_steps (
int
orfloat
, optional, defaults to 500) — Number of update steps between two logs iflogging_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 toTrue
) — Whether to filternan
andinf
losses for logging. If set toTrue
the loss of every step that isnan
orinf
is filtered and the average loss of the current logging window is taken instead.logging_nan_inf_filter
only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. - save_strategy (
str
or 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 everysave_steps
.
If
"epoch"
or"steps"
is chosen, saving will also be performed at the very end of training, always. - save_steps (
int
orfloat
, optional, defaults to 500) — Number of updates steps before two checkpoint saves ifsave_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 inoutput_dir
. Whenload_best_model_at_end
is enabled, the “best” checkpoint according tometric_for_best_model
will always be retained in addition to the most recent ones. For example, forsave_total_limit=5
andload_best_model_at_end
, the four last checkpoints will always be retained alongside the best model. Whensave_total_limit=1
andload_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 toTrue
) — Use safetensors saving and loading for state dicts instead of defaulttorch.load
andtorch.save
. - save_on_each_node (
bool
, optional, defaults toFalse
) — 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.
- save_only_model (
bool
, optional, defaults toFalse
) — When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state. Note that when this is true, you won’t be able to resume training from checkpoint. This enables you to save storage by not storing the optimizer, scheduler & rng state. You can only load the model usingfrom_pretrained
with this option set toTrue
. - restore_callback_states_from_checkpoint (
bool
, optional, defaults toFalse
) — Whether to restore the callback states from the checkpoint. IfTrue
, will override callbacks passed to theTrainer
if they exist in the checkpoint.” - use_cpu (
bool
, optional, defaults toFalse
) — 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_init
function 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 asseed
. This can be used to ensure reproducibility of data sampling, independent of the model seed. - jit_mode_eval (
bool
, optional, defaults toFalse
) — Whether or not to use PyTorch jit trace for inference. - use_ipex (
bool
, optional, defaults toFalse
) — Use Intel extension for PyTorch when it is available. IPEX installation. - bf16 (
bool
, optional, defaults toFalse
) — 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 toFalse
) — Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training. - fp16_opt_level (
str
, optional, defaults to ‘O1’) — Forfp16
training, 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. Usehalf_precision_backend
instead. - half_precision_backend (
str
, optional, defaults to"auto"
) — The backend to use for mixed precision training. Must be one of"auto", "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 toFalse
) — 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 toFalse
) — 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 oftorch.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 toFalse
) — Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. - eval_steps (
int
orfloat
, optional) — Number of update steps between two evaluations ifeval_strategy="steps"
. Will default to the same value aslogging_steps
if 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, theTrainer
will 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 argumentmems
. - run_name (
str
, optional, defaults tooutput_dir
) — A descriptor for the run. Typically used for wandb, mlflow and comet logging. If not specified, will be the same asoutput_dir
. - disable_tqdm (
bool
, optional) — Whether or not to disable the tqdm progress bars and table of metrics produced by~notebook.NotebookTrainingTracker
in Jupyter Notebooks. Will default toTrue
if the logging level is set to warn or lower (default),False
otherwise. - remove_unused_columns (
bool
, optional, defaults toTrue
) — Whether or not to automatically remove the columns unused by the model forward method. - 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
XxxForQuestionAnswering
in which case it will also include the["start_positions", "end_positions"]
keys. - load_best_model_at_end (
bool
, optional, defaults toFalse
) — 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. Seesave_total_limit
for more.When set to
True
, the parameterssave_strategy
needs to be the same aseval_strategy
, and in the case it is “steps”,save_steps
must be a round multiple ofeval_steps
. - metric_for_best_model (
str
, optional) — Use in conjunction withload_best_model_at_end
to 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 andload_best_model_at_end=True
(to use the evaluation loss).If you set this value,
greater_is_better
will default toTrue
. Don’t forget to set it toFalse
if your metric is better when lower. - greater_is_better (
bool
, optional) — Use in conjunction withload_best_model_at_end
andmetric_for_best_model
to specify if better models should have a greater metric or not. Will default to:True
ifmetric_for_best_model
is set to a value that doesn’t end in"loss"
.False
ifmetric_for_best_model
is not set, or set to a value that ends in"loss"
.
- ignore_data_skip (
bool
, optional, defaults toFalse
) — 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 toTrue
, 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. - fsdp (
bool
,str
or list ofFSDPOption
, 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."hybrid_shard"
: ApplyFULL_SHARD
within a node, and replicate parameters across nodes."hybrid_shard_zero2"
: ApplySHARD_GRAD_OP
within a node, and replicate parameters across nodes."offload"
: Offload parameters and gradients to CPUs (only compatible with"full_shard"
and"shard_grad_op"
)."auto_wrap"
: Automatically recursively wrap layers with FSDP usingdefault_auto_wrap_policy
.
- fsdp_config (
str
ordict
, optional) — Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of fsdp json config file (e.g.,fsdp_config.json
) or an already loaded json file asdict
.A List of config and its options:
-
min_num_params (
int
, optional, defaults to0
): FSDP’s minimum number of parameters for Default Auto Wrapping. (useful only whenfsdp
field 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 whenfsdp
flag is passed). -
backward_prefetch (
str
, optional) FSDP’s backward prefetch mode. Controls when to prefetch next set of parameters (useful only whenfsdp
field 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 toFalse
) FSDP’s forward prefetch mode (useful only whenfsdp
field 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 toFalse
) FSDP’s limit_all_gathers (useful only whenfsdp
field is passed). If"True"
, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. -
use_orig_params (
bool
, optional, defaults toTrue
) If"True"
, allows non-uniformrequires_grad
during 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 toTrue
) 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 -
cpu_ram_efficient_loading (
bool
, optional, defaults toFalse
) If"True"
, only the first process loads the pretrained model checkpoint while all other processes have empty weights. When this setting as"True"
,sync_module_states
also must to be"True"
, otherwise all the processes except the main process would have random weights leading to unexpected behaviour during training. -
activation_checkpointing (
bool
, optional, defaults toFalse
): 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. -
xla (
bool
, optional, defaults toFalse
): 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 toFalse
): 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.
-
- deepspeed (
str
ordict
, 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 adict
”If enabling any Zero-init, make sure that your model is not initialized until *after* initializing the `TrainingArguments`, else it will not be applied. - accelerator_config (
str
,dict
, orAcceleratorConfig
, optional) — Config to be used with the internalAccelerator
implementation. The value is either a location of accelerator json config file (e.g.,accelerator_config.json
), an already loaded json file asdict
, or an instance ofAcceleratorConfig
.A list of config and its options:
- split_batches (
bool
, optional, defaults toFalse
): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. IfTrue
the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of thenum_processes
you are using. IfFalse
, actual batch size used will be the one set in your script multiplied by the number of processes. - dispatch_batches (
bool
, optional): If set toTrue
, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default toTrue
forDataLoader
whose underlying dataset is anIterableDataset
,False
otherwise. - even_batches (
bool
, optional, defaults toTrue
): If set toTrue
, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers. - use_seedable_sampler (
bool
, optional, defaults toTrue
): Whether or not use a fully seedable random sampler (accelerate.data_loader.SeedableRandomSampler
). Ensures training results are fully reproducable using a different sampling technique. While seed-to-seed results may differ, on average the differences are neglible when using multiple different seeds to compare. Should also be ran with~utils.set_seed
for the best results. - use_configured_state (
bool
, optional, defaults toFalse
): Whether or not to use a pre-configuredAcceleratorState
orPartialState
defined before callingTrainingArguments
. IfTrue
, anAccelerator
orPartialState
must be initialized. Note that by doing so, this could lead to issues with hyperparameter tuning.
- split_batches (
- 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 tolabel_smoothing_factor/num_labels
and1 - label_smoothing_factor + label_smoothing_factor/num_labels
respectively. - debug (
str
or list ofDebugOption
, 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 (
str
ortraining_args.OptimizerNames
, optional, defaults to"adamw_torch"
) — The optimizer to use, such as “adamw_hf”, “adamw_torch”, “adamw_torch_fused”, “adamw_apex_fused”, “adamw_anyprecision”, “adafactor”. SeeOptimizerNames
in training_args.py for a full list of optimizers. - optim_args (
str
, optional) — Optional arguments that are supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore. - group_by_length (
bool
, optional, defaults toFalse
) — 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 unlessgroup_by_length
isTrue
and the dataset is an instance ofDataset
. - report_to (
str
orList[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"
,"dvclive"
,"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 flagfind_unused_parameters
passed toDistributedDataParallel
. Will default toFalse
if gradient checkpointing is used,True
otherwise. - ddp_bucket_cap_mb (
int
, optional) — When using distributed training, the value of the flagbucket_cap_mb
passed toDistributedDataParallel
. - ddp_broadcast_buffers (
bool
, optional) — When using distributed training, the value of the flagbroadcast_buffers
passed toDistributedDataParallel
. Will default toFalse
if gradient checkpointing is used,True
otherwise. - dataloader_pin_memory (
bool
, optional, defaults toTrue
) — Whether you want to pin memory in data loaders or not. Will default toTrue
. - dataloader_persistent_workers (
bool
, optional, defaults toFalse
) — If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default toFalse
. - dataloader_prefetch_factor (
int
, optional) — Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. - skip_memory_metrics (
bool
, optional, defaults toTrue
) — 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 toFalse
) — Whether or not to push the model to the Hub every time the model is saved. If this is activated,output_dir
will begin a git directory synced with the repo (determined byhub_model_id
) and the content will be pushed each time a save is triggered (depending on yoursave_strategy
). Calling save_model() will also trigger a push.If
output_dir
exists, 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 touser_name/output_dir_name
with output_dir_name being the name ofoutput_dir
.Will default to the name of
output_dir
. - hub_strategy (
str
orHubStrategy
, 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 processing class e.g. 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 processing class e.g. 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 withtrainer.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 withhuggingface-cli login
. - hub_private_repo (
bool
, optional, defaults toFalse
) — If True, the Hub repo will be set to private. - hub_always_push (
bool
, optional, defaults toFalse
) — Unless this isTrue
, theTrainer
will skip pushing a checkpoint when the previous push is not finished. - gradient_checkpointing (
bool
, optional, defaults toFalse
) — If True, use gradient checkpointing to save memory at the expense of slower backward pass. - gradient_checkpointing_kwargs (
dict
, optional, defaults toNone
) — Key word arguments to be passed to thegradient_checkpointing_enable
method. - include_inputs_for_metrics (
bool
, optional, defaults toFalse
) — This argument is deprecated. Useinclude_for_metrics
instead, e.g,include_for_metrics = ["inputs"]
. - include_for_metrics (
List[str]
, optional, defaults to[]
) — Include additional data in thecompute_metrics
function if needed for metrics computation. Possible options to add toinclude_for_metrics
list:"inputs"
: Input data passed to the model, intended for calculating input dependent metrics."loss"
: Loss values computed during evaluation, intended for calculating loss dependent metrics.
- eval_do_concat_batches (
bool
, optional, defaults toTrue
) — Whether to recursively concat inputs/losses/labels/predictions across batches. IfFalse
, will instead store them as lists, with each batch kept separate. - auto_find_batch_size (
bool
, optional, defaults toFalse
) — 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 toFalse
) — IfTrue
, 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 fortorch.distributed.init_process_group
calls, 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 toFalse
) — This argument is deprecated.mps
device will be used if it is available similar tocuda
device. - torch_compile (
bool
, optional, defaults toFalse
) — Whether or not to compile the model using PyTorch 2.0torch.compile
.This will use the best defaults for the
torch.compile
API. You can customize the defaults with the argumenttorch_compile_backend
andtorch_compile_mode
but 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 intorch.compile
. If set to any value,torch_compile
will be set toTrue
.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 intorch.compile
. If set to any value,torch_compile
will be set toTrue
.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.
- split_batches (
bool
, optional) — Whether or not the accelerator should split the batches yielded by the dataloaders across the devices during distributed training. Ifset to
True
, the actual batch size used will be the same on any kind of distributed processes, but it must be around multiple of the number of processes you are using (such as GPUs).
- 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.
- include_num_input_tokens_seen (
bool
, optional) — Whether or not to track the number of input tokens seen throughout training.May be slower in distributed training as gather operations must be called.
- neftune_noise_alpha (
Optional[float]
) — If notNone
, this will activate NEFTune noise embeddings. This can drastically improve model performance for instruction fine-tuning. Check out the original paper and the original code. Support transformersPreTrainedModel
and alsoPeftModel
from peft. The original paper used values in the range [5.0, 15.0]. - optim_target_modules (
Union[str, List[str]]
, optional) — The target modules to optimize, i.e. the module names that you would like to train, right now this is used only for GaLore algorithm https://arxiv.org/abs/2403.03507 See: https://github.com/jiaweizzhao/GaLore for more details. You need to make sure to pass a valid GaloRe optimizer, e.g. one of: “galore_adamw”, “galore_adamw_8bit”, “galore_adafactor” and make sure that the target modules arenn.Linear
modules only. - batch_eval_metrics (
Optional[bool]
, defaults toFalse
) — If set toTrue
, evaluation will call compute_metrics at the end of each batch to accumulate statistics rather than saving all eval logits in memory. When set toTrue
, you must pass a compute_metrics function that takes a boolean argumentcompute_result
, which when passedTrue
, will trigger the final global summary statistics from the batch-level summary statistics you’ve accumulated over the evaluation set. - eval_on_start (
bool
, optional, defaults toFalse
) — Whether to perform a evaluation step (sanity check) before the training to ensure the validation steps works correctly. - eval_use_gather_object (
bool
, optional, defaults toFalse
) — Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices. This should only be enabled if users are not just returning tensors, and this is actively discouraged by PyTorch. - use_liger_kernel (
bool
, optional, defaults toFalse
) — Whether enable Liger Kernel for LLM model training. It can effectively increase multi-GPU training throughput by ~20% and reduces memory usage by ~60%, works out of the box with flash attention, PyTorch FSDP, and Microsoft DeepSpeed. Currently, it supports llama, mistral, mixtral and gemma models.
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.
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 number of steps used for a linear warmup.
main_process_first
< source >( local = True desc = 'work' )
Parameters
- local (
bool
, optional, defaults toTrue
) — ifTrue
first means process of rank 0 of each node ifFalse
first means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to uselocal=False
so 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
< source >( train_batch_size: int = 8 eval_batch_size: int = 8 drop_last: bool = False num_workers: int = 0 pin_memory: bool = True persistent_workers: bool = False prefetch_factor: Optional = None auto_find_batch_size: bool = False ignore_data_skip: bool = False sampler_seed: Optional = None )
Parameters
- drop_last (
bool
, optional, defaults toFalse
) — 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 toTrue
) — Whether you want to pin memory in data loaders or not. Will default toTrue
. - persistent_workers (
bool
, optional, defaults toFalse
) — If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default toFalse
. - prefetch_factor (
int
, optional) — Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. - auto_find_batch_size (
bool
, optional, defaults toFalse
) — 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 toFalse
) — 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 toTrue
, 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 asself.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.
set_evaluate
< source >( strategy: Union = 'no' steps: int = 500 batch_size: int = 8 accumulation_steps: Optional = None delay: Optional = None loss_only: bool = False jit_mode: bool = False )
Parameters
- strategy (
str
or 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) everysteps
."epoch"
: Evaluation is done at the end of each epoch.
Setting a
strategy
different from"no"
will setself.do_eval
toTrue
. - steps (
int
, optional, defaults to 500) — Number of update steps between two evaluations ifstrategy="steps"
. - batch_size (
int
optional, 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 eval_strategy. - loss_only (
bool
, optional, defaults toFalse
) — 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 evaluation.
set_logging
< source >( strategy: Union = 'steps' steps: int = 500 report_to: Union = 'none' level: str = 'passive' first_step: bool = False nan_inf_filter: bool = False on_each_node: bool = False replica_level: str = 'passive' )
Parameters
- strategy (
str
or 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 everylogging_steps
.
- steps (
int
, optional, defaults to 500) — Number of update steps between two logs ifstrategy="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 (
str
orList[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"
,"dvclive"
,"flyte"
,"mlflow"
,"neptune"
,"tensorboard"
, and"wandb"
. Use"all"
to report to all integrations installed,"none"
for no integrations. - first_step (
bool
, optional, defaults toFalse
) — Whether to log and evaluate the firstglobal_step
or not. - nan_inf_filter (
bool
, optional, defaults toTrue
) — Whether to filternan
andinf
losses for logging. If set toTrue
the loss of every step that isnan
orinf
is filtered and the average loss of the current logging window is taken instead.nan_inf_filter
only 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 toTrue
) — In multinode distributed training, whether to log usinglog_level
once per node, or only on the main node. - replica_level (
str
, optional, defaults to"passive"
) — Logger log level to use on replicas. Same choices aslog_level
A method that regroups all arguments linked to logging.
set_lr_scheduler
< source >( name: Union = 'linear' num_epochs: float = 3.0 max_steps: int = -1 warmup_ratio: float = 0 warmup_steps: int = 0 )
Parameters
- name (
str
orSchedulerType
, optional, defaults to"linear"
) — The scheduler type to use. See the documentation ofSchedulerType
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. Overridesnum_train_epochs
. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) untilmax_steps
is reached. - warmup_ratio (
float
, optional, defaults to 0.0) — Ratio of total training steps used for a linear warmup from 0 tolearning_rate
. - warmup_steps (
int
, optional, defaults to 0) — Number of steps used for a linear warmup from 0 tolearning_rate
. Overrides any effect ofwarmup_ratio
.
A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.
set_optimizer
< source >( name: Union = 'adamw_torch' learning_rate: float = 5e-05 weight_decay: float = 0 beta1: float = 0.9 beta2: float = 0.999 epsilon: float = 1e-08 args: Optional = None )
Parameters
- name (
str
ortraining_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 whenoptim="adamw_anyprecision"
).
A method that regroups all arguments linked to the optimizer and its hyperparameters.
set_push_to_hub
< source >( model_id: str strategy: Union = 'every_save' token: Optional = None private_repo: bool = False always_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 (
str
orHubStrategy
, 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 processing_class e.g. 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 processing_class e.g. 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 withtrainer.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 withhuggingface-cli login
. - private_repo (
bool
, optional, defaults toFalse
) — If True, the Hub repo will be set to private. - always_push (
bool
, optional, defaults toFalse
) — Unless this isTrue
, theTrainer
will 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 on your self.save_strategy
). Calling save_model() will also trigger a push.
set_save
< source >( strategy: Union = 'steps' steps: int = 500 total_limit: Optional = None on_each_node: bool = False )
Parameters
- strategy (
str
or 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 everysave_steps
.
- steps (
int
, optional, defaults to 500) — Number of updates steps before two checkpoint saves ifstrategy="steps"
. - total_limit (
int
, optional) — If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints inoutput_dir
. - on_each_node (
bool
, optional, defaults toFalse
) — 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 checkpoint saving.
set_testing
< source >( batch_size: int = 8 loss_only: bool = False jit_mode: bool = False )
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
.
set_training
< source >( learning_rate: float = 5e-05 batch_size: int = 8 weight_decay: float = 0 num_epochs: float = 3 max_steps: int = -1 gradient_accumulation_steps: int = 1 seed: int = 42 gradient_checkpointing: bool = False )
Parameters
- learning_rate (
float
, optional, defaults to 5e-5) — The initial learning rate for the optimizer. - batch_size (
int
optional, 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. Overridesnum_train_epochs
. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) untilmax_steps
is reached. - 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_step
training 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_init
function to instantiate the model if it has some randomly initialized parameters. - gradient_checkpointing (
bool
, optional, defaults toFalse
) — 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
.
Serializes this instance while replace Enum
by their values (for JSON serialization support). It obfuscates
the token values by removing their value.
Serializes this instance to a JSON string.
Sanitized serialization to use with TensorBoard’s hparams
Seq2SeqTrainingArguments
class transformers.Seq2SeqTrainingArguments
< source >( output_dir: str overwrite_output_dir: bool = False do_train: bool = False do_eval: bool = False do_predict: bool = False eval_strategy: Union = 'no' prediction_loss_only: bool = False per_device_train_batch_size: int = 8 per_device_eval_batch_size: int = 8 per_gpu_train_batch_size: Optional = None per_gpu_eval_batch_size: Optional = None gradient_accumulation_steps: int = 1 eval_accumulation_steps: Optional = None eval_delay: Optional = 0 torch_empty_cache_steps: Optional = None learning_rate: float = 5e-05 weight_decay: float = 0.0 adam_beta1: float = 0.9 adam_beta2: float = 0.999 adam_epsilon: float = 1e-08 max_grad_norm: float = 1.0 num_train_epochs: float = 3.0 max_steps: int = -1 lr_scheduler_type: Union = 'linear' lr_scheduler_kwargs: Union = <factory> warmup_ratio: float = 0.0 warmup_steps: int = 0 log_level: Optional = 'passive' log_level_replica: Optional = 'warning' log_on_each_node: bool = True logging_dir: Optional = None logging_strategy: Union = 'steps' logging_first_step: bool = False logging_steps: float = 500 logging_nan_inf_filter: bool = True save_strategy: Union = 'steps' save_steps: float = 500 save_total_limit: Optional = None save_safetensors: Optional = True save_on_each_node: bool = False save_only_model: bool = False restore_callback_states_from_checkpoint: bool = False no_cuda: bool = False use_cpu: bool = False use_mps_device: bool = False seed: int = 42 data_seed: Optional = None jit_mode_eval: bool = False use_ipex: bool = False bf16: bool = False fp16: bool = False fp16_opt_level: str = 'O1' half_precision_backend: str = 'auto' bf16_full_eval: bool = False fp16_full_eval: bool = False tf32: Optional = None local_rank: int = -1 ddp_backend: Optional = None tpu_num_cores: Optional = None tpu_metrics_debug: bool = False debug: Union = '' dataloader_drop_last: bool = False eval_steps: Optional = None dataloader_num_workers: int = 0 dataloader_prefetch_factor: Optional = None past_index: int = -1 run_name: Optional = None disable_tqdm: Optional = None remove_unused_columns: Optional = True label_names: Optional = None load_best_model_at_end: Optional = False metric_for_best_model: Optional = None greater_is_better: Optional = None ignore_data_skip: bool = False fsdp: Union = '' fsdp_min_num_params: int = 0 fsdp_config: Union = None fsdp_transformer_layer_cls_to_wrap: Optional = None accelerator_config: Union = None deepspeed: Union = None label_smoothing_factor: float = 0.0 optim: Union = 'adamw_torch' optim_args: Optional = None adafactor: bool = False group_by_length: bool = False length_column_name: Optional = 'length' report_to: Union = None ddp_find_unused_parameters: Optional = None ddp_bucket_cap_mb: Optional = None ddp_broadcast_buffers: Optional = None dataloader_pin_memory: bool = True dataloader_persistent_workers: bool = False skip_memory_metrics: bool = True use_legacy_prediction_loop: bool = False push_to_hub: bool = False resume_from_checkpoint: Optional = None hub_model_id: Optional = None hub_strategy: Union = 'every_save' hub_token: Optional = None hub_private_repo: bool = False hub_always_push: bool = False gradient_checkpointing: bool = False gradient_checkpointing_kwargs: Union = None include_inputs_for_metrics: bool = False include_for_metrics: List = <factory> eval_do_concat_batches: bool = True fp16_backend: str = 'auto' evaluation_strategy: Union = None push_to_hub_model_id: Optional = None push_to_hub_organization: Optional = None push_to_hub_token: Optional = None mp_parameters: str = '' auto_find_batch_size: bool = False full_determinism: bool = False torchdynamo: Optional = None ray_scope: Optional = 'last' ddp_timeout: Optional = 1800 torch_compile: bool = False torch_compile_backend: Optional = None torch_compile_mode: Optional = None dispatch_batches: Optional = None split_batches: Optional = None include_tokens_per_second: Optional = False include_num_input_tokens_seen: Optional = False neftune_noise_alpha: Optional = None optim_target_modules: Union = None batch_eval_metrics: bool = False eval_on_start: bool = False use_liger_kernel: Optional = False eval_use_gather_object: Optional = False average_tokens_across_devices: Optional = False sortish_sampler: bool = False predict_with_generate: bool = False generation_max_length: Optional = None generation_num_beams: Optional = None generation_config: Union = None )
Parameters
- output_dir (
str
) — The output directory where the model predictions and checkpoints will be written. - overwrite_output_dir (
bool
, optional, defaults toFalse
) — IfTrue
, overwrite the content of the output directory. Use this to continue training ifoutput_dir
points to a checkpoint directory. - do_train (
bool
, optional, defaults toFalse
) — 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 toTrue
ifeval_strategy
is 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 toFalse
) — 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. - eval_strategy (
str
or 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) everyeval_steps
."epoch"
: Evaluation is done at the end of each epoch.
- prediction_loss_only (
bool
, optional, defaults toFalse
) — 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_step
training 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 eval_strategy. - torch_empty_cache_steps (
int
, optional) — Number of steps to wait before callingtorch.<device>.empty_cache()
. If left unset or set to None, cache will not be emptied.This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about 10% slower performance.
- learning_rate (
float
, optional, defaults to 5e-5) — The initial learning rate forAdamW
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 inAdamW
optimizer. - adam_beta1 (
float
, optional, defaults to 0.9) — The beta1 hyperparameter for theAdamW
optimizer. - adam_beta2 (
float
, optional, defaults to 0.999) — The beta2 hyperparameter for theAdamW
optimizer. - adam_epsilon (
float
, optional, defaults to 1e-8) — The epsilon hyperparameter for theAdamW
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. Overridesnum_train_epochs
. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) untilmax_steps
is reached. - lr_scheduler_type (
str
orSchedulerType
, optional, defaults to"linear"
) — The scheduler type to use. See the documentation ofSchedulerType
for all possible values. - lr_scheduler_kwargs (‘dict’, optional, defaults to {}) — The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.
- warmup_ratio (
float
, optional, defaults to 0.0) — Ratio of total training steps used for a linear warmup from 0 tolearning_rate
. - warmup_steps (
int
, optional, defaults to 0) — Number of steps used for a linear warmup from 0 tolearning_rate
. Overrides any effect ofwarmup_ratio
. - log_level (
str
, optional, defaults topassive
) — 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 aslog_level
” - log_on_each_node (
bool
, optional, defaults toTrue
) — In multinode distributed training, whether to log usinglog_level
once 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 (
str
or 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 everylogging_steps
.
- logging_first_step (
bool
, optional, defaults toFalse
) — Whether to log the firstglobal_step
or not. - logging_steps (
int
orfloat
, optional, defaults to 500) — Number of update steps between two logs iflogging_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 toTrue
) — Whether to filternan
andinf
losses for logging. If set toTrue
the loss of every step that isnan
orinf
is filtered and the average loss of the current logging window is taken instead.logging_nan_inf_filter
only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. - save_strategy (
str
or 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 everysave_steps
.
If
"epoch"
or"steps"
is chosen, saving will also be performed at the very end of training, always. - save_steps (
int
orfloat
, optional, defaults to 500) — Number of updates steps before two checkpoint saves ifsave_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 inoutput_dir
. Whenload_best_model_at_end
is enabled, the “best” checkpoint according tometric_for_best_model
will always be retained in addition to the most recent ones. For example, forsave_total_limit=5
andload_best_model_at_end
, the four last checkpoints will always be retained alongside the best model. Whensave_total_limit=1
andload_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 toTrue
) — Use safetensors saving and loading for state dicts instead of defaulttorch.load
andtorch.save
. - save_on_each_node (
bool
, optional, defaults toFalse
) — 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.
- save_only_model (
bool
, optional, defaults toFalse
) — When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state. Note that when this is true, you won’t be able to resume training from checkpoint. This enables you to save storage by not storing the optimizer, scheduler & rng state. You can only load the model usingfrom_pretrained
with this option set toTrue
. - restore_callback_states_from_checkpoint (
bool
, optional, defaults toFalse
) — Whether to restore the callback states from the checkpoint. IfTrue
, will override callbacks passed to theTrainer
if they exist in the checkpoint.” - use_cpu (
bool
, optional, defaults toFalse
) — 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_init
function 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 asseed
. This can be used to ensure reproducibility of data sampling, independent of the model seed. - jit_mode_eval (
bool
, optional, defaults toFalse
) — Whether or not to use PyTorch jit trace for inference. - use_ipex (
bool
, optional, defaults toFalse
) — Use Intel extension for PyTorch when it is available. IPEX installation. - bf16 (
bool
, optional, defaults toFalse
) — 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 toFalse
) — Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training. - fp16_opt_level (
str
, optional, defaults to ‘O1’) — Forfp16
training, 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. Usehalf_precision_backend
instead. - half_precision_backend (
str
, optional, defaults to"auto"
) — The backend to use for mixed precision training. Must be one of"auto", "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 toFalse
) — 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 toFalse
) — 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 oftorch.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 toFalse
) — Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. - eval_steps (
int
orfloat
, optional) — Number of update steps between two evaluations ifeval_strategy="steps"
. Will default to the same value aslogging_steps
if 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, theTrainer
will 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 argumentmems
. - run_name (
str
, optional, defaults tooutput_dir
) — A descriptor for the run. Typically used for wandb, mlflow and comet logging. If not specified, will be the same asoutput_dir
. - disable_tqdm (
bool
, optional) — Whether or not to disable the tqdm progress bars and table of metrics produced by~notebook.NotebookTrainingTracker
in Jupyter Notebooks. Will default toTrue
if the logging level is set to warn or lower (default),False
otherwise. - remove_unused_columns (
bool
, optional, defaults toTrue
) — Whether or not to automatically remove the columns unused by the model forward method. - 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
XxxForQuestionAnswering
in which case it will also include the["start_positions", "end_positions"]
keys. - load_best_model_at_end (
bool
, optional, defaults toFalse
) — 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. Seesave_total_limit
for more.When set to
True
, the parameterssave_strategy
needs to be the same aseval_strategy
, and in the case it is “steps”,save_steps
must be a round multiple ofeval_steps
. - metric_for_best_model (
str
, optional) — Use in conjunction withload_best_model_at_end
to 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 andload_best_model_at_end=True
(to use the evaluation loss).If you set this value,
greater_is_better
will default toTrue
. Don’t forget to set it toFalse
if your metric is better when lower. - greater_is_better (
bool
, optional) — Use in conjunction withload_best_model_at_end
andmetric_for_best_model
to specify if better models should have a greater metric or not. Will default to:True
ifmetric_for_best_model
is set to a value that doesn’t end in"loss"
.False
ifmetric_for_best_model
is not set, or set to a value that ends in"loss"
.
- ignore_data_skip (
bool
, optional, defaults toFalse
) — 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 toTrue
, 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. - fsdp (
bool
,str
or list ofFSDPOption
, 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."hybrid_shard"
: ApplyFULL_SHARD
within a node, and replicate parameters across nodes."hybrid_shard_zero2"
: ApplySHARD_GRAD_OP
within a node, and replicate parameters across nodes."offload"
: Offload parameters and gradients to CPUs (only compatible with"full_shard"
and"shard_grad_op"
)."auto_wrap"
: Automatically recursively wrap layers with FSDP usingdefault_auto_wrap_policy
.
- fsdp_config (
str
ordict
, optional) — Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of fsdp json config file (e.g.,fsdp_config.json
) or an already loaded json file asdict
.A List of config and its options:
-
min_num_params (
int
, optional, defaults to0
): FSDP’s minimum number of parameters for Default Auto Wrapping. (useful only whenfsdp
field 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 whenfsdp
flag is passed). -
backward_prefetch (
str
, optional) FSDP’s backward prefetch mode. Controls when to prefetch next set of parameters (useful only whenfsdp
field 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 toFalse
) FSDP’s forward prefetch mode (useful only whenfsdp
field 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 toFalse
) FSDP’s limit_all_gathers (useful only whenfsdp
field is passed). If"True"
, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. -
use_orig_params (
bool
, optional, defaults toTrue
) If"True"
, allows non-uniformrequires_grad
during 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 toTrue
) 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 -
cpu_ram_efficient_loading (
bool
, optional, defaults toFalse
) If"True"
, only the first process loads the pretrained model checkpoint while all other processes have empty weights. When this setting as"True"
,sync_module_states
also must to be"True"
, otherwise all the processes except the main process would have random weights leading to unexpected behaviour during training. -
activation_checkpointing (
bool
, optional, defaults toFalse
): 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. -
xla (
bool
, optional, defaults toFalse
): 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 toFalse
): 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.
-
- deepspeed (
str
ordict
, 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 adict
”If enabling any Zero-init, make sure that your model is not initialized until *after* initializing the `TrainingArguments`, else it will not be applied. - accelerator_config (
str
,dict
, orAcceleratorConfig
, optional) — Config to be used with the internalAccelerator
implementation. The value is either a location of accelerator json config file (e.g.,accelerator_config.json
), an already loaded json file asdict
, or an instance ofAcceleratorConfig
.A list of config and its options:
- split_batches (
bool
, optional, defaults toFalse
): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. IfTrue
the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of thenum_processes
you are using. IfFalse
, actual batch size used will be the one set in your script multiplied by the number of processes. - dispatch_batches (
bool
, optional): If set toTrue
, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default toTrue
forDataLoader
whose underlying dataset is anIterableDataset
,False
otherwise. - even_batches (
bool
, optional, defaults toTrue
): If set toTrue
, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers. - use_seedable_sampler (
bool
, optional, defaults toTrue
): Whether or not use a fully seedable random sampler (accelerate.data_loader.SeedableRandomSampler
). Ensures training results are fully reproducable using a different sampling technique. While seed-to-seed results may differ, on average the differences are neglible when using multiple different seeds to compare. Should also be ran with~utils.set_seed
for the best results. - use_configured_state (
bool
, optional, defaults toFalse
): Whether or not to use a pre-configuredAcceleratorState
orPartialState
defined before callingTrainingArguments
. IfTrue
, anAccelerator
orPartialState
must be initialized. Note that by doing so, this could lead to issues with hyperparameter tuning.
- split_batches (
- 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 tolabel_smoothing_factor/num_labels
and1 - label_smoothing_factor + label_smoothing_factor/num_labels
respectively. - debug (
str
or list ofDebugOption
, 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 (
str
ortraining_args.OptimizerNames
, optional, defaults to"adamw_torch"
) — The optimizer to use, such as “adamw_hf”, “adamw_torch”, “adamw_torch_fused”, “adamw_apex_fused”, “adamw_anyprecision”, “adafactor”. SeeOptimizerNames
in training_args.py for a full list of optimizers. - optim_args (
str
, optional) — Optional arguments that are supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore. - group_by_length (
bool
, optional, defaults toFalse
) — 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 unlessgroup_by_length
isTrue
and the dataset is an instance ofDataset
. - report_to (
str
orList[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"
,"dvclive"
,"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 flagfind_unused_parameters
passed toDistributedDataParallel
. Will default toFalse
if gradient checkpointing is used,True
otherwise. - ddp_bucket_cap_mb (
int
, optional) — When using distributed training, the value of the flagbucket_cap_mb
passed toDistributedDataParallel
. - ddp_broadcast_buffers (
bool
, optional) — When using distributed training, the value of the flagbroadcast_buffers
passed toDistributedDataParallel
. Will default toFalse
if gradient checkpointing is used,True
otherwise. - dataloader_pin_memory (
bool
, optional, defaults toTrue
) — Whether you want to pin memory in data loaders or not. Will default toTrue
. - dataloader_persistent_workers (
bool
, optional, defaults toFalse
) — If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default toFalse
. - dataloader_prefetch_factor (
int
, optional) — Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. - skip_memory_metrics (
bool
, optional, defaults toTrue
) — 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 toFalse
) — Whether or not to push the model to the Hub every time the model is saved. If this is activated,output_dir
will begin a git directory synced with the repo (determined byhub_model_id
) and the content will be pushed each time a save is triggered (depending on yoursave_strategy
). Calling save_model() will also trigger a push.If
output_dir
exists, 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 touser_name/output_dir_name
with output_dir_name being the name ofoutput_dir
.Will default to the name of
output_dir
. - hub_strategy (
str
orHubStrategy
, 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 processing class e.g. 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 processing class e.g. 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 withtrainer.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 withhuggingface-cli login
. - hub_private_repo (
bool
, optional, defaults toFalse
) — If True, the Hub repo will be set to private. - hub_always_push (
bool
, optional, defaults toFalse
) — Unless this isTrue
, theTrainer
will skip pushing a checkpoint when the previous push is not finished. - gradient_checkpointing (
bool
, optional, defaults toFalse
) — If True, use gradient checkpointing to save memory at the expense of slower backward pass. - gradient_checkpointing_kwargs (
dict
, optional, defaults toNone
) — Key word arguments to be passed to thegradient_checkpointing_enable
method. - include_inputs_for_metrics (
bool
, optional, defaults toFalse
) — This argument is deprecated. Useinclude_for_metrics
instead, e.g,include_for_metrics = ["inputs"]
. - include_for_metrics (
List[str]
, optional, defaults to[]
) — Include additional data in thecompute_metrics
function if needed for metrics computation. Possible options to add toinclude_for_metrics
list:"inputs"
: Input data passed to the model, intended for calculating input dependent metrics."loss"
: Loss values computed during evaluation, intended for calculating loss dependent metrics.
- eval_do_concat_batches (
bool
, optional, defaults toTrue
) — Whether to recursively concat inputs/losses/labels/predictions across batches. IfFalse
, will instead store them as lists, with each batch kept separate. - auto_find_batch_size (
bool
, optional, defaults toFalse
) — 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 toFalse
) — IfTrue
, 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 fortorch.distributed.init_process_group
calls, 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 toFalse
) — This argument is deprecated.mps
device will be used if it is available similar tocuda
device. - torch_compile (
bool
, optional, defaults toFalse
) — Whether or not to compile the model using PyTorch 2.0torch.compile
.This will use the best defaults for the
torch.compile
API. You can customize the defaults with the argumenttorch_compile_backend
andtorch_compile_mode
but 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 intorch.compile
. If set to any value,torch_compile
will be set toTrue
.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 intorch.compile
. If set to any value,torch_compile
will be set toTrue
.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.
- split_batches (
bool
, optional) — Whether or not the accelerator should split the batches yielded by the dataloaders across the devices during distributed training. Ifset to
True
, the actual batch size used will be the same on any kind of distributed processes, but it must be around multiple of the number of processes you are using (such as GPUs).
- 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.
- include_num_input_tokens_seen (
bool
, optional) — Whether or not to track the number of input tokens seen throughout training.May be slower in distributed training as gather operations must be called.
- neftune_noise_alpha (
Optional[float]
) — If notNone
, this will activate NEFTune noise embeddings. This can drastically improve model performance for instruction fine-tuning. Check out the original paper and the original code. Support transformersPreTrainedModel
and alsoPeftModel
from peft. The original paper used values in the range [5.0, 15.0]. - optim_target_modules (
Union[str, List[str]]
, optional) — The target modules to optimize, i.e. the module names that you would like to train, right now this is used only for GaLore algorithm https://arxiv.org/abs/2403.03507 See: https://github.com/jiaweizzhao/GaLore for more details. You need to make sure to pass a valid GaloRe optimizer, e.g. one of: “galore_adamw”, “galore_adamw_8bit”, “galore_adafactor” and make sure that the target modules arenn.Linear
modules only. - batch_eval_metrics (
Optional[bool]
, defaults toFalse
) — If set toTrue
, evaluation will call compute_metrics at the end of each batch to accumulate statistics rather than saving all eval logits in memory. When set toTrue
, you must pass a compute_metrics function that takes a boolean argumentcompute_result
, which when passedTrue
, will trigger the final global summary statistics from the batch-level summary statistics you’ve accumulated over the evaluation set. - eval_on_start (
bool
, optional, defaults toFalse
) — Whether to perform a evaluation step (sanity check) before the training to ensure the validation steps works correctly. - eval_use_gather_object (
bool
, optional, defaults toFalse
) — Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices. This should only be enabled if users are not just returning tensors, and this is actively discouraged by PyTorch. - use_liger_kernel (
bool
, optional, defaults toFalse
) — Whether enable Liger Kernel for LLM model training. It can effectively increase multi-GPU training throughput by ~20% and reduces memory usage by ~60%, works out of the box with flash attention, PyTorch FSDP, and Microsoft DeepSpeed. Currently, it supports llama, mistral, mixtral and gemma models. - sortish_sampler (
bool
, optional, defaults toFalse
) — 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 toFalse
) — Whether to use generate to calculate generative metrics (ROUGE, BLEU). - generation_max_length (
int
, optional) — Themax_length
to use on each evaluation loop whenpredict_with_generate=True
. Will default to themax_length
value of the model configuration. - generation_num_beams (
int
, optional) — Thenum_beams
to use on each evaluation loop whenpredict_with_generate=True
. Will default to thenum_beams
value of the model configuration. - generation_config (
str
orPath
or GenerationConfig, optional) — Allows to load a GenerationConfig from thefrom_pretrained
method. This can be either:- a string, the model id of a pretrained model configuration hosted inside a model repo on huggingface.co.
- 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.
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.