training_args.py 67.1 KB
Newer Older
Sylvain Gugger's avatar
Sylvain Gugger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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.

15
import contextlib
Julien Chaumond's avatar
Julien Chaumond committed
16
import json
17
import math
Julien Plu's avatar
Julien Plu committed
18
import os
19
import warnings
20
from dataclasses import asdict, dataclass, field
21
from enum import Enum
22
from pathlib import Path
23
from typing import Any, Dict, List, Optional
Julien Chaumond's avatar
Julien Chaumond committed
24

25
from .debug_utils import DebugOption
26
27
from .trainer_utils import EvaluationStrategy, HubStrategy, IntervalStrategy, SchedulerType, ShardedDDPOption
from .utils import (
28
    ExplicitEnum,
Sylvain Gugger's avatar
Sylvain Gugger committed
29
    cached_property,
30
    get_full_repo_name,
Sylvain Gugger's avatar
Sylvain Gugger committed
31
32
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
Sylvain Gugger's avatar
Sylvain Gugger committed
33
    is_torch_available,
Stas Bekman's avatar
Stas Bekman committed
34
    is_torch_bf16_available,
35
    is_torch_tf32_available,
Sylvain Gugger's avatar
Sylvain Gugger committed
36
    is_torch_tpu_available,
37
    logging,
Sylvain Gugger's avatar
Sylvain Gugger committed
38
39
    torch_required,
)
Julien Chaumond's avatar
Julien Chaumond committed
40
41
42
43


if is_torch_available():
    import torch
Lai Wei's avatar
Lai Wei committed
44
    import torch.distributed as dist
Julien Chaumond's avatar
Julien Chaumond committed
45

46
if is_torch_tpu_available():
Lysandre Debut's avatar
Lysandre Debut committed
47
48
    import torch_xla.core.xla_model as xm

49

Sylvain Gugger's avatar
Sylvain Gugger committed
50
51
52
53
54
if is_sagemaker_mp_enabled():
    import smdistributed.modelparallel.torch as smp

    smp.init()

Lysandre Debut's avatar
Lysandre Debut committed
55

Lysandre Debut's avatar
Lysandre Debut committed
56
logger = logging.get_logger(__name__)
57
58
log_levels = logging.get_log_levels_dict().copy()
trainer_log_levels = dict(**log_levels, passive=-1)
59
60


Julien Plu's avatar
Julien Plu committed
61
62
63
64
65
66
67
68
69
70
71
def default_logdir() -> str:
    """
    Same default as PyTorch
    """
    import socket
    from datetime import datetime

    current_time = datetime.now().strftime("%b%d_%H-%M-%S")
    return os.path.join("runs", current_time + "_" + socket.gethostname())


72
73
74
75
76
77
78
class OptimizerNames(ExplicitEnum):
    """
    Stores the acceptable string identifiers for optimizers.
    """

    ADAMW_HF = "adamw_hf"
    ADAMW_TORCH = "adamw_torch"
79
    ADAMW_TORCH_XLA = "adamw_torch_xla"
80
81
82
83
    ADAMW_APEX_FUSED = "adamw_apex_fused"
    ADAFACTOR = "adafactor"


