TRL documentation

보상 모델링

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

보상 모델링

model badge

개요

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

이 포스트 트레이닝 방법은 Younes Belkada가 기여했습니다.

빠른 시작

이 예제는 TRL의 RewardTrainer를 사용하여 보상 모델을 학습하는 방법을 보여줍니다. 대규모, 세밀하고 다양한 선호 데이터셋인 UltraFeedback dataset에서 Qwen 3 0.6B 모델을 학습합니다.

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는 preference 데이터셋 유형(암시적 및 명시적 프롬프트 모두)을 지원합니다. RewardTrainer는 standard 및 conversational 데이터셋 형식 모두와 호환됩니다. conversational 데이터셋이 제공되면 트레이너는 데이터셋에 채팅 템플릿을 자동으로 적용합니다.

# 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 데이터셋을 사용한 예시는 다음과 같습니다:

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"])))
{
    "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를 참조하세요. RewardTrainer는 모델의 토크나이저를 사용하여 각 입력을 토큰화합니다. 프롬프트와 완성문(chosen 및 rejected)이 별도로 제공되는 경우(명시적 프롬프트 케이스)에는 토큰화 전에 이를 연결합니다.

손실 계산

입력 시퀀스(프롬프트)를 x x 이고, y+ y^+ 그리고 y− y^- 각각 선택된 시퀀스와 거부된 시퀀스라고 합시다. Bradley-Terry 모델(Bradley & Terry, 1952), 에 대해 y+ y^+ 이 y− y^- 보다 선호될 확률은 보상 함수 r r 일 때 p(y+≻y−∣x)=σ(r(x,y+)−r(x,y−)) p(y^+ ≻ y^- |x) = \sigma(r(x, y^+)−r(x, y^-)) , 여기서 σ σ 시그모이드 함수입니다.

보상 모델 rθ(x,y) r_\theta(x, y) 은 선호하는 응답 y+ y^+ 에 비선호 응답보다 더 높은 점수를 부여하도록 학습됩니다. y− y^- . 손실 함수는 관찰된 선호도의 음의 로그 가능도(negative log-likelihood)로 정의됩니다: L(θ)=−E(x,y+,y−)∼D[log⁡σ(rθ(x,y+)−rθ(x,y−))]. \mathcal{L}(\theta) = - \mathbb{E}_{(x,y^+,y^-) \sim \mathcal{D}} \left[ \log \sigma(r_\theta(x, y^+) - r_\theta(x, y^-)) \right].

Bradley-Terry 모델은 과소결정(underdetermined)되어 있어, 모든 보상 값에 상수를 더해도 선호 확률은 변하지 않습니다. 이를 해결하기 위해 Helping or Herding? Reward Model Ensembles Mitigate but do not Eliminate Reward Hacking 논문은 보상이 0을 중심으로 분포하도록 유도하는 보조 손실 항을 추가하는 방법을 제안합니다. 이 동작은 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에 직접 전달할 수 있습니다. 예를 들어, 다른 정밀도로 모델을 로드하려면

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

model_init_kwargs={"dtype": torch.bfloat16} 인수를 RewardConfig에 전달하여 수행할 수 있습니다.

from trl import RewardConfig

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

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

PEFT로 어댑터 학습

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

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의 학습을 계속할 수도 있습니다. 이를 위해 먼저 RewardTrainer 외부에서 PeftModel을 로드한 후, peft_config 인자를 전달하지 않고 trainer에 직접 전달합니다.

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

어댑터를 학습할 때는 새로운 매개변수만 학습되므로 일반적으로 더 높은 학습률(≈1e‑3)을 사용합니다.

RewardConfig(learning_rate=1e-3, ...)

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

RewardTrainer는 tool calling 기능이 있는 모델의 fine-tuning을 완전히 지원합니다. 이 경우 각 데이터셋 예시에는 다음이 포함되어야 합니다:

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

기대하는 데이터셋 구조에 대한 자세한 내용은 Dataset Format — Tool Calling 섹션을 참고하세요.

RewardTrainer

클래스 trl.RewardTrainer

< >

( model: str | PreTrainedModel | PeftModelargs: trl.trainer.reward_config.RewardConfig | None = Nonedata_collator: collections.abc.Callable[[list[typing.Any]], dict[str, typing.Any]] | None = Nonetrain_dataset: datasets.arrow_dataset.Dataset | datasets.iterable_dataset.IterableDataset | None = Noneeval_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 = Noneprocessing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = Nonecompute_metrics: collections.abc.Callable[[transformers.trainer_utils.EvalPrediction], dict] | None = Nonecallbacks: list[transformers.trainer_callback.TrainerCallback] | None = Noneoptimizers: 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 = Nonepreprocess_logits_for_metrics: collections.abc.Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = Nonequantization_config: BitsAndBytesConfig | None = Nonepeft_config: PeftConfig | None = None )

매개변수

  • model (str 또는 PreTrainedModel 또는 PeftModel) — 학습할 모델. 다음 중 하나일 수 있습니다:
    • huggingface.co의 모델 저장소에 호스팅된 사전 학습 모델의 model id인 문자열, 또는 save_pretrained를 사용하여 모델 가중치를 저장한 디렉터리의 경로, 예: './my_model_directory/'입니다. 모델은 args.model_init_kwargs의 키워드 인수를 사용하여 AutoModelForSequenceClassification.from_pretrained로 로드됩니다. args.model_init_kwargs에 dtype이 지정되지 않은 경우 기본값은 float32입니다. 이는 (Transformers v5부터) 모델 구성에서 dtype을 추론하는 from_pretrained와 다릅니다.
    • 시퀀스 분류 PreTrainedModel 객체.
    • 시퀀스 분류 PeftModel 객체.
  • args (RewardConfig, 선택 사항) — 이 trainer의 설정입니다. None인 경우 기본 설정이 사용됩니다.
  • data_collator (DataCollator, 선택 사항) — 처리된 train_dataset 또는 eval_dataset 요소 목록에서 배치(batch)를 형성하는 데 사용할 함수입니다. 기본값은 DataCollatorForPreference입니다.
  • train_dataset (Dataset 또는 IterableDataset) — 학습에 사용할 Dataset입니다. 이 trainer는 preference 형식(암시적 및 명시적 프롬프트 모두)을 지원합니다. 샘플의 형식은 다음과 같습니다:
    • Standard: 각 샘플에는 일반 텍스트가 포함됩니다.
    • 대화형: 각 샘플에는 구조화된 메시지(예: 역할 및 내용)가 포함됩니다.

    Trainer는 chosen_ids와 rejected_ids 필드를 포함하는 경우, 처리된 데이터셋(토큰화됨)도 지원합니다.

    train_dataset이 IterableDataset(예: 스트리밍 데이터셋)인 경우, 그 길이를 추론할 수 없으므로 학습 루프를 제한하고 학습률 스케줄러를 구성하는 데 필요한 총 학습 단계 수를 지정하기 위해 학습 인자에 max_steps를 설정해야 합니다.

  • eval_dataset (Dataset, IterableDataset, DatasetDict, IterableDatasetDict 또는 dict[str, Dataset | IterableDataset]) — 평가에 사용할 Dataset입니다. train_dataset과 동일한 요구 사항을 충족해야 합니다.
  • processing_class (PreTrainedTokenizerBase, 선택 사항) — 데이터를 처리하는 데 사용되는 Tokenizer입니다. None인 경우, 모델 이름으로 from_pretrained를 통해 토크나이저가 로드됩니다. 패딩 토큰인 processing_class.pad_token이 설정되어 있어야 합니다. 처리 클래스에 패딩 토큰이 설정되지 않은 경우, processing_class.eos_token이 기본값으로 사용됩니다.
  • compute_metrics (Callable[[EvalPrediction], dict], 선택 사항) — 평가 시 메트릭을 계산하는 데 사용되는 함수입니다. EvalPrediction를 인자로 받아 문자열에서 메트릭 값으로 매핑된 딕셔너리를 반환해야 합니다. batch_eval_metrics가 True로 설정된 RewardConfig를 전달하는 경우, compute_metrics 함수는 불리언 compute_result 인자를 받아야 합니다. 이는 마지막 평가 배치 이후에 트리거되며, 함수가 배치 수준의 통계를 누적하는 대신 전역 요약 통계를 계산하고 반환해야 함을 나타냅니다.
  • callbacks (의 목록 TrainerCallback, 선택 사항) — 학습 루프를 사용자 정의할 콜백 목록입니다. 여기.

    기본으로 사용되는 콜백 중 하나를 제거하려면 remove_callback 메서드를 사용하세요.

  • optimizers (tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None], 선택 사항, 기본값 (None, None)) — 사용할 옵티마이저와 스케줄러를 포함하는 튜플입니다. 기본적으로 모델에 AdamW 인스턴스와 args에 의해 제어되는 get_linear_schedule_with_warmup로 생성된 스케줄러를 사용합니다.
  • optimizer_cls_and_kwargs (tuple[Type[torch.optim.Optimizer], Dict[str, Any]], 선택 사항) — 사용할 옵티마이저 클래스와 키워드 인수를 포함하는 튜플입니다. optim 과 optim_args 의 args. 을(를) 덮어씁니다. optimizers 인수와 호환되지 않습니다.

    optimizers와 달리, 이 인수는 Trainer를 초기화하기 전에 모델 매개변수를 올바른 장치에 배치할 필요가 없도록 합니다.

  • preprocess_logits_for_metrics (Callable[[torch.Tensor, torch.Tensor], torch.Tensor], 선택 사항) — 평가 단계마다 logits를 캐시하기 직전에 전처리하는 함수입니다. logits와 labels라는 두 개의 텐서를 받아야 하며, 원하는 방식으로 처리된 logits를 반환해야 합니다. 이 함수가 수행한 수정 사항은 compute_metrics.

    데이터셋에 라벨이 없는 경우 라벨(두 번째 매개변수)은 None이 됩니다.

  • quantization_config (BitsAndBytesConfig, 선택 사항) — 모델 식별자로부터 모델을 로드할 때 사용되는 양자화 구성입니다. QLoRA 학습을 위해 peft_config와 함께 사용하세요. 모델이 이미 인스턴스화되었거나 args.model_init_kwargs에 quantization_config도 설정된 경우 무시됩니다.
  • peft_config (PeftConfig, 선택 사항) — 모델을 래핑하는 데 사용되는 PEFT 구성입니다. None인 경우 모델은 래핑되지 않습니다. 로드된 모델이 causal LM인 경우, 보상 헤드가 올바르게 학습되도록 PEFT 구성에서 modules_to_save=["score"]를 설정하는 것이 강력히 권장됩니다.

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

