The Trainer and TFTrainer classes provide an API for feature-complete training in most standard use cases. It’s used in most of the example scripts.
Before instantiating your Trainer/TFTrainer, create a TrainingArguments/TFTrainingArguments to access all the points of customization during training.
The API supports distributed training on multiple GPUs/TPUs, mixed precision through NVIDIA Apex and Native AMP for PyTorch and tf.keras.mixed_precision for TensorFlow.
Both Trainer and TFTrainer contain the basic training loop which supports the above features. To inject custom behavior you can subclass them and override the following methods:
create_optimizer and create_scheduler methods
separately.The Trainer class is optimized for 🤗 Transformers models and can have surprising behaviors when you use it on other models. When using it on your own model, make sure:
labels argument is provided and that loss is returned as the first
element of the tuple (if your model returns tuples)label_names in your
TrainingArguments to indicate their name to the Trainer) but none
of them should be named "label".Here is an example of how to customize Trainer using a custom loss function for multi-label classification:
from torch import nn
from transformers import Trainer
class MultilabelTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
labels = inputs.get("labels")
outputs = model(**inputs)
logits = outputs.get('logits')
loss_fct = nn.BCEWithLogitsLoss()
loss = loss_fct(logits.view(-1, self.model.config.num_labels),
labels.float().view(-1, self.model.config.num_labels))
return (loss, outputs) if return_outputs else lossAnother way to customize the training loop behavior for the PyTorch Trainer is to use callbacks that can inspect the training loop state (for progress reporting, logging on TensorBoard or other ML platforms…) and take decisions (like early stopping).
( model: typing.Union[transformers.modeling_utils.PreTrainedModel, torch.nn.modules.module.Module] = None args: TrainingArguments = None data_collator: typing.Optional[DataCollator] = None train_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = None eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = None tokenizer: typing.Optional[transformers.tokenization_utils_base.PreTrainedTokenizerBase] = None model_init: typing.Callable[[], transformers.modeling_utils.PreTrainedModel] = None compute_metrics: typing.Union[typing.Callable[[transformers.trainer_utils.EvalPrediction], typing.Dict], NoneType] = None callbacks: typing.Optional[typing.List[transformers.trainer_callback.TrainerCallback]] = None optimizers: typing.Tuple[torch.optim.optimizer.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None) )
Parameters
torch.nn.Module, optional) —
The model to train, evaluate or use for predictions. If not provided, a model_init must be passed.
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.
Important attributes:
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.False if model parallel or deepspeed is used, or if the default
TrainingArguments.place_model_on_device is overridden to return False .train (e.g. when evaluate is called
while in train)( callback )
Add a callback to the current list of TrainerCallback.
A helper wrapper that creates an appropriate context manager for autocast while feeding it the desired
arguments, depending on the situation.
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
Setup the optimizer.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer’s init through optimizers, or subclass and override this method in a subclass.
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer’s init through optimizers, or subclass and override this method (or create_optimizer
and/or create_scheduler) in a subclass.
( num_training_steps: int optimizer: Optimizer = None )
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument.
( eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = None ignore_keys: typing.Optional[typing.List[str]] = None metric_key_prefix: str = 'eval' )
Parameters
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.
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.
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)
Returns
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.
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.
( dataloader: DataLoader description: str prediction_loss_only: typing.Optional[bool] = None ignore_keys: typing.Optional[typing.List[str]] = None metric_key_prefix: str = 'eval' )
Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict().
Works both with or without labels.
(
inputs: typing.Dict[str, typing.Union[torch.Tensor, typing.Any]]
)
→
int
For models that inherit from PreTrainedModel, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method.
( eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = None )
Returns the evaluation DataLoader.
Subclass and override this method if you want to inject some custom behavior.
( test_dataset: Dataset )
Returns the test DataLoader.
Subclass and override this method if you want to inject some custom behavior.
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.
(
hp_space: typing.Union[typing.Callable[[ForwardRef('optuna.Trial')], typing.Dict[str, float]], NoneType] = None
compute_objective: typing.Union[typing.Callable[[typing.Dict[str, float]], float], NoneType] = None
n_trials: int = 20
direction: str = 'minimize'
backend: typing.Union[ForwardRef('str'), transformers.trainer_utils.HPSearchBackend, NoneType] = None
hp_name: typing.Union[typing.Callable[[ForwardRef('optuna.Trial')], str], NoneType] = None
**kwargs
)
→
transformers.trainer_utils.BestRun
Parameters
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.
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().
int, optional, defaults to 100) —
The number of trial runs to test.
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.
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:
Returns
transformers.trainer_utils.BestRun
All the information about the best run.
Launch an hyperparameter search using optuna or Ray Tune or SigOpt. The optimized quantity is
determined by compute_objective, which defaults to a function returning the evaluation loss when no
metric is provided, the sum of all metrics otherwise.
To use this method, you need to have provided a model_init when initializing your
Trainer: we need to reinitialize the model at each new run. This is incompatible
with the optimizers argument, so you need to subclass Trainer and override the
method create_optimizer_and_scheduler() for custom optimizer/scheduler.
Initializes a git repo in self.args.hub_model_id.
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process.
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be True for one process).
( logs: typing.Dict[str, float] )
Log logs on the various objects watching training.
Subclass and override this method to inject custom behavior.
( split metrics )
Log metrics in a specially formatted way
Under distributed environment this is done only for a process with rank 0.
Notes on memory reports:
In order to get memory usage report you need to install psutil. You can do that with pip install psutil.
Now when this method is run, you will see a report that will include: :
init_mem_cpu_alloc_delta = 1301MB init_mem_cpu_peaked_delta = 154MB init_mem_gpu_alloc_delta = 230MB init_mem_gpu_peaked_delta = 0MB train_mem_cpu_alloc_delta = 1345MB train_mem_cpu_peaked_delta = 0MB train_mem_gpu_alloc_delta = 693MB train_mem_gpu_peaked_delta = 7MB
Understanding the reports:
the first segment, e.g., train__, tells you which stage the metrics are for. Reports starting 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’s
__init__, train, evaluate and predict calls.
Because evaluation calls may happen during train, we can’t handle nested invocations because
torch.cuda.max_memory_allocated is a single counter, so if it gets reset by a nested eval call, train’s
tracker will report incorrect info. If this pytorch issue
gets resolved it will be possible to change this class to be re-entrant. Until then we will only track the outer
level of train, evaluate and predict methods. Which means that if eval is called during train,
it’s the latter that will account for its memory usage and that of the former.
This also means that if any other tool that is used along the Trainer calls
torch.cuda.reset_peak_memory_stats, the gpu peak memory stats could be invalid. And the
Trainer will disrupt the normal behavior of any such tools that rely on calling
torch.cuda.reset_peak_memory_stats themselves.
For best performance you may want to consider turning the memory profiling off for production runs.
(
metrics: typing.Dict[str, float]
)
→
metrics (Dict[str, float])
Reformat Trainer metrics values to a human-readable format
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__
(
callback
)
→
TrainerCallback
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).
( test_dataset: Dataset ignore_keys: typing.Optional[typing.List[str]] = None metric_key_prefix: str = 'test' )
Parameters
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__
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.
str, optional, defaults to "test") —
An optional prefix to be used as the metrics key prefix. For example the metrics “bleu” will be named
“test_bleu” if the prefix is “test” (default)
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in evaluate().
If your predictions or labels have different sequence length (for instance because you’re doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100.
Returns: NamedTuple A namedtuple with the following keys:
np.ndarray): The predictions on test_dataset.np.ndarray, _optional): The labels (if the dataset contained some).Dict[str, float], optional): The potential dictionary of metrics (if the dataset
contained labels).( dataloader: DataLoader description: str prediction_loss_only: typing.Optional[bool] = None ignore_keys: typing.Optional[typing.List[str]] = None metric_key_prefix: str = 'eval' )
Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict().
Works both with or without labels.
( model: Module inputs: typing.Dict[str, typing.Union[torch.Tensor, typing.Any]] prediction_loss_only: bool ignore_keys: typing.Optional[typing.List[str]] = None ) → Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]
Parameters
nn.Module) —
The model to evaluate.
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.
bool) —
Whether or not to return the loss only.
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.
Returns
Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]
A tuple with the loss, logits and labels (each being optional).
Perform an evaluation step on model using obj:inputs.
Subclass and override to inject custom behavior.
( commit_message: typing.Optional[str] = 'End of training' blocking: bool = True **kwargs )
Parameters
str, optional, defaults to "End of training") —
Message to commit while pushing.
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().
Returns
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
Upload self.model and self.tokenizer to the 🤗 model hub on the repo self.args.hub_model_id.
( callback )
Remove a callback from the current list of TrainerCallback.
( split metrics combined = True )
Save metrics into a json file for that split, e.g. train_results.json.
Under distributed environment this is done only for a process with rank 0.
To understand the metrics please read the docstring of log_metrics(). The only
difference is that raw unformatted numbers are saved in the current method.
Will save the model, so you can reload it using from_pretrained().
Will only save from the main process.
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model
Under distributed environment this is done only for a process with rank 0.
( resume_from_checkpoint: typing.Union[str, bool, NoneType] = None trial: typing.Union[ForwardRef('optuna.Trial'), typing.Dict[str, typing.Any]] = None ignore_keys_for_eval: typing.Optional[typing.List[str]] = None **kwargs )
Parameters
str or bool, optional) —
If a str, local path to a saved checkpoint as saved by a previous instance of
Trainer. If a bool and equals True, load the last checkpoint in
args.output_dir as saved by a previous instance of Trainer. If present,
training will resume from the model/optimizer/scheduler states loaded here.
optuna.Trial or Dict[str, Any], optional) —
The trial run or the hyperparameter dictionary for hyperparameter search.
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
Main training entry point.
(
model: Module
inputs: typing.Dict[str, typing.Union[torch.Tensor, typing.Any]]
)
→
torch.Tensor
Parameters
nn.Module) —
The model to train.
Dict[str, Union[torch.Tensor, Any]]) —
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument labels. Check your model’s documentation for all accepted arguments.
Returns
torch.Tensor
The tensor with training loss on this batch.
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
( eval_dataset: typing.Optional[torch.utils.data.dataset.Dataset] = None ignore_keys: typing.Optional[typing.List[str]] = None metric_key_prefix: str = 'eval' max_length: typing.Optional[int] = None num_beams: typing.Optional[int] = None )
Parameters
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.
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.
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)
int, optional) —
The maximum target length to use when predicting with the generate method.
int, optional) —
Number of beams for beam search that will be used when predicting with the generate method. 1 means no
beam search.
Returns
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.
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.
( test_dataset: Dataset ignore_keys: typing.Optional[typing.List[str]] = None metric_key_prefix: str = 'eval' max_length: typing.Optional[int] = None num_beams: typing.Optional[int] = None )
Parameters
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__
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.
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)
int, optional) —
The maximum target length to use when predicting with the generate method.
int, optional) —
Number of beams for beam search that will be used when predicting with the generate method. 1 means no
beam search.
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in evaluate().
If your predictions or labels have different sequence lengths (for instance because you’re doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100.
Returns: NamedTuple A namedtuple with the following keys:
np.ndarray): The predictions on test_dataset.np.ndarray, _optional): The labels (if the dataset contained some).Dict[str, float], optional): The potential dictionary of metrics (if the dataset
contained labels).( model: TFPreTrainedModel args: TFTrainingArguments train_dataset: typing.Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None eval_dataset: typing.Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None compute_metrics: typing.Union[typing.Callable[[transformers.trainer_utils.EvalPrediction], typing.Dict], NoneType] = None tb_writer: typing.Optional[tensorflow.python.ops.summary_ops_v2.SummaryWriter] = None optimizers: typing.Tuple[keras.optimizer_v2.optimizer_v2.OptimizerV2, keras.optimizer_v2.learning_rate_schedule.LearningRateSchedule] = (None, None) )
Parameters
Dataset, optional) —
The dataset to use for training. The dataset should yield tuples of (features, labels) where
features is a dict of input features and labels is the labels. If labels is a tensor, the loss
is calculated by the model by calling model(features, labels=labels). If labels is a dict, such as
when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling
model(features, **labels).
Dataset, optional) —
The dataset to use for evaluation. The dataset should yield tuples of (features, labels) where
features is a dict of input features and labels is the labels. If labels is a tensor, the loss
is calculated by the model by calling model(features, labels=labels). If labels is a dict, such as
when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling
model(features, **labels).
Callable[[EvalPrediction], Dict], optional) —
The function that will be used to compute metrics at evaluation. Must take a
EvalPrediction and return a dictionary string to metric values.
tf.summary.SummaryWriter, optional) —
Object to write to TensorBoard.
Tuple[tf.keras.optimizers.Optimizer, tf.keras.optimizers.schedules.LearningRateSchedule], optional) —
A tuple containing the optimizer and the scheduler to use. The optimizer default to an instance of
tf.keras.optimizers.Adam if args.weight_decay_rate is 0 else an instance of
AdamWeightDecay. The scheduler will default to an instance of
tf.keras.optimizers.schedules.PolynomialDecay if args.num_warmup_steps is 0 else an
instance of WarmUp.
TFTrainer is a simple but feature-complete training and eval loop for TensorFlow, optimized for 🤗 Transformers.
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
TFTrainer’s init through optimizers, or subclass and override this method.
( eval_dataset: typing.Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None )
Parameters
Dataset, optional) —
Pass a dataset if you wish to override self.eval_dataset. The dataset should yield tuples of
(features, labels) where features is a dict of input features and labels is the labels. If
labels is a tensor, the loss is calculated by the model by calling model(features, labels=labels). If labels is a dict, such as when using a QuestionAnswering head model with
multiple targets, the loss is instead calculated by calling model(features, **labels).
Returns
A dictionary containing the evaluation loss and the potential metrics computed from the predictions.
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).
( eval_dataset: typing.Optional[tensorflow.python.data.ops.dataset_ops.DatasetV2] = None )
Parameters
Dataset, optional) —
If provided, will override self.eval_dataset. The dataset should yield tuples of (features, labels) where features is a dict of input features and labels is the labels. If labels is
a tensor, the loss is calculated by the model by calling model(features, labels=labels). If
labels is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss
is instead calculated by calling model(features, **labels).
Returns the evaluation Dataset.
Subclass and override this method if you want to inject some custom behavior.
( test_dataset: DatasetV2 )
Parameters
Dataset) —
The dataset to use. The dataset should yield tuples of (features, labels) where features is a
dict of input features and labels is the labels. If labels is a tensor, the loss is calculated
by the model by calling model(features, labels=labels). If labels is a dict, such as when using
a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling
model(features, **labels).
Returns a test Dataset.
Subclass and override this method if you want to inject some custom behavior.
Returns the training Dataset.
Subclass and override this method if you want to inject some custom behavior.
( logs: typing.Dict[str, float] )
Log logs on the various objects watching training.
Subclass and override this method to inject custom behavior.
( test_dataset: DatasetV2 )
Parameters
Dataset) —
Dataset to run the predictions on. The dataset should yield tuples of (features, labels) where
features is a dict of input features and labels is the labels. If labels is a tensor, the
loss is calculated by the model by calling model(features, labels=labels). If labels is a dict,
such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated
by calling model(features, **labels)
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().
Returns: NamedTuple A namedtuple with the following keys:
np.ndarray): The predictions on test_dataset.np.ndarray, _optional): The labels (if the dataset contained some).Dict[str, float], optional): The potential dictionary of metrics (if the dataset
contained labels).( dataset: DatasetV2 steps: int num_examples: int description: str prediction_loss_only: typing.Optional[bool] = None )
Prediction/evaluation loop, shared by evaluate() and predict().
Works both with or without labels.
Compute the prediction on features and update the loss with labels.
Subclass and override to inject some custom behavior.
(
features
labels
training
)
→
A tuple of two tf.Tensor
Computes the loss of the given features and labels pair.
Subclass and override this method if you want to inject some custom behavior.
Will save the model, so you can reload it using from_pretrained().
Setup the optional Comet.ml integration.
Environment:
COMET_MODE:
(Optional): str - “OFFLINE”, “ONLINE”, or “DISABLED”
COMET_PROJECT_NAME:
(Optional): str - Comet.ml project name for experiments
COMET_OFFLINE_DIRECTORY:
(Optional): str - folder to use for saving offline experiments when COMET_MODE is “OFFLINE”
For a number of configurable items in the environment, see here <https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables>__
Setup the optional Weights & Biases (wandb) integration.
One can subclass and override this method to customize the setup if needed. Find more information here <https://docs.wandb.com/huggingface>__. You can also override the following environment variables:
Environment: WANDB_PROJECT: (Optional): str - “huggingface” by default, set this to a custom string to store results in a different project. WANDB_DISABLED: (Optional): boolean - defaults to false, set to “true” to disable wandb entirely.
Train method to train the model.
Perform a training step on features and labels.
Subclass and override to inject some custom behavior.
( output_dir: str overwrite_output_dir: bool = False do_train: bool = False do_eval: bool = False do_predict: bool = False evaluation_strategy: IntervalStrategy = 'no' prediction_loss_only: bool = False per_device_train_batch_size: int = 8 per_device_eval_batch_size: int = 8 per_gpu_train_batch_size: typing.Optional[int] = None per_gpu_eval_batch_size: typing.Optional[int] = None gradient_accumulation_steps: int = 1 eval_accumulation_steps: typing.Optional[int] = None learning_rate: float = 5e-05 weight_decay: float = 0.0 adam_beta1: float = 0.9 adam_beta2: float = 0.999 adam_epsilon: float = 1e-08 max_grad_norm: float = 1.0 num_train_epochs: float = 3.0 max_steps: int = -1 lr_scheduler_type: SchedulerType = 'linear' warmup_ratio: float = 0.0 warmup_steps: int = 0 log_level: typing.Optional[str] = 'passive' log_level_replica: typing.Optional[str] = 'passive' log_on_each_node: bool = True logging_dir: typing.Optional[str] = None logging_strategy: IntervalStrategy = 'steps' logging_first_step: bool = False logging_steps: int = 500 logging_nan_inf_filter: str = True save_strategy: IntervalStrategy = 'steps' save_steps: int = 500 save_total_limit: typing.Optional[int] = None save_on_each_node: bool = False no_cuda: bool = False seed: int = 42 bf16: bool = False fp16: bool = False fp16_opt_level: str = 'O1' half_precision_backend: str = 'auto' bf16_full_eval: bool = False fp16_full_eval: bool = False tf32: bool = None local_rank: int = -1 xpu_backend: str = None tpu_num_cores: typing.Optional[int] = None tpu_metrics_debug: bool = False debug: str = '' dataloader_drop_last: bool = False eval_steps: int = None dataloader_num_workers: int = 0 past_index: int = -1 run_name: typing.Optional[str] = None disable_tqdm: typing.Optional[bool] = None remove_unused_columns: typing.Optional[bool] = True label_names: typing.Optional[typing.List[str]] = None load_best_model_at_end: typing.Optional[bool] = False metric_for_best_model: typing.Optional[str] = None greater_is_better: typing.Optional[bool] = None ignore_data_skip: bool = False sharded_ddp: str = '' deepspeed: typing.Optional[str] = None label_smoothing_factor: float = 0.0 adafactor: bool = False group_by_length: bool = False length_column_name: typing.Optional[str] = 'length' report_to: typing.Optional[typing.List[str]] = None ddp_find_unused_parameters: typing.Optional[bool] = None dataloader_pin_memory: bool = True skip_memory_metrics: bool = True use_legacy_prediction_loop: bool = False push_to_hub: bool = False resume_from_checkpoint: typing.Optional[str] = None hub_model_id: str = None hub_strategy: HubStrategy = 'every_save' hub_token: str = None gradient_checkpointing: bool = False fp16_backend: str = 'auto' push_to_hub_model_id: str = None push_to_hub_organization: str = None push_to_hub_token: str = None mp_parameters: str = '' )
Parameters
str) —
The output directory where the model predictions and checkpoints will be written.
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.
bool, optional, defaults to False) —
Whether to run training or not. This argument is not directly used by Trainer, it’s
intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
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, it’s intended to be used by your training/evaluation scripts instead. See
the example scripts for more
details.
bool, optional, defaults to False) —
Whether to run predictions on the test set or not. This argument is not directly used by
Trainer, it’s intended to be used by your training/evaluation scripts instead. See
the example scripts for more
details.
str or IntervalStrategy, optional, defaults to "no") —
The evaluation strategy to adopt during training. Possible values are:
"no": No evaluation is done during training."steps": Evaluation is done (and logged) every eval_steps."epoch": Evaluation is done at the end of each epoch.bool, optional, defaults to False) —
When performing evaluation and generating predictions, only returns the loss.
int, optional, defaults to 8) —
The batch size per GPU/TPU core/CPU for training.
int, optional, defaults to 8) —
The batch size per GPU/TPU core/CPU for evaluation.
int, optional, defaults to 1) —
Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process.
For the main process the log level defaults to 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.
Get number of steps used for a linear warmup.
( local = True desc = 'work' )
Parameters
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.
str, optional, defaults to "work") —
a work description to be used in debug logs
A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when it’s finished releasing the replicas.
One such use is for datasets’s map feature which to be efficient should be run once on the main
process, which upon completion saves a cached version of results and which then automatically gets loaded
by the replicas.
Serializes this instance while replace Enum by their values (for JSON serialization support). It obfuscates
the token values by removing their value.
Serializes this instance to a JSON string.
Sanitized serialization to use with TensorBoard’s hparams
( output_dir: str overwrite_output_dir: bool = False do_train: bool = False do_eval: bool = False do_predict: bool = False evaluation_strategy: IntervalStrategy = 'no' prediction_loss_only: bool = False per_device_train_batch_size: int = 8 per_device_eval_batch_size: int = 8 per_gpu_train_batch_size: typing.Optional[int] = None per_gpu_eval_batch_size: typing.Optional[int] = None gradient_accumulation_steps: int = 1 eval_accumulation_steps: typing.Optional[int] = None learning_rate: float = 5e-05 weight_decay: float = 0.0 adam_beta1: float = 0.9 adam_beta2: float = 0.999 adam_epsilon: float = 1e-08 max_grad_norm: float = 1.0 num_train_epochs: float = 3.0 max_steps: int = -1 lr_scheduler_type: SchedulerType = 'linear' warmup_ratio: float = 0.0 warmup_steps: int = 0 log_level: typing.Optional[str] = 'passive' log_level_replica: typing.Optional[str] = 'passive' log_on_each_node: bool = True logging_dir: typing.Optional[str] = None logging_strategy: IntervalStrategy = 'steps' logging_first_step: bool = False logging_steps: int = 500 logging_nan_inf_filter: str = True save_strategy: IntervalStrategy = 'steps' save_steps: int = 500 save_total_limit: typing.Optional[int] = None save_on_each_node: bool = False no_cuda: bool = False seed: int = 42 bf16: bool = False fp16: bool = False fp16_opt_level: str = 'O1' half_precision_backend: str = 'auto' bf16_full_eval: bool = False fp16_full_eval: bool = False tf32: bool = None local_rank: int = -1 xpu_backend: str = None tpu_num_cores: typing.Optional[int] = None tpu_metrics_debug: bool = False debug: str = '' dataloader_drop_last: bool = False eval_steps: int = None dataloader_num_workers: int = 0 past_index: int = -1 run_name: typing.Optional[str] = None disable_tqdm: typing.Optional[bool] = None remove_unused_columns: typing.Optional[bool] = True label_names: typing.Optional[typing.List[str]] = None load_best_model_at_end: typing.Optional[bool] = False metric_for_best_model: typing.Optional[str] = None greater_is_better: typing.Optional[bool] = None ignore_data_skip: bool = False sharded_ddp: str = '' deepspeed: typing.Optional[str] = None label_smoothing_factor: float = 0.0 adafactor: bool = False group_by_length: bool = False length_column_name: typing.Optional[str] = 'length' report_to: typing.Optional[typing.List[str]] = None ddp_find_unused_parameters: typing.Optional[bool] = None dataloader_pin_memory: bool = True skip_memory_metrics: bool = True use_legacy_prediction_loop: bool = False push_to_hub: bool = False resume_from_checkpoint: typing.Optional[str] = None hub_model_id: str = None hub_strategy: HubStrategy = 'every_save' hub_token: str = None gradient_checkpointing: bool = False fp16_backend: str = 'auto' push_to_hub_model_id: str = None push_to_hub_organization: str = None push_to_hub_token: str = None mp_parameters: str = '' sortish_sampler: bool = False predict_with_generate: bool = False generation_max_length: typing.Optional[int] = None generation_num_beams: typing.Optional[int] = None )
Parameters
str) —
The output directory where the model predictions and checkpoints will be written.
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.
bool, optional, defaults to False) —
Whether to run training or not. This argument is not directly used by Trainer, it’s
intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
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, it’s intended to be used by your training/evaluation scripts instead. See
the example scripts for more
details.
bool, optional, defaults to False) —
Whether to run predictions on the test set or not. This argument is not directly used by
Trainer, it’s intended to be used by your training/evaluation scripts instead. See
the example scripts for more
details.
str or IntervalStrategy, optional, defaults to "no") —
The evaluation strategy to adopt during training. Possible values are:
"no": No evaluation is done during training."steps": Evaluation is done (and logged) every eval_steps."epoch": Evaluation is done at the end of each epoch.bool, optional, defaults to False) —
When performing evaluation and generating predictions, only returns the loss.
int, optional, defaults to 8) —
The batch size per GPU/TPU core/CPU for training.
int, optional, defaults to 8) —
The batch size per GPU/TPU core/CPU for evaluation.
int, optional, defaults to 1) —
Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
sortishsampler (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.
predictwith_generate (bool, _optional, defaults to False):
Whether to use generate to calculate generative metrics (ROUGE, BLEU).
generationmax_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.
generationnum_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.
( output_dir: str overwrite_output_dir: bool = False do_train: bool = False do_eval: bool = False do_predict: bool = False evaluation_strategy: IntervalStrategy = 'no' prediction_loss_only: bool = False per_device_train_batch_size: int = 8 per_device_eval_batch_size: int = 8 per_gpu_train_batch_size: typing.Optional[int] = None per_gpu_eval_batch_size: typing.Optional[int] = None gradient_accumulation_steps: int = 1 eval_accumulation_steps: typing.Optional[int] = None learning_rate: float = 5e-05 weight_decay: float = 0.0 adam_beta1: float = 0.9 adam_beta2: float = 0.999 adam_epsilon: float = 1e-08 max_grad_norm: float = 1.0 num_train_epochs: float = 3.0 max_steps: int = -1 lr_scheduler_type: SchedulerType = 'linear' warmup_ratio: float = 0.0 warmup_steps: int = 0 log_level: typing.Optional[str] = 'passive' log_level_replica: typing.Optional[str] = 'passive' log_on_each_node: bool = True logging_dir: typing.Optional[str] = None logging_strategy: IntervalStrategy = 'steps' logging_first_step: bool = False logging_steps: int = 500 logging_nan_inf_filter: str = True save_strategy: IntervalStrategy = 'steps' save_steps: int = 500 save_total_limit: typing.Optional[int] = None save_on_each_node: bool = False no_cuda: bool = False seed: int = 42 bf16: bool = False fp16: bool = False fp16_opt_level: str = 'O1' half_precision_backend: str = 'auto' bf16_full_eval: bool = False fp16_full_eval: bool = False tf32: bool = None local_rank: int = -1 xpu_backend: str = None tpu_num_cores: typing.Optional[int] = None tpu_metrics_debug: bool = False debug: str = '' dataloader_drop_last: bool = False eval_steps: int = None dataloader_num_workers: int = 0 past_index: int = -1 run_name: typing.Optional[str] = None disable_tqdm: typing.Optional[bool] = None remove_unused_columns: typing.Optional[bool] = True label_names: typing.Optional[typing.List[str]] = None load_best_model_at_end: typing.Optional[bool] = False metric_for_best_model: typing.Optional[str] = None greater_is_better: typing.Optional[bool] = None ignore_data_skip: bool = False sharded_ddp: str = '' deepspeed: typing.Optional[str] = None label_smoothing_factor: float = 0.0 adafactor: bool = False group_by_length: bool = False length_column_name: typing.Optional[str] = 'length' report_to: typing.Optional[typing.List[str]] = None ddp_find_unused_parameters: typing.Optional[bool] = None dataloader_pin_memory: bool = True skip_memory_metrics: bool = True use_legacy_prediction_loop: bool = False push_to_hub: bool = False resume_from_checkpoint: typing.Optional[str] = None hub_model_id: str = None hub_strategy: HubStrategy = 'every_save' hub_token: str = None gradient_checkpointing: bool = False fp16_backend: str = 'auto' push_to_hub_model_id: str = None push_to_hub_organization: str = None push_to_hub_token: str = None mp_parameters: str = '' tpu_name: str = None tpu_zone: str = None gcp_project: str = None poly_power: float = 1.0 xla: bool = False )
Parameters
str) —
The output directory where the model predictions and checkpoints will be written.
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.
bool, optional, defaults to False) —
Whether to run training or not. This argument is not directly used by Trainer, it’s
intended to be used by your training/evaluation scripts instead. See the example scripts for more details.
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, it’s intended to be used by your training/evaluation scripts instead. See
the example scripts for more
details.
bool, optional, defaults to False) —
Whether to run predictions on the test set or not. This argument is not directly used by
Trainer, it’s intended to be used by your training/evaluation scripts instead. See
the example scripts for more
details.
str or IntervalStrategy, optional, defaults to "no") —
The evaluation strategy to adopt during training. Possible values are:
"no": No evaluation is done during training."steps": Evaluation is done (and logged) every eval_steps."epoch": Evaluation is done at the end of each epoch.int, optional, defaults to 8) —
The batch size per GPU/TPU core/CPU for training.
int, optional, defaults to 8) —
The batch size per GPU/TPU core/CPU for evaluation.
gradientaccumulation_steps — (int, _optional, defaults to 1):
Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
By default, Trainer will save all checkpoints in the output_dir you set in the
TrainingArguments you are using. Those will go in subfolder named checkpoint-xxx with xxx
being the step at which the training was at.
Resuming training from a checkpoint can be done when calling train() with either:
resume_from_checkpoint=True which will resume training from the latest checkpointresume_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 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)By default Trainer will use logging.INFO for the main process and logging.WARNING for
the replicas if any.
These defaults can be overridden to use any of the 5 logging levels with TrainingArguments’s
arguments:
log_level - for the main processlog_level_replica - for the replicasFurther, if TrainingArguments’s log_on_each_node is set to False only the main node will
use the log level settings for its main process, all other nodes will use the log level settings for replicas.
Note that Trainer is going to set transformers’s log level separately for each node in its
__init__(). So you may want to set this sooner (see the next example) if you tap into other
transformers functionality before creating the Trainer object.
Here is an example of how this can be used in an application:
[...]
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:
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:
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:
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)
When resuming from a checkpoint generated by Trainer all efforts are made to restore the python, numpy and pytorch RNG states to the same states as they were at the moment of saving that checkpoint, which should make the “stop and resume” style of training as close as possible to non-stop training.
However, due to various default non-deterministic pytorch settings this might not fully work. If you want full
determinism please refer to Controlling sources of randomness. As explained in the document, that some of those settings
that make things deterministic (.e.g., torch.backends.cudnn.deterministic) may slow things down, therefore this
can’t be done by default, but you can enable those yourself if needed.
The Trainer has been extended to support libraries that may dramatically improve your training time and fit much bigger models.
Currently it supports third party solutions, DeepSpeed and FairScale, which implement parts of the paper ZeRO: Memory Optimizations Toward Training Trillion Parameter Models, by Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He.
This provided support is new and experimental as of this writing.
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 and Deepspeed, there are a few common issues that one may encounter while building any PyTorch extension that needs to build CUDA extensions.
Therefore, if you encounter a CUDA-related build issue while doing one of the following or both:
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.
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:
which nvccIf you don’t have CUDA installed system-wide, install it first. You will find the instructions by using your favorite search engine. For example, if you’re on Ubuntu you may want to search for: ubuntu cuda 10.2 install.
Another possible common problem is that you may have more than one CUDA toolkit installed system-wide. For example you may have:
/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:
echo $PATH
echo $LD_LIBRARY_PATHso you get an idea of what is inside.
It’s possible that LD_LIBRARY_PATH is empty.
PATH lists the locations of where executables can be found and LD_LIBRARY_PATH is for where shared libraries
are to looked for. In both cases, earlier entries have priority over the later ones. : is used to separate multiple
entries.
Now, to tell the build program where to find the specific CUDA toolkit, insert the desired paths to be listed first by doing:
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATHNote that we aren’t overwriting the existing values, but prepending instead.
Of course, adjust the version number, the full path if need be. Check that the directories you assign actually do
exist. lib64 sub-directory is where the various CUDA .so objects, like libcudart.so reside, it’s unlikely
that your system will have it named differently, but if it is adjust it to reflect your reality.
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:
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.
By integrating FairScale the Trainer provides support for the following features from the ZeRO paper:
You will need at least two GPUs to use this feature.
Installation:
Install the library via pypi:
pip install fairscale
or via transformers’ extras:
pip install transformers[fairscale]
(will become available starting from transformers==4.6.0)
or find more details on the FairScale’s GitHub page.
If you’re still struggling with the build, first make sure to read 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:
pip install fairscale --no-build-isolation .
or:
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-*.whlfairscale also has issues with building against pytorch-nightly, so if you use it you may have to try one of:
pip uninstall -y fairscale; pip install fairscale --pre \ -f https://download.pytorch.org/whl/nightly/cu110/torch_nightly.html \ --no-cache --no-build-isolation
or:
pip install -v --disable-pip-version-check . \ -f https://download.pytorch.org/whl/nightly/cu110/torch_nightly.html --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.
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:
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 simpleNotes:
--fp16 too, to make things even faster.--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.--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:
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_2zero_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:
--fp16 too, to make things even faster.cpu_offload additional option requires --fp16.Known caveats:
--predict_with_generate in the run_translation.py script.--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".Moved to deepspeed-trainer-integration.
Moved to deepspeed-installation.
Moved to deepspeed-multi-gpu.
Moved to deepspeed-one-gpu.
Moved to deepspeed-notebook.
Moved to deepspeed-config.
Moved to deepspeed-config-passing.
Moved to deepspeed-config-shared.
Moved to deepspeed-zero.
Moved to deepspeed-zero2-config.
Moved to deepspeed-zero3-config.
Moved to deepspeed-nvme.
Moved to deepspeed-zero2-zero3-performance.
Moved to deepspeed-zero2-example.
Moved to deepspeed-zero3-example.
Moved to deepspeed-optimizer.
Moved to deepspeed-scheduler.
Moved to deepspeed-fp32.
Moved to deepspeed-amp.
Moved to deepspeed-bs.
Moved to deepspeed-grad-acc.
Moved to deepspeed-grad-clip.
Moved to deepspeed-weight-extraction.