84
85
86
@dataclass
class TrainingArguments:
    """
Sylvain Gugger's avatar
Sylvain Gugger committed
87
88
    TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop
    itself**.
89

Sylvain Gugger's avatar
Sylvain Gugger committed
90
91
92
    Using [`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.
93
94

    Parameters:
95
        output_dir (`str`):
96
            The output directory where the model predictions and checkpoints will be written.
97
        overwrite_output_dir (`bool`, *optional*, defaults to `False`):
Sylvain Gugger's avatar
Sylvain Gugger committed
98
99
            If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir`
            points to a checkpoint directory.
100
        do_train (`bool`, *optional*, defaults to `False`):
Sylvain Gugger's avatar
Sylvain Gugger committed
101
102
            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
103
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
104
        do_eval (`bool`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
105
106
107
            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
108
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
109
        do_predict (`bool`, *optional*, defaults to `False`):
Sylvain Gugger's avatar
Sylvain Gugger committed
110
111
            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
112
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
113
        evaluation_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
114
115
            The evaluation strategy to adopt during training. Possible values are:

116
117
118
                - `"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.
119

120
        prediction_loss_only (`bool`, *optional*, defaults to `False`):
121
            When performing evaluation and generating predictions, only returns the loss.
122
        per_device_train_batch_size (`int`, *optional*, defaults to 8):
123
            The batch size per GPU/TPU core/CPU for training.
124
        per_device_eval_batch_size (`int`, *optional*, defaults to 8):
125
            The batch size per GPU/TPU core/CPU for evaluation.
126
        gradient_accumulation_steps (`int`, *optional*, defaults to 1):
127
            Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
128

129
            <Tip warning={true}>
130

Sylvain Gugger's avatar
Sylvain Gugger committed
131
132
            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.
133
134
135
136

            </Tip>

        eval_accumulation_steps (`int`, *optional*):
137
138
139
            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).
140
        eval_delay (`float`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
141
142
            Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
            evaluation_strategy.
143
144
145
        learning_rate (`float`, *optional*, defaults to 5e-5):
            The initial learning rate for [`AdamW`] optimizer.
        weight_decay (`float`, *optional*, defaults to 0):
Sylvain Gugger's avatar
Sylvain Gugger committed
146
147
            The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`]
            optimizer.
148
149
150
151
152
153
154
        adam_beta1 (`float`, *optional*, defaults to 0.9):
            The beta1 hyperparameter for the [`AdamW`] optimizer.
        adam_beta2 (`float`, *optional*, defaults to 0.999):
            The beta2 hyperparameter for the [`AdamW`] optimizer.
        adam_epsilon (`float`, *optional*, defaults to 1e-8):
            The epsilon hyperparameter for the [`AdamW`] optimizer.
        max_grad_norm (`float`, *optional*, defaults to 1.0):
155
            Maximum gradient norm (for gradient clipping).
156
        num_train_epochs(`float`, *optional*, defaults to 3.0):
Sylvain Gugger's avatar
Sylvain Gugger committed
157
158
            Total number of training epochs to perform (if not an integer, will perform the decimal part percents of
            the last epoch before stopping training).
159
        max_steps (`int`, *optional*, defaults to -1):
Sylvain Gugger's avatar
Sylvain Gugger committed
160
161
162
            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
163
        lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
Sylvain Gugger's avatar
Sylvain Gugger committed
164
            The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values.
165
166
167
        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):
Sylvain Gugger's avatar
Sylvain Gugger committed
168
            Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`.
169
        log_level (`str`, *optional*, defaults to `passive`):
170
171
172
            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.
173
174
175
176
        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
177
            node.
178
179
180
181
        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 [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
182
183
            The logging strategy to adopt during training. Possible values are:

184
185
186
187
188
189
190
191
192
                - `"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`):
Stas Bekman's avatar
Stas Bekman committed
193
194
            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.
195

196
197
            <Tip>

Sylvain Gugger's avatar
Sylvain Gugger committed
198
199
            `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.
200

201
            </Tip>
202

203
        save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
204
            The checkpoint save strategy to adopt during training. Possible values are:
205

206
207
208
209
210
211
                - `"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*):
212
            If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
213
214
            `output_dir`.
        save_on_each_node (`bool`, *optional*, defaults to `False`):
215
216
217
218
219
            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.
220
        no_cuda (`bool`, *optional*, defaults to `False`):
Alan deLevie's avatar
Alan deLevie committed
221
            Whether to not use CUDA even when it is available or not.
222
        seed (`int`, *optional*, defaults to 42):
223
            Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the
Sylvain Gugger's avatar
Sylvain Gugger committed
224
            [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters.
225
226
227
228
        data_seed (`int`, *optional*):
            Random seed to be used with data samplers. If not set, random generators for data sampling will use the
            same seed as `seed`. This can be used to ensure reproducibility of data sampling, independent of the model
            seed.
229
        bf16 (`bool`, *optional*, defaults to `False`):
230
231
            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.
232
        fp16 (`bool`, *optional*, defaults to `False`):
233
            Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
234
        fp16_opt_level (`str`, *optional*, defaults to 'O1'):
Sylvain Gugger's avatar
Sylvain Gugger committed
235
236
            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).
237
238
239
        fp16_backend (`str`, *optional*, defaults to `"auto"`):
            This argument is deprecated. Use `half_precision_backend` instead.
        half_precision_backend (`str`, *optional*, defaults to `"auto"`):
Sylvain Gugger's avatar
Sylvain Gugger committed
240
241
242
            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.
243
        bf16_full_eval (`bool`, *optional*, defaults to `False`):
244
245
            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.
246
        fp16_full_eval (`bool`, *optional*, defaults to `False`):
247
248
            Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm
            metric values.
249
        tf32 (`bool`, *optional*):
Stas Bekman's avatar
Stas Bekman committed
250
251
252
253
            Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends
            on PyTorch's version default of `torch.backends.cuda.matmul.allow_tf32`. For more details please refer to
            the [TF32](https://huggingface.co/docs/transformers/performance#tf32) documentation. This is an
            experimental API and it may change.
254
        local_rank (`int`, *optional*, defaults to -1):
255
            Rank of the process during distributed training.
256
257
258
        xpu_backend (`str`, *optional*):
            The backend to use for xpu distributed training. Must be one of `"mpi"` or `"ccl"`.
        tpu_num_cores (`int`, *optional*):
Tiger's avatar
Tiger committed
259
            When training on TPU, the number of TPU cores (automatically passed by launcher script).
260
        dataloader_drop_last (`bool`, *optional*, defaults to `False`):
261
262
            Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
            or not.
263
        eval_steps (`int`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
264
265
            Number of update steps between two evaluations if `evaluation_strategy="steps"`. Will default to the same
            value as `logging_steps` if not set.
266
        dataloader_num_workers (`int`, *optional*, defaults to 0):
Sylvain Gugger's avatar
Sylvain Gugger committed
267
268
            Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the
            main process.
269
        past_index (`int`, *optional*, defaults to -1):
Sylvain Gugger's avatar
Sylvain Gugger committed
270
271
272
273
            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`.
274
        run_name (`str`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
275
276
            A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and
            [mlflow](https://www.mlflow.org/) logging.
277
        disable_tqdm (`bool`, *optional*):
278
            Whether or not to disable the tqdm progress bars and table of metrics produced by
Sylvain Gugger's avatar
Sylvain Gugger committed
279
280
            [`~notebook.NotebookTrainingTracker`] in Jupyter Notebooks. Will default to `True` if the logging level is
            set to warn or lower (default), `False` otherwise.
281
282
        remove_unused_columns (`bool`, *optional*, defaults to `True`):
            If using `datasets.Dataset` datasets, whether or not to automatically remove the columns unused by the
283
            model forward method.
284

285
286
            (Note that this behavior is not implemented for [`TFTrainer`] yet.)
        label_names (`List[str]`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
287
            The list of keys in your dictionary of inputs that correspond to the labels.
Sylvain Gugger's avatar
Sylvain Gugger committed
288

Sylvain Gugger's avatar
Sylvain Gugger committed
289
290
            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"]`.
291
        load_best_model_at_end (`bool`, *optional*, defaults to `False`):
Sylvain Gugger's avatar
Sylvain Gugger committed
292
            Whether or not to load the best model found during training at the end of training.
293

294
295
            <Tip>

Sylvain Gugger's avatar
Sylvain Gugger committed
296
297
            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`.
298
299

            </Tip>
300

301
302
        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
Sylvain Gugger's avatar
Sylvain Gugger committed
303
304
            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).
305

Sylvain Gugger's avatar
Sylvain Gugger committed
306
307
            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.
308
        greater_is_better (`bool`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
309
310
            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:
311

Sylvain Gugger's avatar
Sylvain Gugger committed
312
            - `True` if `metric_for_best_model` is set to a value that isn't `"loss"` or `"eval_loss"`.
313
314
            - `False` if `metric_for_best_model` is not set, or set to `"loss"` or `"eval_loss"`.
        ignore_data_skip (`bool`, *optional*, defaults to `False`):
315
            When resuming training, whether or not to skip the epochs and batches to get the data loading at the same
Sylvain Gugger's avatar
Sylvain Gugger committed
316
317
            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.
318
319
        sharded_ddp (`bool`, `str` or list of [`~trainer_utils.ShardedDDPOption`], *optional*, defaults to `False`):
            Use Sharded DDP training from [FairScale](https://github.com/facebookresearch/fairscale) (in distributed
320
            training only). This is an experimental feature.
321
322
323

            A list of options along the following:

Sylvain Gugger's avatar
Sylvain Gugger committed
324
325
326
327
328
            - `"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`).
329
            - `"offload"`: to add ZeRO-offload (only compatible with `"zero_dp_2"` and `"zero_dp_3"`).
330
331

            If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty
332
333
334
            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
335
            evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,
336
337
            `ds_config.json`) or an already loaded json file as a `dict`"
        label_smoothing_factor (`float`, *optional*, defaults to 0.0):
Sylvain Gugger's avatar
Sylvain Gugger committed
338
            The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded
Sylvain Gugger's avatar
Sylvain Gugger committed
339
340
            labels are changed from 0s and 1s to `label_smoothing_factor/num_labels` and `1 - label_smoothing_factor +
            label_smoothing_factor/num_labels` respectively.
341
        debug (`str` or list of [`~debug_utils.DebugOption`], *optional*, defaults to `""`):
342
343
344
345
            Enable one or more debug features. This is an experimental feature.

            Possible options are:

Sylvain Gugger's avatar
Sylvain Gugger committed
346
347
            - `"underflow_overflow"`: detects overflow in model's input/outputs and reports the last frames that led to
              the event
348
            - `"tpu_metrics_debug"`: print debug metrics on TPU
349
350

            The options should be separated by whitespaces.
351
352
        optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_hf"`):
            The optimizer to use: adamw_hf, adamw_torch, adamw_apex_fused, or adafactor.
353
        adafactor (`bool`, *optional*, defaults to `False`):
354
            This argument is deprecated. Use `--optim adafactor` instead.
355
        group_by_length (`bool`, *optional*, defaults to `False`):
JohnnyC08's avatar
JohnnyC08 committed
356
            Whether or not to group together samples of roughly the same length in the training dataset (to minimize
357
            padding applied and be more efficient). Only useful if applying dynamic padding.
358
        length_column_name (`str`, *optional*, defaults to `"length"`):
359
            Column name for precomputed lengths. If the column exists, grouping by length will use these values rather
Sylvain Gugger's avatar
Sylvain Gugger committed
360
361
            than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an
            instance of `Dataset`.
362
363
        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"`,
Sylvain Gugger's avatar
Sylvain Gugger committed
364
365
            `"comet_ml"`, `"mlflow"`, `"tensorboard"` and `"wandb"`. Use `"all"` to report to all integrations
            installed, `"none"` for no integrations.
366
367
        ddp_find_unused_parameters (`bool`, *optional*):
            When using distributed training, the value of the flag `find_unused_parameters` passed to
Sylvain Gugger's avatar
Sylvain Gugger committed
368
            `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
369
        ddp_bucket_cap_mb (`int`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
370
            When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.
371
372
373
        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`):
374
375
            Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows
            down the training and evaluation speed.
376
        push_to_hub (`bool`, *optional*, defaults to `False`):
Sylvain Gugger's avatar
Sylvain Gugger committed
377
378
            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
379
380
            content will be pushed each time a save is triggered (depending on your `save_strategy`). Calling
            [`~Trainer.save_model`] will also trigger a push.
Sylvain Gugger's avatar
Sylvain Gugger committed
381
382
383
384

            <Tip warning={true}>

            If `output_dir` exists, it needs to be a local clone of the repository to which the [`Trainer`] will be
Sylvain Gugger's avatar
Sylvain Gugger committed
385
            pushed.
Sylvain Gugger's avatar
Sylvain Gugger committed
386
387
388

            </Tip>

389
        resume_from_checkpoint (`str`, *optional*):
390
            The path to a folder with a valid checkpoint for your model. This argument is not directly used by
Sylvain Gugger's avatar
Sylvain Gugger committed
391
            [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example
392
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
393
394
        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
395
            which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
396
            for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
Sylvain Gugger's avatar
Sylvain Gugger committed
397
398
            `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the
            name of `output_dir`.
399

400
401
            Will default to to the name of `output_dir`.
        hub_strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
402
403
            Defines the scope of what is pushed to the Hub and when. Possible values are:

Sylvain Gugger's avatar
Sylvain Gugger committed
404
            - `"end"`: push the model, its configuration, the tokenizer (if passed along to the [`Trainer`]) and a
Sylvain Gugger's avatar
Sylvain Gugger committed
405
              draft of a model card when the [`~Trainer.save_model`] method is called.
Sylvain Gugger's avatar
Sylvain Gugger committed
406
407
408
409
410
411
            - `"every_save"`: push the model, its configuration, the tokenizer (if passed along to the [`Trainer`]) and
              a draft of a model card each time there is a model save. The pushes are asynchronous to not block
              training, and in case the save are very frequent, a new push is only attempted if the previous one is
              finished. A last push is made with the final model at the end of training.
            - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
              last-checkpoint, allowing you to resume training easily with
412
              `trainer.train(resume_from_checkpoint="last-checkpoint")`.
Sylvain Gugger's avatar
Sylvain Gugger committed
413
414
            - `"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)
415

416
        hub_token (`str`, *optional*):
417
            The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
418
419
            `huggingface-cli login`.
        gradient_checkpointing (`bool`, *optional*, defaults to `False`):
420
            If True, use gradient checkpointing to save memory at the expense of slower backward pass.
421
422
423
        include_inputs_for_metrics (`bool`, *optional*, defaults to `False`):
            Whether or not the inputs will be passed to the `compute_metrics` function. This is intended for metrics
            that need inputs, predictions and references for scoring calculation in Metric class.
424
425
    """

