training_args¶
-
class
TrainingArguments
(output_dir: str, overwrite_output_dir: bool = False, do_train: bool = False, do_eval: bool = False, do_predict: bool = False, do_export: bool = False, evaluation_strategy: paddlenlp.trainer.trainer_utils.IntervalStrategy = 'no', prediction_loss_only: bool = False, per_device_train_batch_size: int = 8, per_device_eval_batch_size: int = 8, gradient_accumulation_steps: int = 1, 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: str = 'linear', warmup_ratio: float = 0.0, warmup_steps: int = 0, log_on_each_node: bool = True, logging_dir: Optional[str] = None, logging_strategy: paddlenlp.trainer.trainer_utils.IntervalStrategy = 'steps', logging_first_step: bool = False, logging_steps: int = 500, save_strategy: paddlenlp.trainer.trainer_utils.IntervalStrategy = 'steps', save_steps: int = 500, save_total_limit: 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', bf16_full_eval: bool = False, fp16_full_eval: bool = False, sharding: str = '', sharding_degree: int = - 1, recompute: bool = False, scale_loss: float = 32768, minimum_eval_times: Optional[int] = None, local_rank: int = - 1, dataloader_drop_last: bool = False, eval_steps: Optional[int] = None, dataloader_num_workers: int = 0, past_index: int = - 1, run_name: Optional[str] = None, device: Optional[str] = 'gpu', disable_tqdm: Optional[bool] = None, remove_unused_columns: Optional[bool] = True, label_names: Optional[List[str]] = None, load_best_model_at_end: Optional[bool] = False, metric_for_best_model: Optional[str] = None, greater_is_better: Optional[bool] = None, ignore_data_skip: bool = False, optim: str = 'adamw', report_to: Optional[List[str]] = None, resume_from_checkpoint: Optional[str] = None, skip_memory_metrics: bool = True, flatten_param_grads: Optional[bool] = False, lazy_data_processing: Optional[bool] = True)[source]¶ Bases:
object
TrainingArguments is the subset of the arguments we use in our example scripts which relate to the training loop itself.
Using [
PdArgumentParser
] 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.- Parameters
output_dir (
str
) – The output directory where the model predictions and checkpoints will be written.overwrite_output_dir (
bool
, optional, defaults toFalse
) – IfTrue
, overwrite the content of the output directory. Use this to continue training ifoutput_dir
points to a checkpoint directory.do_train (
bool
, optional, defaults toFalse
) – Whether to run training or not. This argument is not directly used by [Trainer
], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.do_eval (
bool
, optional) – Whether to run evaluation on the validation set or not. Will be set toTrue
ifevaluation_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](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.do_predict (
bool
, optional, defaults toFalse
) – Whether to run predictions on the test set or not. This argument is not directly used by [Trainer
], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.do_export (
bool
, optional, defaults toFalse
) – Whether to export inference model or not. This argument is not directly used by [Trainer
], it’s intended to be used by your training/evaluation scripts instead.evaluation_strategy (
str
or [IntervalStrategy
], optional, defaults to"no"
) –The evaluation strategy to adopt during training. Possible values are:
"no"
: No evaluation is done during training."steps"
: Evaluation is done (and logged) everyeval_steps
."epoch"
: Evaluation is done at the end of each epoch.
prediction_loss_only (
bool
, optional, defaults toFalse
) – When performing evaluation and generating predictions, only returns the loss.per_device_train_batch_size (
int
, optional, defaults to 8) – The batch size per GPU core/CPU for training.per_device_eval_batch_size (
int
, optional, defaults to 8) – The batch size per GPU core/CPU for evaluation.gradient_accumulation_steps (
int
, optional, defaults to 1) –Number of updates steps to accumulate the gradients for, before performing a backward/update pass.
<Tip warning={true}>
When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every
gradient_accumulation_steps * xxx_step
training examples.</Tip>
learning_rate (
float
, optional, defaults to 5e-5) – The initial learning rate for [AdamW
] optimizer.weight_decay (
float
, optional, defaults to 0) – The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [AdamW
] optimizer.adam_beta1 (
float
, optional, defaults to 0.9) – The beta1 hyperparameter for the [AdamW
] optimizer.adam_beta2 (
float
, optional, defaults to 0.999) – The beta2 hyperparameter for the [AdamW
] optimizer.adam_epsilon (
float
, optional, defaults to 1e-8) – The epsilon hyperparameter for the [AdamW
] optimizer.max_grad_norm (
float
, optional, defaults to 1.0) – Maximum gradient norm (for gradient clipping).num_train_epochs (
float
, optional, defaults to 3.0) – Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).max_steps (
int
, optional, defaults to -1) – If set to a positive number, the total number of training steps to perform. Overridesnum_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 exhaustedlr_scheduler_type (
str
or [SchedulerType
], optional, defaults to"linear"
) – The scheduler type to use. See the documentation of [SchedulerType
] for all possible values.warmup_ratio (
float
, optional, defaults to 0.0) – Ratio of total training steps used for a linear warmup from 0 tolearning_rate
.warmup_steps (
int
, optional, defaults to 0) – Number of steps used for a linear warmup from 0 tolearning_rate
. Overrides any effect ofwarmup_ratio
.log_on_each_node (
bool
, optional, defaults toTrue
) – In multinode distributed training, whether to log usinglog_level
once per node, or only on the main node.logging_dir (
str
, optional) – log directory. Will default to output_dir/runs/**CURRENT_DATETIME_HOSTNAME**.logging_strategy (
str
or [IntervalStrategy
], optional, defaults to"steps"
) –The logging strategy to adopt during training. Possible values are:
"no"
: No logging is done during training."epoch"
: Logging is done at the end of each epoch."steps"
: Logging is done everylogging_steps
.
logging_first_step (
bool
, optional, defaults toFalse
) – Whether to log and evaluate the firstglobal_step
or not.logging_steps (
int
, optional, defaults to 500) – Number of update steps between two logs iflogging_strategy="steps"
.save_strategy (
str
or [IntervalStrategy
], optional, defaults to"steps"
) –The checkpoint save strategy to adopt during training. Possible values are:
"no"
: No save is done during training."epoch"
: Save is done at the end of each epoch."steps"
: Save is done everysave_steps
.
save_steps (
int
, optional, defaults to 500) – Number of updates steps before two checkpoint saves ifsave_strategy="steps"
.save_total_limit (
int
, optional) – If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints inoutput_dir
.save_on_each_node (
bool
, optional, defaults toFalse
) –When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one.
This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node.
no_cuda (
bool
, optional, defaults toFalse
) – Whether to not use CUDA even when it is available or not.seed (
int
, optional, defaults to 42) – Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [model_init
] function to instantiate the model if it has some randomly initialized parameters.fp16 (
bool
, optional, defaults toFalse
) – Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.fp16_opt_level (
str
, optional, defaults to ‘O1’) – Forfp16
training, AMP optimization level selected in [‘O0’, ‘O1’, ‘O2’]. See details at https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api/paddle/amp/auto_cast_cn.htmlsharding (
str
, optional, defaults to ``) –Whether or not to use Paddle Sharding Data Parallel training (in distributed training only). The base option should be
stage1
,stage2
orstage3
and you can add CPU-offload tostage2
orstage3
like this:stage2 offload
orstage3 offload
. Each stage means:stage1 : optimizer state segmentation stage2 : optimizer state + gradient segmentation stage3 : parameter + gradient + optimizer state segmentation offload : offload parameters to cpu
sharding_degree (
int
, optional, defaults to-1
) – Sharding parameter in certain cards group. For example, aussume we use 2 machines each with 8 cards, then set sharding_degree=8, sharding will only communication inside machine. default -1 means sharding parameters between all workers.recompute (
bool
, optional, defaults toFalse
) – Recompute the forward pass to calculate gradients. Used for saving memory. Only support for networks with transformer blocks.scale_loss (
float
, optional, defaults to 32768) – The value of initial scale_loss for fp16. (default: 32768)local_rank (
int
, optional, defaults to -1) – Rank of the process during distributed training.dataloader_drop_last (
bool
, optional, defaults toFalse
) – Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.eval_steps (
int
, optional) – Number of update steps between two evaluations ifevaluation_strategy="steps"
. Will default to the same value aslogging_steps
if not set.dataloader_num_workers (
int
, optional, defaults to 0) – Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process.past_index (
int
, optional, defaults to -1) – Some models like TransformerXL or XLNet can make use of the past hidden states for their predictions. If this argument is set to a positive int, theTrainer
will use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argumentmems
.run_name (
str
, optional) – A descriptor for the run. Typically used for logging.disable_tqdm (
bool
, optional) – Whether or not to disable the tqdm progress bars and table of metrics. Will default toTrue
if the logging level is set to warn or lower (default),False
otherwise.remove_unused_columns (
bool
, optional, defaults toTrue
) – If usingdatasets.Dataset
datasets, whether or not to automatically remove the columns unused by the model forward method.label_names (
List[str]
, optional) – The list of keys in your dictionary of inputs that correspond to the labels. Will eventually default to["labels"]
except if the model used is one of theXxxForQuestionAnswering
in which case it will default to["start_positions", "end_positions"]
.load_best_model_at_end (
bool
, optional, defaults toFalse
) –Whether or not to load the best model found during training at the end of training.
<Tip>
When set to
True
, the parameterssave_strategy
needs to be the same aseval_strategy
, and in the case it is “steps”,save_steps
must be a round multiple ofeval_steps
.</Tip>
metric_for_best_model (
str
, optional) –Use in conjunction with
load_best_model_at_end
to specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix"eval_"
. Will default to"loss"
if unspecified andload_best_model_at_end=True
(to use the evaluation loss).If you set this value,
greater_is_better
will default toTrue
. Don’t forget to set it toFalse
if your metric is better when lower.greater_is_better (
bool
, optional) –Use in conjunction with
load_best_model_at_end
andmetric_for_best_model
to specify if better models should have a greater metric or not. Will default to:True
ifmetric_for_best_model
is set to a value that isn’t"loss"
or"eval_loss"
.False
ifmetric_for_best_model
is not set, or set to"loss"
or"eval_loss"
.
ignore_data_skip (
bool
, optional, defaults toFalse
) – When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set toTrue
, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.optim (
str
or [training_args.OptimizerNames
], optional, defaults to"adamw"
) – The optimizer to use: adamw, or adafactor.length_column_name (
str
, optional, defaults to"length"
) – Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unlessgroup_by_length
isTrue
and the dataset is an instance ofDataset
.report_to (
str
orList[str]
, optional, defaults to"visualdl"
) – The list of integrations to report the results and logs to. Supported platforms is"visualdl"
."none"
for no integrations.resume_from_checkpoint (
str
, optional) – The path to a folder with a valid checkpoint for your model. This argument is not directly used by [Trainer
], it’s intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples) for more details.flatten_param_grads (
bool
, optional) – Whether use flatten_param_grads method in optimizer, only used on NPU devices. Default isFalse
.
-
property
train_batch_size
¶ The actual batch size for training.
-
property
eval_batch_size
¶ The actual batch size for evaluation.
-
property
current_device
¶ The device used by this process.
-
property
world_size
¶ The number of processes used in parallel.
-
property
process_index
¶ The index of the current process used.
-
property
local_process_index
¶ The index of the local process used.
-
property
should_log
¶ Whether or not the current process should produce log.
-
property
should_save
¶ Whether or not the current process should write to disk, e.g., to save models and checkpoints.
-
main_process_first
(local=True, desc='work')[source]¶ A context manager for paddle 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
’smap
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.- Parameters
local (
bool
, optional, defaults toTrue
) – ifTrue
first means process of rank 0 of each node ifFalse
first means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to uselocal=False
so that only the main process of the first node will do the processing. If however, the filesystem is not shared, then the main process of each node will need to do the processing, which is the default behavior.desc (
str
, optional, defaults to"work"
) – a work description to be used in debug logs