이 클래스는 Trainer 클래스를 래핑한 것으로, 해당 클래스의 모든 속성과 메서드를 상속합니다.

예:

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

< >

( resume_from_checkpoint: str | bool | None = Nonetrial: optuna.Trial | dict[str, Any] | None = Noneignore_keys_for_eval: list[str] | None = None ) → ~trainer_utils.TrainOutput

매개변수

  • 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

< >

( output_dir: str | None = None_internal_call: bool = False )

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

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

push_to_hub

< >

( commit_message: str | None = 'End of training'blocking: bool = Truetoken: str | None = Nonerevision: str | None = Noneprivate: bool | None = None**kwargs )

매개변수

  • commit_message (str, 선택 사항, 기본값 "End of training") — 푸시할 때 커밋할 메시지입니다.
  • blocking (bool, 선택 사항, 기본값 True) — git push가 완료된 후에만 함수가 반환되어야 하는지 여부.
  • token (str, 선택 사항, 기본값 None) — Trainer의 원래 args를 덮어쓸 수 있는 쓰기 권한이 있는 토큰.
  • revision (str, 선택 사항) — 커밋할 git revision입니다. 기본값은 “main” 브랜치의 head입니다.
  • private (bool, 선택 사항) — 리포지토리가 생성될 때 비공개로 만들지 여부입니다. 기본값은 args.hub_private_repo입니다. 리포지토리가 이미 존재하는 경우 효과가 없습니다.
  • kwargs (dict[str, Any], 선택) — ~Trainer.create_model_card에 함께 전달되는 추가 키워드 인자입니다.

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

