# 奖励函数

该模块包含一些有用的奖励函数，主要用于与 [GRPOTrainer](/docs/trl/v1.19.0/zh/grpo_trainer#trl.GRPOTrainer) 和 [RLOOTrainer](/docs/trl/v1.19.0/zh/rloo_trainer#trl.RLOOTrainer) 配合使用。

## accuracy_reward[[trl.rewards.accuracy_reward]]

#### trl.rewards.accuracy_reward[[trl.rewards.accuracy_reward]]

```python
trl.rewards.accuracy_reward(completions: list[list[dict[str, str]]], solution: list[str], log_extra: collections.abc.Callable[[str, list], None] | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/trl/blob/v1.19.0/trl/rewards/accuracy_rewards.py#L127)

**参数：**

completions (`list[list[dict[str, str]]]`) : 待评估的补全列表。每个补全必须是一个包含一条消息的列表，即一个包含键 `"content"` 的字典，其值为补全文本。

solution (`list[str]`) : 问题/题目/提示的原始文本答案列表。

log_extra (`callable`，*可选*)：用于将额外列记录到 completions 表的回调函数，由 trainer 自动提供。默认值为 `None`，以便在 trainer 之外直接调用该函数（例如用于测试）。

- ****kwargs** : 额外的关键字参数。此函数不使用这些参数，但函数签名中需要包含它们，以确保与 [GRPOTrainer](/docs/trl/v1.19.0/zh/grpo_trainer#trl.GRPOTrainer) 等训练器的兼容性。

用于检查补全结果是否与真实值匹配的奖励函数。
- 如果 gold 和 prediction 均可解析 → 使用数学验证。
- 如果 gold 无法解析 → 返回 `None` 以跳过该示例。

示例：
```python
>>> from trl.rewards import accuracy_reward

>>> solutions = [r"\frac{1}{3}", r"\frac{1}{3}"]
>>> completions = [
...     [{"role": "assistant", "content": r"My answer is \boxed{\frac{1}{3}}"}],
...     [{"role": "assistant", "content": r"My answer is \boxed{\frac{1}{2}}"}],
... ]
>>> accuracy_reward(completions, solutions)
[1.0, 0.0]
```

## reasoning_accuracy_reward[[trl.rewards.reasoning_accuracy_reward]]

#### trl.rewards.reasoning_accuracy_reward[[trl.rewards.reasoning_accuracy_reward]]

```python
trl.rewards.reasoning_accuracy_reward(completions: list[list[dict[str, str]]], solution: list[str], reasoning_delimiters: list[str] | None = None, log_extra: collections.abc.Callable[[str, list], None] | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/trl/blob/v1.19.0/trl/rewards/accuracy_rewards.py#L290)

**参数：**

completions (`list[list[dict[str, str]]]`) : 待评估的补全列表。每个补全必须是一个包含一条消息的列表，即一个包含键 `"content"` 的字典，其值为补全文本。

solution (`list[str]`) : 问题/题目/提示的原始文本答案列表。

reasoning_delimiters (`list[str]]`, *可选*) : 指示推理内容结束位置的字符串列表。最终答案假定位于这些分隔符最后一次出现之后。如果为 `None`，则默认为 `["</think>"]`。

log_extra (`callable`，*可选*)：用于将额外列记录到 completions 表的回调函数，由 trainer 自动提供。默认值为 `None`，以便在 trainer 之外直接调用该函数（例如用于测试）。

- ****kwargs** : 额外的关键字参数。此函数不使用这些参数，但函数签名中需要包含它们，以确保与 [GRPOTrainer](/docs/trl/v1.19.0/zh/grpo_trainer#trl.GRPOTrainer) 等训练器的兼容性。

一个奖励函数，用于移除推理内容并检查最终答案是否与真实值匹配。
- 如果 gold 和 prediction 均可解析 → 使用数学验证。
- 如果 gold 无法解析 → 返回 `None` 以跳过该示例。

示例：
```python
>>> from trl.rewards import reasoning_accuracy_reward

>>> reasoning_delimiters = ["</think>"]
>>> solutions = [r"\frac{1}{3}", r"\frac{1}{3}", r"\frac{1}{3}"]
>>> completions = [
...     [
...         {
...             "role": "assistant",
...             "content": r"<think> Reasoning content </think> The final answer is \boxed{\frac{1}{3}}",
...         }
...     ],
...     [
...         {
...             "role": "assistant",
...             "content": r"<think> Reasoning content </think> The final answer is \boxed{\frac{1}{2}}",
...         }
...     ],
...     [
...         {
...             "role": "assistant",
...             "content": r"<think> Reasoning content with partial answers \boxed{\frac{1}{3}} but no final answer",
...         }
...     ],
... ]
>>> reasoning_accuracy_reward(completions, solutions, reasoning_delimiters=reasoning_delimiters)
[1.0, 0.0, 0.0]
```

## get_cosine_scaled_reward[[trl.rewards.get_cosine_scaled_reward]]

#### trl.rewards.get_cosine_scaled_reward[[trl.rewards.get_cosine_scaled_reward]]

```python
trl.rewards.get_cosine_scaled_reward(max_len: int, min_value_wrong: float = -1.0, max_value_wrong: float = -0.5, min_value_correct: float = 0.5, max_value_correct: float = 1.0)
```

[源代码](https://github.com/huggingface/trl/blob/v1.19.0/trl/rewards/accuracy_rewards.py#L185)

**参数：**

max_len (`int`) : 用于归一化余弦调度的最大生成长度（以 token 计），$L_{\max}$。

min_value_wrong (`float`, *可选*，默认为 `-1.0`)：最短长度下错误补全的奖励值。

max_value_wrong (`float`, *可选*，默认为 `-0.5`)：在最长长度下，错误补全的奖励值。

min_value_correct (`float`, *可选*，默认为 `0.5`)：在最长长度下正确完成的奖励。

max_value_correct (`float`, *可选*，默认为 `1.0`)：最短长度下正确完成的奖励。

**返回：** `Callable`

一个奖励函数，接收补全内容、其对应的解以及 token id，并返回一个奖励列表（对于无法解析的 gold solution 示例，返回 `None`）。

一种奖励函数，按照余弦调度根据完成长度对正确性奖励进行缩放，以鼓励简洁的推理。参考：“Demystifying Long Chain-of-Thought Reasoning”论文的附录 C.1（https://huggingface.co/papers/2502.03373）。

正确性由数学验证确定（如 [accuracy_reward()](/docs/trl/v1.19.0/zh/rewards#trl.rewards.accuracy_reward) 所示），长度指补全 token 的数量。奖励沿余弦调度在短补全和长补全的边界之间进行插值：

$$ R_{\text{cosine}}(y) = v_{\min} + \frac{1}{2}(v_{\max} - v_{\min})\left(1 + \cos\left(\frac{|y|}{L_{\max}}\pi\right)\right) $$

对于**正确**的补全，$(v_{\min}, v_{\max}) = (\texttt{min\_value\_correct}, \texttt{max\_value\_correct})$，因此较短的补全会获得更高的奖励。对于**错误**的补全，边界被交换为 $(v_{\min}, v_{\max}) = (\texttt{max\_value\_wrong}, \texttt{min\_value\_wrong})$，因此较短的补全会受到更严厉的惩罚（较长的错误补全受到的惩罚较轻，从而保留了探索性）。当标准答案无法解析时，该示例将被跳过（奖励为 `None`），与 [accuracy_reward()](/docs/trl/v1.19.0/zh/rewards#trl.rewards.accuracy_reward) 中的处理方式相同。

示例：
```python
>>> from trl.rewards import get_cosine_scaled_reward

>>> cosine_scaled_reward = get_cosine_scaled_reward(max_len=100)
>>> completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
>>> solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
>>> completion_ids = [[1] * 50, [1] * 50]  # both completions are 50 tokens, half of max_len
>>> cosine_scaled_reward(completions, solution, completion_ids)
[0.75, -0.75]
```

## think_format_reward[[trl.rewards.think_format_reward]]

#### trl.rewards.think_format_reward[[trl.rewards.think_format_reward]]

```python
trl.rewards.think_format_reward(completions: list[list[dict[str, str]]], **kwargs)
```

[源代码](https://github.com/huggingface/trl/blob/v1.19.0/trl/rewards/format_rewards.py#L18)

**参数：**

completions (`list[list[dict[str, str]]]`) : 待评估的补全列表。每个补全必须是一个包含一条消息的列表，即一个包含键 `"content"` 的字典，其值为补全文本。

- ****kwargs** : 额外的关键字参数。此函数不使用这些参数，但函数签名中需要包含它们，以确保与 [GRPOTrainer](/docs/trl/v1.19.0/zh/grpo_trainer#trl.GRPOTrainer) 等训练器的兼容性。

**返回：** `list[float]`

奖励列表，其中每个奖励在补全内容符合预期格式时为 1.0，否则为 0.0。

一个奖励函数，用于检查推理过程是否被包裹在 `"<think>"` 和 `"</think>"` 标签内。如果格式正确，该函数返回奖励值 1.0，否则返回 0.0。

示例：
```python
>>> from trl.rewards import think_format_reward

>>> completions = [
...     [{"content": "<think>\nThis is my reasoning.\n</think>\nThis is my answer."}],
...     [{"content": "<think>\nThis is my reasoning.\nThis is my answer."}],
... ]
>>> think_format_reward(completions)
[1.0, 0.0]
```

## get_repetition_penalty_reward[[trl.rewards.get_repetition_penalty_reward]]

#### trl.rewards.get_repetition_penalty_reward[[trl.rewards.get_repetition_penalty_reward]]

```python
trl.rewards.get_repetition_penalty_reward(ngram_size: int = 3, max_penalty: float = -1.0)
```

[源代码](https://github.com/huggingface/trl/blob/v1.19.0/trl/rewards/other_rewards.py#L18)

**参数：**

ngram_size (`int`，*可选*，默认为 `3`)：要考虑的 token n-gram 的大小。

max_penalty (`float`, *可选*，默认为 `-1.0`)：最负的惩罚值，应用于完全重复的补全。必须为非正值。

**返回：** `Callable`

一个奖励函数，接收一个补全 token id 列表，并返回一个惩罚列表（每个值均在 `[max_penalty, 0.0]` 范围内）。

用于惩罚补全内容中重复 n-gram 的奖励函数，旨在抑制退化、重复的文本（当使用长度或格式塑形奖励时，这是一种常见的失效模式和奖励作弊策略）。参考：“Demystifying Long Chain-of-Thought Reasoning” 论文的附录 C.2（https://huggingface.co/papers/2502.03373）。

该惩罚与补全中重复 n-gram 的比例成正比：

$$ R_{\text{repetition}}(y) = \left(1 - \frac{\#\,\text{unique } n\text{-grams}}{\#\,\text{total } n\text{-grams}}\right) \times p $$

其中 $p$ 为 `max_penalty`。没有重复 n-gram 的补全获得 `0.0` 的奖励，而完全重复的补全则趋近于 `max_penalty`。n-gram 基于补全的 token id 计算（论文将惩罚应用于重复的 token），因此奖励由分词器定义且与语言无关。token 数少于 `ngram_size` 的补全获得 `0.0` 的奖励。

示例：
```python
>>> from trl.rewards import get_repetition_penalty_reward

>>> repetition_penalty = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
>>> completion_ids = [[1, 2, 3, 4], [5, 5, 5, 5, 5]]
>>> repetition_penalty(completion_ids)
[0.0, -0.75]
```

## get_soft_overlong_punishment[[trl.rewards.get_soft_overlong_punishment]]

#### trl.rewards.get_soft_overlong_punishment[[trl.rewards.get_soft_overlong_punishment]]

```python
trl.rewards.get_soft_overlong_punishment(max_completion_len: int, soft_punish_cache: int)
```

[源代码](https://github.com/huggingface/trl/blob/v1.19.0/trl/rewards/other_rewards.py#L83)

**参数：**

max_completion_len (`int`) : 补全的最大长度，\( L_{\max} \)。

soft_punish_cache (`int`) : 补全的最小长度，\( L_{\text{cache}} \)。如果设置为 `0`，则不应用最小长度限制。

用于惩罚过长补全的奖励函数。它仅用于惩罚过长的补全，而不会奖励较短的补全。参考：DAPO 论文中的公式 (13)（https://huggingface.co/papers/2503.14476）

$$ R_{\text{length}}(y) = \begin{cases} 0, & |y| \le L_{\max} - L_{\text{cache}} \\ \dfrac{(L_{\max} - L_{\text{cache}}) - |y|}{L_{\text{cache}}}, & L_{\max} - L_{\text{cache}} < |y| \le L_{\max} \\ -1, & L_{\max} < |y| \end{cases} $$

示例：
```python
>>> from trl.rewards import get_soft_overlong_punishment

>>> soft_overlong_punishment = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
>>> completion_ids = [[1] * 90]  # simulating a completion with 90 tokens. 90 is between 80 and 100.
>>> soft_overlong_punishment(completion_ids)
>>> [-0.5]
```

