# 보상 모델링

[![model badge](https://img.shields.io/badge/All_models-Reward_Trainer-blue)](https://huggingface.co/models?other=reward-trainer,trl)

## 개요

TRL은 보상 모델 학습을 위한 결과 기반 보상 모델링(ORM) 트레이너를 지원합니다.

이 포스트 트레이닝 방법은 [Younes Belkada](https://huggingface.co/ybelkada)가 기여했습니다.

## 빠른 시작

이 예제는 TRL의 [RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)를 사용하여 보상 모델을 학습하는 방법을 보여줍니다. 대규모, 세밀하고 다양한 선호 데이터셋인 [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized)에서 [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) 모델을 학습합니다.

```python
from trl import RewardTrainer
from datasets import load_dataset

trainer = RewardTrainer(
    model="Qwen/Qwen3-0.6B",
    train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"),
)
trainer.train()
```

## 기대되는 데이터셋 유형 및 형식

[RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)는 [preference](dataset_formats#preference) 데이터셋 유형(암시적 및 명시적 프롬프트 모두)을 지원합니다. [RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)는 [standard](dataset_formats#standard) 및 [conversational](dataset_formats#conversational) 데이터셋 형식 모두와 호환됩니다. conversational 데이터셋이 제공되면 트레이너는 데이터셋에 채팅 템플릿을 자동으로 적용합니다.

```python
# Standard preference (implicit prompt)
{"chosen": "The sky is blue.",
 "rejected": "The sky is green."}

# Conversational preference (implicit prompt)
{"chosen": [{"role": "user", "content": "What color is the sky?"},
            {"role": "assistant", "content": "It is blue."}],
 "rejected": [{"role": "user", "content": "What color is the sky?"},
              {"role": "assistant", "content": "It is green."}]}

# Standard preference (explicit prompt)
{"prompt": "The sky is",
 "chosen": " blue.",
 "rejected": " green."}

# Conversational preference (explicit prompt)
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
 "chosen": [{"role": "assistant", "content": "It is blue."}],
 "rejected": [{"role": "assistant", "content": "It is green."}]}
```

데이터셋이 이러한 형식 중 하나에 해당하지 않는 경우, 예상되는 형식으로 변환하기 위해 전처리할 수 있습니다. [lmarena-ai/arena-human-preference-55k](https://huggingface.co/datasets/lmarena-ai/arena-human-preference-55k) 데이터셋을 사용한 예시는 다음과 같습니다:

```python
from datasets import load_dataset
import json

dataset = load_dataset("lmarena-ai/arena-human-preference-55k")

# Filter out ties
dataset = dataset.filter(lambda example: example["winner_tie"] == 0)

# Create 'chosen' and 'rejected' fields based on the winner column
def response_a_b_to_chosen_rejected(example):
    if example["winner_model_a"] == 1:
        example["chosen"] = example["response_a"]
        example["rejected"] = example["response_b"]
    else:
        example["chosen"] = example["response_b"]
        example["rejected"] = example["response_a"]
    return example

dataset = dataset.map(response_a_b_to_chosen_rejected)

# Convert to conversational format
def make_conversation(example):
    prompt = json.loads(example["prompt"])[0]  # '["What color is the sky?"]' -> "What color is the sky?"
    chosen = json.loads(example["chosen"])[0]
    rejected = json.loads(example["rejected"])[0]
    return {
        "chosen": [{"role": "user", "content": prompt}, {"role": "assistant", "content": chosen}],
        "rejected": [{"role": "user", "content": prompt}, {"role": "assistant", "content": rejected}],
    }

dataset = dataset.map(make_conversation)

# Keep only necessary columns
dataset = dataset.select_columns(["chosen", "rejected"])

print(next(iter(dataset["train"])))
```

```json
{
    "chosen": [
        {"role": "user", "content": "Is it morally right to try to have a certain percentage of females on managerial positions?"},
        {"role": "assistant", "content": "The question of whether it is morally right to aim for a certain percentage of females..."},
    ],
    "rejected": [
        {"role": "user", "content": "Is it morally right to try to have a certain percentage of females on managerial positions?"},
        {"role": "assistant", "content": "As an AI, I don't have personal beliefs or opinions. However, ..."},
    ],
}
```

## 학습 방법 심층 분석

Reward Models (RMs)는 일반적으로 선호하는 응답과 선호하지 않는 응답의 쌍을 포함하는 데이터셋을 사용하여 지도 학습으로 학습됩니다. 목표는 선호하는 응답에 더 높은 점수를 부여하는 함수를 학습하여, 모델이 선호도에 기반하여 출력을 순위 매기도록 하는 것입니다.

이 섹션에서는 보상 모델링이 실제로 어떻게 작동하는지, 주요 단계인 **전처리**와 **손실 계산**를 중심으로 설명합니다.

### 전처리 및 토큰화

학습 중 각 예시는 **chosen** 및 **rejected** 필드를 포함해야 합니다. 예상되는 형식에 대한 자세한 내용은 [Dataset formats - Preference](dataset_formats#preference)를 참조하세요. [RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)는 모델의 토크나이저를 사용하여 각 입력을 토큰화합니다. 프롬프트와 완성문(chosen 및 rejected)이 별도로 제공되는 경우(명시적 프롬프트 케이스)에는 토큰화 전에 연결됩니다.

### 손실 계산

\\( x \\)를 입력 시퀀스(프롬프트)라고 하고, \\( y^+ \\)와 \\( y^- \\)를 각각 선택된 시퀀스와 거부된 시퀀스라고 합시다. Bradley-Terry 모델([Bradley & Terry, 1952](https://www.jstor.org/stable/2334029))에서 보상 함수 \\( r \\)가 주어졌을 때, \\( y^+ \\)가 \\( y^- \\)보다 선호될 확률은 \\( p(y^+ ≻ y^- |x) = \sigma(r(x, y^+)−r(x, y^-)) \\)이며, 여기서 \\( σ \\)는 시그모이드 함수입니다.

보상 모델 \\( r_\theta(x, y) \\)은 선호되지 않는 응답 \\( y^- \\)보다 선호되는 응답 \\( y^+ \\)에 더 높은 점수를 부여하도록 학습됩니다. 손실은 관찰된 선호도의 음의 로그 가능도(negative log-likelihood)로 정의됩니다:

$$ \mathcal{L}(\theta) = - \mathbb{E}_{(x,y^+,y^-) \sim \mathcal{D}} \left[ \log \sigma(r_\theta(x, y^+) - r_\theta(x, y^-)) \right]. $$

> [!TIP]
> Bradley-Terry 모델은 과소결정(underdetermined)되어 있어, 모든 보상 값에 상수를 더해도 선호 확률은 변하지 않습니다. 이를 해결하기 위해 [Helping or Herding? Reward Model Ensembles Mitigate but do not Eliminate Reward Hacking](https://huggingface.co/papers/2312.09244) 논문은 보상이 0을 중심으로 분포하도록 유도하는 보조 손실 항을 추가하는 방법을 제안합니다. 이 동작은 [RewardConfig](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardConfig)의 `center_rewards_coefficient` 파라미터로 제어됩니다. 권장 값은 `1e-2`입니다.

## 기록된 지표

학습 및 평가 중에 다음 메트릭을 기록합니다:

- `global_step`: 지금까지 수행된 옵티마이저 스텝의 총 개수.
- `epoch`: 데이터셋 반복에 기반한 현재 epoch 번호
- `num_tokens`: 지금까지 처리된 토큰의 총 개수.
- `loss`: 마지막 로깅 구간의 평균 손실.
- `accuracy`: 마지막 로깅 구간의 평균으로 계산된 올바른 예측의 비율(즉, 모델이 거부된 응답보다 선택된 응답에 더 높은 점수를 부여한 경우).
- `min_reward`: 모델이 할당하는 최소 보상 점수입니다. 이 값은 로깅 간격에 걸쳐 평균화됩니다.
- `mean_reward`: 마지막 로깅 간격 동안 모델이 부여한 평균 보상 점수.
- `max_reward`: 모델이 할당하는 최대 보상 점수입니다. 이 값은 로깅 간격에 걸쳐 평균화됩니다.
- `margin`: 마지막 로깅 구간의 평균 마진(선택된 보상과 거부된 보상의 차이).
- `learning_rate`: 현재 학습률입니다. 스케줄러를 사용하는 경우 동적으로 변경될 수 있습니다.
- `grad_norm`: 그라디언트 클리핑 전에 계산된 그라디언트의 L2 노름.

## 커스터마이징

### 모델 초기화

`from_pretrained()` 메서드의 kwargs를 [RewardConfig](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardConfig)에 직접 전달할 수 있습니다. 예를 들어, 다른 정밀도로 모델을 로드하려면

```python
model = AutoModelForSequenceClassification.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16)
```

`model_init_kwargs={"dtype": torch.bfloat16}` 인수를 [RewardConfig](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardConfig)에 전달하여 수행할 수 있습니다.

```python
from trl import RewardConfig

training_args = RewardConfig(
    model_init_kwargs={"dtype": torch.bfloat16},
)
```

`from_pretrained()`의 모든 키워드 인자가 지원되지만, `num_labels`는 자동으로 1로 설정되므로 제외됩니다.

### PEFT로 어댑터 학습

🤗 PEFT 라이브러리와 긴밀한 통합을 지원하여, 사용자는 전체 모델을 학습하는 대신 어댑터를 편리하게 학습하고 Hub에 공유할 수 있습니다.

```python
from datasets import load_dataset
from trl import RewardTrainer
from peft import LoraConfig

dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")

trainer = RewardTrainer(
    "Qwen/Qwen3-4B",
    train_dataset=dataset,
    peft_config=LoraConfig(modules_to_save=["score"])  # important to include the score head when base model is not a sequence classification model
)

trainer.train()
```

[PeftModel](https://huggingface.co/docs/peft/v0.22.0/en/package_reference/peft_model#peft.PeftModel)의 학습을 계속 진행할 수도 있습니다. 이를 위해 먼저 [RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer) 외부에서 `PeftModel`을 로드한 후, `peft_config` 인자를 전달하지 않고 trainer에 직접 전달합니다.

```python
from datasets import load_dataset
from trl import RewardTrainer
from peft import AutoPeftModelForCausalLM

model = AutoPeftModelForCausalLM.from_pretrained("trl-lib/Qwen3-4B-Reward-LoRA", is_trainable=True)
dataset = load_dataset("trl-lib/Capybara", split="train")

trainer = RewardTrainer(
    model=model,
    train_dataset=dataset,
)

trainer.train()
```

> [!TIP]
> 어댑터를 학습할 때는 새로운 매개변수만 학습되므로 일반적으로 더 높은 학습률(≈1e‑3)을 사용합니다.
>
> ```python
> RewardConfig(learning_rate=1e-3, ...)
> ```

## 보상 모델링을 활용한 도구 호출

[RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)는 _tool calling_ 기능이 있는 모델의 fine-tuning을 완전히 지원합니다. 이 경우 각 데이터셋 예시에는 다음이 포함되어야 합니다:

- 도구 호출(`tool_calls`) 및 도구 응답(`tool` 역할 메시지)을 포함한 대화 메시지
- `tools` 열에 있는 사용 가능한 도구 목록, 일반적으로 JSON 스키마로 제공됩니다

기대하는 데이터셋 구조에 대한 자세한 내용은 [Dataset Format — Tool Calling](dataset_formats#tool-calling) 섹션을 참고하세요.

## RewardTrainer[[trl.RewardTrainer]]

#### trl.RewardTrainer[[trl.RewardTrainer]]

```python
trl.RewardTrainer(model: str | PreTrainedModel | PeftModel, args: trl.trainer.reward_config.RewardConfig | None = None, data_collator: collections.abc.Callable[[list[typing.Any]], dict[str, typing.Any]] | None = None, train_dataset: datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset | None = None, eval_dataset: datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset | datasets.dataset_dict.DatasetDict | datasets.dataset_dict.IterableDatasetDict | dict[str, datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset] | None = None, processing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = None, compute_metrics: collections.abc.Callable[[transformers.trainer_utils.EvalPrediction], dict] | None = None, callbacks: list[transformers.trainer_callback.TrainerCallback] | None = None, optimizers: tuple[typing.Optional[torch.optim.Optimizer], typing.Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None), optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, typing.Any]] | None = None, preprocess_logits_for_metrics: collections.abc.Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, quantization_config: BitsAndBytesConfig | None = None, peft_config: PeftConfig | None = None)
```

[소스](https://github.com/huggingface/trl/blob/v1.18.2/trl/trainer/reward_trainer.py#L233)

**매개변수:**

model (`str` 또는 [PreTrainedModel](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/model#transformers.PreTrainedModel) 또는 [PeftModel](https://huggingface.co/docs/peft/v0.22.0/en/package_reference/peft_model#peft.PeftModel)) : 학습할 모델. 다음 중 하나일 수 있습니다:  - huggingface.co의 모델 저장소에 호스팅된 사전 학습 모델의 *model id*인 문자열, 또는 [save_pretrained](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/model#transformers.PreTrainedModel.save_pretrained)를 사용하여 모델 가중치를 저장한 *directory*의 경로, 예: `'./my_model_directory/'`. 모델은 `args.model_init_kwargs`의 키워드 인수를 사용하여 `AutoModelForSequenceClassification.from_pretrained`로 로드됩니다. `args.model_init_kwargs`에 `dtype`가 지정되지 않으면 기본값은 `float32`입니다. 이는 (Transformers v5부터) 모델 구성에서 dtype을 추론하는 [from_pretrained](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained)와 다릅니다. - 시퀀스 분류 [PreTrainedModel](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/model#transformers.PreTrainedModel) 객체. - 시퀀스 분류 [PeftModel](https://huggingface.co/docs/peft/v0.22.0/en/package_reference/peft_model#peft.PeftModel) 객체.

args ([RewardConfig](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardConfig), *선택 사항*) : 이 trainer의 설정입니다. `None`인 경우 기본 설정이 사용됩니다.

data_collator (`DataCollator`, *선택 사항*) : 처리된 `train_dataset` 또는 `eval_dataset`의 요소 목록에서 배치(batch)를 형성하는 데 사용할 함수입니다. 기본값은 `DataCollatorForPreference`입니다.

train_dataset ([Dataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset) 또는 [IterableDataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.IterableDataset)) : 학습에 사용할 Dataset입니다. 이 trainer는 [preference](#preference) 유형(암시적 및 명시적 프롬프트 모두)을 지원합니다. 샘플의 형식은 다음과 같습니다: - [Standard](dataset_formats#standard): 각 샘플에 일반 텍스트가 포함됩니다. - [Conversational](dataset_formats#conversational): 각 샘플에 구조화된 메시지(예: role과 content)가 포함됩니다.  trainer는 `chosen_ids`와 `rejected_ids` 필드를 포함하는 한, 처리된 dataset(tokenized)도 지원합니다.  `train_dataset`이 [IterableDataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.IterableDataset)(예: 스트리밍 dataset)인 경우, 길이를 추론할 수 없으므로 학습 루프를 제한하고 학습률 스케줄러를 구성하는 데 필요한 총 학습 단계 수를 위해 학습 인자에 `max_steps`를 설정해야 합니다.

eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset), [IterableDataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.IterableDataset), [DatasetDict](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.DatasetDict), [IterableDatasetDict](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.IterableDatasetDict) 또는 `dict[str, Dataset | IterableDataset]`) : 평가에 사용할 Dataset입니다. `train_dataset`과 동일한 요구 사항을 충족해야 합니다.

processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.23.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), *선택 사항*) : 데이터를 처리하는 데 사용되는 토크나이저입니다. `None`인 경우, [from_pretrained](https://huggingface.co/docs/transformers/v5.23.0/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained)를 사용하여 모델 이름에서 토크나이저가 로드됩니다. 패딩 토큰인 `processing_class.pad_token`이 설정되어 있어야 합니다. 처리 클래스에 패딩 토큰이 설정되지 않은 경우, `processing_class.eos_token`이 기본값으로 사용됩니다.

compute_metrics (`Callable[[EvalPrediction], dict]`, *선택 사항*) : 평가 시 메트릭을 계산하는 데 사용되는 함수입니다. [EvalPrediction](https://huggingface.co/docs/transformers/v5.23.0/en/internal/trainer_utils#transformers.EvalPrediction)를 인자로 받아 문자열에서 메트릭 값으로 매핑된 딕셔너리를 반환해야 합니다. `batch_eval_metrics`가 `True`로 설정된 [RewardConfig](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardConfig)를 전달하는 경우, `compute_metrics` 함수는 불리언 `compute_result` 인자를 받아야 합니다. 이는 마지막 평가 배치 이후에 트리거되며, 함수가 배치 수준의 통계를 누적하는 대신 전역 요약 통계를 계산하고 반환해야 함을 나타냅니다.

callbacks ([TrainerCallback](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/callback#transformers.TrainerCallback) 목록, *선택 사항*) : 학습 루프를 커스터마이징할 콜백 목록입니다. [여기](https://huggingface.co/docs/transformers/main_classes/callback)에 자세히 설명된 기본 콜백 목록에 추가됩니다. 사용 중인 기본 콜백 중 하나를 제거하려면 [remove_callback](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/trainer#transformers.Trainer.remove_callback) 메서드를 사용하세요.

optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *선택 사항*, 기본값 `(None, None)`) : 사용할 옵티마이저와 스케줄러를 포함하는 튜플입니다. 기본적으로 모델에 `AdamW` 인스턴스와 `args`에 의해 제어되는 [get_linear_schedule_with_warmup](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup)로 생성된 스케줄러를 사용합니다.

optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *선택*) : 사용할 optimizer 클래스와 키워드 인수를 포함하는 튜플입니다. `args`의 `optim` 및 `optim_args`를 오버라이드합니다. `optimizers` 인수와 호환되지 않습니다. `optimizers`와 달리, 이 인수는 Trainer를 초기화하기 전에 모델 파라미터를 올바른 장치에 배치할 필요가 없도록 합니다.

preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *선택*) : 각 평가 단계에서 logits를 캐시하기 직전에 logits를 전처리하는 함수입니다. logits와 labels의 두 텐서를 받아야 하며, 원하는 방식으로 처리된 logits를 반환해야 합니다. 이 함수가 수행한 수정 사항은 `compute_metrics`가 받는 예측 값에 반영됩니다. 데이터셋에 labels가 없는 경우 labels(두 번째 매개변수)는 `None`이 됩니다.

quantization_config ([BitsAndBytesConfig](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/quantization#transformers.BitsAndBytesConfig), *선택 사항*) : 모델 식별자로부터 모델을 로드할 때 사용되는 양자화 구성입니다. QLoRA 학습을 위해 `peft_config`와 함께 사용하세요. 모델이 이미 인스턴스화되었거나 `args.model_init_kwargs`에 `quantization_config`도 설정된 경우 무시됩니다.

peft_config ([PeftConfig](https://huggingface.co/docs/peft/v0.22.0/en/package_reference/config#peft.PeftConfig), *선택 사항*) : 모델을 래핑하는 데 사용되는 PEFT 구성입니다. `None`인 경우 모델은 래핑되지 않습니다. 로드된 모델이 causal LM인 경우, 보상 헤드가 올바르게 학습되도록 PEFT 구성에서 `modules_to_save=["score"]`를 설정하는 것이 강력히 권장됩니다.

결과 기반 보상 모델(ORM)을 위한 Trainer

이 클래스는 [Trainer](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/trainer#transformers.Trainer) 클래스를 래핑한 것으로, 해당 클래스의 모든 속성과 메서드를 상속합니다.

예:

```python
>>> from trl import RewardTrainer
>>> from datasets import load_dataset

>>> dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")

>>> trainer = RewardTrainer(
...     model="Qwen/Qwen2.5-0.5B-Instruct",
...     train_dataset=dataset,
... )
>>> trainer.train()
```

#### train[[trl.RewardTrainer.train]]

```python
train(resume_from_checkpoint: str | bool | None = None, trial: optuna.Trial | dict[str, Any] | None = None, ignore_keys_for_eval: list[str] | None = None)
```

[소스](https://github.com/huggingface/trl/blob/v1.18.2/transformers/trainer.py#L1450)

**매개변수:**

resume_from_checkpoint (`str` 또는 `bool`, *선택 사항*) : `str`인 경우, 이전 `Trainer` 인스턴스가 저장한 체크포인트의 로컬 경로입니다. `bool`이고 `True`와 같으면, 이전 `Trainer` 인스턴스가 저장한 *args.output_dir*의 마지막 체크포인트를 로드합니다. 이 값이 존재하면, 여기서 로드된 모델/옵티마이저/스케줄러 상태로부터 학습이 재개됩니다.

trial (`optuna.Trial` 또는 `dict[str, Any]`, *선택*) : 하이퍼파라미터 탐색을 위한 트라이얼 실행 또는 하이퍼파라미터 사전.

ignore_keys_for_eval (`list[str]`, *선택 사항*) : 모델의 출력(사전에 해당하는 경우)에서 학습 중 평가 시 예측을 수집할 때 무시해야 할 키의 목록입니다.

**반환값:** `~trainer_utils.TrainOutput`

전체 스텝 수, 학습 손실, 메트릭을 포함하는 객체.

주요 학습 진입점.

#### save_model[[trl.RewardTrainer.save_model]]

```python
save_model(output_dir: str | None = None, _internal_call: bool = False)
```

[소스](https://github.com/huggingface/trl/blob/v1.18.2/transformers/trainer.py#L4077)

모델을 저장하므로 `from_pretrained()`를 사용하여 다시 로드할 수 있습니다.

main 프로세스에서만 저장합니다.

#### push_to_hub[[trl.RewardTrainer.push_to_hub]]

```python
push_to_hub(commit_message: str | None = 'End of training', blocking: bool = True, token: str | None = None, revision: str | None = None, private: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/trl/blob/v1.18.2/transformers/trainer.py#L4337)

**매개변수:**

commit_message (`str`, *선택 사항*, 기본값 `"End of training"`) : push할 때 커밋할 메시지.

blocking (`bool`, *선택 사항*, 기본값 `True`) : `git push`가 완료된 후에만 함수가 반환되어야 하는지 여부.

token (`str`, *선택 사항*, 기본값 `None`) : Trainer의 원래 args를 덮어쓸 수 있는 쓰기 권한이 있는 토큰입니다.

revision (`str`, *선택 사항*) : 커밋할 git 리비전입니다. 기본값은 "main" 브랜치의 head입니다.

private (`bool`, *선택 사항*) : 저장소가 생성될 때 비공개로 만들지 여부입니다. 기본값은 `args.hub_private_repo`입니다. 저장소가 이미 존재하는 경우 효과가 없습니다.

kwargs (`dict[str, Any]`, *선택*) : `~Trainer.create_model_card`에 함께 전달되는 추가 키워드 인자입니다.

**반환값:**

`blocking=False`인 경우 모델이 push된 저장소의 URL 또는 `blocking=True`인 경우 커밋 진행 상황을 추적하는 `Future` 객체를 반환합니다.

`self.args.hub_model_id` 저장소에 `self.model`과 `self.processing_class`를 🤗 모델 허브에 업로드합니다.

## RewardConfig[[trl.RewardConfig]]

#### trl.RewardConfig[[trl.RewardConfig]]

```python
trl.RewardConfig(output_dir: str | None = None, per_device_train_batch_size: int = 8, num_train_epochs: float = 3.0, max_steps: int = -1, learning_rate: float = 0.0001, lr_scheduler_type: transformers.trainer_utils.SchedulerType | str = 'linear', lr_scheduler_kwargs: dict | str | None = None, warmup_steps: float = 0, optim: transformers.training_args.OptimizerNames | str = 'adamw_torch_fused', optim_args: str | None = None, weight_decay: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-08, optim_target_modules: None | str | list[str] = None, gradient_accumulation_steps: int = 1, average_tokens_across_devices: bool = True, max_grad_norm: float = 1.0, label_smoothing_factor: float = 0.0, bf16: bool | None = None, fp16: bool = False, bf16_full_eval: bool = False, fp16_full_eval: bool = False, tf32: bool | None = None, activation_checkpointing: bool | None = None, activation_checkpointing_kwargs: dict[str, typing.Any] | str | None = None, gradient_checkpointing: bool | None = None, gradient_checkpointing_kwargs: dict[str, typing.Any] | str | None = None, torch_compile: bool = False, torch_compile_backend: str | None = None, torch_compile_mode: str | None = None, use_liger_kernel: bool = False, liger_kernel_config: dict[str, bool] | None = None, use_cache: bool = False, neftune_noise_alpha: float | None = None, torch_empty_cache_steps: int | None = None, auto_find_batch_size: bool = False, logging_strategy: transformers.trainer_utils.IntervalStrategy | str = 'steps', logging_steps: float = 10, logging_first_step: bool = False, log_on_each_node: bool = True, logging_nan_inf_filter: bool = True, include_num_input_tokens_seen: str | bool = 'no', log_level: str = 'passive', log_level_replica: str = 'warning', disable_tqdm: bool | None = None, report_to: None | str | list[str] = 'none', run_name: str | None = None, project: str = 'huggingface', trackio_space_id: str | None = None, trackio_bucket_id: str | None = None, trackio_static_space_id: typing.Union[str, NoneType, typing.Literal[False]] = None, eval_strategy: transformers.trainer_utils.IntervalStrategy | str = 'no', eval_steps: float | None = None, eval_delay: float = 0, per_device_eval_batch_size: int = 8, prediction_loss_only: bool = False, eval_on_start: bool = False, eval_do_concat_batches: bool = True, eval_use_gather_object: bool = False, eval_accumulation_steps: int | None = None, include_for_metrics: list[str] = <factory>, batch_eval_metrics: bool = False, save_only_model: bool = False, save_strategy: transformers.trainer_utils.SaveStrategy | str = 'steps', save_steps: float = 500, save_on_each_node: bool = False, save_total_limit: int | None = None, enable_jit_checkpoint: bool = False, push_to_hub: bool = False, hub_token: str | None = None, hub_private_repo: bool | None = None, hub_model_id: str | None = None, hub_strategy: transformers.trainer_utils.HubStrategy | str = 'every_save', hub_always_push: bool = False, hub_revision: str | None = None, load_best_model_at_end: bool = False, metric_for_best_model: str | None = None, greater_is_better: bool | None = None, ignore_data_skip: bool = False, restore_callback_states_from_checkpoint: bool = False, full_determinism: bool = False, seed: int = 42, data_seed: int | None = None, use_cpu: bool = False, accelerator_config: dict | str | None = None, parallelism_config: accelerate.parallelism_config.ParallelismConfig | None = None, dataloader_drop_last: bool = False, dataloader_num_workers: int = 0, dataloader_pin_memory: bool = True, dataloader_persistent_workers: bool = False, dataloader_prefetch_factor: int | None = None, dataloader_multiprocessing_context: str | None = None, dataloader_in_order: bool = True, remove_unused_columns: bool = True, label_names: list[str] | None = None, train_sampling_strategy: str = 'random', length_column_name: str = 'length', ddp_find_unused_parameters: bool | None = None, ddp_bucket_cap_mb: int | None = None, ddp_broadcast_buffers: bool | None = None, ddp_static_graph: bool | None = None, ddp_backend: str | None = None, ddp_timeout: int = 1800, fsdp: str | None = None, fsdp_config: dict[str, typing.Any] | str | None = None, deepspeed: dict | str | None = None, debug: str | list[transformers.debug_utils.DebugOption] = '', skip_memory_metrics: bool = True, do_train: bool = False, do_eval: bool = False, do_predict: bool = False, resume_from_checkpoint: str | None = None, local_rank: int = -1, model_init_kwargs: dict[str, typing.Any] | str | None = None, trust_remote_code: bool = False, chat_template_path: str | None = None, disable_dropout: bool = True, dataset_num_proc: int | None = None, eos_token: str | None = None, max_length: int | None = 1024, pad_to_multiple_of: int | str | None = 'auto', center_rewards_coefficient: float | None = None, activation_offloading: bool = False, pad_token: str | None = None)
```

[소스](https://github.com/huggingface/trl/blob/v1.18.2/trl/trainer/reward_config.py#L23)

**모델을 제어하는 매개변수:**

model_init_kwargs (`dict[str, Any]`, *선택*) : [RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)의 `model` 인수가 문자열로 제공될 때 [from_pretrained](https://huggingface.co/docs/transformers/v5.23.0/en/model_doc/auto#transformers.AutoModelForSequenceClassification.from_pretrained)에 사용되는 키워드 인수입니다. `revision` 값은 토크나이저를 로드할 때에도 사용됩니다.

trust_remote_code (`bool`, *optional*, defaults to `False`) : Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to [from_pretrained](https://huggingface.co/docs/transformers/v5.23.0/en/model_doc/auto#transformers.AutoModelForSequenceClassification.from_pretrained) and [from_pretrained](https://huggingface.co/docs/transformers/v5.23.0/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained).

chat_template_path (`str`, *선택 사항*) : 지정된 경우, 모델의 채팅 템플릿을 설정합니다. 이는 토크나이저의 경로(로컬 디렉터리 또는 Hugging Face Hub 모델)이거나 Jinja 템플릿 파일의 직접 경로일 수 있습니다. Jinja 파일을 사용하는 경우, 템플릿에서 참조하는 특수 토큰이 토크나이저에 추가되었는지 및 모델의 임베딩 레이어가 이에 맞게 조정되었는지 확인해야 합니다.

disable_dropout (`bool`, *선택 사항*, 기본값 `True`) : 모델에서 dropout을 비활성화할지 여부.

**데이터 전처리를 제어하는 매개변수:**

dataset_num_proc (`int`, *선택 사항*) : 데이터셋 처리에 사용할 프로세스 수.

eos_token (`str`, *선택 사항*) : 턴 또는 시퀀스의 끝을 나타내는 데 사용되는 토큰. `None`인 경우 기본값은 `processing_class.eos_token`입니다.

max_length (`int` 또는 `None`, *선택 사항*, 기본값 `1024`) : 토큰화된 시퀀스의 최대 길이. chosen 시퀀스 또는 rejected 시퀀스 중 하나가 이 값을 초과하면 해당 샘플은 필터링됩니다. `None`인 경우 필터링이 적용되지 않습니다.

pad_to_multiple_of (`int` 또는 `str`, *선택 사항*, 기본값 `"auto"`) : 값이 설정되면 시퀀스는 해당 값의 배수로 패딩됩니다. `"auto"`는 Neuron(AWS Trainium)에서 입력 형식별로 한 번씩 컴파일되므로 128의 배수로 패딩하고, 다른 환경에서는 패딩하지 않습니다.

**학습을 제어하는 매개변수:**

center_rewards_coefficient (`float`, *선택 사항*) : 보상 모델이 평균이 0인 보상을 출력하도록 장려하는 계수([이 논문](https://huggingface.co/papers/2312.09244), 식 2에서 제안). 권장 값: `0.01`.

activation_offloading (`bool`, *선택 사항*, 기본값 `False`) : activations를 CPU로 offload할지 여부.

**비추천되는 매개변수:**

pad_token :   `pad_token` 매개변수는 비추천(deprecated)되며 v2.0.0 버전에서 제거됩니다. 대신 `tokenizer.pad_token`을 직접 설정하고 trainer에 `processing_class`로 전달하세요.

[RewardTrainer](/docs/trl/v1.18.2/ko/reward_trainer#trl.RewardTrainer)의 설정 클래스입니다.

이 클래스에는 Reward 학습에 특화된 매개변수만 포함되어 있습니다. 학습 인자의 전체 목록은 [TrainingArguments](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/trainer#transformers.TrainingArguments) 문서를 참조하세요. 이 클래스의 기본값은 [TrainingArguments](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/trainer#transformers.TrainingArguments)의 기본값과 다를 수 있습니다.

[HfArgumentParser](https://huggingface.co/docs/transformers/v5.23.0/en/internal/trainer_utils#transformers.HfArgumentParser)를 사용하면 이 클래스를 커맨드 라인에서 지정할 수 있는 [argparse](https://docs.python.org/3/library/argparse#module-argparse) 인수로 변환할 수 있습니다.

> [!NOTE]
> 이러한 파라미터는 [TrainingArguments](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/trainer#transformers.TrainingArguments)와 다른 기본값을 가집니다: - `logging_steps`: `500` 대신 `10`이 기본값입니다. - `gradient_checkpointing`: `False` 대신 `True`가 기본값입니다. - `bf16`: `fp16`가 설정되지 않은 경우 `False` 대신 `True`가 기본값입니다. - `learning_rate`: `5e-5` 대신 `1e-4`가 기본값입니다.