426
    output_dir: str = field(
427
        metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
428
429
    )
    overwrite_output_dir: bool = field(
430
431
432
        default=False,
        metadata={
            "help": (
433
                "Overwrite the content of the output directory. "
434
435
436
                "Use this to continue training if output_dir points to a checkpoint directory."
            )
        },
437
438
439
    )

    do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
440
    do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
Julien Chaumond's avatar
Julien Chaumond committed
441
    do_predict: bool = field(default=False, metadata={"help": "Whether to run predictions on the test set."})
442
    evaluation_strategy: IntervalStrategy = field(
443
        default="no",
Sylvain Gugger's avatar
Sylvain Gugger committed
444
        metadata={"help": "The evaluation strategy to use."},
445
    )
446
    prediction_loss_only: bool = field(
Lysandre's avatar
Lysandre committed
447
448
        default=False,
        metadata={"help": "When performing evaluation and predictions, only returns the loss."},
449
    )
450

451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    per_device_train_batch_size: int = field(
        default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."}
    )
    per_device_eval_batch_size: int = field(
        default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}
    )

    per_gpu_train_batch_size: Optional[int] = field(
        default=None,
        metadata={
            "help": "Deprecated, the use of `--per_device_train_batch_size` is preferred. "
            "Batch size per GPU/TPU core/CPU for training."
        },
    )
    per_gpu_eval_batch_size: Optional[int] = field(
        default=None,
        metadata={
468
            "help": "Deprecated, the use of `--per_device_eval_batch_size` is preferred. "
469
470
471
472
            "Batch size per GPU/TPU core/CPU for evaluation."
        },
    )

473
    gradient_accumulation_steps: int = field(
474
475
        default=1,
        metadata={"help": "Number of updates steps to accumulate before performing a backward/update pass."},
476
    )
477
478
479
480
    eval_accumulation_steps: Optional[int] = field(
        default=None,
        metadata={"help": "Number of predictions steps to accumulate before moving the tensors to the CPU."},
    )
481

482
483
    eval_delay: Optional[float] = field(
        default=0,
Sylvain Gugger's avatar
Sylvain Gugger committed
484
485
486
487
        metadata={
            "help": "Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy."
        },
    )
488

489
490
491
492
493
    learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
    weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
    adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
    adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
    adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
494
495
496
497
498
499
500
    max_grad_norm: float = field(default=1.0, metadata={"help": "Max gradient norm."})

    num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
    max_steps: int = field(
        default=-1,
        metadata={"help": "If > 0: set total number of training steps to perform. Override num_train_epochs."},
    )
Sylvain Gugger's avatar
Sylvain Gugger committed
501
502
503
504
    lr_scheduler_type: SchedulerType = field(
        default="linear",
        metadata={"help": "The scheduler type to use."},
    )
505
506
507
    warmup_ratio: float = field(
        default=0.0, metadata={"help": "Linear warmup over warmup_ratio fraction of total steps."}
    )
508
509
    warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})

510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    log_level: Optional[str] = field(
        default="passive",
        metadata={
            "help": "Logger log level to use on the main node. 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. Defaults to 'passive'.",
            "choices": trainer_log_levels.keys(),
        },
    )
    log_level_replica: Optional[str] = field(
        default="passive",
        metadata={
            "help": "Logger log level to use on replica nodes. Same choices and defaults as ``log_level``",
            "choices": trainer_log_levels.keys(),
        },
    )
    log_on_each_node: bool = field(
        default=True,
        metadata={
            "help": "When doing a multinode distributed training, whether to log once per node or just once on the main node."
        },
    )
530
    logging_dir: Optional[str] = field(default=None, metadata={"help": "Tensorboard log dir."})
531
    logging_strategy: IntervalStrategy = field(
532
533
534
        default="steps",
        metadata={"help": "The logging strategy to use."},
    )
535
    logging_first_step: bool = field(default=False, metadata={"help": "Log the first global_step"})
536
    logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."})
537
    logging_nan_inf_filter: bool = field(default=True, metadata={"help": "Filter nan and inf losses for logging."})
538
539
540
541
    save_strategy: IntervalStrategy = field(
        default="steps",
        metadata={"help": "The checkpoint save strategy to use."},
    )
