TRL documentation

報酬関数

You are viewing v1.18.0 version. A newer version v1.18.1 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

報酬関数

このモジュールには、主にGRPOTrainerおよびRLOOTrainerで使用することを目的とした、いくつかの有用な報酬関数が含まれています。

accuracy_reward

trl.rewards.accuracy_reward

< >

( 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]]]) — 評価対象の補完のリストです。各補完は1つのメッセージのリスト、つまり補完のテキストを値として持つキー"content"を含む辞書である必要があります。
  • solution (list[str]) — 質問・問題・プロンプトに対する生のテキスト形式の解答のリスト。
  • log_extra (callable、省略可能) — completions テーブルに追加の列を記録するための関数。trainer によって自動的に提供されます。デフォルトは None で、trainer の外側(テストなど)から関数を直接呼び出すことを可能にします。
  • **kwargs — 追加のキーワード引数。この関数はこれらを使用しませんが、GRPOTrainer などのトレーナーとの互換性を確保するために、関数シグネチャに必要です。

ground truthと補完が一致するかを確認する報酬関数。

  • 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

< >

( 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]]]) — 評価対象の補完のリストです。各補完は1つのメッセージのリスト、つまり補完のテキストを値として持つキー"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

< >

( 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) — コサインスケジュールの正規化に使用される、最大コンプリーション長(トークン数)、$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

補完、その解答、およびトークンIDを受け取り、報酬のリストを返す報酬関数(ゴールドの解答が解析できない例にはNone)。

https://huggingface.co/papers/2502.03373 の論文「Demystifying Long Chain-of-Thought Reasoning」の付録 C.1 を参照してください。この報酬関数は、簡潔な推論を優先するために、コサインスケジュールに従って完了長で正解報酬をスケーリングします。

正しさは数学的検証によって判定されます( accuracy_reward()), 参照)。長さは completion トークンの数です。報酬は、短い completion と長い completion の境界の間で、コサインスケジュールに沿って補間されます: Rcosine(y)=vmin⁡+12(vmax⁡−vmin⁡)(1+cos⁡(∣y∣Lmax⁡π)) 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()と同様です。

例:

>>> 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

< >

( completions: list[list[dict[str, str]]]**kwargs ) → list[float]

パラメータ

  • completions (list[list[dict[str, str]]]) — 評価対象の補完のリストです。各補完は1つのメッセージのリスト、つまり補完のテキストを値として持つキー"content"を含む辞書である必要があります。
  • **kwargs — 追加のキーワード引数。この関数はこれらを使用しませんが、GRPOTrainer などのトレーナーとの互換性を確保するために、関数シグネチャに必要です。

戻り値

list[float]

報酬のリスト。各報酬は、補完が期待される形式と一致する場合に1.0、それ以外の場合は0.0です。

"<think>"と"</think>"タグで囲まれた推論プロセスかどうかを確認する報酬関数です。形式が正しい場合は1.0、それ以外の場合は0.0を返します。

例:

>>> 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

< >

( ngram_size: int = 3max_penalty: float = -1.0 ) → Callable

パラメータ

  • ngram_size (int、任意、デフォルトは3) — 考慮するトークン n-gram のサイズ。
  • max_penalty (float、任意、デフォルトは-1.0) — 最も負のペナルティです。完全に反復的な補完に適用されます。非正値である必要があります。

戻り値

Callable

completionのトークンIDのリストを受け取り、ペナルティのリスト(それぞれ[max_penalty, 0.0]の範囲)を返す報酬関数。

補完内の繰り返しn-gramをペナルティする報酬関数。劣化・反復的なテキストを抑制するために使用されます(長さや形式を整形する報酬が使用される場合の一般的な失敗モードおよび報酬ハッキング戦略です)。参考文献: 「Demystifying Long Chain-of-Thought Reasoning」論文の付録C.2(https://huggingface.co/papers/2502.03373)。

ペナルティは、補完における繰り返し n-gram の割合に比例します: Rrepetition(y)=(1−# unique n-grams# total n-grams)×p R_{\text{repetition}}(y) = \left(1 - \frac{\#\,\text{unique } n\text{-grams}}{\#\,\text{total } n\text{-grams}}\right) \times p

ここで pp は max_penalty. 繰り返し n-gram を含まない補完には 0.0, 、完全に繰り返しのある補完は max_penalty. の報酬が与えられます。n-gram は補完のトークン ID に対して計算されます(論文では繰り返しトークンにペナルティを適用しています)。そのため、報酬はトークナイザーによって定義され、言語に依存しません。 ngram_size トークン未満の補完には 0.0.

例:

>>> 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

< >

( max_completion_len: intsoft_punish_cache: int )

パラメータ

  • max_completion_len (int) — 補完の最大長 ( L_{\max} )。
  • soft_punish_cache (int) — 補完の最小長、 ( L_{\text{cache}‌} )。0に設定すると、最小長は適用されません。

長すぎる補完をペナルティする報酬関数です。長すぎる補完にペナルティを課すために使用されますが、短い補完を報酬として評価するためには使用されません。参照: DAPO論文の式(13) (https://huggingface.co/papers/2503.14476) Rlength(y)={0,∣y∣≤Lmax⁡−Lcache(Lmax⁡−Lcache)−∣y∣Lcache,Lmax⁡−Lcache<∣y∣≤Lmax⁡−1,Lmax⁡<∣y∣ 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}

例:

>>> 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]
Update on GitHub