---
local: trainer
sections:
- local: transformers.Trainer
  title: Trainer
- local: transformers.Seq2SeqTrainer
  title: Seq2SeqTrainer
- local: transformers.TrainingArguments
  title: TrainingArguments
- local: transformers.Seq2SeqTrainingArguments
  title: Seq2SeqTrainingArguments
- local: checkpoints
  title: Checkpoints
- local: logging
  title: Logging
- local: randomness
  title: Randomness
- local: specific-gpus-selection
  title: Specific GPUs Selection
- local: trainer-integrations
  sections:
  - local: cuda-extension-installation-notes
    sections:
    - local: possible-problem-1
      title: 'Possible problem #1'
    - local: possible-problem-2
      title: 'Possible problem #2'
    - local: possible-problem-3
      title: 'Possible problem #3'
    title: CUDA Extension Installation Notes
  - local: fairscale
    title: FairScale
  title: Trainer Integrations
title: Trainer
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2020 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="trainer">Trainer</h1>

The [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) class provides an API for feature-complete training in PyTorch for most standard use cases. It's used in most of the [example scripts](../examples).

Before instantiating your [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), create a [TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments) to access all the points of customization during training.

The API supports distributed training on multiple GPUs/TPUs, mixed precision through [NVIDIA Apex](https://github.com/NVIDIA/apex) and Native AMP for PyTorch.

The [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) contains the basic training loop which supports the above features. To inject custom behavior you can subclass them and override the following methods:

- **get_train_dataloader** -- Creates the training DataLoader.
- **get_eval_dataloader** -- Creates the evaluation DataLoader.
- **get_test_dataloader** -- Creates the test DataLoader.
- **log** -- Logs information on the various objects watching training.
- **create_optimizer_and_scheduler** -- Sets up the optimizer and learning rate scheduler if they were not passed at
  init. Note, that you can also subclass or override the `create_optimizer` and `create_scheduler` methods
  separately.
- **create_optimizer** -- Sets up the optimizer if it wasn't passed at init.
- **create_scheduler** -- Sets up the learning rate scheduler if it wasn't passed at init.
- **compute_loss** - Computes the loss on a batch of training inputs.
- **training_step** -- Performs a training step.
- **prediction_step** -- Performs an evaluation/test step.
- **evaluate** -- Runs an evaluation loop and returns metrics.
- **predict** -- Returns predictions (with metrics if labels are available) on a test set.

<Tip warning=&amp;lcub;true}>

The [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) class is optimized for 🤗 Transformers models and can have surprising behaviors
when you use it on other models. When using it on your own model, make sure:

- your model always return tuples or subclasses of [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput).
- your model can compute the loss if a `labels` argument is provided and that loss is returned as the first
  element of the tuple (if your model returns tuples)
- your model can accept multiple label arguments (use the `label_names` in your [TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments) to indicate their name to the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer)) but none of them should be named `"label"`.

</Tip>

Here is an example of how to customize [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) to use a weighted loss (useful when you have an unbalanced training set):

```python
from torch import nn
from transformers import Trainer


class CustomTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False):
        labels = inputs.get("labels")
        # forward pass
        outputs = model(**inputs)
        logits = outputs.get("logits")
        # compute custom loss (suppose one has 3 labels with different weights)
        loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0]))
        loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
        return (loss, outputs) if return_outputs else loss
```

Another way to customize the training loop behavior for the PyTorch [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) is to use [callbacks](callback) that can inspect the training loop state (for progress reporting, logging on TensorBoard or other ML platforms...) and take decisions (like early stopping).


<h2 id="transformers.Trainer">Trainer</h2>

<div class="docstring">