542
543
544
545
    save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."})
    save_total_limit: Optional[int] = field(
        default=None,
        metadata={
546
            "help": (
547
                "Limit the total amount of checkpoints. "
548
549
                "Deletes the older checkpoints in the output_dir. Default is unlimited checkpoints"
            )
550
551
        },
    )
552
553
554
555
556
557
    save_on_each_node: bool = field(
        default=False,
        metadata={
            "help": "When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one"
        },
    )
Lysandre Debut's avatar
Lysandre Debut committed
558
    no_cuda: bool = field(default=False, metadata={"help": "Do not use CUDA even when it is available"})
559
    seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
560
    data_seed: int = field(default=None, metadata={"help": "Random seed to be used with data samplers."})
561
562
563
564
565
566
    bf16: bool = field(
        default=False,
        metadata={
            "help": "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA architecture. This is an experimental API and it may change."
        },
    )
567
568
    fp16: bool = field(
        default=False,
569
        metadata={"help": "Whether to use fp16 (mixed) precision instead of 32-bit"},
570
571
572
573
    )
    fp16_opt_level: str = field(
        default="O1",
        metadata={
574
            "help": (
575
                "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
576
577
                "See details at https://nvidia.github.io/apex/amp.html"
            )
578
579
        },
    )
580
    half_precision_backend: str = field(
581
        default="auto",
582
583
584
585
586
587
588
        metadata={"help": "The backend to be used for half precision.", "choices": ["auto", "amp", "apex"]},
    )
    bf16_full_eval: bool = field(
        default=False,
        metadata={
            "help": "Whether to use full bfloat16 evaluation instead of 32-bit. This is an experimental API and it may change."
        },
589
    )
590
591
    fp16_full_eval: bool = field(
        default=False,
592
        metadata={"help": "Whether to use full float16 evaluation instead of 32-bit"},
593
    )
594
595
596
597
598
599
    tf32: bool = field(
        default=None,
        metadata={
            "help": "Whether to enable tf32 mode, available in Ampere and newer GPU architectures. This is an experimental API and it may change."
        },
    )
600
    local_rank: int = field(default=-1, metadata={"help": "For distributed training: local_rank"})
601
602
603
604
    xpu_backend: str = field(
        default=None,
        metadata={"help": "The backend to be used for distributed training on Intel XPU.", "choices": ["mpi", "ccl"]},
    )
Lysandre Debut's avatar
Lysandre Debut committed
605
606
607
    tpu_num_cores: Optional[int] = field(
        default=None, metadata={"help": "TPU: Number of TPU cores (automatically passed by launcher script)"}
    )
608
609
    tpu_metrics_debug: bool = field(
        default=False,
610
611
612
613
614
615
616
617
618
619
620
        metadata={
            "help": "Deprecated, the use of `--debug tpu_metrics_debug` is preferred. TPU: Whether to print debug metrics"
        },
    )
    debug: str = field(
        default="",
        metadata={
            "help": "Whether or not to enable debug mode. Current options: "
            "`underflow_overflow` (Detect underflow and overflow in activations and weights), "
            "`tpu_metrics_debug` (print debug metrics on TPU)."
        },
621
    )
Lysandre Debut's avatar
Lysandre Debut committed
622

Setu Shah's avatar
Setu Shah committed
623
624
625
    dataloader_drop_last: bool = field(
        default=False, metadata={"help": "Drop the last incomplete batch if it is not divisible by the batch size."}
    )
626
    eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."})
Chady Kamar's avatar
Chady Kamar committed
627
628
    dataloader_num_workers: int = field(
        default=0,
Sylvain Gugger's avatar
Sylvain Gugger committed
629
630
631
        metadata={
            "help": "Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process."
        },
Chady Kamar's avatar
Chady Kamar committed
632
    )
Setu Shah's avatar
Setu Shah committed
633

634
635
636
637
638
    past_index: int = field(
        default=-1,
        metadata={"help": "If >=0, uses the corresponding part of the output as the past state for next step."},
    )

639
640
641
    run_name: Optional[str] = field(
        default=None, metadata={"help": "An optional descriptor for the run. Notably used for wandb logging."}
    )
642
643
644
645
    disable_tqdm: Optional[bool] = field(
        default=None, metadata={"help": "Whether or not to disable the tqdm progress bars."}
    )

646
647
648
    remove_unused_columns: Optional[bool] = field(
        default=True, metadata={"help": "Remove columns not required by the model when using an nlp.Dataset."}
    )
Sylvain Gugger's avatar
Sylvain Gugger committed
649
650
651
652
    label_names: Optional[List[str]] = field(
        default=None, metadata={"help": "The list of keys in your dictionary of inputs that correspond to the labels."}
    )

653
654
655
656
657
658
659
660
661
662
    load_best_model_at_end: Optional[bool] = field(
        default=False,
        metadata={"help": "Whether or not to load the best model found during training at the end of training."},
    )
    metric_for_best_model: Optional[str] = field(
        default=None, metadata={"help": "The metric to use to compare two different models."}
    )
    greater_is_better: Optional[bool] = field(
        default=None, metadata={"help": "Whether the `metric_for_best_model` should be maximized or not."}
    )
663
664
665
666
667
668
    ignore_data_skip: bool = field(
        default=False,
        metadata={
            "help": "When resuming training, whether or not to skip the first epochs and batches to get to the same training data."
        },
    )
669
670
671
672
673
    sharded_ddp: str = field(
        default="",
        metadata={
            "help": "Whether or not to use sharded DDP training (in distributed training only). The base option "
            "should be `simple`, `zero_dp_2` or `zero_dp_3` and you can add CPU-offload to `zero_dp_2` or `zero_dp_3` "
674
675
            "like this: zero_dp_2 offload` or `zero_dp_3 offload`. You can add auto-wrap to `zero_dp_2` or "
            "with the same syntax: zero_dp_2 auto_wrap` or `zero_dp_3 auto_wrap`.",
676
        },
677
    )
678
679
    deepspeed: Optional[str] = field(
        default=None,
680
681
682
        metadata={
            "help": "Enable deepspeed and pass the path to deepspeed json config file (e.g. ds_config.json) or an already loaded json file as a dict"
        },
683
    )
Sylvain Gugger's avatar
Sylvain Gugger committed
684
685
686
    label_smoothing_factor: float = field(
        default=0.0, metadata={"help": "The label smoothing epsilon to apply (zero means no label smoothing)."}
    )
687
688
689
690
    optim: OptimizerNames = field(
        default="adamw_hf",
        metadata={"help": "The optimizer to use."},
    )
691
    adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
692
693
694
695
    group_by_length: bool = field(
        default=False,
        metadata={"help": "Whether or not to group samples of roughly the same length together when batching."},
    )
696
697
698
699
    length_column_name: Optional[str] = field(
        default="length",
        metadata={"help": "Column name with precomputed lengths to use when grouping by length."},
    )
700
701
702
    report_to: Optional[List[str]] = field(
        default=None, metadata={"help": "The list of integrations to report the results and logs to."}
    )
703
704
705
706
707
708
709
    ddp_find_unused_parameters: Optional[bool] = field(
        default=None,
        metadata={
            "help": "When using distributed training, the value of the flag `find_unused_parameters` passed to "
            "`DistributedDataParallel`."
        },
    )
710
711
712
713
714
715
716
    ddp_bucket_cap_mb: Optional[int] = field(
        default=None,
        metadata={
            "help": "When using distributed training, the value of the flag `bucket_cap_mb` passed to "
            "`DistributedDataParallel`."
        },
    )
