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: 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, eval_accumulation_steps: int | None = None, learning_rate: float = 5e-05, weight_decay: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-08, max_grad_norm: float = 1.0, num_train_epochs: float = 1.0, max_steps: int = -1, lr_scheduler_type: str = 'linear', warmup_ratio: float = 0.0, warmup_steps: int = 0, num_cycles: float = 0.5, lr_end: float = 1e-07, power: float = 1.0, log_on_each_node: bool = True, logging_dir: str | None = None, logging_strategy: IntervalStrategy = 'steps', logging_first_step: bool = False, logging_steps: int = 500, save_strategy: IntervalStrategy = 'steps', save_steps: int = 500, save_total_limit: int | None = 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', amp_master_grad: bool = False, bf16_full_eval: bool = False, fp16_full_eval: bool = False, amp_custom_black_list: List[str] | None = None, amp_custom_white_list: List[str] | None = None, sharding: str = '', sharding_degree: int = -1, sharding_parallel_degree: int = -1, save_sharded_model: bool = False, load_sharded_model: bool = False, tensor_parallel_degree: int = -1, pipeline_parallel_degree: int = -1, sep_parallel_degree: int = -1, data_parallel_config: str = '', tensor_parallel_config: str = '', pipeline_parallel_config: str = '', sharding_parallel_config: str = '', hybrid_parallel_topo_order: str | None = None, recompute: bool = False, scale_loss: float = 32768, minimum_eval_times: int | None = None, local_rank: int = -1, dataloader_drop_last: bool = False, eval_steps: int | None = None, max_evaluate_steps: int = -1, dataloader_num_workers: int = 0, past_index: int = -1, run_name: str | None = None, device: str | None = 'gpu', disable_tqdm: bool | None = None, remove_unused_columns: bool | None = True, label_names: List[str] | None = None, load_best_model_at_end: bool | None = False, metric_for_best_model: str | None = None, greater_is_better: bool | None = None, ignore_data_skip: bool = False, optim: str = 'adamw', report_to: List[str] | None = None, wandb_api_key: str | None = None, resume_from_checkpoint: str | None = None, skip_memory_metrics: bool = True, flatten_param_grads: bool | None = False, lazy_data_processing: bool | None = True, skip_profile_timer: bool | None = True, distributed_dataloader: bool | None = False, unified_checkpoint: bool | None = False, to_static: bool | None = False, unified_checkpoint_config: str | None = '', ignore_load_lr_and_optim: bool | None = False, ignore_save_lr_and_optim: bool | None = False, force_reshard_pp: bool | None = False, enable_auto_parallel: bool | None = False)[源代码]#
基类:
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.- 参数:
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](PaddlePaddle/PaddleNLP) 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](PaddlePaddle/PaddleNLP) 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](PaddlePaddle/PaddleNLP) 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>
eval_accumulation_steps (
int
, optional) -- Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but requires more memory).learning_rate (
float
, optional, defaults to 5e-5) -- The initial learning rate for [AdamW
] 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 1.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
.num_cycles (
float
, optional, defaults to 0.5) -- The number of waves in the cosine scheduler.lr_end (
float
, optional, defaults to 1e-7) -- The end LR used in the polynomial scheduler.power (
float
, optional, defaults to 1.0) -- The power factor used in the polynomial scheduler.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.htmlamp_custom_black_list (
List[str]
, optional, defaults toNone
) -- The custom black_list. The set of ops that support fp16/bf16 calculation and are considered numerically-dangerous and whose effects may also be observed in downstream ops. These ops will not be converted to fp16/bf16.amp_custom_white_list (
List[str]
, optional, defaults toNone
) --- The custom white_list. It’s the set of ops that support fp16/bf16 calculation and are considered numerically-safe and
performance-critical. These ops will be converted to fp16/bf16.
amp_master_grad (
bool
, optional, defaults toFalse
) -- For amp opt level=’O2’, whether to use float32 weight gradients for calculations such as gradient clipping, weight decay, and weight updates. If master_grad is enabled, the weight gradients will be float32 dtype after the backpropagation. Default is False, there is only float16 weight gradients. Note: only support model parallel and pipeline parallel for now !!!sharding (
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_parallel_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_parallel_degree=8, sharding will only communication inside machine. default -1 means sharding parameters between all workers.tensor_parallel_degree (
int
, optional, defaults to-1
) -- Tensor parallelism is parallel technique proposed in (https://arxiv.org/pdf/2104.04473.pdf see 2.3 Tensor Model Parallelism). This technique splits one transformer layer into multi-cards (For examples, tensor_parallel_degree=4, will split a layer to 4-parts) tensor_parallel_degree means split the transformer layer to how many parts. default -1 for not use tensor parallel, Suggest tensor_parallel_degree<=8 for better proformance. Note, this need model support in source code, currently GPT/BLOOM/LLAMA/BLOOM/CLM/CHATGLM is supported.pipeline_parallel_degree (
int
, optional, defaults to-1
) -- Pipeline parallelism is parallel technique proposed in (https://arxiv.org/pdf/2104.04473.pdf see 2.2 Pipeline Model Parallelism). Pipeline parallelism assigns multi-transformer layers to different cards, the micro batch data stream passed between cards like pipelines. pipeline_parallel_degree means split all transformer layers to how many stages. default -1 for not use pipeline parallel. Note. this need model support in source code, see llama modeling_pp.py filesep_parallel_degree (
int
, optional, defaults to-1
) -- The paddle sequence parallel strategy. It can reduce the GPU memory of activation to 1/sep, and it is orthogonal to data parallel, sharding stage1, tensor parallel and pipeline parallel strategy.) --
data_parallel_config (
str
, optional) --Some additional configs which affect data parallel performance, we provide some option to config it. following config is support:
enable_allreduce_avg_in_gradinent_scale, it replace
allreduce_sum + scale
pattern withallreduce_avg
when scale gradient in data_parallel, which improve the performance. ONLY supported for auto mode now. gradient_sync_after_accumulate, move gradient sync operations from backward into optimizer step when gradient accumulate enabling, which reduce the sync times to improve performance, but will increase the memory usage. ONLY supported for auto mode now.tensor_parallel_config (
str
, optional) --Some additional configs which affect model parallel performance, we provide some option to config it. following config is support:
enable_mp_async_allreduce, it supports all_reduce(dx) overlap with matmul(dw) in ColumnParallelLinear backward when it set True, which can accelerate model parallel performance. enable_mp_skip_c_identity, it supports skip c_identity in ColumnParallelLinear and RowParallelLinear. It only works when set mp_async_allreduce is True. It can accelerate model parallel further. enable_mp_fused_linear_param_grad_add, it supports fused_linear_param_grad_add in ColumnParallelLinear (cuda >= 11.6). It only works when mp_async_allreduce is true. It can accelerate model parallel further. enable_delay_scale_loss, accumulate gradients util optimizer step, all gradients div by accumute step. instead of div accumute step on loss directly.
pipeline_parallel_config (
str
, optional) --Some additional config it highly affect the useage of pipeline parallel, we provide some option to config it. following config is support:
disable_p2p_cache_shape, if you max sequence length is varying, please set disable_p2p_cache_shape. disable_partial_send_recv, optmize send speed for tensor parallel. enable_delay_scale_loss, accumulate gradients util optimizer step, all gradients div by inner pipeline accumute step. instead of div accumute step on loss directly. enable_dp_comm_overlap, fuse data parallel gradient communication. enable_sharding_comm_overlap, fuse sharding stage 1 parallel gradient communication. enable_release_grads, reduce peak memory usage by releasing gradients after each iteration. The creation of gradients will be postponed until backward propagation of the next iteration. enable_overlap_p2p_comm, overlap p2p communication with computation. enable_clear_every_step_cache, clear every step cache for pipeline parallel. disable_non_batch_p2p_comm, disable batched send/recv in pipeline parallel mode.
sharding_parallel_config (
str
, optional) --Some additional config it highly affect the useage of sharding parallel, we provide some option to config it. following config is support:
enable_stage1_tensor_fusion, fuse small tensors into big tensor chunks to accelerate communications, may increase memory occupation enable_stage1_overlap, fuse small tensors into big tensor chunks to accelerate communications and do communication overlap with backward computation, may harm the backward speed enable_stage2_overlap, overlap stage2 NCCL communication with computation. There are some constraints for the overlap, such as the logging_step should be bigger than 1 for broadcast overlap and no other sync could be called during the training for broadcast overlap. disable_stage1_reduce_avg, replace reduce_avg with original reduce_sum+scale in stage1, which can be used for accuracy verification.
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.max_evaluate_steps (
int
, optional, defaults to -1) -- If set to a positive number, the total number of evaluation steps to perform.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 are"visualdl"
/"wandb"
/"tensorboard"
."none"
for no integrations.wandb_api_key (
str
, optional) -- Weights & Biases (WandB) API key(s) for authentication with the WandB service.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](PaddlePaddle/PaddleNLP) for more details.flatten_param_grads (
bool
, optional) -- Whether use flatten_param_grads method in optimizer, only used on NPU devices. Default isFalse
.skip_profile_timer (
bool
, optional) -- Whether skip profile timer, timer will record time usage of forward/ backward/ step, etc.distributed_dataloader (
bool
, optional) -- Whether to use distributed dataloader. Default isFalse
.
- property train_batch_size: int#
The actual batch size for training.
- property eval_batch_size: int#
The actual batch size for evaluation.
- property current_device: paddle.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 logical_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.
- For model state:
work for data parallel, tensor parallel, sharding
- For optimizer state:
work for data parallel, tensor parallel not work for sharding
- property should_save_model_state#
Whether or not the current process should write to disk, e.g., to save models and checkpoints.
- For model state:
work for data parallel, tensor parallel, sharding
- For optimizer state:
work for data parallel, tensor parallel not work for sharding
- main_process_first(local=True, desc='work')[源代码]#
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.- 参数:
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