Transformers documentation

超参数搜索

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

超参数搜索

学习率、批大小和训练轮数等超参数会显著影响训练结果。Trainer.hyperparameter_search() 通过运行多次试验来寻找最佳组合,每次试验使用一组不同的值,并返回其中表现最好的一个。

每次试验都会使用 model_init 初始化一个全新的模型,采样新的超参数,运行完整的训练循环,并向搜索后端报告一个目标值。后端利用每个目标值来指导下一次试验。所有试验完成后,最佳超参数将以 ~trainer.utils.BestRun 的形式返回。

初始化模型

在每次试验开始时使用全新的模型,以避免受到之前运行状态的影响。model_init 会在每次试验开始时被调用并返回一个新的模型实例,因此每次试验都从相同的初始权重开始。

from transformers import AutoModelForCausalLM

def model_init(trial):
    return AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B")

trainer = Trainer(
    model_init=model_init,
    args=args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
)

不要同时传入 model= 和 model_init=,否则 Trainer 会抛出错误。

定义搜索空间

创建一个用于定义搜索空间的函数。其格式取决于后端。如果未定义 hp_space 函数,默认搜索将覆盖 learning_rate、num_train_epochs 和 per_device_train_batch_size。

# install one of these hyperparam search backends
pip install optuna
pip install wandb
pip install ray[tune]
Optuna
Ray Tune
Weights & Biases

Optuna 是一个用于超参数优化的轻量级框架。

def hp_space(trial):
    return {
        "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True),
        "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [16, 32, 64, 128]),
    }

运行搜索

提供一个可选的 compute_objective 函数来定义优化目标。如果存在 eval_loss,则默认使用它;否则,默认使用所有指标值的总和。请显式传入一个函数,以避免依赖此回退机制。搜索 backend 会在给定的 direction 下,针对 n_trials 次运行来优化该目标。

def compute_objective(metrics):
    return metrics["eval_loss"]

best_run = trainer.hyperparameter_search(
    hp_space=hp_space,
    compute_objective=compute_objective,
    n_trials=30,               # how many trials to run
    direction="minimize",      # or "maximize" for metrics like accuracy/F1
    backend="optuna",          # "optuna", "ray", or "wandb"
)

hyperparameter_search() 返回一个 ~trainer.utils.BestRun,其中包含目标函数值以及最优的超参数组合。

best_run = trainer.hyperparameter_search(...)

best_run.objective        # 0.38  (best eval loss)
best_run.hyperparameters  # {"learning_rate": 5e-5, "num_train_epochs": 4, ...}

将最佳超参数应用于 TrainingArguments,并在完整数据集上重新训练。

Update on GitHub