717
718
719
    dataloader_pin_memory: bool = field(
        default=True, metadata={"help": "Whether or not to pin memory for DataLoader."}
    )
720
    skip_memory_metrics: bool = field(
721
        default=True, metadata={"help": "Whether or not to skip adding of memory profiler reports to metrics."}
722
    )
723
724
725
    use_legacy_prediction_loop: bool = field(
        default=False, metadata={"help": "Whether or not to use the legacy prediction_loop in the Trainer."}
    )
Sylvain Gugger's avatar
Sylvain Gugger committed
726
727
728
    push_to_hub: bool = field(
        default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."}
    )
729
730
731
732
    resume_from_checkpoint: Optional[str] = field(
        default=None,
        metadata={"help": "The path to a folder with a valid checkpoint for your model."},
    )
733
734
735
    hub_model_id: str = field(
        default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."}
    )
736
737
738
739
    hub_strategy: HubStrategy = field(
        default="every_save",
        metadata={"help": "The hub strategy to use when `--push_to_hub` is activated."},
    )
740
    hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."})
741
742
743
744
745
746
    gradient_checkpointing: bool = field(
        default=False,
        metadata={
            "help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass."
        },
    )
747
748
749
    include_inputs_for_metrics: bool = field(
        default=False, metadata={"help": "Whether or not the inputs will be passed to the `compute_metrics` function."}
    )
750
    # Deprecated arguments
751
752
753
754
    fp16_backend: str = field(
        default="auto",
        metadata={"help": "Deprecated. Use half_precision_backend instead", "choices": ["auto", "amp", "apex"]},
    )
755
756
757
758
759
760
761
    push_to_hub_model_id: str = field(
        default=None, metadata={"help": "The name of the repository to which push the `Trainer`."}
    )
    push_to_hub_organization: str = field(
        default=None, metadata={"help": "The name of the organization in with to which push the `Trainer`."}
    )
    push_to_hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."})
762
    _n_gpu: int = field(init=False, repr=False, default=-1)
Sylvain Gugger's avatar
Sylvain Gugger committed
763
764
765
766
    mp_parameters: str = field(
        default="",
        metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in Trainer"},
    )
767

Sylvain Gugger's avatar
Sylvain Gugger committed
768
    def __post_init__(self):
769
770
771
772
773
774
        # Handle --use_env option in torch.distributed.launch (local_rank not passed as an arg then).
        # This needs to happen before any call to self.device or self.n_gpu.
        env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
        if env_local_rank != -1 and env_local_rank != self.local_rank:
            self.local_rank = env_local_rank

775
        # convert to int
776
        self.log_level = trainer_log_levels[self.log_level]
777
        self.log_level_replica = trainer_log_levels[self.log_level_replica]
778

779
780
781
782
783
        # expand paths, if not os.makedirs("~/bar") will make directory
        # in the current directory instead of the actual home
        # 聽see https://github.com/huggingface/transformers/issues/10628
        if self.output_dir is not None:
            self.output_dir = os.path.expanduser(self.output_dir)
784
785
        if self.logging_dir is None and self.output_dir is not None:
            self.logging_dir = os.path.join(self.output_dir, default_logdir())
786
787
788
        if self.logging_dir is not None:
            self.logging_dir = os.path.expanduser(self.logging_dir)

Sylvain Gugger's avatar
Sylvain Gugger committed
789
790
        if self.disable_tqdm is None:
            self.disable_tqdm = logger.getEffectiveLevel() > logging.WARN
791
792
793
794
795
796

        if isinstance(self.evaluation_strategy, EvaluationStrategy):
            warnings.warn(
                "using `EvaluationStrategy` for `evaluation_strategy` is deprecated and will be removed in version 5 of 馃 Transformers. Use `IntervalStrategy` instead",
                FutureWarning,
            )
797
798
            # Go back to the underlying string or we won't be able to instantiate `IntervalStrategy` on it.
            self.evaluation_strategy = self.evaluation_strategy.value
799
800
801
802

        self.evaluation_strategy = IntervalStrategy(self.evaluation_strategy)
        self.logging_strategy = IntervalStrategy(self.logging_strategy)
        self.save_strategy = IntervalStrategy(self.save_strategy)
803
        self.hub_strategy = HubStrategy(self.hub_strategy)
804

Sylvain Gugger's avatar
Sylvain Gugger committed
805
        self.lr_scheduler_type = SchedulerType(self.lr_scheduler_type)
806
        if self.do_eval is False and self.evaluation_strategy != IntervalStrategy.NO:
807
            self.do_eval = True
808
809
810
811
812
813
814
815
816
817
818
819
820
821

        # eval_steps has to be defined and non-zero, fallbacks to logging_steps if the latter is non-zero
        if self.evaluation_strategy == IntervalStrategy.STEPS and (self.eval_steps is None or self.eval_steps == 0):
            if self.logging_steps > 0:
                logger.info(f"using `logging_steps` to initialize `eval_steps` to {self.logging_steps}")
                self.eval_steps = self.logging_steps
            else:
                raise ValueError(
                    f"evaluation strategy {self.evaluation_strategy} requires either non-zero --eval_steps or --logging_steps"
                )

        # logging_steps must be non-zero for logging_strategy that is other than 'no'
        if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps == 0:
            raise ValueError(f"logging strategy {self.logging_strategy} requires non-zero --logging_steps")
822

823
824
825
826
827
828
829
830
831
832
833
834
835
        # Sanity checks for load_best_model_at_end: we require save and eval strategies to be compatible.
        if self.load_best_model_at_end:
            if self.evaluation_strategy != self.save_strategy:
                raise ValueError(
                    "--load_best_model_at_end requires the save and eval strategy to match, but found\n- Evaluation "
                    f"strategy: {self.evaluation_strategy}\n- Save strategy: {self.save_strategy}"
                )
            if self.evaluation_strategy == IntervalStrategy.STEPS and self.save_steps % self.eval_steps != 0:
                raise ValueError(
                    "--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation "
                    f"steps, but found {self.save_steps}, which is not a round multiple of {self.eval_steps}."
                )

836
837
838
839
        if self.load_best_model_at_end and self.metric_for_best_model is None:
            self.metric_for_best_model = "loss"
        if self.greater_is_better is None and self.metric_for_best_model is not None:
            self.greater_is_better = self.metric_for_best_model not in ["loss", "eval_loss"]
840
841
        if self.run_name is None:
            self.run_name = self.output_dir
842

843
844
845
846
847
848
849
        if self.fp16_backend and self.fp16_backend != "auto":
            warnings.warn(
                "`fp16_backend` is deprecated and will be removed in version 5 of 馃 Transformers. Use `half_precision_backend` instead",
                FutureWarning,
            )
            self.half_precision_backend = self.fp16_backend

Stas Bekman's avatar
Stas Bekman committed
850
851
852
        if (self.bf16 or self.bf16_full_eval) and not is_torch_bf16_available():
            raise ValueError("Your setup doesn't support bf16. You need Ampere GPU, torch>=1.10, cuda>=11.0")

853
854
855
856
857
858
859
860
861
        if self.fp16 and self.bf16:
            raise ValueError("At most one of fp16 and bf16 can be True, but not both")
        if self.bf16:
            if self.half_precision_backend == "apex":
                raise ValueError(
                    " `--half_precision_backend apex`: bf16 is not supported by apex. Use `--half_precision_backend amp` instead"
                )
            if not (self.sharded_ddp == "" or not self.sharded_ddp):
                raise ValueError("sharded_ddp is not supported with bf16")
