# 보상 함수

이 모듈에는 주로 [GRPOTrainer](/docs/trl/v1.19.0/ko/grpo_trainer#trl.GRPOTrainer) 및 [RLOOTrainer](/docs/trl/v1.19.0/ko/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]]]`) : 평가할 completions의 목록입니다. 각 completion은 하나의 메시지로 구성된 목록이어야 하며, 즉 completion의 텍스트가 값인 `"content"` 키를 포함하는 딕셔너리여야 합니다.

solution (`list[str]`) : 질문/문제/프롬프트에 대한 원시 텍스트 솔루션 목록.

log_extra (`callable`, *선택 사항*) : trainer가 자동으로 제공하는 completions 테이블에 추가 열을 기록하기 위한 Callable입니다. trainer 외부에서 함수를 직접 호출할 수 있도록(예: 테스트용) 기본값은 `None`입니다.

- ****kwargs** : 추가 키워드 인자입니다. 이 함수는 해당 인자를 사용하지 않지만, [GRPOTrainer](/docs/trl/v1.19.0/ko/grpo_trainer#trl.GRPOTrainer)와 같은 trainer와의 호환성을 보장하기 위해 함수 시그니처에 필요합니다.

ground truth와 completion이 일치하는지 확인하는 reward function입니다.
- 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]]]`) : 평가할 completions의 목록입니다. 각 completion은 하나의 메시지로 구성된 목록이어야 하며, 즉 completion의 텍스트가 값인 `"content"` 키를 포함하는 딕셔너리여야 합니다.

solution (`list[str]`) : 질문/문제/프롬프트에 대한 원시 텍스트 솔루션 목록.

reasoning_delimiters (`list[str]]`, *선택 사항*) : 추론 콘텐츠가 끝나는 위치를 나타내는 문자열 목록입니다. 최종 답변은 이러한 구분자 중 마지막 발생 위치 이후에 있다고 가정합니다. `None`인 경우 기본값은 `["</think>"]`입니다.

log_extra (`callable`, *선택 사항*) : trainer가 자동으로 제공하는 completions 테이블에 추가 열을 기록하기 위한 Callable입니다. trainer 외부에서 함수를 직접 호출할 수 있도록(예: 테스트용) 기본값은 `None`입니다.

- ****kwargs** : 추가 키워드 인자입니다. 이 함수는 해당 인자를 사용하지 않지만, [GRPOTrainer](/docs/trl/v1.19.0/ko/grpo_trainer#trl.GRPOTrainer)와 같은 trainer와의 호환성을 보장하기 위해 함수 시그니처에 필요합니다.

추론 내용을 제거하고 최종 답이 ground truth와 일치하는지 확인하는 reward function
- 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`) : 코사인 스케줄을 정규화하는 데 사용되는 최대 완성 길이(토큰 단위), $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를 받아서 보상 목록을 반환하는 보상 함수(해석할 수 없는 gold solution이 있는 예제는 `None`을 반환).

"Demystifying Long Chain-of-Thought Reasoning" 논문의 부록 C.1을 참고하세요. 이 보상 함수는 간결한 추론을 선호하도록 cosine 스케줄에 따라 완료 길이에 따라 정확도 보상을 스케일링합니다.

정확성은 수학 검증(예: [accuracy_reward()](/docs/trl/v1.19.0/ko/rewards#trl.rewards.accuracy_reward))에 의해 결정되며, 길이는 완성 토큰의 수입니다. 보상은 짧은 완성본과 긴 완성본의 경계 사이에서 코사인 스케줄을 따라 보간됩니다:

$$ 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()](/docs/trl/v1.19.0/ko/rewards#trl.rewards.accuracy_reward)와 마찬가지로 해당 예제는 건너뜁니다(보상 `None`).

예:
```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]]]`) : 평가할 completions의 목록입니다. 각 completion은 하나의 메시지로 구성된 목록이어야 하며, 즉 completion의 텍스트가 값인 `"content"` 키를 포함하는 딕셔너리여야 합니다.

- ****kwargs** : 추가 키워드 인자입니다. 이 함수는 해당 인자를 사용하지 않지만, [GRPOTrainer](/docs/trl/v1.19.0/ko/grpo_trainer#trl.GRPOTrainer)와 같은 trainer와의 호환성을 보장하기 위해 함수 시그니처에 필요합니다.

**반환값:** `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`) : 고려할 토큰 n-gram의 크기입니다.

max_penalty (`float`, *선택 사항*, 기본값 `-1.0`) : 완전히 반복적인 완성문에 적용되는 가장 큰 음수 페널티. 0 이하의 값이어야 합니다.

**반환값:** `Callable`

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

completion에서 반복되는 n-gram을 패널티로 부과하는 보상 함수로, 퇴화적이고 반복적인 텍스트를 억제하는 데 사용됩니다(길이 또는 형식 기반 보상을 사용할 때 흔히 발생하는 실패 모드이자 보상 해킹 전략). 참고: "Demystifying Long Chain-of-Thought Reasoning" 논문의 부록 C.2(https://huggingface.co/papers/2502.03373).

페널티는 완성 결과에서 반복된 n-그램의 비율에 비례합니다:

$$ R_{\text{repetition}}(y) = \left(1 - \frac{\#\,고유한 n-그램 수}{\#\,전체 n-그램 수}\right) \times p $$

여기서 $p$는 `max_penalty`입니다. 반복되는 n-gram이 없는 completion은 `0.0`의 보상을, 완전히 반복적인 completion은 `max_penalty`에 근접하는 보상을 받습니다. n-gram은 completion의 토큰 ID를 기준으로 계산되며(논문에서는 반복되는 토큰에 페널티를 적용), 따라서 보상은 tokenizer에 의해 정의되고 언어에 무관합니다. `ngram_size`보다 적은 수의 토큰을 가진 completion은 `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]
```

