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は、報酬モデルの学習を行うためのOutcome-supervised Reward Modeling (ORM) Trainerをサポートしています。

このポストトレーニング手法は、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^- . 損失は、観測された選好の負の対数尤度として定義されます。 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モデルは過不足なく決定されておらず、すべての報酬に定数を加えても選好確率は変化しません。これを解決するために、Helping or Herding? Reward Model Ensembles Mitigate but do not Eliminate Reward Hackingでは、報酬がゼロを中心に分布するよう促する補助的な損失項の追加を提案しています。これは、RewardConfig内のcenter_rewards_coefficientパラメータで制御されます。推奨値は1e-2です。

記録されたメトリクス

学習と評価の実行中、以下のメトリクスを記録します:

  • global_step: 現在までに実行されたオプティマイザーステップの総数。
  • 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引数を渡さずに、そのままトレーナーに直接渡します。

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機能を持つモデルのファインチューニングを完全にサポートしています。この場合、各データセットの例には以下を含める必要があります。

  • ツール呼び出し(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、任意) — このトレーナーの設定です。None の場合、デフォルトの設定が使用されます。
  • data_collator (DataCollator, 省略可) — 処理済みのtrain_datasetまたはeval_datasetの要素のリストからバッチを形成するために使用する関数。 デフォルトではDataCollatorForPreferenceが使用されます。
  • train_dataset (Dataset または IterableDataset) — 学習に使用するデータセット。このトレーナーは preference タイプ(暗黙的プロンプトおよび明示的プロンプトの両方)をサポートしています。サンプルの形式は次のいずれかです:
    • Standard: 各サンプルにはプレーンテキストが含まれています。
    • 対話形式: 各サンプルには構造化されたメッセージ(例: roleとcontent)が含まれます。

    プロセッサは、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、任意) — データを処理するために使用されるトークナイザー。None の場合、モデル名から from_pretrained を使用してトークナイザーが読み込まれます。パディングトークン processing_class.pad_token が設定されている必要があります。処理クラスにパディングトークンが設定されていない場合、processing_class.eos_token がデフォルトとして使用されます。
  • compute_metrics (Callable[[EvalPrediction], dict], 省略可) — 評価時にメトリクスを計算するために使用される関数。EvalPrediction を引数に取り、メトリクス名(文字列)からメトリクス値への辞書を返す必要があります。RewardConfig を batch_eval_metrics が True に設定された状態で渡す場合、compute_metrics 関数はブール型の compute_result 引数を受け取らなければなりません。これは最後の評価バッチの後にトリガーされ、関数がバッチレベルの統計を累積するのではなく、グローバルなサマリー統計を計算して返す必要があることを示します。
  • callbacks (のリスト TrainerCallback, 省略可) — トレーニングループをカスタマイズするためのコールバックのリスト。デフォルトのコールバックのリストに追加されます。デフォルトのコールバックの詳細は こちら.

    デフォルトで使用するコールバックの1つを削除したい場合は、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 をキャッシュする直前に、それらを前処理する関数です。2 つのテンソル(logits と labels)を受け取り、所望の処理が施された logits を返す必要があります。この関数による変更は、 compute_metrics.

    ラベル(第2引数)は、データセットにラベルが含まれていない場合、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()を使用して再読み込みできます。

メインプロセスからのみ保存します。

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 の元の引数を上書きするための書き込み権限を持つトークン。
  • revision (str, 省略可) — コミット元の git リビジョンです。“main” ブランチのヘッドがデフォルトです。
  • private (bool、省略可) — リポジトリ作成時にプライベートにするかどうか。デフォルトはargs.hub_private_repoです。リポジトリが既に存在する場合は、この引数は無効です。
  • kwargs (dict[str, Any]、省略可) — ~Trainer.create_model_card に渡される追加のキーワード引数。

self.args.hub_model_id のリポジトリに、self.model と self.processing_class を 🤗 model hub にアップロードします。

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, 任意) — 指定すると、モデルのチャットテンプレートが設定されます。これは、トークナイザーへのパス(ローカルディレクトリまたは 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, 任意) — 報酬モデルが平均ゼロの報酬を出力することを促すための係数(この論文、式2で提案)。推奨値: 0.01。
  • activation_offloading (bool、任意、デフォルトはFalse) — アクティベーションをCPUにオフロードするかどうか。

非推奨のパラメータ

  • pad_token —

    パラメータ pad_token は非推奨となり、バージョン v2.0.0 で削除されます。代わりに、tokenizer.pad_token を直接設定し、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