862
863
864
865
866
867
868
869
870

        self.optim = OptimizerNames(self.optim)
        if self.adafactor:
            warnings.warn(
                "`--adafactor` is deprecated and will be removed in version 5 of 馃 Transformers. Use `--optim adafactor` instead",
                FutureWarning,
            )
            self.optim = OptimizerNames.ADAFACTOR

871
872
        if (
            is_torch_available()
873
874
            and (self.device.type != "cuda")
            and not (self.device.type == "xla" and "GPU_NUM_DEVICES" in os.environ)
875
876
            and (self.fp16 or self.fp16_full_eval or self.bf16 or self.bf16_full_eval)
        ):
877
            raise ValueError(
878
                "Mixed precision training with AMP or APEX (`--fp16` or `--bf16`) and half precision evaluation (`--fp16_full_eval` or `--bf16_full_eval`) can only be used on CUDA devices."
879
            )
880

881
882
883
884
885
886
887
888
889
890
891
        if is_torch_available() and self.tf32 is not None:
            if self.tf32:
                if is_torch_tf32_available():
                    torch.backends.cuda.matmul.allow_tf32 = True
                else:
                    raise ValueError("--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7")
            else:
                if is_torch_tf32_available():
                    torch.backends.cuda.matmul.allow_tf32 = False
                # no need to assert on else

892
        if self.report_to is None:
893
894
895
896
897
898
899
            logger.info(
                "The default value for the training argument `--report_to` will change in v5 (from all installed "
                "integrations to none). In v5, you will need to use `--report_to all` to get the same behavior as "
                "now. You should start updating your code and make this info disappear :-)."
            )
            self.report_to = "all"
        if self.report_to == "all" or self.report_to == ["all"]:
900
901
902
903
            # Import at runtime to avoid a circular import.
            from .integrations import get_available_reporting_integrations

            self.report_to = get_available_reporting_integrations()
904
905
906
907
        elif self.report_to == "none" or self.report_to == ["none"]:
            self.report_to = []
        elif not isinstance(self.report_to, list):
            self.report_to = [self.report_to]
908

909
910
911
912
913
914
915
        if self.warmup_ratio < 0 or self.warmup_ratio > 1:
            raise ValueError("warmup_ratio must lie in range [0,1]")
        elif self.warmup_ratio > 0 and self.warmup_steps > 0:
            logger.info(
                "Both warmup_ratio and warmup_steps given, warmup_steps will override any effect of warmup_ratio during training"
            )

916
917
918
919
920
921
922
923
924
        if isinstance(self.sharded_ddp, bool):
            self.sharded_ddp = "simple" if self.sharded_ddp else ""
        if isinstance(self.sharded_ddp, str):
            self.sharded_ddp = [ShardedDDPOption(s) for s in self.sharded_ddp.split()]
        if self.sharded_ddp == [ShardedDDPOption.OFFLOAD]:
            raise ValueError(
                "`--sharded_ddp offload` can't work on its own. It needs to be added to `--sharded_ddp zero_dp_2` or "
                '`--sharded_ddp zero_dp_3`. For example, `--sharded_ddp "zero_dp_2 offload"`.'
            )
925
        elif len(self.sharded_ddp) > 1 and ShardedDDPOption.SIMPLE in self.sharded_ddp:
926
927
928
929
            raise ValueError("`--sharded_ddp simple` is not compatible with any other option.")
        elif ShardedDDPOption.ZERO_DP_2 in self.sharded_ddp and ShardedDDPOption.ZERO_DP_3 in self.sharded_ddp:
            raise ValueError("`--sharded_ddp zero_dp_2` is not compatible with `--sharded_ddp zero_dp_3`.")

930
931
932
933
934
935
936
937
938
939
        if self.tpu_metrics_debug:
            warnings.warn(
                "using `--tpu_metrics_debug` is deprecated and will be removed in version 5 of 馃 Transformers. Use `--debug tpu_metrics_debug` instead",
                FutureWarning,
            )
            self.debug += " tpu_metrics_debug"
            self.tpu_metrics_debug = False
        if isinstance(self.debug, str):
            self.debug = [DebugOption(s) for s in self.debug.split()]

940
941
942
        if self.deepspeed:
            # - must be run very last in arg parsing, since it will use a lot of these settings.
            # - must be run before the model is created.
943
            from transformers.deepspeed import HfTrainerDeepSpeedConfig
944

945
946
947
948
            # will be used later by the Trainer
            # note: leave self.deepspeed unmodified in case a user relies on it not to be modified)
            self.hf_deepspeed_config = HfTrainerDeepSpeedConfig(self.deepspeed)
            self.hf_deepspeed_config.trainer_config_process(self)
949

950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
        if self.push_to_hub_token is not None:
            warnings.warn(
                "`--push_to_hub_token` is deprecated and will be removed in version 5 of 馃 Transformers. Use "
                "`--hub_token` instead.",
                FutureWarning,
            )
            self.hub_token = self.push_to_hub_token

        if self.push_to_hub_model_id is not None:
            self.hub_model_id = get_full_repo_name(
                self.push_to_hub_model_id, organization=self.push_to_hub_organization, token=self.hub_token
            )
            if self.push_to_hub_organization is not None:
                warnings.warn(
                    "`--push_to_hub_model_id` and `--push_to_hub_organization` are deprecated and will be removed in "
                    "version 5 of 馃 Transformers. Use `--hub_model_id` instead and pass the full repo name to this "
                    f"argument (in this case {self.hub_model_id}).",
                    FutureWarning,
                )
            else:
                warnings.warn(
                    "`--push_to_hub_model_id` is deprecated and will be removed in version 5 of 馃 Transformers. Use "
                    "`--hub_model_id` instead and pass the full repo name to this argument (in this case "
                    f"{self.hub_model_id}).",
                    FutureWarning,
                )
        elif self.push_to_hub_organization is not None:
            self.hub_model_id = f"{self.push_to_hub_organization}/{Path(self.output_dir).name}"
            warnings.warn(
                "`--push_to_hub_organization` is deprecated and will be removed in version 5 of 馃 Transformers. Use "
                "`--hub_model_id` instead and pass the full repo name to this argument (in this case "
                f"{self.hub_model_id}).",
                FutureWarning,
            )
984

985
    def __str__(self):
986
        self_as_dict = asdict(self)
987
988
989

        # Remove deprecated arguments. That code should be removed once
        # those deprecated arguments are removed from TrainingArguments. (TODO: v5)
990
991
        del self_as_dict["per_gpu_train_batch_size"]
        del self_as_dict["per_gpu_eval_batch_size"]
992

993
994
        self_as_dict = {k: f"<{k.upper()}>" if k.endswith("_token") else v for k, v in self_as_dict.items()}

995
996
997
998
        attrs_as_str = [f"{k}={v},\n" for k, v in sorted(self_as_dict.items())]
        return f"{self.__class__.__name__}(\n{''.join(attrs_as_str)})"

    __repr__ = __str__
999

Julien Chaumond's avatar
Julien Chaumond committed
1000
1001
    @property
    def train_batch_size(self) -> int:
1002
        """
1003
        The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training).
1004
        """
1005
1006
1007
1008
1009
1010
        if self.per_gpu_train_batch_size:
            logger.warning(
                "Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future "
                "version. Using `--per_device_train_batch_size` is preferred."
            )
        per_device_batch_size = self.per_gpu_train_batch_size or self.per_device_train_batch_size
