TRL documentation
奖励函数
奖励函数
该模块包含一些有用的奖励函数,主要用于与 GRPOTrainer 和 RLOOTrainer 配合使用。
accuracy_reward
trl.rewards.accuracy_reward
< source >( completions: list[list[dict[str, str]]]solution: list[str]log_extra: collections.abc.Callable[[str, list], None] | None = None**kwargs )
参数
- completions (
list[list[dict[str, str]]]) — 待评估的补全列表。每个补全必须是一个包含一条消息的列表,即一个包含键"content"的字典,其值为补全文本。 - solution (
list[str]) — 问题/题目/提示的原始文本答案列表。 - log_extra (
callable,可选) — 用于将额外列记录到 completions 表的回调函数,由 trainer 自动提供。默认值为None,以便在 trainer 之外直接调用该函数(例如用于测试)。 - **kwargs — 额外的关键字参数。此函数不使用这些参数,但函数签名中需要包含它们,以确保与 GRPOTrainer 等训练器的兼容性。
用于检查补全结果是否与真实值匹配的奖励函数。
- 如果 gold 和 prediction 均可解析 → 使用数学验证。
- 如果 gold 无法解析 → 返回
None以跳过该示例。
示例:
>>> 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
< source >( completions: list[list[dict[str, str]]]solution: list[str]reasoning_delimiters: list[str] | None = Nonelog_extra: collections.abc.Callable[[str, list], None] | None = None**kwargs )
参数
- 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 等训练器的兼容性。
一个奖励函数,用于移除推理内容并检查最终答案是否与真实值匹配。
- 如果 gold 和 prediction 均可解析 → 使用数学验证。
- 如果 gold 无法解析 → 返回
None以跳过该示例。
示例:
>>> 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
< source >( max_len: intmin_value_wrong: float = -1.0max_value_wrong: float = -0.5min_value_correct: float = 0.5max_value_correct: float = 1.0 ) → Callable
参数
- 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()), ),而长度是补全 token 的数量。奖励函数在短补全和长补全的边界之间沿余弦调度进行插值:
对于正确的补全,$(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() 中的处理方式相同。
示例:
>>> 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
< source >( completions: list[list[dict[str, str]]]**kwargs ) → list[float]
参数
- completions (
list[list[dict[str, str]]]) — 待评估的补全列表。每个补全必须是一个包含一条消息的列表,即一个包含键"content"的字典,其值为补全文本。 - **kwargs — 额外的关键字参数。此函数不使用这些参数,但函数签名中需要包含它们,以确保与 GRPOTrainer 等训练器的兼容性。
返回值
list[float]
奖励列表,其中每个奖励在补全内容符合预期格式时为 1.0,否则为 0.0。
一个奖励函数,用于检查推理过程是否被包裹在 "<think>" 和 "</think>" 标签内。如果格式正确,该函数返回奖励值 1.0,否则返回 0.0。
get_repetition_penalty_reward
trl.rewards.get_repetition_penalty_reward
< source >( ngram_size: int = 3max_penalty: float = -1.0 ) → Callable
用于惩罚补全内容中重复 n-gram 的奖励函数,旨在抑制退化、重复的文本(这是在使用长度或格式塑形奖励时常见的失败模式和奖励黑客策略)。参考: “Demystifying Long Chain-of-Thought Reasoning” 论文的附录 C.2(https://huggingface.co/papers/2502.03373)。
惩罚与补全中重复 n-gram 的比例成正比:
其中 为 max_penalty. 未包含重复 n-gram 的补全将获得 0.0, 的奖励,而完全重复的补全则趋近于 max_penalty. n-gram 基于补全的 token id 计算(论文将惩罚应用于重复的 token),因此奖励由分词器定义且与语言无关。长度少于 ngram_size 个 token 的补全将获得 0.0.
get_soft_overlong_punishment
trl.rewards.get_soft_overlong_punishment
< source >( max_completion_len: intsoft_punish_cache: int )
用于惩罚过长补全的奖励函数。它仅用于惩罚过长的补全,而不会奖励较短的补全。参考:DAPO 论文中的公式 (13)(https://huggingface.co/papers/2503.14476)
示例:
>>> 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]