<docstring><name>class transformers.Trainer</name><anchor>transformers.Trainer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L199</source><parameters>[{"name": "model", "val": ": typing.Union[transformers.modeling_utils.PreTrainedModel, torch.nn.modules.module.Module] = None"}, {"name": "args", "val": ": TrainingArguments = None"}, {"name": "data_collator", "val": ": typing.Optional[DataCollator] = None"}, {"name": "train_dataset", "val": ": typing.Optional[torch.utils.data.dataset.Dataset] = None"}, {"name": "eval_dataset", "val": ": typing.Optional[torch.utils.data.dataset.Dataset] = None"}, {"name": "tokenizer", "val": ": typing.Optional[transformers.tokenization_utils_base.PreTrainedTokenizerBase] = None"}, {"name": "model_init", "val": ": typing.Callable[[], transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "compute_metrics", "val": ": typing.Union[typing.Callable[[transformers.trainer_utils.EvalPrediction], typing.Dict], NoneType] = None"}, {"name": "callbacks", "val": ": typing.Optional[typing.List[transformers.trainer_callback.TrainerCallback]] = None"}, {"name": "optimizers", "val": ": typing.Tuple[torch.optim.optimizer.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None)"}, {"name": "preprocess_logits_for_metrics", "val": ": typing.Callable[[torch.Tensor, torch.Tensor], torch.Tensor] = None"}]</parameters><paramsdesc>- **model** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel) or `torch.nn.Module`, *optional*) --
  The model to train, evaluate or use for predictions. If not provided, a `model_init` must be passed.

  <Tip>

  [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) is optimized to work with the [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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.

  </Tip>

- **args** ([TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments), *optional*) --
  The arguments to tweak for training. Will default to a basic instance of [TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.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 of `train_dataset` or `eval_dataset`. Will
  default to [default_data_collator()](/docs/transformers/pr_15592/en/main_classes/data_collator#transformers.default_data_collator) if no `tokenizer` is provided, an instance of
  [DataCollatorWithPadding](/docs/transformers/pr_15592/en/main_classes/data_collator#transformers.DataCollatorWithPadding) otherwise.
- **train_dataset** (`torch.utils.data.Dataset` or `torch.utils.data.IterableDataset`, *optional*) --
  The dataset to use for training. If it is an `datasets.Dataset`, columns not accepted by the
  `model.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 attribute `generator` that is a
  `torch.Generator` for the randomization that must be identical on all processes (and the Trainer will
  manually set the seed of this `generator` at each epoch) or have a `set_epoch()` method that internally
  sets the seed of the RNGs used.
- **eval_dataset** (`torch.utils.data.Dataset`, *optional*) --
  The dataset to use for evaluation. If it is an `datasets.Dataset`, columns not accepted by the
  `model.forward()` method are automatically removed.
- **tokenizer** ([PreTrainedTokenizerBase](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), *optional*) --
  The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the
  maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an
  interrupted training or reuse the fine-tuned model.
- **model_init** (`Callable[[], PreTrainedModel]`, *optional*) --
  A function that instantiates the model to be used. If provided, each call to [train()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.train) will start
  from a new instance of the model as given by this function.

  The function may have zero argument, or a single one containing the optuna/Ray Tune/SigOpt trial object, to
  be able to choose different architectures according to hyper parameters (such as layer count, sizes of
  inner layers, dropout probabilities etc).
- **compute_metrics** (`Callable[[EvalPrediction], Dict]`, *optional*) --
  The function that will be used to compute metrics at evaluation. Must take a [EvalPrediction](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.EvalPrediction) and return
  a dictionary string to metric values.
- **callbacks** (List of [TrainerCallback](/docs/transformers/pr_15592/en/main_classes/callback#transformers.TrainerCallback), *optional*) --
  A list of callbacks to customize the training loop. Will add those to the list of default callbacks
  detailed in [here](callback).

  If you want to remove one of the default callbacks used, use the [Trainer.remove_callback()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.remove_callback) method.
- **optimizers** (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*) -- A tuple
  containing the optimizer and the scheduler to use. Will default to an instance of [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) on your model
  and a scheduler given by [get_linear_schedule_with_warmup()](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) controlled by `args`.
- **preprocess_logits_for_metrics** (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*) --
  A function that preprocess the logits right before caching them at each evaluation step. Must take two
  tensors, the logits and the labels, and return the logits once processed as desired. The modifications made
  by this function will be reflected in the predictions received by `compute_metrics`.

  Note that the labels (second parameter) will be `None` if the dataset does not have them.</paramsdesc><paramgroups>0</paramgroups></docstring>

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](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)
  subclass.
- **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
  original model. This is the model that should be used for the forward pass. For example, under `DeepSpeed`,
  the inner model is wrapped in `DeepSpeed` and then again in `torch.nn.DistributedDataParallel`. If the inner
  model hasn't been wrapped, then `self.model_wrapped` is the same as `self.model`.
- **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
  data parallelism, this means some of the model layers are split on different GPUs).
- **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
  to `False` if model parallel or deepspeed is used, or if the default
  `TrainingArguments.place_model_on_device` is overridden to return `False` .
- **is_in_train** -- Whether or not a model is currently running `train` (e.g. when `evaluate` is called while
  in `train`)




<div class="docstring">
<docstring><name>add\_callback</name><anchor>transformers.Trainer.add_callback</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L513</source><parameters>[{"name": "callback", "val": ""}]</parameters><paramsdesc>- **callback** (`type` or `TrainerCallback`) --
  A `TrainerCallback` class or an instance of a `TrainerCallback`. In the
  first case, will instantiate a member of that class.</paramsdesc><paramgroups>0</paramgroups></docstring>

Add a callback to the current list of `TrainerCallback`.




</div>
<div class="docstring">
<docstring><name>autocast\_smart\_context\_manager</name><anchor>transformers.Trainer.autocast_smart_context_manager</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L1940</source><parameters>[]</parameters></docstring>

A helper wrapper that creates an appropriate context manager for `autocast` while feeding it the desired
arguments, depending on the situation.


</div>
<div class="docstring">
<docstring><name>compute\_loss</name><anchor>transformers.Trainer.compute_loss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2004</source><parameters>[{"name": "model", "val": ""}, {"name": "inputs", "val": ""}, {"name": "return_outputs", "val": " = False"}]</parameters></docstring>

How the loss is computed by Trainer. By default, all models return the loss in the first element.

Subclass and override for custom behavior.


</div>
<div class="docstring">
<docstring><name>create\_optimizer</name><anchor>transformers.Trainer.create_optimizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L827</source><parameters>[]</parameters></docstring>

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.


</div>
<div class="docstring">
<docstring><name>create\_optimizer\_and\_scheduler</name><anchor>transformers.Trainer.create_optimizer_and_scheduler</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L816</source><parameters>[{"name": "num_training_steps", "val": ": int"}]</parameters></docstring>

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.


</div>
<div class="docstring">
<docstring><name>create\_scheduler</name><anchor>transformers.Trainer.create_scheduler</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L912</source><parameters>[{"name": "num_training_steps", "val": ": int"}, {"name": "optimizer", "val": ": Optimizer = None"}]</parameters><paramsdesc>- **num_training_steps** (int) -- The number of training steps to do.</paramsdesc><paramgroups>0</paramgroups></docstring>

Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or
passed as an argument.




</div>
<div class="docstring">
<docstring><name>evaluate</name><anchor>transformers.Trainer.evaluate</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2218</source><parameters>[{"name": "eval_dataset", "val": ": typing.Optional[torch.utils.data.dataset.Dataset] = None"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "metric_key_prefix", "val": ": str = 'eval'"}]</parameters><paramsdesc>- **eval_dataset** (`Dataset`, *optional*) --
  Pass a dataset if you wish to override `self.eval_dataset`. If it is an `datasets.Dataset`, columns not
  accepted by the `model.forward()` method are automatically removed. It must implement the `__len__`
  method.
- **ignore_keys** (`Lst[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)</paramsdesc><paramgroups>0</paramgroups><retdesc>A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.</retdesc></docstring>

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.






</div>
<div class="docstring">
<docstring><name>evaluation\_loop</name><anchor>transformers.Trainer.evaluation_loop</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2346</source><parameters>[{"name": "dataloader", "val": ": DataLoader"}, {"name": "description", "val": ": str"}, {"name": "prediction_loss_only", "val": ": typing.Optional[bool] = None"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "metric_key_prefix", "val": ": str = 'eval'"}]</parameters></docstring>

Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.

Works both with or without labels.


</div>
<div class="docstring">
<docstring><name>floating\_point\_ops</name><anchor>transformers.Trainer.floating_point_ops</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2667</source><parameters>[{"name": "inputs", "val": ": typing.Dict[str, typing.Union[torch.Tensor, typing.Any]]"}]</parameters><paramsdesc>- **inputs** (`Dict[str, Union[torch.Tensor, Any]]`) --
  The inputs and targets of the model.</paramsdesc><paramgroups>0</paramgroups><rettype>`int`</rettype><retdesc>The number of floating-point operations.</retdesc></docstring>

For models that inherit from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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.








</div>
<div class="docstring">
<docstring><name>get\_eval\_dataloader</name><anchor>transformers.Trainer.get_eval_dataloader</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L726</source><parameters>[{"name": "eval_dataset", "val": ": typing.Optional[torch.utils.data.dataset.Dataset] = None"}]</parameters><paramsdesc>- **eval_dataset** (`torch.utils.data.Dataset`, *optional*) --
  If provided, will override `self.eval_dataset`. If it is an `datasets.Dataset`, columns not accepted by
  the `model.forward()` method are automatically removed. It must implement `__len__`.</paramsdesc><paramgroups>0</paramgroups></docstring>

Returns the evaluation `DataLoader`.

Subclass and override this method if you want to inject some custom behavior.




</div>
<div class="docstring">
<docstring><name>get\_optimizer\_cls\_and\_kwargs</name><anchor>transformers.Trainer.get_optimizer_cls_and_kwargs</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L864</source><parameters>[{"name": "args", "val": ": TrainingArguments"}]</parameters><paramsdesc>- **args** (`transformers.training_args.TrainingArguments`) --
  The training arguments for the training session.</paramsdesc><paramgroups>0</paramgroups></docstring>

Returns the optimizer class and optimizer parameters based on the training arguments.




</div>
<div class="docstring">
<docstring><name>get\_test\_dataloader</name><anchor>transformers.Trainer.get_test_dataloader</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L773</source><parameters>[{"name": "test_dataset", "val": ": Dataset"}]</parameters><paramsdesc>- **test_dataset** (`torch.utils.data.Dataset`, *optional*) --
  The test dataset to use. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()`
  method are automatically removed. It must implement `__len__`.</paramsdesc><paramgroups>0</paramgroups></docstring>

Returns the test `DataLoader`.

Subclass and override this method if you want to inject some custom behavior.




</div>
<div class="docstring">
<docstring><name>get\_train\_dataloader</name><anchor>transformers.Trainer.get_train_dataloader</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L651</source><parameters>[]</parameters></docstring>

Returns the training `DataLoader`.

Will use no sampler if `self.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.


</div>
<div class="docstring">
<docstring><name>hyperparameter\_search</name><anchor>transformers.Trainer.hyperparameter_search</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L1801</source><parameters>[{"name": "hp_space", "val": ": typing.Union[typing.Callable[[ForwardRef('optuna.Trial')], typing.Dict[str, float]], NoneType] = None"}, {"name": "compute_objective", "val": ": typing.Union[typing.Callable[[typing.Dict[str, float]], float], NoneType] = None"}, {"name": "n_trials", "val": ": int = 20"}, {"name": "direction", "val": ": str = 'minimize'"}, {"name": "backend", "val": ": typing.Union[ForwardRef('str'), transformers.trainer_utils.HPSearchBackend, NoneType] = None"}, {"name": "hp_name", "val": ": typing.Union[typing.Callable[[ForwardRef('optuna.Trial')], str], NoneType] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **hp_space** (`Callable[["optuna.Trial"], Dict[str, float]]`, *optional*) --
  A function that defines the hyperparameter search space. Will default to
  `default_hp_space_optuna()`or `default_hp_space_ray()`or
  `default_hp_space_sigopt()`depending on your backend.
- **compute_objective** (`Callable[[Dict[str, float]], float]`, *optional*) --
  A function computing the objective to minimize or maximize from the metrics returned by the `evaluate`
  method. Will default to `default_compute_objective()`
- **n_trials** (`int`, *optional*, defaults to 100) --
  The number of trial runs to test.
- **direction(`str`,** *optional*, defaults to `"minimize"`) --
  Whether to optimize greater or lower objects. Can be `"minimize"` or `"maximize"`, you should pick
  `"minimize"` when optimizing the validation loss, `"maximize"` when optimizing one or several metrics.
- **backend(`str`** or `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.
  kwargs --
  Additional keyword arguments passed along to `optuna.create_study` or `ray.tune.run`. For more
  information see:

  - the documentation of
    [optuna.create_study](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html)
  - the documentation of [tune.run](https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run)
  - the documentation of [sigopt](https://app.sigopt.com/docs/endpoints/experiments/create)</paramsdesc><paramgroups>0</paramgroups><rettype>`trainer_utils.BestRun`/rettype><retdesc>All the information about the best run.</retdesc></docstring>

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.

<Tip warning=&amp;lcub;true}>

To use this method, you need to have provided a `model_init` when initializing your [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer): we need to
reinitialize the model at each new run. This is incompatible with the `optimizers` argument, so you need to
subclass [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) and override the method [create_optimizer_and_scheduler()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.create_optimizer_and_scheduler) for custom
optimizer/scheduler.

</Tip>








</div>
<div class="docstring">
<docstring><name>init\_git\_repo</name><anchor>transformers.Trainer.init_git_repo</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2685</source><parameters>[{"name": "at_init", "val": ": bool = False"}]</parameters><paramsdesc>- **at_init** (`bool`, *optional*, defaults to `False`) --
  Whether this function is called before any training or not. If `self.args.overwrite_output_dir` is
  `True` and `at_init` is `True`, the path to the repo (which is `self.args.output_dir`) might be wiped
  out.</paramsdesc><paramgroups>0</paramgroups></docstring>

Initializes a git repo in `self.args.hub_model_id`.




</div>
<div class="docstring">
<docstring><name>is\_local\_process\_zero</name><anchor>transformers.Trainer.is_local_process_zero</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2028</source><parameters>[]</parameters></docstring>

Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several
machines) main process.


</div>
<div class="docstring">
<docstring><name>is\_world\_process\_zero</name><anchor>transformers.Trainer.is_world_process_zero</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2035</source><parameters>[]</parameters></docstring>

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).


</div>
<div class="docstring">
<docstring><name>log</name><anchor>transformers.Trainer.log</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L1894</source><parameters>[{"name": "logs", "val": ": typing.Dict[str, float]"}]</parameters><paramsdesc>- **logs** (`Dict[str, float]`) --
  The values to log.</paramsdesc><paramgroups>0</paramgroups></docstring>

Log `logs` on the various objects watching training.

Subclass and override this method to inject custom behavior.




</div>
<div class="docstring">
<docstring><name>log\_metrics</name><anchor>transformers.trainer_pt_utils.log_metrics</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer_pt_utils.py#L855</source><parameters>[{"name": "split", "val": ""}, {"name": "metrics", "val": ""}]</parameters><paramsdesc>- **split** (`str`) --
  Mode/split name: one of `train`, `eval`, `test`
- **metrics** (`Dict[str, float]`) --
  The metrics returned from train/evaluate/predictmetrics: metrics dict</paramsdesc><paramgroups>0</paramgroups></docstring>

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 with `init_`
  will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the
  `__init__` will be reported along with the `eval_` metrics.
- the third segment, is either `cpu` or `gpu`, tells you whether it's the general RAM or the gpu0 memory
  metric.
- `*_alloc_delta` - is the difference in the used/allocated memory counter between the end and the start of the
  stage - it can be negative if a function released more memory than it allocated.
- `*_peaked_delta` - is any extra memory that was consumed and then freed - relative to the current allocated
  memory counter - it is never negative. When you look at the metrics of any stage you add up `alloc_delta` +
  `peaked_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](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.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](https://github.com/pytorch/pytorch/issues/16266) 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](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) calls
`torch.cuda.reset_peak_memory_stats`, the gpu peak memory stats could be invalid. And the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.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.


</div>
<div class="docstring">
<docstring><name>metrics\_format</name><anchor>transformers.trainer_pt_utils.metrics_format</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer_pt_utils.py#L829</source><parameters>[{"name": "metrics", "val": ": typing.Dict[str, float]"}]</parameters><paramsdesc>- **metrics** (`Dict[str, float]`) --
  The metrics returned from train/evaluate/predict</paramsdesc><paramgroups>0</paramgroups><rettype>metrics (`Dict[str, float]`)</rettype><retdesc>The reformatted metrics</retdesc></docstring>

Reformat Trainer metrics values to a human-readable format








</div>
<div class="docstring">
<docstring><name>num\_examples</name><anchor>transformers.Trainer.num_examples</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L929</source><parameters>[{"name": "dataloader", "val": ": DataLoader"}]</parameters></docstring>

Helper to get number of samples in a `DataLoader` by accessing its dataset.

Will raise an exception if the underlying dataset does not implement method `__len__`


</div>
<div class="docstring">
<docstring><name>pop\_callback</name><anchor>transformers.Trainer.pop_callback</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L524</source><parameters>[{"name": "callback", "val": ""}]</parameters><paramsdesc>- **callback** (`type` or `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.</paramsdesc><paramgroups>0</paramgroups><rettype>`TrainerCallback`</rettype><retdesc>The callback removed, if found.</retdesc></docstring>

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).








</div>
<div class="docstring">
<docstring><name>predict</name><anchor>transformers.Trainer.predict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2287</source><parameters>[{"name": "test_dataset", "val": ": Dataset"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "metric_key_prefix", "val": ": str = 'test'"}]</parameters><paramsdesc>- **test_dataset** (`Dataset`) --
  Dataset to run the predictions on. If it is an `datasets.Dataset`, columns not accepted by the
  `model.forward()` method are automatically removed. Has to implement the method `__len__`
- **ignore_keys** (`Lst[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)</paramsdesc><paramgroups>0</paramgroups></docstring>

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()`.



<Tip>

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.

</Tip>

Returns: *NamedTuple* A namedtuple with the following keys:

- predictions (`np.ndarray`): The predictions on `test_dataset`.
- label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).
- metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained
  labels).


</div>
<div class="docstring">
<docstring><name>prediction\_loop</name><anchor>transformers.Trainer.prediction_loop</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2862</source><parameters>[{"name": "dataloader", "val": ": DataLoader"}, {"name": "description", "val": ": str"}, {"name": "prediction_loss_only", "val": ": typing.Optional[bool] = None"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "metric_key_prefix", "val": ": str = 'eval'"}]</parameters></docstring>

Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.

Works both with or without labels.


</div>
<div class="docstring">
<docstring><name>prediction\_step</name><anchor>transformers.Trainer.prediction_step</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2570</source><parameters>[{"name": "model", "val": ": Module"}, {"name": "inputs", "val": ": typing.Dict[str, typing.Union[torch.Tensor, typing.Any]]"}, {"name": "prediction_loss_only", "val": ": bool"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}]</parameters><paramsdesc>- **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** (`Lst[str]`, *optional*) --
  A list of keys in the output of your model (if it is a dictionary) that should be ignored when
  gathering predictions.</paramsdesc><paramgroups>0</paramgroups><rettype>Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]</rettype><retdesc>A tuple with the loss,
logits and labels (each being optional).</retdesc></docstring>

Perform an evaluation step on `model` using `inputs`.

Subclass and override to inject custom behavior.








</div>
<div class="docstring">
<docstring><name>push\_to\_hub</name><anchor>transformers.Trainer.push_to_hub</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2808</source><parameters>[{"name": "commit_message", "val": ": typing.Optional[str] = 'End of training'"}, {"name": "blocking", "val": ": bool = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **commit_message** (`str`, *optional*, defaults to `"End of training"`) --
  Message to commit while pushing.
- **blocking** (`bool`, *optional*, defaults to `True`) --
  Whether the function should return only when the `git push` has finished.
  kwargs --
  Additional keyword arguments passed along to `create_model_card()`</paramsdesc><paramgroups>0</paramgroups><retdesc>The url of the commit of your model in the given repository if `blocking=False`, a tuple with the url of
the commit and an object to track the progress of the commit if `blocking=True`</retdesc></docstring>

Upload *self.model* and *self.tokenizer* to the 🤗 model hub on the repo *self.args.hub_model_id*.






</div>
<div class="docstring">
<docstring><name>remove\_callback</name><anchor>transformers.Trainer.remove_callback</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L540</source><parameters>[{"name": "callback", "val": ""}]</parameters><paramsdesc>- **callback** (`type` or `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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Remove a callback from the current list of `TrainerCallback`.




</div>
<div class="docstring">
<docstring><name>save\_metrics</name><anchor>transformers.trainer_pt_utils.save_metrics</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer_pt_utils.py#L945</source><parameters>[{"name": "split", "val": ""}, {"name": "metrics", "val": ""}, {"name": "combined", "val": " = True"}]</parameters><paramsdesc>- **split** (`str`) --
  Mode/split name: one of `train`, `eval`, `test`, `all`
- **metrics** (`Dict[str, float]`) --
  The metrics returned from train/evaluate/predict
- **combined** (`bool`, *optional*, defaults to `True`) --
  Creates combined metrics by updating `all_results.json` with metrics of this call</paramsdesc><paramgroups>0</paramgroups></docstring>

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.



</div>
<div class="docstring">
<docstring><name>save\_model</name><anchor>transformers.Trainer.save_model</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L2047</source><parameters>[{"name": "output_dir", "val": ": typing.Optional[str] = None"}, {"name": "_internal_call", "val": ": bool = False"}]</parameters></docstring>

Will save the model, so you can reload it using `from_pretrained()`.

Will only save from the main process.


</div>
<div class="docstring">
<docstring><name>save\_state</name><anchor>transformers.trainer_pt_utils.save_state</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer_pt_utils.py#L983</source><parameters>[]</parameters></docstring>

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.


</div>
<div class="docstring">
<docstring><name>train</name><anchor>transformers.Trainer.train</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L1093</source><parameters>[{"name": "resume_from_checkpoint", "val": ": typing.Union[str, bool, NoneType] = None"}, {"name": "trial", "val": ": typing.Union[ForwardRef('optuna.Trial'), typing.Dict[str, typing.Any]] = None"}, {"name": "ignore_keys_for_eval", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **resume_from_checkpoint** (`str` or `bool`, *optional*) --
  If a `str`, local path to a saved checkpoint as saved by a previous instance of [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer). If a
  `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance
  of [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer). If present, training will resume from the model/optimizer/scheduler states loaded here.
- **trial** (`optuna.Trial` or `Dict[str, Any]`, *optional*) --
  The trial run or the hyperparameter dictionary for hyperparameter search.
- **ignore_keys_for_eval** (`List[str]`, *optional*) --
  A list of keys in the output of your model (if it is a dictionary) that should be ignored when
  gathering predictions for evaluation during the training.
  kwargs --
  Additional keyword arguments used to hide deprecated arguments</paramsdesc><paramgroups>0</paramgroups></docstring>

Main training entry point.




</div>
<div class="docstring">
<docstring><name>training\_step</name><anchor>transformers.Trainer.training_step</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer.py#L1955</source><parameters>[{"name": "model", "val": ": Module"}, {"name": "inputs", "val": ": typing.Dict[str, typing.Union[torch.Tensor, typing.Any]]"}]</parameters><paramsdesc>- **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.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.Tensor`</rettype><retdesc>The tensor with training loss on this batch.</retdesc></docstring>

Perform a training step on a batch of inputs.

Subclass and override to inject custom behavior.








</div></div>

<h2 id="transformers.Seq2SeqTrainer">Seq2SeqTrainer</h2>

<div class="docstring">

<div class="docstring">
<docstring><name>evaluate</name><anchor>transformers.Seq2SeqTrainer.evaluate</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer_seq2seq.py#L31</source><parameters>[{"name": "eval_dataset", "val": ": typing.Optional[torch.utils.data.dataset.Dataset] = None"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "metric_key_prefix", "val": ": str = 'eval'"}, {"name": "max_length", "val": ": typing.Optional[int] = None"}, {"name": "num_beams", "val": ": typing.Optional[int] = None"}]</parameters><paramsdesc>- **eval_dataset** (`Dataset`, *optional*) --
  Pass a dataset if you wish to override `self.eval_dataset`. If it is an `datasets.Dataset`, columns not
  accepted by the `model.forward()` method are automatically removed. It must implement the `__len__`
  method.
- **ignore_keys** (`List[str]`, *optional*) --
  A list of keys in the output of your model (if it is a dictionary) that should be ignored when
  gathering predictions.
- **metric_key_prefix** (`str`, *optional*, defaults to `"eval"`) --
  An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
  "eval_bleu" if the prefix is `"eval"` (default)
- **max_length** (`int`, *optional*) --
  The maximum target length to use when predicting with the generate method.
- **num_beams** (`int`, *optional*) --
  Number of beams for beam search that will be used when predicting with the generate method. 1 means no
  beam search.</paramsdesc><paramgroups>0</paramgroups><retdesc>A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.</retdesc></docstring>

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.






</div>
<div class="docstring">
<docstring><name>predict</name><anchor>transformers.Seq2SeqTrainer.predict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/trainer_seq2seq.py#L72</source><parameters>[{"name": "test_dataset", "val": ": Dataset"}, {"name": "ignore_keys", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "metric_key_prefix", "val": ": str = 'test'"}, {"name": "max_length", "val": ": typing.Optional[int] = None"}, {"name": "num_beams", "val": ": typing.Optional[int] = None"}]</parameters><paramsdesc>- **test_dataset** (`Dataset`) --
  Dataset to run the predictions on. If it is an `datasets.Dataset`, columns not accepted by the
  `model.forward()` method are automatically removed. Has to implement the method `__len__`
- **ignore_keys** (`List[str]`, *optional*) --
  A list of keys in the output of your model (if it is a dictionary) that should be ignored when
  gathering predictions.
- **metric_key_prefix** (`str`, *optional*, defaults to `"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.</paramsdesc><paramgroups>0</paramgroups></docstring>

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()`.



<Tip>

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.

</Tip>

Returns: *NamedTuple* A namedtuple with the following keys:

- predictions (`np.ndarray`): The predictions on `test_dataset`.
- label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).
- metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained
  labels).


</div></div>

<h2 id="transformers.TrainingArguments">TrainingArguments</h2>

<div class="docstring">

<docstring><name>class transformers.TrainingArguments</name><anchor>transformers.TrainingArguments</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L86</source><parameters>[{"name": "output_dir", "val": ": str"}, {"name": "overwrite_output_dir", "val": ": bool = False"}, {"name": "do_train", "val": ": bool = False"}, {"name": "do_eval", "val": ": bool = False"}, {"name": "do_predict", "val": ": bool = False"}, {"name": "evaluation_strategy", "val": ": IntervalStrategy = 'no'"}, {"name": "prediction_loss_only", "val": ": bool = False"}, {"name": "per_device_train_batch_size", "val": ": int = 8"}, {"name": "per_device_eval_batch_size", "val": ": int = 8"}, {"name": "per_gpu_train_batch_size", "val": ": typing.Optional[int] = None"}, {"name": "per_gpu_eval_batch_size", "val": ": typing.Optional[int] = None"}, {"name": "gradient_accumulation_steps", "val": ": int = 1"}, {"name": "eval_accumulation_steps", "val": ": typing.Optional[int] = None"}, {"name": "learning_rate", "val": ": float = 5e-05"}, {"name": "weight_decay", "val": ": float = 0.0"}, {"name": "adam_beta1", "val": ": float = 0.9"}, {"name": "adam_beta2", "val": ": float = 0.999"}, {"name": "adam_epsilon", "val": ": float = 1e-08"}, {"name": "max_grad_norm", "val": ": float = 1.0"}, {"name": "num_train_epochs", "val": ": float = 3.0"}, {"name": "max_steps", "val": ": int = -1"}, {"name": "lr_scheduler_type", "val": ": SchedulerType = 'linear'"}, {"name": "warmup_ratio", "val": ": float = 0.0"}, {"name": "warmup_steps", "val": ": int = 0"}, {"name": "log_level", "val": ": typing.Optional[str] = 'passive'"}, {"name": "log_level_replica", "val": ": typing.Optional[str] = 'passive'"}, {"name": "log_on_each_node", "val": ": bool = True"}, {"name": "logging_dir", "val": ": typing.Optional[str] = None"}, {"name": "logging_strategy", "val": ": IntervalStrategy = 'steps'"}, {"name": "logging_first_step", "val": ": bool = False"}, {"name": "logging_steps", "val": ": int = 500"}, {"name": "logging_nan_inf_filter", "val": ": str = True"}, {"name": "save_strategy", "val": ": IntervalStrategy = 'steps'"}, {"name": "save_steps", "val": ": int = 500"}, {"name": "save_total_limit", "val": ": typing.Optional[int] = None"}, {"name": "save_on_each_node", "val": ": bool = False"}, {"name": "no_cuda", "val": ": bool = False"}, {"name": "seed", "val": ": int = 42"}, {"name": "bf16", "val": ": bool = False"}, {"name": "fp16", "val": ": bool = False"}, {"name": "fp16_opt_level", "val": ": str = 'O1'"}, {"name": "half_precision_backend", "val": ": str = 'auto'"}, {"name": "bf16_full_eval", "val": ": bool = False"}, {"name": "fp16_full_eval", "val": ": bool = False"}, {"name": "tf32", "val": ": bool = None"}, {"name": "local_rank", "val": ": int = -1"}, {"name": "xpu_backend", "val": ": str = None"}, {"name": "tpu_num_cores", "val": ": typing.Optional[int] = None"}, {"name": "tpu_metrics_debug", "val": ": bool = False"}, {"name": "debug", "val": ": str = ''"}, {"name": "dataloader_drop_last", "val": ": bool = False"}, {"name": "eval_steps", "val": ": int = None"}, {"name": "dataloader_num_workers", "val": ": int = 0"}, {"name": "past_index", "val": ": int = -1"}, {"name": "run_name", "val": ": typing.Optional[str] = None"}, {"name": "disable_tqdm", "val": ": typing.Optional[bool] = None"}, {"name": "remove_unused_columns", "val": ": typing.Optional[bool] = True"}, {"name": "label_names", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "load_best_model_at_end", "val": ": typing.Optional[bool] = False"}, {"name": "metric_for_best_model", "val": ": typing.Optional[str] = None"}, {"name": "greater_is_better", "val": ": typing.Optional[bool] = None"}, {"name": "ignore_data_skip", "val": ": bool = False"}, {"name": "sharded_ddp", "val": ": str = ''"}, {"name": "deepspeed", "val": ": typing.Optional[str] = None"}, {"name": "label_smoothing_factor", "val": ": float = 0.0"}, {"name": "optim", "val": ": OptimizerNames = 'adamw_hf'"}, {"name": "adafactor", "val": ": bool = False"}, {"name": "group_by_length", "val": ": bool = False"}, {"name": "length_column_name", "val": ": typing.Optional[str] = 'length'"}, {"name": "report_to", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "ddp_find_unused_parameters", "val": ": typing.Optional[bool] = None"}, {"name": "ddp_bucket_cap_mb", "val": ": typing.Optional[int] = None"}, {"name": "dataloader_pin_memory", "val": ": bool = True"}, {"name": "skip_memory_metrics", "val": ": bool = True"}, {"name": "use_legacy_prediction_loop", "val": ": bool = False"}, {"name": "push_to_hub", "val": ": bool = False"}, {"name": "resume_from_checkpoint", "val": ": typing.Optional[str] = None"}, {"name": "hub_model_id", "val": ": str = None"}, {"name": "hub_strategy", "val": ": HubStrategy = 'every_save'"}, {"name": "hub_token", "val": ": str = None"}, {"name": "gradient_checkpointing", "val": ": bool = False"}, {"name": "fp16_backend", "val": ": str = 'auto'"}, {"name": "push_to_hub_model_id", "val": ": str = None"}, {"name": "push_to_hub_organization", "val": ": str = None"}, {"name": "push_to_hub_token", "val": ": str = None"}, {"name": "mp_parameters", "val": ": str = ''"}]</parameters><paramsdesc>- **output_dir** (`str`) --
  The output directory where the model predictions and checkpoints will be written.
- **overwrite_output_dir** (`bool`, *optional*, defaults to `False`) --
  If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir`
  points to a checkpoint directory.
- **do_train** (`bool`, *optional*, defaults to `False`) --
  Whether to run training or not. This argument is not directly used by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's intended to be used
  by your training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **do_eval** (`bool`, *optional*) --
  Whether to run evaluation on the validation set or not. Will be set to `True` if `evaluation_strategy` is
  different from `"no"`. This argument is not directly used by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's intended to be used by your
  training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **do_predict** (`bool`, *optional*, defaults to `False`) --
  Whether to run predictions on the test set or not. This argument is not directly used by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's
  intended to be used by your training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **evaluation_strategy** (`str` or [IntervalStrategy](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `"no"`) --
  The evaluation strategy to adopt during training. Possible values are:

  - `"no"`: No evaluation is done during training.
  - `"steps"`: Evaluation is done (and logged) every `eval_steps`.
  - `"epoch"`: Evaluation is done at the end of each epoch.

- **prediction_loss_only** (`bool`, *optional*, defaults to `False`) --
  When performing evaluation and generating predictions, only returns the loss.
- **per_device_train_batch_size** (`int`, *optional*, defaults to 8) --
  The batch size per GPU/TPU core/CPU for training.
- **per_device_eval_batch_size** (`int`, *optional*, defaults to 8) --
  The batch size per GPU/TPU 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.

  <Tip warning=&amp;lcub;true}>

  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.

  </Tip>

- **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/TPU before being moved to the CPU (faster but
  requires more memory).
- **learning_rate** (`float`, *optional*, defaults to 5e-5) --
  The initial learning rate for [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **weight_decay** (`float`, *optional*, defaults to 0) --
  The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW)
  optimizer.
- **adam_beta1** (`float`, *optional*, defaults to 0.9) --
  The beta1 hyperparameter for the [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **adam_beta2** (`float`, *optional*, defaults to 0.999) --
  The beta2 hyperparameter for the [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **adam_epsilon** (`float`, *optional*, defaults to 1e-8) --
  The epsilon hyperparameter for the [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **max_grad_norm** (`float`, *optional*, defaults to 1.0) --
  Maximum gradient norm (for gradient clipping).
- **num_train_epochs(`float`,** *optional*, defaults to 3.0) --
  Total number of training epochs to perform (if not an integer, will perform the decimal part percents of
  the last epoch before stopping training).
- **max_steps** (`int`, *optional*, defaults to -1) --
  If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  In case of using a finite iterable dataset the training may stop before reaching the set number of steps
  when all data is exhausted
- **lr_scheduler_type** (`str` or [SchedulerType](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.SchedulerType), *optional*, defaults to `"linear"`) --
  The scheduler type to use. See the documentation of [SchedulerType](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.SchedulerType) for all possible values.
- **warmup_ratio** (`float`, *optional*, defaults to 0.0) --
  Ratio of total training steps used for a linear warmup from 0 to `learning_rate`.
- **warmup_steps** (`int`, *optional*, defaults to 0) --
  Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`.
- **log_level** (`str`, *optional*, defaults to `passive`) --
  Logger log level to use on the main process. Possible choices are the log levels as strings: 'debug',
  'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and lets the
  application set the level.
- **log_level_replica** (`str`, *optional*, defaults to `passive`) --
  Logger log level to use on replicas. Same choices as `log_level`"
- **log_on_each_node** (`bool`, *optional*, defaults to `True`) --
  In multinode distributed training, whether to log using `log_level` once per node, or only on the main
  node.
- **logging_dir** (`str`, *optional*) --
  [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to
  *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***.
- **logging_strategy** (`str` or [IntervalStrategy](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `"steps"`) --
  The logging strategy to adopt during training. Possible values are:

  - `"no"`: No logging is done during training.
  - `"epoch"`: Logging is done at the end of each epoch.
  - `"steps"`: Logging is done every `logging_steps`.

- **logging_first_step** (`bool`, *optional*, defaults to `False`) --
  Whether to log and evaluate the first `global_step` or not.
- **logging_steps** (`int`, *optional*, defaults to 500) --
  Number of update steps between two logs if `logging_strategy="steps"`.
- **logging_nan_inf_filter** (`bool`, *optional*, defaults to `True`) --
  Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan`
  or `inf` is filtered and the average loss of the current logging window is taken instead.

  <Tip>

  `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.

  </Tip>

- **save_strategy** (`str` or [IntervalStrategy](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `"steps"`) --
  The checkpoint save strategy to adopt during training. Possible values are:

  - `"no"`: No save is done during training.
  - `"epoch"`: Save is done at the end of each epoch.
  - `"steps"`: Save is done every `save_steps`.
- **save_steps** (`int`, *optional*, defaults to 500) --
  Number of updates steps before two checkpoint saves if `save_strategy="steps"`.
- **save_total_limit** (`int`, *optional*) --
  If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
  `output_dir`.
- **save_on_each_node** (`bool`, *optional*, defaults to `False`) --
  When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
  the main one.

  This should not be activated when the different nodes use the same storage as the files will be saved with
  the same names for each node.
- **no_cuda** (`bool`, *optional*, defaults to `False`) --
  Whether to not use CUDA even when it is available or not.
- **seed** (`int`, *optional*, defaults to 42) --
  Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the
  `model_init` function to instantiate the model if it has some randomly initialized parameters.
- **bf16** (`bool`, *optional*, defaults to `False`) --
  Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher
  NVIDIA architecture. This is an experimental API and it may change.
- **fp16** (`bool`, *optional*, defaults to `False`) --
  Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
- **fp16_opt_level** (`str`, *optional*, defaults to 'O1') --
  For `fp16` training, Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details on
  the [Apex documentation](https://nvidia.github.io/apex/amp).
- **fp16_backend** (`str`, *optional*, defaults to `"auto"`) --
  This argument is deprecated. Use `half_precision_backend` instead.
- **half_precision_backend** (`str`, *optional*, defaults to `"auto"`) --
  The backend to use for mixed precision training. Must be one of `"auto"`, `"amp"` or `"apex"`. `"auto"`
  will use AMP or APEX depending on the PyTorch version detected, while the other choices will force the
  requested backend.
- **bf16_full_eval** (`bool`, *optional*, defaults to `False`) --
  Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm
  metric values. This is an experimental API and it may change.
- **fp16_full_eval** (`bool`, *optional*, defaults to `False`) --
  Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm
  metric values.
- **tf32** (`bool`, *optional*) --
  Whether to enable tf32 mode, available in Ampere and newer GPU architectures. This is an experimental API
  and it may change.
- **local_rank** (`int`, *optional*, defaults to -1) --
  Rank of the process during distributed training.
- **xpu_backend** (`str`, *optional*) --
  The backend to use for xpu distributed training. Must be one of `"mpi"` or `"ccl"`.
- **tpu_num_cores** (`int`, *optional*) --
  When training on TPU, the number of TPU cores (automatically passed by launcher script).
- **dataloader_drop_last** (`bool`, *optional*, defaults to `False`) --
  Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
  or not.
- **eval_steps** (`int`, *optional*) --
  Number of update steps between two evaluations if `evaluation_strategy="steps"`. Will default to the same
  value as `logging_steps` if not set.
- **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](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of
  the past hidden states for their predictions. If this argument is set to a positive int, the `Trainer` 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 argument `mems`.
- **run_name** (`str`, *optional*) --
  A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and
  [mlflow](https://www.mlflow.org/) logging.
- **disable_tqdm** (`bool`, *optional*) --
  Whether or not to disable the tqdm progress bars and table of metrics produced by
  `NotebookTrainingTracker` in Jupyter Notebooks. Will default to `True` if the logging level is
  set to warn or lower (default), `False` otherwise.
- **remove_unused_columns** (`bool`, *optional*, defaults to `True`) --
  If using `datasets.Dataset` datasets, whether or not to automatically remove the columns unused by the
  model forward method.

  (Note that this behavior is not implemented for `TFTrainer`yet.)
- **label_names** (`List[str]`, *optional*) --
  The list of keys in your dictionary of inputs that correspond to the labels.

  Will eventually default to `["labels"]` except if the model used is one of the `XxxForQuestionAnswering` in
  which case it will default to `["start_positions", "end_positions"]`.
- **load_best_model_at_end** (`bool`, *optional*, defaults to `False`) --
  Whether or not to load the best model found during training at the end of training.

  <Tip>

  When set to `True`, the parameters `save_strategy` needs to be the same as `eval_strategy`, and in the case
  it is "steps", `save_steps` must be a round multiple of `eval_steps`.

  </Tip>

- **metric_for_best_model** (`str`, *optional*) --
  Use in conjunction with `load_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 and `load_best_model_at_end=True` (to use the evaluation loss).

  If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if
  your metric is better when lower.
- **greater_is_better** (`bool`, *optional*) --
  Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models
  should have a greater metric or not. Will default to:

  - `True` if `metric_for_best_model` is set to a value that isn't `"loss"` or `"eval_loss"`.
  - `False` if `metric_for_best_model` is not set, or set to `"loss"` or `"eval_loss"`.
- **ignore_data_skip** (`bool`, *optional*, defaults to `False`) --
  When resuming training, whether or not to skip the epochs and batches to get the data loading at the same
  stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step
  can take a long time) but will not yield the same results as the interrupted training would have.
- **sharded_ddp** (`bool`, `str` or list of `ShardedDDPOption` *optional*, defaults to `False`) --
  Use Sharded DDP training from [FairScale](https://github.com/facebookresearch/fairscale) (in distributed
  training only). This is an experimental feature.

  A list of options along the following:

  - `"simple"`: to use first instance of sharded DDP released by fairscale (`ShardedDDP`) similar to ZeRO-2.
  - `"zero_dp_2"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in
    Zero-2 mode (with `reshard_after_forward=False`).
  - `"zero_dp_3"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in
    Zero-3 mode (with `reshard_after_forward=True`).
  - `"offload"`: to add ZeRO-offload (only compatible with `"zero_dp_2"` and `"zero_dp_3"`).

  If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty
  list for `False` and `["simple"]` for `True`.
- **deepspeed** (`str` or `dict`, *optional*) --
  Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may
  evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,
  `ds_config.json`) or an already loaded json file as a `dict`"
- **label_smoothing_factor** (`float`, *optional*, defaults to 0.0) --
  The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded
  labels are changed from 0s and 1s to `label_smoothing_factor/num_labels` and `1 - label_smoothing_factor +
  label_smoothing_factor/num_labels` respectively.
- **debug** (`str` or list of `DebugOption` *optional*, defaults to `""`) --
  Enable one or more debug features. This is an experimental feature.

  Possible options are:

  - `"underflow_overflow"`: detects overflow in model's input/outputs and reports the last frames that led to
    the event
  - `"tpu_metrics_debug"`: print debug metrics on TPU

  The options should be separated by whitespaces.
- **optim** (`str` or `training_args.OptimizerNames` *optional*, defaults to `"adamw_hf"`) --
  The optimizer to use: adamw_hf, adamw_torch, adamw_apex_fused, or adafactor.
- **adafactor** (`bool`, *optional*, defaults to `False`) --
  This argument is deprecated. Use `--optim adafactor` instead.
- **group_by_length** (`bool`, *optional*, defaults to `False`) --
  Whether or not to group together samples of roughly the same length in the training dataset (to minimize
  padding applied and be more efficient). Only useful if applying dynamic padding.
- **length_column_name** (`str`, *optional*, defaults to `"length"`) --
  Column name for precomputed lengths. If the column exists, grouping by length will use these values rather
  than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an
  instance of `Dataset`.
- **report_to** (`str` or `List[str]`, *optional*, defaults to `"all"`) --
  The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
  `"comet_ml"`, `"mlflow"`, `"tensorboard"` and `"wandb"`. Use `"all"` to report to all integrations
  installed, `"none"` for no integrations.
- **ddp_find_unused_parameters** (`bool`, *optional*) --
  When using distributed training, the value of the flag `find_unused_parameters` passed to
  `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
- **ddp_bucket_cap_mb** (`int`, *optional*) --
  When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.
- **dataloader_pin_memory** (`bool`, *optional*, defaults to `True`) --
  Whether you want to pin memory in data loaders or not. Will default to `True`.
- **skip_memory_metrics** (`bool`, *optional*, defaults to `True`) --
  Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows
  down the training and evaluation speed.
- **push_to_hub** (`bool`, *optional*, defaults to `False`) --
  Whether or not to push the model to the Hub every time the model is saved. If this is activated,
  `output_dir` will begin a git directory synced with the the repo (determined by `hub_model_id`) and the
  content will be pushed each time a save is triggered (depending on your `save_strategy`). Calling
  [save_model()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.save_model) will also trigger a push.

  <Tip warning=&amp;lcub;true}>

  If `output_dir` exists, it needs to be a local clone of the repository to which the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) will be
  pushed.

  </Tip>

- **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](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's intended to be used by your training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **hub_model_id** (`str`, *optional*) --
  The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
  which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
  for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
  `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the
  name of `output_dir`.

  Will default to to the name of `output_dir`.
- **hub_strategy** (`str` or `HubStrategy` *optional*, defaults to `"every_save"`) --
  Defines the scope of what is pushed to the Hub and when. Possible values are:

  - `"end"`: push the model, its configuration, the tokenizer (if passed along to the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer)) and a
    draft of a model card when the [save_model()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.save_model) method is called.
  - `"every_save"`: push the model, its configuration, the tokenizer (if passed along to the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer)) and
    a draft of a model card each time there is a model save. The pushes are asynchronous to not block
    training, and in case the save are very frequent, a new push is only attempted if the previous one is
    finished. A last push is made with the final model at the end of training.
  - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
    last-checkpoint, allowing you to resume training easily with
    `trainer.train(resume_from_checkpoint="last-checkpoint")`.
  - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the output
    folder (so you will get one checkpoint folder per folder in your final repository)

- **hub_token** (`str`, *optional*) --
  The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
  `huggingface-cli login`.
- **gradient_checkpointing** (`bool`, *optional*, defaults to `False`) --
  If True, use gradient checkpointing to save memory at the expense of slower backward pass.</paramsdesc><paramgroups>0</paramgroups></docstring>

TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop
itself**.

Using [HfArgumentParser](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
command line.





<div class="docstring">
<docstring><name>get\_process\_log\_level</name><anchor>transformers.TrainingArguments.get_process_log_level</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L1194</source><parameters>[]</parameters></docstring>

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 `logging.INFO` 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`.


</div>
<div class="docstring">
<docstring><name>get\_warmup\_steps</name><anchor>transformers.TrainingArguments.get_warmup_steps</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L1278</source><parameters>[{"name": "num_training_steps", "val": ": int"}]</parameters></docstring>

Get number of steps used for a linear warmup.


</div>
<div class="docstring">
<docstring><name>main\_process\_first</name><anchor>transformers.TrainingArguments.main_process_first</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L1225</source><parameters>[{"name": "local", "val": " = True"}, {"name": "desc", "val": " = 'work'"}]</parameters><paramsdesc>- **local** (`bool`, *optional*, defaults to `True`) --
  if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node
  rank 0 In multi-node environment with a shared filesystem you most likely will want to use
  `local=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</paramsdesc><paramgroups>0</paramgroups></docstring>

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.




</div>
<div class="docstring">
<docstring><name>to\_dict</name><anchor>transformers.TrainingArguments.to_dict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L1287</source><parameters>[]</parameters></docstring>

Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
the token values by removing their value.


</div>
<div class="docstring">
<docstring><name>to\_json\_string</name><anchor>transformers.TrainingArguments.to_json_string</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L1302</source><parameters>[]</parameters></docstring>

Serializes this instance to a JSON string.


</div>
<div class="docstring">
<docstring><name>to\_sanitized\_dict</name><anchor>transformers.TrainingArguments.to_sanitized_dict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args.py#L1308</source><parameters>[]</parameters></docstring>

Sanitized serialization to use with TensorBoard’s hparams


</div></div>

<h2 id="transformers.Seq2SeqTrainingArguments">Seq2SeqTrainingArguments</h2>

<div class="docstring">

<docstring><name>class transformers.Seq2SeqTrainingArguments</name><anchor>transformers.Seq2SeqTrainingArguments</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/training_args_seq2seq.py#L28</source><parameters>[{"name": "output_dir", "val": ": str"}, {"name": "overwrite_output_dir", "val": ": bool = False"}, {"name": "do_train", "val": ": bool = False"}, {"name": "do_eval", "val": ": bool = False"}, {"name": "do_predict", "val": ": bool = False"}, {"name": "evaluation_strategy", "val": ": IntervalStrategy = 'no'"}, {"name": "prediction_loss_only", "val": ": bool = False"}, {"name": "per_device_train_batch_size", "val": ": int = 8"}, {"name": "per_device_eval_batch_size", "val": ": int = 8"}, {"name": "per_gpu_train_batch_size", "val": ": typing.Optional[int] = None"}, {"name": "per_gpu_eval_batch_size", "val": ": typing.Optional[int] = None"}, {"name": "gradient_accumulation_steps", "val": ": int = 1"}, {"name": "eval_accumulation_steps", "val": ": typing.Optional[int] = None"}, {"name": "learning_rate", "val": ": float = 5e-05"}, {"name": "weight_decay", "val": ": float = 0.0"}, {"name": "adam_beta1", "val": ": float = 0.9"}, {"name": "adam_beta2", "val": ": float = 0.999"}, {"name": "adam_epsilon", "val": ": float = 1e-08"}, {"name": "max_grad_norm", "val": ": float = 1.0"}, {"name": "num_train_epochs", "val": ": float = 3.0"}, {"name": "max_steps", "val": ": int = -1"}, {"name": "lr_scheduler_type", "val": ": SchedulerType = 'linear'"}, {"name": "warmup_ratio", "val": ": float = 0.0"}, {"name": "warmup_steps", "val": ": int = 0"}, {"name": "log_level", "val": ": typing.Optional[str] = 'passive'"}, {"name": "log_level_replica", "val": ": typing.Optional[str] = 'passive'"}, {"name": "log_on_each_node", "val": ": bool = True"}, {"name": "logging_dir", "val": ": typing.Optional[str] = None"}, {"name": "logging_strategy", "val": ": IntervalStrategy = 'steps'"}, {"name": "logging_first_step", "val": ": bool = False"}, {"name": "logging_steps", "val": ": int = 500"}, {"name": "logging_nan_inf_filter", "val": ": str = True"}, {"name": "save_strategy", "val": ": IntervalStrategy = 'steps'"}, {"name": "save_steps", "val": ": int = 500"}, {"name": "save_total_limit", "val": ": typing.Optional[int] = None"}, {"name": "save_on_each_node", "val": ": bool = False"}, {"name": "no_cuda", "val": ": bool = False"}, {"name": "seed", "val": ": int = 42"}, {"name": "bf16", "val": ": bool = False"}, {"name": "fp16", "val": ": bool = False"}, {"name": "fp16_opt_level", "val": ": str = 'O1'"}, {"name": "half_precision_backend", "val": ": str = 'auto'"}, {"name": "bf16_full_eval", "val": ": bool = False"}, {"name": "fp16_full_eval", "val": ": bool = False"}, {"name": "tf32", "val": ": bool = None"}, {"name": "local_rank", "val": ": int = -1"}, {"name": "xpu_backend", "val": ": str = None"}, {"name": "tpu_num_cores", "val": ": typing.Optional[int] = None"}, {"name": "tpu_metrics_debug", "val": ": bool = False"}, {"name": "debug", "val": ": str = ''"}, {"name": "dataloader_drop_last", "val": ": bool = False"}, {"name": "eval_steps", "val": ": int = None"}, {"name": "dataloader_num_workers", "val": ": int = 0"}, {"name": "past_index", "val": ": int = -1"}, {"name": "run_name", "val": ": typing.Optional[str] = None"}, {"name": "disable_tqdm", "val": ": typing.Optional[bool] = None"}, {"name": "remove_unused_columns", "val": ": typing.Optional[bool] = True"}, {"name": "label_names", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "load_best_model_at_end", "val": ": typing.Optional[bool] = False"}, {"name": "metric_for_best_model", "val": ": typing.Optional[str] = None"}, {"name": "greater_is_better", "val": ": typing.Optional[bool] = None"}, {"name": "ignore_data_skip", "val": ": bool = False"}, {"name": "sharded_ddp", "val": ": str = ''"}, {"name": "deepspeed", "val": ": typing.Optional[str] = None"}, {"name": "label_smoothing_factor", "val": ": float = 0.0"}, {"name": "optim", "val": ": OptimizerNames = 'adamw_hf'"}, {"name": "adafactor", "val": ": bool = False"}, {"name": "group_by_length", "val": ": bool = False"}, {"name": "length_column_name", "val": ": typing.Optional[str] = 'length'"}, {"name": "report_to", "val": ": typing.Optional[typing.List[str]] = None"}, {"name": "ddp_find_unused_parameters", "val": ": typing.Optional[bool] = None"}, {"name": "ddp_bucket_cap_mb", "val": ": typing.Optional[int] = None"}, {"name": "dataloader_pin_memory", "val": ": bool = True"}, {"name": "skip_memory_metrics", "val": ": bool = True"}, {"name": "use_legacy_prediction_loop", "val": ": bool = False"}, {"name": "push_to_hub", "val": ": bool = False"}, {"name": "resume_from_checkpoint", "val": ": typing.Optional[str] = None"}, {"name": "hub_model_id", "val": ": str = None"}, {"name": "hub_strategy", "val": ": HubStrategy = 'every_save'"}, {"name": "hub_token", "val": ": str = None"}, {"name": "gradient_checkpointing", "val": ": bool = False"}, {"name": "fp16_backend", "val": ": str = 'auto'"}, {"name": "push_to_hub_model_id", "val": ": str = None"}, {"name": "push_to_hub_organization", "val": ": str = None"}, {"name": "push_to_hub_token", "val": ": str = None"}, {"name": "mp_parameters", "val": ": str = ''"}, {"name": "sortish_sampler", "val": ": bool = False"}, {"name": "predict_with_generate", "val": ": bool = False"}, {"name": "generation_max_length", "val": ": typing.Optional[int] = None"}, {"name": "generation_num_beams", "val": ": typing.Optional[int] = None"}]</parameters><paramsdesc>- **output_dir** (`str`) --
  The output directory where the model predictions and checkpoints will be written.
- **overwrite_output_dir** (`bool`, *optional*, defaults to `False`) --
  If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir`
  points to a checkpoint directory.
- **do_train** (`bool`, *optional*, defaults to `False`) --
  Whether to run training or not. This argument is not directly used by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's intended to be used
  by your training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **do_eval** (`bool`, *optional*) --
  Whether to run evaluation on the validation set or not. Will be set to `True` if `evaluation_strategy` is
  different from `"no"`. This argument is not directly used by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's intended to be used by your
  training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **do_predict** (`bool`, *optional*, defaults to `False`) --
  Whether to run predictions on the test set or not. This argument is not directly used by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's
  intended to be used by your training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **evaluation_strategy** (`str` or [IntervalStrategy](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `"no"`) --
  The evaluation strategy to adopt during training. Possible values are:

  - `"no"`: No evaluation is done during training.
  - `"steps"`: Evaluation is done (and logged) every `eval_steps`.
  - `"epoch"`: Evaluation is done at the end of each epoch.

- **prediction_loss_only** (`bool`, *optional*, defaults to `False`) --
  When performing evaluation and generating predictions, only returns the loss.
- **per_device_train_batch_size** (`int`, *optional*, defaults to 8) --
  The batch size per GPU/TPU core/CPU for training.
- **per_device_eval_batch_size** (`int`, *optional*, defaults to 8) --
  The batch size per GPU/TPU 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.

  <Tip warning=&amp;lcub;true}>

  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.

  </Tip>

- **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/TPU before being moved to the CPU (faster but
  requires more memory).
- **learning_rate** (`float`, *optional*, defaults to 5e-5) --
  The initial learning rate for [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **weight_decay** (`float`, *optional*, defaults to 0) --
  The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW)
  optimizer.
- **adam_beta1** (`float`, *optional*, defaults to 0.9) --
  The beta1 hyperparameter for the [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **adam_beta2** (`float`, *optional*, defaults to 0.999) --
  The beta2 hyperparameter for the [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **adam_epsilon** (`float`, *optional*, defaults to 1e-8) --
  The epsilon hyperparameter for the [AdamW](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.AdamW) optimizer.
- **max_grad_norm** (`float`, *optional*, defaults to 1.0) --
  Maximum gradient norm (for gradient clipping).
- **num_train_epochs(`float`,** *optional*, defaults to 3.0) --
  Total number of training epochs to perform (if not an integer, will perform the decimal part percents of
  the last epoch before stopping training).
- **max_steps** (`int`, *optional*, defaults to -1) --
  If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
  In case of using a finite iterable dataset the training may stop before reaching the set number of steps
  when all data is exhausted
- **lr_scheduler_type** (`str` or [SchedulerType](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.SchedulerType), *optional*, defaults to `"linear"`) --
  The scheduler type to use. See the documentation of [SchedulerType](/docs/transformers/pr_15592/en/main_classes/optimizer_schedules#transformers.SchedulerType) for all possible values.
- **warmup_ratio** (`float`, *optional*, defaults to 0.0) --
  Ratio of total training steps used for a linear warmup from 0 to `learning_rate`.
- **warmup_steps** (`int`, *optional*, defaults to 0) --
  Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`.
- **log_level** (`str`, *optional*, defaults to `passive`) --
  Logger log level to use on the main process. Possible choices are the log levels as strings: 'debug',
  'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and lets the
  application set the level.
- **log_level_replica** (`str`, *optional*, defaults to `passive`) --
  Logger log level to use on replicas. Same choices as `log_level`"
- **log_on_each_node** (`bool`, *optional*, defaults to `True`) --
  In multinode distributed training, whether to log using `log_level` once per node, or only on the main
  node.
- **logging_dir** (`str`, *optional*) --
  [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to
  *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***.
- **logging_strategy** (`str` or [IntervalStrategy](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `"steps"`) --
  The logging strategy to adopt during training. Possible values are:

  - `"no"`: No logging is done during training.
  - `"epoch"`: Logging is done at the end of each epoch.
  - `"steps"`: Logging is done every `logging_steps`.

- **logging_first_step** (`bool`, *optional*, defaults to `False`) --
  Whether to log and evaluate the first `global_step` or not.
- **logging_steps** (`int`, *optional*, defaults to 500) --
  Number of update steps between two logs if `logging_strategy="steps"`.
- **logging_nan_inf_filter** (`bool`, *optional*, defaults to `True`) --
  Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan`
  or `inf` is filtered and the average loss of the current logging window is taken instead.

  <Tip>

  `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.

  </Tip>

- **save_strategy** (`str` or [IntervalStrategy](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `"steps"`) --
  The checkpoint save strategy to adopt during training. Possible values are:

  - `"no"`: No save is done during training.
  - `"epoch"`: Save is done at the end of each epoch.
  - `"steps"`: Save is done every `save_steps`.
- **save_steps** (`int`, *optional*, defaults to 500) --
  Number of updates steps before two checkpoint saves if `save_strategy="steps"`.
- **save_total_limit** (`int`, *optional*) --
  If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
  `output_dir`.
- **save_on_each_node** (`bool`, *optional*, defaults to `False`) --
  When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
  the main one.

  This should not be activated when the different nodes use the same storage as the files will be saved with
  the same names for each node.
- **no_cuda** (`bool`, *optional*, defaults to `False`) --
  Whether to not use CUDA even when it is available or not.
- **seed** (`int`, *optional*, defaults to 42) --
  Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the
  `model_init` function to instantiate the model if it has some randomly initialized parameters.
- **bf16** (`bool`, *optional*, defaults to `False`) --
  Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher
  NVIDIA architecture. This is an experimental API and it may change.
- **fp16** (`bool`, *optional*, defaults to `False`) --
  Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
- **fp16_opt_level** (`str`, *optional*, defaults to 'O1') --
  For `fp16` training, Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details on
  the [Apex documentation](https://nvidia.github.io/apex/amp).
- **fp16_backend** (`str`, *optional*, defaults to `"auto"`) --
  This argument is deprecated. Use `half_precision_backend` instead.
- **half_precision_backend** (`str`, *optional*, defaults to `"auto"`) --
  The backend to use for mixed precision training. Must be one of `"auto"`, `"amp"` or `"apex"`. `"auto"`
  will use AMP or APEX depending on the PyTorch version detected, while the other choices will force the
  requested backend.
- **bf16_full_eval** (`bool`, *optional*, defaults to `False`) --
  Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm
  metric values. This is an experimental API and it may change.
- **fp16_full_eval** (`bool`, *optional*, defaults to `False`) --
  Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm
  metric values.
- **tf32** (`bool`, *optional*) --
  Whether to enable tf32 mode, available in Ampere and newer GPU architectures. This is an experimental API
  and it may change.
- **local_rank** (`int`, *optional*, defaults to -1) --
  Rank of the process during distributed training.
- **xpu_backend** (`str`, *optional*) --
  The backend to use for xpu distributed training. Must be one of `"mpi"` or `"ccl"`.
- **tpu_num_cores** (`int`, *optional*) --
  When training on TPU, the number of TPU cores (automatically passed by launcher script).
- **dataloader_drop_last** (`bool`, *optional*, defaults to `False`) --
  Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
  or not.
- **eval_steps** (`int`, *optional*) --
  Number of update steps between two evaluations if `evaluation_strategy="steps"`. Will default to the same
  value as `logging_steps` if not set.
- **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](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of
  the past hidden states for their predictions. If this argument is set to a positive int, the `Trainer` 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 argument `mems`.
- **run_name** (`str`, *optional*) --
  A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and
  [mlflow](https://www.mlflow.org/) logging.
- **disable_tqdm** (`bool`, *optional*) --
  Whether or not to disable the tqdm progress bars and table of metrics produced by
  `NotebookTrainingTracker` in Jupyter Notebooks. Will default to `True` if the logging level is
  set to warn or lower (default), `False` otherwise.
- **remove_unused_columns** (`bool`, *optional*, defaults to `True`) --
  If using `datasets.Dataset` datasets, whether or not to automatically remove the columns unused by the
  model forward method.

  (Note that this behavior is not implemented for `TFTrainer`yet.)
- **label_names** (`List[str]`, *optional*) --
  The list of keys in your dictionary of inputs that correspond to the labels.

  Will eventually default to `["labels"]` except if the model used is one of the `XxxForQuestionAnswering` in
  which case it will default to `["start_positions", "end_positions"]`.
- **load_best_model_at_end** (`bool`, *optional*, defaults to `False`) --
  Whether or not to load the best model found during training at the end of training.

  <Tip>

  When set to `True`, the parameters `save_strategy` needs to be the same as `eval_strategy`, and in the case
  it is "steps", `save_steps` must be a round multiple of `eval_steps`.

  </Tip>

- **metric_for_best_model** (`str`, *optional*) --
  Use in conjunction with `load_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 and `load_best_model_at_end=True` (to use the evaluation loss).

  If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if
  your metric is better when lower.
- **greater_is_better** (`bool`, *optional*) --
  Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models
  should have a greater metric or not. Will default to:

  - `True` if `metric_for_best_model` is set to a value that isn't `"loss"` or `"eval_loss"`.
  - `False` if `metric_for_best_model` is not set, or set to `"loss"` or `"eval_loss"`.
- **ignore_data_skip** (`bool`, *optional*, defaults to `False`) --
  When resuming training, whether or not to skip the epochs and batches to get the data loading at the same
  stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step
  can take a long time) but will not yield the same results as the interrupted training would have.
- **sharded_ddp** (`bool`, `str` or list of `ShardedDDPOption` *optional*, defaults to `False`) --
  Use Sharded DDP training from [FairScale](https://github.com/facebookresearch/fairscale) (in distributed
  training only). This is an experimental feature.

  A list of options along the following:

  - `"simple"`: to use first instance of sharded DDP released by fairscale (`ShardedDDP`) similar to ZeRO-2.
  - `"zero_dp_2"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in
    Zero-2 mode (with `reshard_after_forward=False`).
  - `"zero_dp_3"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in
    Zero-3 mode (with `reshard_after_forward=True`).
  - `"offload"`: to add ZeRO-offload (only compatible with `"zero_dp_2"` and `"zero_dp_3"`).

  If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty
  list for `False` and `["simple"]` for `True`.
- **deepspeed** (`str` or `dict`, *optional*) --
  Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may
  evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,
  `ds_config.json`) or an already loaded json file as a `dict`"
- **label_smoothing_factor** (`float`, *optional*, defaults to 0.0) --
  The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded
  labels are changed from 0s and 1s to `label_smoothing_factor/num_labels` and `1 - label_smoothing_factor +
  label_smoothing_factor/num_labels` respectively.
- **debug** (`str` or list of `DebugOption` *optional*, defaults to `""`) --
  Enable one or more debug features. This is an experimental feature.

  Possible options are:

  - `"underflow_overflow"`: detects overflow in model's input/outputs and reports the last frames that led to
    the event
  - `"tpu_metrics_debug"`: print debug metrics on TPU

  The options should be separated by whitespaces.
- **optim** (`str` or `training_args.OptimizerNames` *optional*, defaults to `"adamw_hf"`) --
  The optimizer to use: adamw_hf, adamw_torch, adamw_apex_fused, or adafactor.
- **adafactor** (`bool`, *optional*, defaults to `False`) --
  This argument is deprecated. Use `--optim adafactor` instead.
- **group_by_length** (`bool`, *optional*, defaults to `False`) --
  Whether or not to group together samples of roughly the same length in the training dataset (to minimize
  padding applied and be more efficient). Only useful if applying dynamic padding.
- **length_column_name** (`str`, *optional*, defaults to `"length"`) --
  Column name for precomputed lengths. If the column exists, grouping by length will use these values rather
  than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an
  instance of `Dataset`.
- **report_to** (`str` or `List[str]`, *optional*, defaults to `"all"`) --
  The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
  `"comet_ml"`, `"mlflow"`, `"tensorboard"` and `"wandb"`. Use `"all"` to report to all integrations
  installed, `"none"` for no integrations.
- **ddp_find_unused_parameters** (`bool`, *optional*) --
  When using distributed training, the value of the flag `find_unused_parameters` passed to
  `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
- **ddp_bucket_cap_mb** (`int`, *optional*) --
  When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.
- **dataloader_pin_memory** (`bool`, *optional*, defaults to `True`) --
  Whether you want to pin memory in data loaders or not. Will default to `True`.
- **skip_memory_metrics** (`bool`, *optional*, defaults to `True`) --
  Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows
  down the training and evaluation speed.
- **push_to_hub** (`bool`, *optional*, defaults to `False`) --
  Whether or not to push the model to the Hub every time the model is saved. If this is activated,
  `output_dir` will begin a git directory synced with the the repo (determined by `hub_model_id`) and the
  content will be pushed each time a save is triggered (depending on your `save_strategy`). Calling
  [save_model()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.save_model) will also trigger a push.

  <Tip warning=&amp;lcub;true}>

  If `output_dir` exists, it needs to be a local clone of the repository to which the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) will be
  pushed.

  </Tip>

- **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](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer), it's intended to be used by your training/evaluation scripts instead. See the [example
  scripts](https://github.com/huggingface/transformers/tree/master/examples) for more details.
- **hub_model_id** (`str`, *optional*) --
  The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
  which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
  for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
  `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the
  name of `output_dir`.

  Will default to to the name of `output_dir`.
- **hub_strategy** (`str` or `HubStrategy` *optional*, defaults to `"every_save"`) --
  Defines the scope of what is pushed to the Hub and when. Possible values are:

  - `"end"`: push the model, its configuration, the tokenizer (if passed along to the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer)) and a
    draft of a model card when the [save_model()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.save_model) method is called.
  - `"every_save"`: push the model, its configuration, the tokenizer (if passed along to the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer)) and
    a draft of a model card each time there is a model save. The pushes are asynchronous to not block
    training, and in case the save are very frequent, a new push is only attempted if the previous one is
    finished. A last push is made with the final model at the end of training.
  - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
    last-checkpoint, allowing you to resume training easily with
    `trainer.train(resume_from_checkpoint="last-checkpoint")`.
  - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the output
    folder (so you will get one checkpoint folder per folder in your final repository)

- **hub_token** (`str`, *optional*) --
  The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
  `huggingface-cli login`.
- **gradient_checkpointing** (`bool`, *optional*, defaults to `False`) --
  If True, use gradient checkpointing to save memory at the expense of slower backward pass.</paramsdesc><paramgroups>0</paramgroups></docstring>

TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop
itself**.

Using [HfArgumentParser](/docs/transformers/pr_15592/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
command line.



sortish_sampler (`bool`, *optional*, defaults to `False`):
Whether to use a *sortish sampler* or not. Only possible if the underlying datasets are *Seq2SeqDataset* for
now but will become generally available in the near future.

It sorts the inputs according to lengths in order to minimize the padding size, with a bit of randomness for
the training set.
predict_with_generate (`bool`, *optional*, defaults to `False`):
Whether to use generate to calculate generative metrics (ROUGE, BLEU).
generation_max_length (`int`, *optional*):
The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default to the
`max_length` value of the model configuration.
generation_num_beams (`int`, *optional*):
The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default to the
`num_beams` value of the model configuration.


</div>

<h2 id="checkpoints">Checkpoints</h2>

By default, [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) will save all checkpoints in the `output_dir` you set in the
[TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments) you are using. Those will go in subfolder named `checkpoint-xxx` with xxx
being the step at which the training was at.

Resuming training from a checkpoint can be done when calling [Trainer.train()](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer.train) with either:

- `resume_from_checkpoint=True` which will resume training from the latest checkpoint
- `resume_from_checkpoint=checkpoint_dir` which will resume training from the specific checkpoint in the directory
  passed.

In addition, you can easily save your checkpoints on the Model Hub when using `push_to_hub=True`. By default, all
the models saved in intermediate checkpoints are saved in different commits, but not the optimizer state. You can adapt
the `hub-strategy` value of your [TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments) to either:

- `"checkpoint"`: the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to
  resume training easily with `trainer.train(resume_from_checkpoint="output_dir/last-checkpoint")`.
- `"all_checkpoints"`: all checkpoints are pushed like they appear in the output folder (so you will get one
  checkpoint folder per folder in your final repository)


<h2 id="logging">Logging</h2>

By default [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) will use `logging.INFO` for the main process and `logging.WARNING` for the replicas if any.

These defaults can be overridden to use any of the 5 `logging` levels with [TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments)'s
arguments:

- `log_level` - for the main process
- `log_level_replica` - for the replicas

Further, if [TrainingArguments](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.TrainingArguments)'s `log_on_each_node` is set to `False` only the main node will
use the log level settings for its main process, all other nodes will use the log level settings for replicas.

Note that [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) is going to set `transformers`'s log level separately for each node in its
`Trainer.__init__()` So you may want to set this sooner (see the next example) if you tap into other
`transformers` functionality before creating the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) object.

Here is an example of how this can be used in an application:

```python
[...]
logger = logging.getLogger(__name__)

# Setup logging
logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    handlers=[logging.StreamHandler(sys.stdout)],
)

# set the main code and the modules it uses to the same log-level according to the node
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)

trainer = Trainer(...)
```

And then if you only want to see warnings on the main node and all other nodes to not print any most likely duplicated
warnings you could run it as:

```bash
my_app.py ... --log_level warning --log_level_replica error
```

In the multi-node environment if you also don't want the logs to repeat for each node's main process, you will want to
change the above to:

```bash
my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0
```

and then only the main process of the first node will log at the "warning" level, and all other processes on the main
node and all processes on other nodes will log at the "error" level.

If you need your application to be as quiet as possible you could do:

```bash
my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0
```

(add `--log_on_each_node 0` if on multi-node environment)


<h2 id="randomness">Randomness</h2>

When resuming from a checkpoint generated by [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) all efforts are made to restore the
_python_, _numpy_ and _pytorch_ RNG states to the same states as they were at the moment of saving that checkpoint,
which should make the "stop and resume" style of training as close as possible to non-stop training.

However, due to various default non-deterministic pytorch settings this might not fully work. If you want full
determinism please refer to [Controlling sources of randomness](https://pytorch.org/docs/stable/notes/randomness). As explained in the document, that some of those settings
that make things deterministic (.e.g., `torch.backends.cudnn.deterministic`) may slow things down, therefore this
can't be done by default, but you can enable those yourself if needed.


<h2 id="specific-gpus-selection">Specific GPUs Selection</h2>

Let's discuss how you can tell your program which GPUs are to be used and in what order.

When using [`DistributedDataParallel`](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) to use only a subset of your GPUs, you simply specify the number of GPUs to use. For example, if you have 4 GPUs, but you wish to use the first 2 you can do:

```bash
python -m torch.distributed.launch --nproc_per_node=2  trainer-program.py ...
```

if you have either [`accelerate`](https://github.com/huggingface/accelerate) or [`deepspeed`](https://github.com/microsoft/DeepSpeed) installed you can also accomplish the same by using one of:
```bash
accelerate launch --num_processes 2 trainer-program.py ...
```

```bash
deepspeed --num_gpus 2 trainer-program.py ...
```

You don't need to use the Accelerate or [the Deepspeed integration](Deepspeed) features to use these launchers.


Until now you were able to tell the program how many GPUs to use. Now let's discuss how to select specific GPUs and control their order.

The following environment variables help you control which GPUs to use and their order.

**`CUDA_VISIBLE_DEVICES`**

If you have multiple GPUs and you'd like to use only 1 or a few of those GPUs, set the environment variable `CUDA_VISIBLE_DEVICES` to a list of the GPUs to be used.

For example, let's say you have 4 GPUs: 0, 1, 2 and 3. To run only on the physical GPUs 0 and 2, you can do:

```bash
CUDA_VISIBLE_DEVICES=0,2 python -m torch.distributed.launch trainer-program.py ...
```

So now pytorch will see only 2 GPUs, where your physical GPUs 0 and 2 are mapped to `cuda:0` and `cuda:1` correspondingly.

You can even change their order:

```bash
CUDA_VISIBLE_DEVICES=2,0 python -m torch.distributed.launch trainer-program.py ...
```

Here your physical GPUs 0 and 2 are mapped to `cuda:1` and `cuda:0` correspondingly.

The above examples were all for `DistributedDataParallel` use pattern, but the same method works for [`DataParallel`](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html) as well:
```bash
CUDA_VISIBLE_DEVICES=2,0 python trainer-program.py ...
```

To emulate an environment without GPUs simply set this environment variable to an empty value like so:

```bash
CUDA_VISIBLE_DEVICES= python trainer-program.py ...
```

As with any environment variable you can, of course, export those instead of adding these to the command line, as in:


```bash
export CUDA_VISIBLE_DEVICES=0,2
python -m torch.distributed.launch trainer-program.py ...
```

but this approach can be confusing since you may forget you set up the environment variable earlier and not understand why the wrong GPUs are used. Therefore, it's a common practice to set the environment variable just for a specific run on the same command line as it's shown in most examples of this section.

**`CUDA_DEVICE_ORDER`**

There is an additional environment variable `CUDA_DEVICE_ORDER` that controls how the physical devices are ordered. The two choices are:

1. ordered by PCIe bus IDs (matches `nvidia-smi`'s order) - this is the default.

```bash
export CUDA_DEVICE_ORDER=PCI_BUS_ID
```

2. ordered by GPU compute capabilities

```bash
export CUDA_DEVICE_ORDER=FASTEST_FIRST
```

Most of the time you don't need to care about this environment variable, but it's very helpful if you have a lopsided setup where you have an old and a new GPUs physically inserted in such a way so that the slow older card appears to be first. One way to fix that is to swap the cards. But if you can't swap the cards (e.g., if the cooling of the devices gets impacted) then setting `CUDA_DEVICE_ORDER=FASTEST_FIRST` will always put the newer faster card first. It'll be somewhat confusing though since `nvidia-smi` will still report them in the PCIe order.

The other solution to swapping the order is to use:

```bash
export CUDA_VISIBLE_DEVICES=1,0
```
In this example we are working with just 2 GPUs, but of course the same would apply to as many GPUs as your computer has.

Also if you do set this environment variable it's the best to set it in your `~/.bashrc` file or some other startup config file and forget about it.




<h2 id="trainer-integrations">Trainer Integrations</h2>

The [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer) has been extended to support libraries that may dramatically improve your training
time and fit much bigger models.

Currently it supports third party solutions, [DeepSpeed](https://github.com/microsoft/DeepSpeed) and [FairScale](https://github.com/facebookresearch/fairscale/), which implement parts of the paper [ZeRO: Memory Optimizations
Toward Training Trillion Parameter Models, by Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He](https://arxiv.org/abs/1910.02054).

This provided support is new and experimental as of this writing.

<a id='zero-install-notes'></a>

<h3 id="cuda-extension-installation-notes">CUDA Extension Installation Notes</h3>

As of this writing, both FairScale and Deepspeed require compilation of CUDA C++ code, before they can be used.

While all installation issues should be dealt with through the corresponding GitHub Issues of [FairScale](https://github.com/facebookresearch/fairscale/issues) and [Deepspeed](https://github.com/microsoft/DeepSpeed/issues), there are a few common issues that one may encounter while building
any PyTorch extension that needs to build CUDA extensions.

Therefore, if you encounter a CUDA-related build issue while doing one of the following or both:

```bash
pip install fairscale
pip install deepspeed
```

please, read the following notes first.

In these notes we give examples for what to do when `pytorch` has been built with CUDA `10.2`. If your situation is
different remember to adjust the version number to the one you are after.

<h4 id="possible-problem-1">Possible problem #1</h4>

While, Pytorch comes with its own CUDA toolkit, to build these two projects you must have an identical version of CUDA
installed system-wide.

For example, if you installed `pytorch` with `cudatoolkit==10.2` in the Python environment, you also need to have
CUDA `10.2` installed system-wide.

The exact location may vary from system to system, but `/usr/local/cuda-10.2` is the most common location on many
Unix systems. When CUDA is correctly set up and added to the `PATH` environment variable, one can find the
installation location by doing:

```bash
which nvcc
```

If you don't have CUDA installed system-wide, install it first. You will find the instructions by using your favorite
search engine. For example, if you're on Ubuntu you may want to search for: [ubuntu cuda 10.2 install](https://www.google.com/search?q=ubuntu+cuda+10.2+install).

<h4 id="possible-problem-2">Possible problem #2</h4>

Another possible common problem is that you may have more than one CUDA toolkit installed system-wide. For example you
may have:

```bash
/usr/local/cuda-10.2
/usr/local/cuda-11.0
```

Now, in this situation you need to make sure that your `PATH` and `LD_LIBRARY_PATH` environment variables contain
the correct paths to the desired CUDA version. Typically, package installers will set these to contain whatever the
last version was installed. If you encounter the problem, where the package build fails because it can't find the right
CUDA version despite you having it installed system-wide, it means that you need to adjust the 2 aforementioned
environment variables.

First, you may look at their contents:

```bash
echo $PATH
echo $LD_LIBRARY_PATH
```

so you get an idea of what is inside.

It's possible that `LD_LIBRARY_PATH` is empty.

`PATH` lists the locations of where executables can be found and `LD_LIBRARY_PATH` is for where shared libraries
are to looked for. In both cases, earlier entries have priority over the later ones. `:` is used to separate multiple
entries.

Now, to tell the build program where to find the specific CUDA toolkit, insert the desired paths to be listed first by
doing:

```bash
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
```

Note that we aren't overwriting the existing values, but prepending instead.

Of course, adjust the version number, the full path if need be. Check that the directories you assign actually do
exist. `lib64` sub-directory is where the various CUDA `.so` objects, like `libcudart.so` reside, it's unlikely
that your system will have it named differently, but if it is adjust it to reflect your reality.


<h4 id="possible-problem-3">Possible problem #3</h4>

Some older CUDA versions may refuse to build with newer compilers. For example, you my have `gcc-9` but it wants
`gcc-7`.

There are various ways to go about it.

If you can install the latest CUDA toolkit it typically should support the newer compiler.

Alternatively, you could install the lower version of the compiler in addition to the one you already have, or you may
already have it but it's not the default one, so the build system can't see it. If you have `gcc-7` installed but the
build system complains it can't find it, the following might do the trick:

```bash
sudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++
```

Here, we are making a symlink to `gcc-7` from `/usr/local/cuda-10.2/bin/gcc` and since
`/usr/local/cuda-10.2/bin/` should be in the `PATH` environment variable (see the previous problem's solution), it
should find `gcc-7` (and `g++7`) and then the build will succeed.

As always make sure to edit the paths in the example to match your situation.

<h3 id="fairscale">FairScale</h3>

By integrating [FairScale](https://github.com/facebookresearch/fairscale/) the [Trainer](/docs/transformers/pr_15592/en/main_classes/trainer#transformers.Trainer)
provides support for the following features from [the ZeRO paper](https://arxiv.org/abs/1910.02054):

1. Optimizer State Sharding
2. Gradient Sharding
3. Model Parameters Sharding (new and very experimental)
4. CPU offload (new and very experimental)

You will need at least two GPUs to use this feature.


**Installation**:

Install the library via pypi:

```bash
pip install fairscale
```

or via `transformers`' `extras`:

```bash
pip install transformers[fairscale]
```

(available starting from `transformers==4.6.0`) or find more details on [the FairScale's GitHub page](https://github.com/facebookresearch/fairscale/#installation).

If you're still struggling with the build, first make sure to read [CUDA Extension Installation Notes](#zero-install-notes).

If it's still not resolved the build issue, here are a few more ideas.

`fairscale` seems to have an issue with the recently introduced by pip build isolation feature. If you have a problem
with it, you may want to try one of:

```bash
pip install fairscale --no-build-isolation .
```

or:

```bash
git clone https://github.com/facebookresearch/fairscale/
cd fairscale
rm -r dist build
python setup.py bdist_wheel
pip uninstall -y fairscale
pip install dist/fairscale-*.whl
```

`fairscale` also has issues with building against pytorch-nightly, so if you use it you may have to try one of:

```bash
pip uninstall -y fairscale; pip install fairscale --pre \
-f https://download.pytorch.org/whl/nightly/cu110/torch_nightly \
--no-cache --no-build-isolation
```

or:

```bash
pip install -v --disable-pip-version-check . \
-f https://download.pytorch.org/whl/nightly/cu110/torch_nightly --pre
```

Of course, adjust the urls to match the cuda version you use.

If after trying everything suggested you still encounter build issues, please, proceed with the GitHub Issue of
[FairScale](https://github.com/facebookresearch/fairscale/issues).



**Usage**:

To use the first version of Sharded data-parallelism, add `--sharded_ddp simple` to the command line arguments, and
make sure you have added the distributed launcher `-m torch.distributed.launch --nproc_per_node=NUMBER_OF_GPUS_YOU_HAVE` if you haven't been using it already.

For example here is how you could use it for `run_translation.py` with 2 GPUs:

```bash
python -m torch.distributed.launch --nproc_per_node=2 examples/pytorch/translation/run_translation.py \
--model_name_or_path t5-small --per_device_train_batch_size 1   \
--output_dir output_dir --overwrite_output_dir \
--do_train --max_train_samples 500 --num_train_epochs 1 \
--dataset_name wmt16 --dataset_config "ro-en" \
--source_lang en --target_lang ro \
--fp16 --sharded_ddp simple
```

Notes:

- This feature requires distributed training (so multiple GPUs).
- It is not implemented for TPUs.
- It works with `--fp16` too, to make things even faster.
- One of the main benefits of enabling `--sharded_ddp simple` is that it uses a lot less GPU memory, so you should be
  able to use significantly larger batch sizes using the same hardware (e.g. 3x and even bigger) which should lead to
  significantly shorter training time.

3. To use the second version of Sharded data-parallelism, add `--sharded_ddp zero_dp_2` or `--sharded_ddp zero_dp_3` to the command line arguments, and make sure you have added the distributed launcher `-m torch.distributed.launch --nproc_per_node=NUMBER_OF_GPUS_YOU_HAVE` if you haven't been using it already.

For example here is how you could use it for `run_translation.py` with 2 GPUs:

```bash
python -m torch.distributed.launch --nproc_per_node=2 examples/pytorch/translation/run_translation.py \
--model_name_or_path t5-small --per_device_train_batch_size 1   \
--output_dir output_dir --overwrite_output_dir \
--do_train --max_train_samples 500 --num_train_epochs 1 \
--dataset_name wmt16 --dataset_config "ro-en" \
--source_lang en --target_lang ro \
--fp16 --sharded_ddp zero_dp_2
```

`zero_dp_2` is an optimized version of the simple wrapper, while `zero_dp_3` fully shards model weights,
gradients and optimizer states.

Both are compatible with adding `cpu_offload` to enable ZeRO-offload (activate it like this: `--sharded_ddp "zero_dp_2 cpu_offload"`).

Notes:

- This feature requires distributed training (so multiple GPUs).
- It is not implemented for TPUs.
- It works with `--fp16` too, to make things even faster.
- The `cpu_offload` additional option requires `--fp16`.
- This is an area of active development, so make sure you have a source install of fairscale to use this feature as
  some bugs you encounter may have been fixed there already.

Known caveats:

- This feature is incompatible with `--predict_with_generate` in the _run_translation.py_ script.
- Using `--sharded_ddp zero_dp_3` requires wrapping each layer of the model in the special container
  `FullyShardedDataParallelism` of fairscale. It should be used with the option `auto_wrap` if you are not
  doing this yourself: `--sharded_ddp "zero_dp_3 auto_wrap"`.


Sections that were moved:

[ <a href="./deepspeed#deepspeed-trainer-integration">DeepSpeed</a><a id="deepspeed"></a>
| <a href="./deepspeed#deepspeed-installation">Installation</a><a id="installation"></a>
| <a href="./deepspeed#deepspeed-multi-gpu">Deployment with multiple GPUs</a><a id="deployment-with-multiple-gpus"></a>
| <a href="./deepspeed#deepspeed-one-gpu">Deployment with one GPU</a><a id="deployment-with-one-gpu"></a>
| <a href="./deepspeed#deepspeed-notebook">Deployment in Notebooks</a><a id="deployment-in-notebooks"></a>
| <a href="./deepspeed#deepspeed-config">Configuration</a><a id="configuration"></a>
| <a href="./deepspeed#deepspeed-config-passing">Passing Configuration</a><a id="passing-configuration"></a>
| <a href="./deepspeed#deepspeed-config-shared">Shared Configuration</a><a id="shared-configuration"></a>
| <a href="./deepspeed#deepspeed-zero">ZeRO</a><a id="zero"></a>
| <a href="./deepspeed#deepspeed-zero2-config">ZeRO-2 Config</a><a id="zero-2-config"></a>
| <a href="./deepspeed#deepspeed-zero3-config">ZeRO-3 Config</a><a id="zero-3-config"></a>
| <a href="./deepspeed#deepspeed-nvme">NVMe Support</a><a id="nvme-support"></a>
| <a href="./deepspeed#deepspeed-zero2-zero3-performance">ZeRO-2 vs ZeRO-3 Performance</a><a id="zero-2-vs-zero-3-performance"></a>
| <a href="./deepspeed#deepspeed-zero2-example">ZeRO-2 Example</a><a id="zero-2-example"></a>
| <a href="./deepspeed#deepspeed-zero3-example">ZeRO-3 Example</a><a id="zero-3-example"></a>
| <a href="./deepspeed#deepspeed-optimizer">Optimizer</a><a id="optimizer"></a>
| <a href="./deepspeed#deepspeed-scheduler">Scheduler</a><a id="scheduler"></a>
| <a href="./deepspeed#deepspeed-fp32">fp32 Precision</a><a id="fp32-precision"></a>
| <a href="./deepspeed#deepspeed-amp">Automatic Mixed Precision</a><a id="automatic-mixed-precision"></a>
| <a href="./deepspeed#deepspeed-bs">Batch Size</a><a id="batch-size"></a>
| <a href="./deepspeed#deepspeed-grad-acc">Gradient Accumulation</a><a id="gradient-accumulation"></a>
| <a href="./deepspeed#deepspeed-grad-clip">Gradient Clipping</a><a id="gradient-clipping"></a>
| <a href="./deepspeed#deepspeed-weight-extraction">Getting The Model Weights Out</a><a id="getting-the-model-weights-out"></a>
]