1011
        train_batch_size = per_device_batch_size * max(1, self.n_gpu)
1012
        return train_batch_size
Julien Chaumond's avatar
Julien Chaumond committed
1013
1014
1015

    @property
    def eval_batch_size(self) -> int:
1016
        """
1017
        The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training).
1018
        """
1019
1020
1021
1022
1023
1024
        if self.per_gpu_eval_batch_size:
            logger.warning(
                "Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future "
                "version. Using `--per_device_eval_batch_size` is preferred."
            )
        per_device_batch_size = self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
1025
        eval_batch_size = per_device_batch_size * max(1, self.n_gpu)
1026
        return eval_batch_size
Julien Chaumond's avatar
Julien Chaumond committed
1027
1028
1029

    @cached_property
    @torch_required
1030
    def _setup_devices(self) -> "torch.device":
Julien Chaumond's avatar
Julien Chaumond committed
1031
        logger.info("PyTorch: setting up devices")
1032
1033
1034
1035
1036
        if torch.distributed.is_initialized() and self.local_rank == -1:
            logger.warning(
                "torch.distributed process group is initialized, but local_rank == -1. "
                "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"
            )
Julien Chaumond's avatar
Julien Chaumond committed
1037
1038
        if self.no_cuda:
            device = torch.device("cpu")
1039
            self._n_gpu = 0
1040
            if self.local_rank != -1 and not torch.distributed.is_initialized():
1041
1042
1043
1044
1045
1046
1047
                # Initializes distributed backend for cpu
                if self.xpu_backend not in ("mpi", "ccl"):
                    raise ValueError(
                        "CPU distributed training backend is not properly set. "
                        "Please set '--xpu_backend' to either 'mpi' or 'ccl'."
                    )
                torch.distributed.init_process_group(backend=self.xpu_backend)
1048
        elif is_torch_tpu_available():
Lysandre Debut's avatar
Lysandre Debut committed
1049
            device = xm.xla_device()
1050
            self._n_gpu = 0
Sylvain Gugger's avatar
Sylvain Gugger committed
1051
1052
1053
1054
1055
        elif is_sagemaker_mp_enabled():
            local_rank = smp.local_rank()
            device = torch.device("cuda", local_rank)
            self._n_gpu = 1
        elif is_sagemaker_dp_enabled():
Lai Wei's avatar
Lai Wei committed
1056
1057
            dist.init_process_group(backend="smddp")
            self.local_rank = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK"))
Sylvain Gugger's avatar
Sylvain Gugger committed
1058
1059
            device = torch.device("cuda", self.local_rank)
            self._n_gpu = 1
1060
        elif self.deepspeed:
1061
            # deepspeed inits torch.distributed internally
1062
            from .deepspeed import is_deepspeed_available
1063
1064
1065
1066
1067
1068

            if not is_deepspeed_available():
                raise ImportError("--deepspeed requires deepspeed: `pip install deepspeed`.")
            import deepspeed

            deepspeed.init_distributed()
1069
1070
1071
1072
1073
1074

            # workaround for setups like notebooks where the launcher can't be used,
            # but deepspeed requires a dist env.
            # env LOCAL_RANK could be set manually by the user, or via init_distributed if mpi4py is installed
            self.local_rank = int(os.environ.get("LOCAL_RANK", "-1"))

1075
1076
            device = torch.device("cuda", self.local_rank)
            self._n_gpu = 1
Julien Chaumond's avatar
Julien Chaumond committed
1077
1078
1079
        elif self.local_rank == -1:
            # if n_gpu is > 1 we'll use nn.DataParallel.
            # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
1080
1081
1082
1083
1084
            # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
            # trigger an error that a device index is missing. Index 0 takes into account the
            # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
            # will use the first GPU in that env, i.e. GPU#1
            device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
1085
1086
            # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
            # the default value.
1087
            self._n_gpu = torch.cuda.device_count()
Julien Chaumond's avatar
Julien Chaumond committed
1088
1089
        else:
            # Here, we'll use torch.distributed.
1090
            # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
1091
1092
            if not torch.distributed.is_initialized():
                torch.distributed.init_process_group(backend="nccl")
Julien Chaumond's avatar
Julien Chaumond committed
1093
            device = torch.device("cuda", self.local_rank)
1094
            self._n_gpu = 1
1095
1096
1097
1098

        if device.type == "cuda":
            torch.cuda.set_device(device)

1099
        return device
Julien Chaumond's avatar
Julien Chaumond committed
1100
1101
1102
1103

    @property
    @torch_required
    def device(self) -> "torch.device":
1104
1105
1106
        """
        The device used by this process.
        """
1107
        return self._setup_devices
Julien Chaumond's avatar
Julien Chaumond committed
1108
1109
1110
1111

    @property
    @torch_required
    def n_gpu(self):
1112
1113
1114
1115
1116
1117
1118
        """
        The number of GPUs used by this process.

        Note:
            This will only be greater than one when you have multiple GPUs available but are not using distributed
            training. For distributed training, it will always be 1.
        """
1119
1120
1121
        # Make sure `self._n_gpu` is properly setup.
        _ = self._setup_devices
        return self._n_gpu
Julien Chaumond's avatar
Julien Chaumond committed
1122

1123
1124
1125
1126
1127
1128
    @property
    @torch_required
    def parallel_mode(self):
        """
        The current mode used for parallelism if multiple GPUs/TPU cores are available. One of:

1129
1130
1131
1132
1133
        - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU).
        - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`).
        - `ParallelMode.DISTRIBUTED`: several GPUs, each having its own process (uses
          `torch.nn.DistributedDataParallel`).
        - `ParallelMode.TPU`: several TPU cores.
1134
1135
1136
        """
        if is_torch_tpu_available():
            return ParallelMode.TPU
Sylvain Gugger's avatar
Sylvain Gugger committed
1137
1138
1139
1140
        elif is_sagemaker_mp_enabled():
            return ParallelMode.SAGEMAKER_MODEL_PARALLEL
        elif is_sagemaker_dp_enabled():
            return ParallelMode.SAGEMAKER_DATA_PARALLEL
1141
1142
1143
1144
1145
1146
1147
        elif self.local_rank != -1:
            return ParallelMode.DISTRIBUTED
        elif self.n_gpu > 1:
            return ParallelMode.NOT_DISTRIBUTED
        else:
            return ParallelMode.NOT_PARALLEL

1148
1149
1150
1151
1152
1153
1154
1155
    @property
    @torch_required
    def world_size(self):
        """
        The number of processes used in parallel.
        """
        if is_torch_tpu_available():
            return xm.xrt_world_size()
Sylvain Gugger's avatar
Sylvain Gugger committed
1156
        elif is_sagemaker_mp_enabled():
1157
            return smp.dp_size() if not smp.state.cfg.prescaled_batch else smp.rdp_size()
Sylvain Gugger's avatar
Sylvain Gugger committed
1158
        elif is_sagemaker_dp_enabled():
Lai Wei's avatar
Lai Wei committed
1159
            return dist.get_world_size()
1160
1161
1162
1163
        elif self.local_rank != -1:
            return torch.distributed.get_world_size()
        return 1

1164
1165
1166
1167
    @property
    @torch_required
    def process_index(self):
        """
1168
        The index of the current process used.
1169
1170
1171
        """
        if is_torch_tpu_available():
            return xm.get_ordinal()