RewardConfig

클래스 trl.RewardConfig

< >

( output_dir: str | None = Noneper_device_train_batch_size: int = 8num_train_epochs: float = 3.0max_steps: int = -1learning_rate: float = 0.0001lr_scheduler_type: transformers.trainer_utils.SchedulerType | str = 'linear'lr_scheduler_kwargs: dict | str | None = Nonewarmup_steps: float = 0optim: transformers.training_args.OptimizerNames | str = 'adamw_torch_fused'optim_args: str | None = Noneweight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08optim_target_modules: None | str | list[str] = Nonegradient_accumulation_steps: int = 1average_tokens_across_devices: bool = Truemax_grad_norm: float = 1.0label_smoothing_factor: float = 0.0bf16: bool | None = Nonefp16: bool = Falsebf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: bool | None = Noneactivation_checkpointing: bool | None = Noneactivation_checkpointing_kwargs: dict[str, typing.Any] | str | None = Nonegradient_checkpointing: bool = Truegradient_checkpointing_kwargs: dict[str, typing.Any] | str | None = Nonetorch_compile: bool = Falsetorch_compile_backend: str | None = Nonetorch_compile_mode: str | None = Noneuse_liger_kernel: bool = Falseliger_kernel_config: dict[str, bool] | None = Noneuse_cache: bool = Falseneftune_noise_alpha: float | None = Nonetorch_empty_cache_steps: int | None = Noneauto_find_batch_size: bool = Falselogging_strategy: transformers.trainer_utils.IntervalStrategy | str = 'steps'logging_steps: float = 10logging_first_step: bool = Falselog_on_each_node: bool = Truelogging_nan_inf_filter: bool = Trueinclude_num_input_tokens_seen: str | bool = 'no'log_level: str = 'passive'log_level_replica: str = 'warning'disable_tqdm: bool | None = Nonereport_to: None | str | list[str] = 'none'run_name: str | None = Noneproject: str = 'huggingface'trackio_space_id: str | None = Nonetrackio_bucket_id: str | None = Nonetrackio_static_space_id: typing.Union[str, NoneType, typing.Literal[False]] = Noneeval_strategy: transformers.trainer_utils.IntervalStrategy | str = 'no'eval_steps: float | None = Noneeval_delay: float = 0per_device_eval_batch_size: int = 8prediction_loss_only: bool = Falseeval_on_start: bool = Falseeval_do_concat_batches: bool = Trueeval_use_gather_object: bool = Falseeval_accumulation_steps: int | None = Noneinclude_for_metrics: list[str] = <factory>batch_eval_metrics: bool = Falsesave_only_model: bool = Falsesave_strategy: transformers.trainer_utils.SaveStrategy | str = 'steps'save_steps: float = 500save_on_each_node: bool = Falsesave_total_limit: int | None = Noneenable_jit_checkpoint: bool = Falsepush_to_hub: bool = Falsehub_token: str | None = Nonehub_private_repo: bool | None = Nonehub_model_id: str | None = Nonehub_strategy: transformers.trainer_utils.HubStrategy | str = 'every_save'hub_always_push: bool = Falsehub_revision: str | None = Noneload_best_model_at_end: bool = Falsemetric_for_best_model: str | None = Nonegreater_is_better: bool | None = Noneignore_data_skip: bool = Falserestore_callback_states_from_checkpoint: bool = Falsefull_determinism: bool = Falseseed: int = 42data_seed: int | None = Noneuse_cpu: bool = Falseaccelerator_config: dict | str | None = Noneparallelism_config: accelerate.parallelism_config.ParallelismConfig | None = Nonedataloader_drop_last: bool = Falsedataloader_num_workers: int = 0dataloader_pin_memory: bool = Truedataloader_persistent_workers: bool = Falsedataloader_prefetch_factor: int | None = Nonedataloader_multiprocessing_context: str | None = Nonedataloader_in_order: bool = Trueremove_unused_columns: bool = Truelabel_names: list[str] | None = Nonetrain_sampling_strategy: str = 'random'length_column_name: str = 'length'ddp_find_unused_parameters: bool | None = Noneddp_bucket_cap_mb: int | None = Noneddp_broadcast_buffers: bool | None = Noneddp_static_graph: bool | None = Noneddp_backend: str | None = Noneddp_timeout: int = 1800fsdp: str | None = Nonefsdp_config: dict[str, typing.Any] | str | None = Nonedeepspeed: dict | str | None = Nonedebug: str | list[transformers.debug_utils.DebugOption] = ''skip_memory_metrics: bool = Truedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseresume_from_checkpoint: str | None = Nonelocal_rank: int = -1model_init_kwargs: dict[str, typing.Any] | str | None = Nonetrust_remote_code: bool = Falsechat_template_path: str | None = Nonedisable_dropout: bool = Truedataset_num_proc: int | None = Noneeos_token: str | None = Nonemax_length: int | None = 1024pad_to_multiple_of: int | str | None = 'auto'center_rewards_coefficient: float | None = Noneactivation_offloading: bool = Falsepad_token: str | None = None )

