TRL documentation

보상 함수

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.18.0).
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]]]) — 평가할 completions 목록입니다. 각 completion은 메시지 하나, 즉 "content" 키를 포함하고 그 값이 completion 텍스트인 딕셔너리의 목록이어야 합니다.
  • solution (list[str]) — 질문/문제/프롬프트에 대한 원문 솔루션 목록.
  • log_extra (callable, 선택 사항) — trainer가 자동으로 제공하는 completions 테이블에 추가 열을 기록하기 위한 callable입니다. trainer 외부에서 함수를 직접 호출할 수 있도록(예: 테스트용) 기본값은 None입니다.
  • **kwargs — 추가 키워드 인자입니다. 이 함수는 해당 인자를 사용하지 않지만, GRPOTrainer와 같은 trainer와의 호환성을 보장하기 위해 함수 시그니처에 필요합니다.

ground truth와 completion이 일치하는지 확인하는 reward function입니다.

  • 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]]]) — 평가할 completions 목록입니다. 각 completion은 메시지 하나, 즉 "content" 키를 포함하고 그 값이 completion 텍스트인 딕셔너리의 목록이어야 합니다.
  • solution (list[str]) — 질문/문제/프롬프트에 대한 원문 솔루션 목록.
  • reasoning_delimiters (list[str]], 선택 사항) — 추론 콘텐츠가 끝나는 위치를 나타내는 문자열 목록입니다. 최종 답변은 이러한 구분자 중 마지막 발생 위치 이후에 있다고 가정합니다. None인 경우 기본값은 ["</think>"]입니다.
  • log_extra (callable, 선택 사항) — trainer가 자동으로 제공하는 completions 테이블에 추가 열을 기록하기 위한 callable입니다. trainer 외부에서 함수를 직접 호출할 수 있도록(예: 테스트용) 기본값은 None입니다.
  • **kwargs — 추가 키워드 인자입니다. 이 함수는 해당 인자를 사용하지 않지만, GRPOTrainer와 같은 trainer와의 호환성을 보장하기 위해 함수 시그니처에 필요합니다.

추론 내용을 제거하고 최종 답이 ground truth와 일치하는지 확인하는 reward function

  • 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

completions, 해당 솔루션, token ids를 받아서 보상 목록을 반환하는 보상 함수 (해결책이 파싱되지 않는 예제는 None을 반환합니다).

https://huggingface.co/papers/2502.03373에 제시된 “Demystifying Long Chain-of-Thought Reasoning” 논문의 부록 C.1을 참고하여, 간결한 추론을 선호하도록 cosine 스케줄에 따라 completion length로 correctness reward를 스케일링하는 reward function입니다.

정답성은 수학적 검증(예: 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})$으로 바뀌어 더 짧은 완성이 더 큰 패널티를 받습니다(더 긴 잘못된 완성은 패널티가 적어 탐색이 유지됩니다). 정답이 파싱되지 않으면 accuracy_reward()와 마찬가지로 해당 예제가 건너뜁니다(보상 None).

예:

>>> 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]]]) — 평가할 completions 목록입니다. 각 completion은 메시지 하나, 즉 "content" 키를 포함하고 그 값이 completion 텍스트인 딕셔너리의 목록이어야 합니다.
  • **kwargs — 추가 키워드 인자입니다. 이 함수는 해당 인자를 사용하지 않지만, GRPOTrainer와 같은 trainer와의 호환성을 보장하기 위해 함수 시그니처에 필요합니다.

반환값

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) — 완전히 반복적인 완성문에 적용되는 가장 큰 음수 페널티입니다. 0 이하의 값이어야 합니다.

반환값

Callable

completion 토큰 id 목록을 받아 penalty 목록(각각 [max_penalty, 0.0] 범위)을 반환하는 보상 함수입니다.

완료물에서 반복되는 n-그램을 패널티로 부과하는 보상 함수로, 길이 또는 형식 기반 보상이 사용될 때 흔히 발생하는 퇴화적이고 반복적인 텍스트(일반적인 실패 모드이자 보상 해킹 전략)를 억제하는 데 사용됩니다. 참고: “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이 없는 completion은 보상으로 0.0, 을, 완전히 반복적인 completion은 max_penalty. 에 접근합니다. n-gram은 completion의 토큰 ID를 기준으로 계산되며(논문에서는 반복된 토큰에 페널티를 적용), 따라서 보상은 tokenizer에 의해 정의되고 언어에 무관합니다. 토큰 수가 ngram_size 보다 적은 completion은 보상으로 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