Sylvain Gugger's avatar
Sylvain Gugger committed
1172
        elif is_sagemaker_mp_enabled():
1173
            return smp.dp_rank() if not smp.state.cfg.prescaled_batch else smp.rdp_rank()
Sylvain Gugger's avatar
Sylvain Gugger committed
1174
        elif is_sagemaker_dp_enabled():
Lai Wei's avatar
Lai Wei committed
1175
            return dist.get_rank()
1176
1177
1178
1179
        elif self.local_rank != -1:
            return torch.distributed.get_rank()
        return 0

1180
1181
1182
1183
1184
1185
1186
    @property
    @torch_required
    def local_process_index(self):
        """
        The index of the local process used.
        """
        if is_torch_tpu_available():
1187
            return xm.get_local_ordinal()
1188
1189
1190
        elif is_sagemaker_mp_enabled():
            return smp.local_rank()
        elif is_sagemaker_dp_enabled():
Lai Wei's avatar
Lai Wei committed
1191
            return dist.get_rank()
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
        elif self.local_rank != -1:
            return self.local_rank
        return 0

    @property
    def should_log(self):
        """
        Whether or not the current process should produce log.
        """
        if self.log_on_each_node:
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
            return self.local_process_index == 0
        else:
            if is_sagemaker_mp_enabled():
                return smp.rank() == 0
            else:
                return self.process_index == 0

    @property
    def should_save(self):
        """
        Whether or not the current process should write to disk, e.g., to save models and checkpoints.
        """
        if self.save_on_each_node:
1215
1216
1217
1218
1219
1220
1221
            return self.local_process_index == 0
        else:
            if is_sagemaker_mp_enabled():
                return smp.rank() == 0
            else:
                return self.process_index == 0

1222
1223
1224
1225
1226
    def get_process_log_level(self):
        """
        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.

1227
        For the main process the log level defaults to `logging.INFO` unless overridden by `log_level` argument.
1228

Sylvain Gugger's avatar
Sylvain Gugger committed
1229
1230
        For the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica`
        argument.
1231

Sylvain Gugger's avatar
Sylvain Gugger committed
1232
        The choice between the main and replica process settings is made according to the return value of `should_log`.
1233
1234
        """

1235
1236
1237
1238
        log_level_main_node = logging.INFO if self.log_level == -1 else self.log_level
        log_level_replica_node = logging.WARNING if self.log_level_replica == -1 else self.log_level_replica
        return log_level_main_node if self.should_log else log_level_replica_node

1239
1240
1241
1242
1243
    @property
    def place_model_on_device(self):
        """
        Can be subclassed and overridden for some specific integrations.
        """
Sylvain Gugger's avatar
Sylvain Gugger committed
1244
        return not is_sagemaker_mp_enabled()
1245

Sylvain Gugger's avatar
Sylvain Gugger committed
1246
1247
1248
1249
1250
    @property
    def _no_sync_in_gradient_accumulation(self):
        """
        Whether or not to use no_sync for the gradients when doing gradient accumulation.
        """
1251
        return not (self.deepspeed or is_sagemaker_dp_enabled() or is_sagemaker_mp_enabled())
Sylvain Gugger's avatar
Sylvain Gugger committed
1252

1253
1254
1255
    @contextlib.contextmanager
    def main_process_first(self, local=True, desc="work"):
        """
Sylvain Gugger's avatar
Sylvain Gugger committed
1256
1257
        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.
1258

Sylvain Gugger's avatar
Sylvain Gugger committed
1259
1260
1261
        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.
1262
1263

        Args:
1264
            local (`bool`, *optional*, defaults to `True`):
Sylvain Gugger's avatar
Sylvain Gugger committed
1265
1266
                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
1267
                `local=False` so that only the main process of the first node will do the processing. If however, the
1268
1269
                filesystem is not shared, then the main process of each node will need to do the processing, which is
                the default behavior.
1270
            desc (`str`, *optional*, defaults to `"work"`):
1271
1272
1273
1274
                a work description to be used in debug logs

        """
        if is_torch_available() and self.world_size > 1:
1275
            main_process_desc = "main process"
1276
1277
1278
            if local:
                is_main_process = self.local_process_index == 0
                main_process_desc = "main local process"
1279
1280
            elif is_sagemaker_mp_enabled():
                is_main_process = smp.rank() == 0
1281
1282
1283
1284
1285
1286
1287
            else:
                is_main_process = self.process_index == 0

            try:
                if not is_main_process:
                    # tell all replicas to wait
                    logger.debug(f"{self.process_index}: waiting for the {main_process_desc} to perform {desc}")
1288
1289
                    if is_torch_tpu_available():
                        xm.rendezvous(desc)
1290
                    elif is_sagemaker_dp_enabled():
Lai Wei's avatar
Lai Wei committed
1291
                        dist.barrier()
1292
1293
                    else:
                        torch.distributed.barrier()
1294
1295
1296
1297
1298
                yield
            finally:
                if is_main_process:
                    # the wait is over
                    logger.debug(f"{self.process_index}: {main_process_desc} completed {desc}, releasing all replicas")
1299
1300
                    if is_torch_tpu_available():
                        xm.rendezvous(desc)
1301
                    elif is_sagemaker_dp_enabled():
Lai Wei's avatar
Lai Wei committed
1302
                        dist.barrier()
1303
1304
                    else:
                        torch.distributed.barrier()
1305
1306
1307
        else:
            yield

1308
1309
1310
1311
1312
    def get_warmup_steps(self, num_training_steps: int):
        """
        Get number of steps used for a linear warmup.
        """
        warmup_steps = (
1313
            self.warmup_steps if self.warmup_steps > 0 else math.ceil(num_training_steps * self.warmup_ratio)
1314
1315
1316
        )
        return warmup_steps

1317
1318
    def to_dict(self):
        """
1319
1320
        Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
        the token values by removing their value.
1321
        """
1322
        d = asdict(self)
1323
1324
1325
        for k, v in d.items():
            if isinstance(v, Enum):
                d[k] = v.value
1326
1327
            if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):
                d[k] = [x.value for x in v]
1328
1329
            if k.endswith("_token"):
                d[k] = f"<{k.upper()}>"
1330
1331
        return d

Julien Chaumond's avatar
Julien Chaumond committed
1332
1333
1334
1335
    def to_json_string(self):
        """
        Serializes this instance to a JSON string.
        """
1336
        return json.dumps(self.to_dict(), indent=2)
1337
1338
1339
1340
1341

    def to_sanitized_dict(self) -> Dict[str, Any]:
        """
        Sanitized serialization to use with TensorBoard鈥檚 hparams
        """
1342
        d = self.to_dict()
1343
1344
        d = {**d, **{"train_batch_size": self.train_batch_size, "eval_batch_size": self.eval_batch_size}}

1345
1346
1347
        valid_types = [bool, int, float, str]
        if is_torch_available():
            valid_types.append(torch.Tensor)
1348

1349
        return {k: v if type(v) in valid_types else str(v) for k, v in d.items()}
1350
1351
1352
1353
1354
1355


class ParallelMode(Enum):
    NOT_PARALLEL = "not_parallel"
    NOT_DISTRIBUTED = "not_distributed"
    DISTRIBUTED = "distributed"
Sylvain Gugger's avatar
Sylvain Gugger committed
1356
1357
    SAGEMAKER_MODEL_PARALLEL = "sagemaker_model_parallel"
    SAGEMAKER_DATA_PARALLEL = "sagemaker_data_parallel"
1358
    TPU = "tpu"