모델을 제어하는 매개변수

  • model_init_kwargs (dict[str, Any], 선택) — model 인수가 RewardTrainer에 문자열로 제공될 때 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 and from_pretrained.
  • chat_template_path (str, 선택 사항) — 지정된 경우, 모델의 chat template을 설정합니다. 이는 토크나이저의 경로(로컬 디렉터리 또는 Hugging Face Hub 모델)이거나 Jinja template 파일의 직접 경로일 수 있습니다. Jinja 파일을 사용하는 경우, template에서 참조하는 특수 토큰이 토크나이저에 추가되었는지, 그리고 모델의 embedding layer가 이에 맞게 조정되었는지 확인해야 합니다.
  • 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인 보상을 출력하도록 장려하는 계수(이 논문, 식 2에서 제안). 권장 값: 0.01.
  • activation_offloading (bool, 선택 사항, 기본값 False) — 활성화를 CPU로 오프로딩할지 여부입니다.

비추천되는 매개변수

  • pad_token —

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

RewardTrainer의 설정 클래스입니다.

이 클래스에는 Reward 학습에 특화된 매개변수만 포함되어 있습니다. 학습 인자의 전체 목록은 TrainingArguments 문서를 참고하세요. 이 클래스의 기본값은 TrainingArguments의 기본값과 다를 수 있습니다.

HfArgumentParser를 사용하면 이 클래스를 커맨드 라인에서 지정할 수 있는 argparse 인수로 변환할 수 있습니다.

이러한 파라미터는 TrainingArguments와 다른 기본값을 가집니다:

  • logging_steps: 기본값이 500 대신 10입니다.
  • gradient_checkpointing: 기본값이 False가 아닌 True입니다.
  • bf16: fp16가 설정되지 않은 경우 기본값이 False가 아닌 True입니다.
  • learning_rate: 기본값이 5e-5 대신 1e-4입니다.
Update on GitHub