SFTTrainer
-
model (
str | PreTrainedModel) — Model to be trained. Can be either:A string, being the model id of a pretrained model hosted inside a model repo on huggingface.co, or a path to a directory containing model weights saved using save_pretrained, e.g.,'./my_model_directory/'. The model is loaded using<ModelArchitecture>.from_pretrained(where<ModelArchitecture>is derived from the model config) with the keyword arguments inargs.model_init_kwargs.A PreTrainedModel object. If you’re training a model with an MoE architecture and want to include the load balancing/auxilliary loss as a part of the final loss, remember to set theoutput_router_logitsconfig of the model toTrue. -
args (SFTConfig, optional) — Configuration for this trainer. If
None, a default configuration is used. -
data_collator (
DataCollator, optional) — Function to use to form a batch from a list of elements of the processedtrain_datasetoreval_dataset. Will default to DataCollatorForLanguageModeling if the model is a language model and DataCollatorForVisionLanguageModeling if the model is a vision-language model.[!NOTE]
用于将原始 dataset 中的样本整理为可供模型输入的 batch。
-
train_dataset (Dataset or IterableDataset) — Dataset to use for training. SFT supports both language modeling type and prompt-completion type.
The format of the samples can be either:
-
Standard: Each sample contains plain text.
-
Conversational: Each sample contains structured messages (e.g., role and content).
The trainer also supports processed datasets (tokenized) as long as they contain an
input_idsfield.[!NOTE]
支持的具体数据格式有:
{ "text": "The sky is blue." }{ "prompt": "The sky is", "completion": " blue." }{ "messages": [ { "role": "user", "content": "What color is the sky?" }, { "role": "assistant", "content": "It is blue." } ] } -
-
eval_dataset (Dataset, IterableDataset or
dict[str, Dataset | IterableDataset]) — Dataset to use for evaluation. It must meet the same requirements astrain_dataset. -
processing_class (PreTrainedTokenizerBase, ProcessorMixin, optional) — Processing class used to process the data. If
None, the processing class is loaded from the model’s name with from_pretrained. A padding token,tokenizer.pad_token, must be set. If the processing class has not set a padding token,tokenizer.eos_tokenwill be used as the default.[!NOTE]
数据处理类,对于文本数据而言就是
Tokenzier。 -
optimizers (
tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None], optional, defaults to(None, None)) — A tuple containing the optimizer and the scheduler to use. Will default to an instance ofAdamWon your model and a scheduler given by get_linear_schedule_with_warmup controlled byargs.[!NOTE]
优化器和学习率调度器的二元组,默认值为
(AdamW,linear_scheduler_with_warmup)。-
AdamW
AdamW 是对 Adam 优化器的改进版本,其主要贡献是将权重衰减(Weight Decay)从梯度更新中解耦,使正则化更加稳定有效。
权重衰减的作用是让模型参数逐渐变小,使模型更加平滑、简化,从而减少过拟合。传统上,这一作用通常通过在损失函数中加入 L2 正则项来实现,即
$$
L_{\text{reg}}(w) = L(w) + \frac{\lambda}{2}|w|^2,
$$
通过对较大的权重施加惩罚,使其向 0 收缩。对该损失函数求梯度可得
$$
g_t = \nabla_w L(w) + \lambda w,
$$
在使用 SGD 时,参数更新为
$$
w_t = w_{t-1} - \eta \nabla_w L(w) - \eta\lambda w_{t-1},
$$
其中的 $-\eta\lambda w_{t-1}$ 正是权重衰减项。因此在 SGD 中,L2 正则化能够稳定地产生权重衰减。然而,在 Adam 中直接加入 L2 正则化并不能得到正确的权重衰减效果,因为 Adam 会对梯度进行一阶矩和二阶矩的自适应缩放。如果使用
$$
g_t = \nabla_w L(w) + \lambda w,
$$
则 L2 项 $\lambda w$ 会与普通梯度一起被缩放。Adam 的更新过程包括一阶矩与二阶矩的更新:
$$
m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t,\qquad
v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2,
$$
随后进行偏差校正:
$$
\hat{m}_t = \frac{m_t}{1-\beta_1^t},\qquad
\hat{v}t = \frac{v_t}{1-\beta_2^t},
$$
并按如下方式更新参数:
$$
w_t = w{t-1} - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}.
$$
由于梯度被不同程度地缩放,L2 项的衰减强度也会随之变化,不同参数的衰减幅度也会不一致,最终导致正则化效果显著弱化甚至失效。因此,传统的 “Adam + L2 正则化” 并不能实现真正意义上的权重衰减。为了解决这一问题,AdamW 采用了解耦的权重衰减方式:不再将 $\lambda w$ 作为梯度的一部分,而是在参数更新阶段单独进行权重衰减。其更新公式为
$$
w_t = w_{t-1}- \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}
- \eta \lambda w_{t-1}.
$$
前一项是标准的 Adam 更新,后一项是独立的权重衰减操作,不再受到梯度自适应缩放的干扰。这种方式恢复了权重衰减的本质,使正则化强度稳定一致,也因此在深度学习模型(尤其是 Transformer 和大型语言模型)训练中获得显著更好的泛化性能,成为当前主流的优化方法之一。
-
linear_scheduler_with_warmup
常用的学习率调度器,它先进行一段 warmup,让学习率从 0 线性提升到设定的最大学习率,避免训练初期不稳定。完成 warmup 之后,学习率会再从峰值开始,随训练进程线性下降到 0,使模型在后期更平稳地收敛。由于简单可靠,这种调度方式在 Transformer 和大模型训练中十分常用。

