# 奖励建模

[![model badge](https://img.shields.io/badge/All_models-Reward_Trainer-blue)](https://huggingface.co/models?other=reward-trainer,trl)

## 概述

TRL 支持结果监督奖励建模（ORM）训练器，用于训练奖励模型。

此训练后方法由 [Younes Belkada](https://huggingface.co/ybelkada) 贡献。

## 快速入门

本示例演示了如何使用 TRL 中的 [RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 训练奖励模型。我们在 [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized)（一个大规模、细粒度、多样化的偏好数据集）上训练 [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) 模型。

```python
from trl import RewardTrainer
from datasets import load_dataset

trainer = RewardTrainer(
    model="Qwen/Qwen3-0.6B",
    train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"),
)
trainer.train()
```

## 预期的数据集类型和格式

[RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 支持 [preference](dataset_formats#preference) 数据集类型（包括隐式和显式提示）。[RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 兼容 [standard](dataset_formats#standard) 和 [conversational](dataset_formats#conversational) 两种数据集格式。当提供对话式数据集时，训练器会自动将聊天模板应用于该数据集。

```python
# Standard preference (implicit prompt)
{"chosen": "The sky is blue.",
 "rejected": "The sky is green."}

# Conversational preference (implicit prompt)
{"chosen": [{"role": "user", "content": "What color is the sky?"},
            {"role": "assistant", "content": "It is blue."}],
 "rejected": [{"role": "user", "content": "What color is the sky?"},
              {"role": "assistant", "content": "It is green."}]}

# Standard preference (explicit prompt)
{"prompt": "The sky is",
 "chosen": " blue.",
 "rejected": " green."}

# Conversational preference (explicit prompt)
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
 "chosen": [{"role": "assistant", "content": "It is blue."}],
 "rejected": [{"role": "assistant", "content": "It is green."}]}
```

如果您的数据集不属于上述任何一种格式，您可以对其进行预处理，将其转换为预期的格式。以下是使用 [lmarena-ai/arena-human-preference-55k](https://huggingface.co/datasets/lmarena-ai/arena-human-preference-55k) 数据集的示例：

```python
from datasets import load_dataset
import json

dataset = load_dataset("lmarena-ai/arena-human-preference-55k")

# Filter out ties
dataset = dataset.filter(lambda example: example["winner_tie"] == 0)

# Create 'chosen' and 'rejected' fields based on the winner column
def response_a_b_to_chosen_rejected(example):
    if example["winner_model_a"] == 1:
        example["chosen"] = example["response_a"]
        example["rejected"] = example["response_b"]
    else:
        example["chosen"] = example["response_b"]
        example["rejected"] = example["response_a"]
    return example

dataset = dataset.map(response_a_b_to_chosen_rejected)

# Convert to conversational format
def make_conversation(example):
    prompt = json.loads(example["prompt"])[0]  # '["What color is the sky?"]' -> "What color is the sky?"
    chosen = json.loads(example["chosen"])[0]
    rejected = json.loads(example["rejected"])[0]
    return {
        "chosen": [{"role": "user", "content": prompt}, {"role": "assistant", "content": chosen}],
        "rejected": [{"role": "user", "content": prompt}, {"role": "assistant", "content": rejected}],
    }

dataset = dataset.map(make_conversation)

# Keep only necessary columns
dataset = dataset.select_columns(["chosen", "rejected"])

print(next(iter(dataset["train"])))
```

```json
{
    "chosen": [
        {"role": "user", "content": "Is it morally right to try to have a certain percentage of females on managerial positions?"},
        {"role": "assistant", "content": "The question of whether it is morally right to aim for a certain percentage of females..."},
    ],
    "rejected": [
        {"role": "user", "content": "Is it morally right to try to have a certain percentage of females on managerial positions?"},
        {"role": "assistant", "content": "As an AI, I don't have personal beliefs or opinions. However, ..."},
    ],
}
```

## 深入了解训练方法

奖励模型（RMs）通常通过在包含偏好响应与非偏好响应对的数据集上进行监督学习来训练。其目标是学习一个函数，为偏好响应分配更高的分数，从而使模型能够基于偏好对输出进行排序。

本节详细解析奖励建模在实际应用中的工作原理，涵盖关键步骤：**预处理**和**损失计算**。

### 预处理和分词

在训练期间，每个样本预期包含 **chosen** 和 **rejected** 字段。有关预期格式的详细信息，请参阅 [Dataset formats - Preference](dataset_formats#preference)。[RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 使用模型的 tokenizer 对每个输入进行分词。如果提示和补全（chosen 和 rejected）是分开提供的（显式提示情况），它们会在分词之前进行拼接。

### 计算损失

设 \\( x \\) 为输入序列（提示），\\( y^+ \\) 和 \\( y^- \\) 分别为被选中和被拒绝的序列。在 Bradley-Terry 模型（[Bradley & Terry, 1952](https://www.jstor.org/stable/2334029)）下，给定奖励函数 \\( r \\)，\\( y^+ \\) 优于 \\( y^- \\) 的概率为 \\( p(y^+ ≻ y^- |x) = \sigma(r(x, y^+)−r(x, y^-)) \\)，其中 \\( σ \\) 为 sigmoid 函数。

奖励模型 \\( r_\theta(x, y) \\) 的训练目标是使偏好响应 \\( y^+ \\) 的得分高于非偏好响应 \\( y^- \\)。损失函数随后被定义为观测到的偏好的负对数似然：

$$ \mathcal{L}(\theta) = - \mathbb{E}_{(x,y^+,y^-) \sim \mathcal{D}} \left[ \log \sigma(r_\theta(x, y^+) - r_\theta(x, y^-)) \right]. $$

> [!TIP]
> Bradley-Terry 模型是不确定的，这意味着给所有奖励加上一个常数并不会改变偏好概率。为了解决这个问题，[Helping or Herding? Reward Model Ensembles Mitigate but do not Eliminate Reward Hacking](https://huggingface.co/papers/2312.09244) 提出添加一个辅助损失项，以鼓励奖励值围绕零居中。这由 [RewardConfig](/docs/trl/main/zh/reward_trainer#trl.RewardConfig) 中的 `center_rewards_coefficient` 参数控制。推荐值为 `1e-2`。

## 记录的指标

在训练和评估过程中，我们记录以下指标：

- `global_step`：迄今为止已执行的优化器步数总数。
- `epoch`：当前 epoch 编号，基于数据集迭代。
- `num_tokens`：迄今为止处理的 token 总数。
- `loss`：最近一个日志记录间隔内的平均损失。
- `accuracy`：正确预测的比例（即模型为选中的响应分配了比被拒绝的响应更高的分数），取最近一个日志记录区间的平均值。
- `min_reward`：模型分配的最小奖励分数。该值在日志记录区间内取平均值。
- `mean_reward`：模型在最近的日志记录间隔内分配的平均奖励分数。
- `max_reward`：模型分配的最大奖励分数。该值在日志记录区间内取平均值。
- `margin`：最近一个日志记录区间内的平均 margin（即 chosen 奖励与 rejected 奖励之间的差值）。
- `learning_rate`：当前学习率，如果使用调度器，该值可能会动态变化。
- `grad_norm`：梯度裁剪前计算的梯度 L2 范数。

## 自定义

### 模型初始化

您可以直接将`from_pretrained()`方法的kwargs传递给[RewardConfig](/docs/trl/main/zh/reward_trainer#trl.RewardConfig)。例如，如果您想以不同的精度加载模型，类似于

```python
model = AutoModelForSequenceClassification.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16)
```

您可以通过向 [RewardConfig](/docs/trl/main/zh/reward_trainer#trl.RewardConfig) 传递 `model_init_kwargs={"dtype": torch.bfloat16}` 参数来实现此操作。

```python
from trl import RewardConfig

training_args = RewardConfig(
    model_init_kwargs={"dtype": torch.bfloat16},
)
```

请注意，`from_pretrained()` 的所有关键字参数均受支持，但 `num_labels` 除外，该参数会自动设置为 1。

### 使用 PEFT 训练适配器

我们支持与 🤗 PEFT 库的紧密集成，允许任何用户方便地训练适配器并在 Hub 上共享，而无需训练整个模型。

```python
from datasets import load_dataset
from trl import RewardTrainer
from peft import LoraConfig

dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")

trainer = RewardTrainer(
    "Qwen/Qwen3-4B",
    train_dataset=dataset,
    peft_config=LoraConfig(modules_to_save=["score"])  # important to include the score head when base model is not a sequence classification model
)

trainer.train()
```

您还可以继续训练您的 [PeftModel](https://huggingface.co/docs/peft/main/en/package_reference/peft_model#peft.PeftModel)。为此，首先在 [RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 外部加载一个 `PeftModel`，然后直接将其传递给 trainer，而不传入 `peft_config` 参数。

```python
from datasets import load_dataset
from trl import RewardTrainer
from peft import AutoPeftModelForCausalLM

model = AutoPeftModelForCausalLM.from_pretrained("trl-lib/Qwen3-4B-Reward-LoRA", is_trainable=True)
dataset = load_dataset("trl-lib/Capybara", split="train")

trainer = RewardTrainer(
    model=model,
    train_dataset=dataset,
)

trainer.train()
```

> [!TIP]
> 在训练适配器时，由于只学习新参数，通常会使用更高的学习率（≈1e‑3）。
>
> ```python
> RewardConfig(learning_rate=1e-3, ...)
> ```

## 使用奖励模型进行工具调用

[RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 完全支持微调具有 _tool calling_ 能力的模型。在这种情况下，每个数据集示例应包含：

- 对话消息，包括任何工具调用（`tool_calls`）和工具响应（`tool` 角色消息）
- `tools` 列中可用工具列表，通常以 JSON 模式提供

有关预期数据集结构的详细信息，请参阅 [Dataset Format — Tool Calling](dataset_formats#tool-calling) 部分。

## RewardTrainer[[trl.RewardTrainer]]

#### trl.RewardTrainer[[trl.RewardTrainer]]

```python
trl.RewardTrainer(model: str | PreTrainedModel | PeftModel, args: trl.trainer.reward_config.RewardConfig | None = None, data_collator: collections.abc.Callable[[list[typing.Any]], dict[str, typing.Any]] | None = None, train_dataset: datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset | None = None, eval_dataset: datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset | datasets.dataset_dict.DatasetDict | datasets.dataset_dict.IterableDatasetDict | dict[str, datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset] | None = None, processing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = None, compute_metrics: collections.abc.Callable[[transformers.trainer_utils.EvalPrediction], dict] | None = None, callbacks: list[transformers.trainer_callback.TrainerCallback] | None = None, optimizers: tuple[typing.Optional[torch.optim.Optimizer], typing.Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None), optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, typing.Any]] | None = None, preprocess_logits_for_metrics: collections.abc.Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, quantization_config: BitsAndBytesConfig | None = None, peft_config: PeftConfig | None = None)
```

[源代码](https://github.com/huggingface/trl/blob/main/trl/trainer/reward_trainer.py#L237)

**参数：**

model (`str` 或 [PreTrainedModel](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel) 或 [PeftModel](https://huggingface.co/docs/peft/main/en/package_reference/peft_model#peft.PeftModel)) : 要训练的模型。可以是以下之一： - 一个字符串，即托管在 huggingface.co 模型仓库中的预训练模型的 *model id*，或一个包含使用 [save_pretrained](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) 保存的模型权重的 *目录* 的路径，例如 `'./my_model_directory/'`。该模型使用 `AutoModelForSequenceClassification.from_pretrained` 加载，并传入 `args.model_init_kwargs` 中的关键字参数。如果未在 `args.model_init_kwargs` 中指定 `dtype`，则默认为 `float32`。这与 [from_pretrained](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) 不同，在后者中（自 Transformers v5 起），dtype 是从模型配置中推断的。 - 一个序列分类 [PreTrainedModel](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel) 对象。 - 一个序列分类 [PeftModel](https://huggingface.co/docs/peft/main/en/package_reference/peft_model#peft.PeftModel) 对象。

args ([RewardConfig](/docs/trl/main/zh/reward_trainer#trl.RewardConfig)，*可选*)：此训练器的配置。如果为 `None`，则使用默认配置。

data_collator (`DataCollator`, *可选*) : 用于将处理后的 `train_dataset` 或 `eval_dataset` 中的元素列表组合成一个批次的函数。默认值为 `DataCollatorForPreference`。

train_dataset ([Dataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset) 或 [IterableDataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.IterableDataset))：用于训练的 Dataset。该 trainer 支持 [preference](#preference) 类型（包括隐式和显式 prompt）。样本的格式可以是以下两种之一： - [Standard](dataset_formats#standard)：每个样本包含纯文本。 - [Conversational](dataset_formats#conversational)：每个样本包含结构化消息（例如 role 和 content）。 只要包含 `chosen_ids` 和 `rejected_ids` 字段，该 trainer 也支持已处理的数据集（已分词）。 当 `train_dataset` 是 [IterableDataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.IterableDataset)（例如流式数据集）时，必须在训练参数中设置 `max_steps`，因为其长度无法推断，而确定训练循环边界和配置学习率调度器需要知道总的训练步数。

eval_dataset （[Dataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset)、[IterableDataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.IterableDataset)、[DatasetDict](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.DatasetDict)、[IterableDatasetDict](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.IterableDatasetDict) 或 `dict[str, Dataset | IterableDataset]`，*可选*）：用于评估的数据集。它必须满足与 `train_dataset` 相同的要求。

processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/main/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), *可选*) : 用于处理数据的分词器。如果为 `None`，则使用 [from_pretrained](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained) 从模型名称加载分词器。必须设置填充标记 `processing_class.pad_token`。如果处理类未设置填充标记，则默认使用 `processing_class.eos_token`。

compute_metrics (`Callable[[EvalPrediction], dict]`，*可选*)：用于在评估期间计算指标的函数。必须接受一个 [EvalPrediction](https://huggingface.co/docs/transformers/main/en/internal/trainer_utils#transformers.EvalPrediction) 并返回一个从字符串到指标值的字典。当通过 [RewardConfig](/docs/trl/main/zh/reward_trainer#trl.RewardConfig) 将 `batch_eval_metrics` 设置为 `True` 时，您的 `compute_metrics` 函数必须接受一个布尔类型的 `compute_result` 参数。这将在最后一个评估批次之后触发，以指示该函数需要计算并返回全局汇总统计量，而不是累积批次级别的统计量。

callbacks （[TrainerCallback](https://huggingface.co/docs/transformers/main/en/main_classes/callback#transformers.TrainerCallback) 列表，*可选*）：用于自定义训练循环的回调列表。这些回调将被添加到[此处](https://huggingface.co/docs/transformers/main_classes/callback)详述的默认回调列表中。若要移除某个默认使用的回调，请使用 [remove_callback](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.remove_callback) 方法。

optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *可选*，默认为 `(None, None)`) : 一个包含要使用的优化器和调度器的元组。默认情况下，将在您的模型上使用 `AdamW` 的实例，并使用由 `args` 控制的、通过 [get_linear_schedule_with_warmup](https://huggingface.co/docs/transformers/main/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) 给出的调度器。

optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *可选*) : 一个包含优化器类和要使用的关键字参数的元组。覆盖 `args` 中的 `optim` 和 `optim_args`。与 `optimizers` 参数不兼容。与 `optimizers` 不同，此参数避免了在初始化 Trainer 之前将模型参数放置在正确设备上的需求。

preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *可选*) : 一个函数，用于在每次评估步骤缓存 logits 之前对其进行预处理。该函数必须接收两个张量，即 logits 和 labels，并在按预期处理后返回 logits。此函数所做的修改将反映在 `compute_metrics` 接收到的预测结果中。请注意，如果数据集不包含 labels，则 labels（第二个参数）将为 `None`。

quantization_config ([BitsAndBytesConfig](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#transformers.BitsAndBytesConfig)，*可选*)：从模型标识符加载模型时使用的量化配置。与 `peft_config` 结合用于 QLoRA 训练。如果模型已经实例化，或者 `args.model_init_kwargs` 中也设置了 `quantization_config`，则忽略此参数。

peft_config ([PeftConfig](https://huggingface.co/docs/peft/main/en/package_reference/config#peft.PeftConfig)，*可选*)：用于包装模型的 PEFT 配置。如果为 `None`，则不包装模型。请注意，如果加载的模型是因果语言模型，强烈建议在 PEFT 配置中设置 `modules_to_save=["score"]`，以确保奖励头得到正确训练。

用于结果监督奖励模型（ORM）的 Trainer。

此类是 [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) 类的封装，并继承了其所有属性和方法。

示例：

```python
>>> from trl import RewardTrainer
>>> from datasets import load_dataset

>>> dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")

>>> trainer = RewardTrainer(
...     model="Qwen/Qwen2.5-0.5B-Instruct",
...     train_dataset=dataset,
... )
>>> trainer.train()
```

#### train[[trl.RewardTrainer.train]]

```python
train(resume_from_checkpoint: str | bool | None = None, trial: optuna.Trial | dict[str, Any] | None = None, ignore_keys_for_eval: list[str] | None = None)
```

[源代码](https://github.com/huggingface/trl/blob/main/transformers/trainer.py#L1465)

**参数：**

resume_from_checkpoint (`str` 或 `bool`，*可选*)：如果为 `str`，则为之前 `Trainer` 实例保存的检查点的本地路径。如果为 `bool` 且等于 `True`，则加载之前 `Trainer` 实例保存在 *args.output_dir* 中的最后一个检查点。如果存在，训练将从此处加载的模型/优化器/调度器状态恢复。

trial (`optuna.Trial` 或 `dict[str, Any]`，*可选*)：用于超参数搜索的试验运行或超参数字典。

ignore_keys_for_eval (`list[str]`, *可选*) : 模型输出（如果输出是字典）中，在训练期间收集预测结果进行评估时应忽略的键列表。

**返回：** `~trainer_utils.TrainOutput`

包含全局步数、训练损失和指标的 Object。

主要训练入口。

#### save_model[[trl.RewardTrainer.save_model]]

```python
save_model(output_dir: str | None = None, _internal_call: bool = False)
```

[源代码](https://github.com/huggingface/trl/blob/main/transformers/trainer.py#L4129)

将保存模型，以便您可以使用 `from_pretrained()` 重新加载它。

仅从主进程保存。

#### push_to_hub[[trl.RewardTrainer.push_to_hub]]

```python
push_to_hub(commit_message: str | None = 'End of training', blocking: bool = True, token: str | None = None, revision: str | None = None, private: bool | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/trl/blob/main/transformers/trainer.py#L4389)

**参数：**

commit_message (`str`，*可选*，默认为 `"End of training"`)：推送时提交的说明信息。

blocking (`bool`, *可选*, 默认为 `True`) : 函数是否应在 `git push` 完成后才返回。

token (`str`，*可选*，默认为 `None`)：具有写入权限的令牌，用于覆盖 Trainer 的原始参数。

revision (`str`, *可选*) : 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。

private (`bool`, *可选*) : 创建仓库时是否将其设为私有。默认值为 `args.hub_private_repo`。如果仓库已存在，则此参数无效。

kwargs (`dict[str, Any]`，*可选*)：传递给 `~Trainer.create_model_card` 的额外关键字参数。

**返回：**

如果 `blocking=False`，则返回推送模型所在存储库的 URL；如果 `blocking=True`，则返回一个跟踪提交进度的 `Future` 对象。

将 `self.model` 和 `self.processing_class` 上传到 🤗 模型库中的仓库 `self.args.hub_model_id`。

## RewardConfig[[trl.RewardConfig]]

#### trl.RewardConfig[[trl.RewardConfig]]

```python
trl.RewardConfig(output_dir: str | None = None, per_device_train_batch_size: int = 8, num_train_epochs: float = 3.0, max_steps: int = -1, learning_rate: float = 0.0001, lr_scheduler_type: transformers.trainer_utils.SchedulerType | str = 'linear', lr_scheduler_kwargs: dict | str | None = None, warmup_steps: float = 0, optim: transformers.training_args.OptimizerNames | str = 'adamw_torch_fused', optim_args: str | None = None, weight_decay: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-08, optim_target_modules: None | str | list[str] = None, gradient_accumulation_steps: int = 1, average_tokens_across_devices: bool = True, max_grad_norm: float = 1.0, label_smoothing_factor: float = 0.0, bf16: bool | None = None, fp16: bool = False, bf16_full_eval: bool = False, fp16_full_eval: bool = False, tf32: bool | None = None, activation_checkpointing: bool | None = None, activation_checkpointing_kwargs: dict[str, typing.Any] | str | None = None, gradient_checkpointing: bool | None = None, gradient_checkpointing_kwargs: dict[str, typing.Any] | str | None = None, torch_compile: bool = False, torch_compile_backend: str | None = None, torch_compile_mode: str | None = None, use_liger_kernel: bool = False, liger_kernel_config: dict[str, bool] | None = None, use_cache: bool = False, neftune_noise_alpha: float | None = None, torch_empty_cache_steps: int | None = None, auto_find_batch_size: bool = False, logging_strategy: transformers.trainer_utils.IntervalStrategy | str = 'steps', logging_steps: float = 10, logging_first_step: bool = False, log_on_each_node: bool = True, logging_nan_inf_filter: bool = True, include_num_input_tokens_seen: str | bool = 'no', log_level: str = 'passive', log_level_replica: str = 'warning', disable_tqdm: bool | None = None, report_to: None | str | list[str] = 'none', run_name: str | None = None, project: str = 'huggingface', trackio_space_id: str | None = None, trackio_bucket_id: str | None = None, trackio_static_space_id: typing.Union[str, NoneType, typing.Literal[False]] = None, eval_strategy: transformers.trainer_utils.IntervalStrategy | str = 'no', eval_steps: float | None = None, eval_delay: float = 0, per_device_eval_batch_size: int = 8, prediction_loss_only: bool = False, eval_on_start: bool = False, eval_do_concat_batches: bool = True, eval_use_gather_object: bool = False, eval_accumulation_steps: int | None = None, include_for_metrics: list[str] = <factory>, batch_eval_metrics: bool = False, save_only_model: bool = False, save_strategy: transformers.trainer_utils.SaveStrategy | str = 'steps', save_steps: float = 500, save_on_each_node: bool = False, save_total_limit: int | None = None, enable_jit_checkpoint: bool = False, push_to_hub: bool = False, hub_token: str | None = None, hub_private_repo: bool | None = None, hub_model_id: str | None = None, hub_strategy: transformers.trainer_utils.HubStrategy | str = 'every_save', hub_always_push: bool = False, hub_revision: str | None = None, load_best_model_at_end: bool = False, metric_for_best_model: str | None = None, greater_is_better: bool | None = None, ignore_data_skip: bool = False, restore_callback_states_from_checkpoint: bool = False, full_determinism: bool = False, seed: int = 42, data_seed: int | None = None, use_cpu: bool = False, accelerator_config: dict | str | None = None, parallelism_config: accelerate.parallelism_config.ParallelismConfig | None = None, dataloader_drop_last: bool = False, dataloader_num_workers: int = 0, dataloader_pin_memory: bool = True, dataloader_persistent_workers: bool = False, dataloader_prefetch_factor: int | None = None, dataloader_multiprocessing_context: str | None = None, dataloader_in_order: bool = True, remove_unused_columns: bool = True, label_names: list[str] | None = None, train_sampling_strategy: str = 'random', length_column_name: str = 'length', ddp_find_unused_parameters: bool | None = None, ddp_bucket_cap_mb: int | None = None, ddp_broadcast_buffers: bool | None = None, ddp_static_graph: bool | None = None, ddp_backend: str | None = None, ddp_timeout: int = 1800, fsdp: str | None = None, fsdp_config: dict[str, typing.Any] | str | None = None, deepspeed: dict | str | None = None, debug: str | list[transformers.debug_utils.DebugOption] = '', skip_memory_metrics: bool = True, do_train: bool = False, do_eval: bool = False, do_predict: bool = False, resume_from_checkpoint: str | None = None, local_rank: int = -1, model_init_kwargs: dict[str, typing.Any] | str | None = None, trust_remote_code: bool = False, chat_template_path: str | None = None, disable_dropout: bool = True, dataset_num_proc: int | None = None, eos_token: str | None = None, max_length: int | None = 1024, pad_to_multiple_of: int | str | None = 'auto', center_rewards_coefficient: float | None = None, activation_offloading: bool = False, pad_token: str | None = None)
```

[源代码](https://github.com/huggingface/trl/blob/main/trl/trainer/reward_config.py#L25)

**控制模型的参数：**

model_init_kwargs (`dict[str, Any]`, *可选*) : [from_pretrained](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForSequenceClassification.from_pretrained) 的关键字参数，当 [RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 的 `model` 参数以字符串形式提供时使用。加载分词器时也会使用 `revision` 的值。

trust_remote_code (`bool`，*可选*，默认为 `False`)：是否允许加载包含自定义 Python 代码的模型和分词器。该参数会转发给 [from_pretrained](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForSequenceClassification.from_pretrained) 和 [from_pretrained](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained)。

chat_template_path (`str`, *可选*) : 如果指定，则设置模型的聊天模板。这可以是 tokenizer 的路径（本地目录或 Hugging Face Hub 模型），也可以是直接指向 Jinja 模板文件的路径。使用 Jinja 文件时，必须确保模板中引用的任何特殊 token 都已添加到 tokenizer 中，并且模型的嵌入层已相应调整大小。

disable_dropout (`bool`，*可选*，默认为 `True`)：是否禁用模型中的 dropout。

**控制数据预处理的参数：**

dataset_num_proc (`int`, *可选*) : 用于处理数据集的进程数。

eos_token (`str`, *可选*) : 用于指示轮次或序列结束标记的 Token。如果为 `None`，则默认为 `processing_class.eos_token`。

max_length (`int` 或 `None`，*可选*，默认为 `1024`)：标记化序列的最大长度。如果 chosen 或 rejected 序列中任意一个超过此值，该样本将被过滤掉。如果为 `None`，则不应用过滤。

pad_to_multiple_of (`int` 或 `str`，*可选*，默认为 `"auto"`)：如果设置，序列将被填充为该值的倍数。`"auto"` 在 Neuron（AWS Trainium）上填充为 128 的倍数，因为 Neuron 针对每个输入形状编译一次；在计算能力为 9.x 或 10.x 的 NVIDIA GPU（H100、B200）上使用 SDPA 注意力时，也会填充为 128 的倍数，因为 cuDNN 会在主机内存中为每个输入形状保留一个图。在其他情况下不会进行填充。

**控制训练的参数：**

center_rewards_coefficient (`float`, *可选*) : 用于激励奖励模型输出均值为零的奖励的系数（由[这篇论文](https://huggingface.co/papers/2312.09244)的公式 2 提出）。推荐值：`0.01`。

activation_offloading (`bool`，*可选*，默认为 `False`)：是否将激活值卸载到 CPU。

**已弃用的参数：**

pad_token :   参数 `pad_token` 已弃用，并将在 v2.0.0 中移除。请直接将 `tokenizer.pad_token` 设置为 `processing_class` 并传递给 trainer。

[RewardTrainer](/docs/trl/main/zh/reward_trainer#trl.RewardTrainer) 的配置类。

此类仅包含 Reward 训练特有的参数。完整的训练参数列表请参阅 [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) 文档。请注意，此类中的默认值可能与 [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) 中的不同。

使用 [HfArgumentParser](https://huggingface.co/docs/transformers/main/en/internal/trainer_utils#transformers.HfArgumentParser)，我们可以将该类转换为可在命令行中指定的 [argparse](https://docs.python.org/3/library/argparse#module-argparse) 参数。

> [!NOTE]
> 这些参数的默认值与 [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) 不同： - `logging_steps`：默认值为 `10`，而非 `500`。 - `gradient_checkpointing`：默认值为 `True`，而非 `False`。 - `bf16`：如果未设置 `fp16`，则默认值为 `True`，而非 `False`。 - `learning_rate`：默认值为 `1e-4`，而非 `5e-5`。