-
-
peft_config (PeftConfig, optional) — PEFT configuration used to wrap the model. If
None, the model is not wrapped.[!NOTE]
参数高效微微调相关配置,类型为
PEFTConfig。
SFTConfig
基础训练相关
-
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. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) untilmax_stepsis reached. -
per_device_train_batch_size (
int, optional, defaults to 8) — The batch size per device. The global batch size is computed as:per_device_train_batch_size * number_of_devicesin multi-GPU or distributed setups. -
gradient_accumulation_steps (
int, optional, defaults to 1) — Number of updates steps to accumulate the gradients for, before performing a backward/update pass. -
max_length (
intorNone, optional, defaults to1024) — Maximum length of the tokenized sequence. Sequences longer thanmax_lengthare truncated from the right. IfNone, no truncation is applied. When packing is enabled, this value sets the sequence length.
训练优化相关
-
bf16 (
bool, optional, defaults toFalse) — Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. -
fp16 (
bool, optional, defaults toFalse) — Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.[!note]
bf16和fb16对比:
特性 FP16(float16) BF16(bfloat16) 总位数 16-bit 16-bit 尾数(精度) 10-bit 7-bit 指数位(数值范围) 5-bit 8-bit 数值范围 小,容易溢出/下溢 大,几乎等同 FP32,几乎不会溢出 是否需要loss scaling 需要 不需要 兼容性 所有 GPU 仅Ampere 及以上代数 -
half_precision_backend (
str, optional, defaults to"auto") — The backend to use for mixed precision training. Must be one of"auto", "apex", "cpu_amp"."auto"will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend. -
activation_offloading (
bool, optional, defaults toFalse) — Whether to offload the activations to the CPU.[!NOTE]
将前向传播中的激活值临时移到 CPU 来降低显存占用。
-
gradient_checkpointing (
bool, optional, defaults toFalse) — If True, use gradient checkpointing to save memory at the expense of slower backward pass.[!NOTE]
在前向传播中只保留部分激活值,并在反向传播时按需重新计算其余激活,以此减少显存占用。
-
weight_decay (
float, optional, defaults to 0) — The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights inAdamWoptimizer.[!NoTE]
AdamW优化器的权重衰减系数。
-
max_grad_norm (
float, optional, defaults to 1.0) — Maximum gradient norm (for gradient clipping).[!note]
梯度裁剪(Gradient Clipping)的最大范数。
评估相关
- eval_strategy (
stror 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. - eval_steps (
intorfloat, optional) — Number of update steps between two evaluations ifeval_strategy="steps". Will default to the same value aslogging_stepsif not set. Should be an integer or a float in range[0,1). If smaller than 1, will be interpreted as ratio of total training steps. - per_device_eval_batch_size (
int, optional, defaults to 8) — The batch size per device accelerator core/CPU for evaluation.
学习率调度相关
-
learning_rate (
float, optional, defaults to 5e-5) — The initial learning rate forAdamWoptimizer. -
lr_scheduler_type (
stror 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.
损失计算相关
-
completion_only_loss (
bool, optional) — Whether to compute loss only on the completion part of the sequence. If set toTrue, loss is computed only on the completion, which is supported only for prompt-completion datasets. IfFalse, loss is computed on the entire sequence. IfNone(default), the behavior depends on the dataset: loss is computed on the completion for prompt-completion datasets, and on the full sequence for language modeling datasets.[!note]
训练时只计算"prompt-completion"数据集中的completion部分的loss,如下图所示:

-
assistant_only_loss (
bool, optional, defaults toFalse) — Whether to compute loss only on the assistant part of the sequence. If set toTrue, loss is computed only on the assistant responses, which is supported only for conversational datasets. IfFalse, loss is computed on the entire sequence.[!note]
训练时只计算对话数据集中assistant部分的loss,如下图所示

保存相关
-
output_dir (
str, optional, defaults to"trainer_output") — The output directory where the model predictions and checkpoints will be written. -
save_strategy (
strorSaveStrategy, 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."best": Save is done whenever a newbest_metricis achieved.If"epoch"or"steps"is chosen, saving will also be performed at the very end of training, always. -
save_steps (
intorfloat, optional, defaults to 500) — Number of updates steps before two checkpoint saves ifsave_strategy="steps". Should be an integer or a float in range[0,1). If smaller than 1, will be interpreted as ratio of total training steps. -
save_total_limit (
int, optional) — If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints inoutput_dir. Whenload_best_model_at_endis enabled, the “best” checkpoint according tometric_for_best_modelwill always be retained in addition to the most recent ones. For example, forsave_total_limit=5andload_best_model_at_end, the four last checkpoints will always be retained alongside the best model. Whensave_total_limit=1andload_best_model_at_end, it is possible that two checkpoints are saved: the last one and the best one (if they are different). -
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. When this option is enabled, the best checkpoint will always be saved. Seesave_total_limitfor more. -
metric_for_best_model (
str, optional) — Use in conjunction withload_best_model_at_endto 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_".If not specified, this will default to
"loss"when eitherload_best_model_at_end == Trueorlr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU(to use the evaluation loss).If you set this value,
greater_is_betterwill default toTrueunless the name ends with “loss”. Don’t forget to set it toFalseif your metric is better when lower. -
greater_is_better (
bool, optional) — Use in conjunction withload_best_model_at_endandmetric_for_best_modelto specify if better models should have a greater metric or not. Will default to:Trueifmetric_for_best_modelis set to a value that doesn’t end in"loss".Falseifmetric_for_best_modelis not set, or set to a value that ends in"loss".
日志相关
-
logging_dir (
str, optional) — TensorBoard log directory. Will default to output_dir/runs/CURRENT_DATETIME_HOSTNAME. -
logging_strategy (
stror 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_steps (
intorfloat, optional, defaults to 500) — Number of update steps between two logs iflogging_strategy="steps". Should be an integer or a float in range[0,1). If smaller than 1, will be interpreted as ratio of total training steps.
