TRL documentation

A2PO

You are viewing v1.18.0 version. A newer version v1.18.1 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

A2PO

model badge

TRLは、Kianté Brantley、Mingyu Chen、Zhaolin Gao、Jason D. Lee、Wen Sun、Wenhao Zhan、およびXuezhou Zhangによる論文Accelerating RL for LLM Reasoning with Optimal Advantage Regressionに記載されているA*-PO(Optimal Advantage Regression)をサポートしています。

論文の要旨は以下の通りです:

強化学習(RL)は、複雑な推論能力を向上させるために大規模言語モデル(LLM)をファインチューニングする強力なツールとして台頭しています。しかし、最先端のポリシー最適化手法は、プロンプトごとの複数回の生成が必要であることや、現在のポリシーのクリティクネットワークやアドバンテージ推定に依存していることにより、主に高い計算オーバーヘッドとメモリ消費量に苦しんでいます。本論文では、A*-POという新しい2段階のポリシー最適化フレームワークを提案します。この手法は最適なアドバンテージ関数を直接近似し、推論タスクにおけるLLMの効率的な学習を可能にします。第1段階では、参照ポリシーからのオフラインサンプリングを利用して最適な価値関数 V* を推定し、コストのかかるオンラインの価値推定の必要性を排除します。第2段階では、プロンプトごとに1回の生成のみで、単純な最小二乗回帰損失を用いてオンポリシー更新を実行します。理論的には、パフォーマンスの保証を確立し、複雑な探索戦略を必要とせずにKL正則化されたRLの目的関数を最適化できることを証明します。実証的に、A*-POは幅広い数学的推論ベンチマークにおいて競争力のあるパフォーマンスを達成すると同時に、PPO、GRPO、REBELと比較して、トレーニング時間を最大2倍短縮し、ピークメモリ使用量を30%以上削減します。

使用方法

A*-POは二値で検証可能な報酬(r ∈ {0, 1})を前提とし、2段階で実行されます:

  1. オフラインの価値推定。 学習の前に、すべてのプロンプトに対して参照ポリシーからnum_value_samples個の補完がサンプリングされ、reward_funcsでスコアリングされます。最適な価値V*(x) = β₁·log(mean_i exp(r(x, yᵢ)/β₁))が推定され、プロンプトごとにキャッシュされます。
  2. オンポリシー回帰。 学習中、現在のポリシーからプロンプトごとに1つの補完が生成されます。損失は、暗黙の報酬 β₂·log(π(y|x)/π_ref(y|x)) と最適アドバンテージ r(x, y) − V*(x) の間の二乗誤差です。
from trl.experimental.a2po import A2POConfig, A2POTrainer

# A*-PO assumes a binary, verifiable reward in {0, 1}.
def reward_correct(completions, ground_truth, **kwargs):
    return [float(completion.strip() == truth) for completion, truth in zip(completions, ground_truth)]

training_args = A2POConfig(
    output_dir="Qwen2.5-0.5B-A2PO",
    num_value_samples=8,  # Stage 1: samples per prompt from the reference policy to estimate V*
    beta1=0.5,  # Stage 1: KL temperature for the V* estimate
    beta2=1e-3,  # Stage 2: KL temperature for the regression target
)
trainer = A2POTrainer(
    model="Qwen/Qwen2.5-0.5B",
    reward_funcs=reward_correct,
    args=training_args,
    train_dataset=...,
)
trainer.train()

V* は参照ポリシーのサンプルから完全に推定されるため、A*-PO は参照ポリシーの Pass@K を超えることはできません。公式実装は ZhaolinGao/A-PO で確認できます。

A2POTrainer

class trl.experimental.a2po.A2POTrainer

< >

( model: transformers.modeling_utils.PreTrainedModel | strreward_funcs: collections.abc.Callable[..., list[float]] | list[collections.abc.Callable[..., list[float]]]args: trl.experimental.a2po.a2po_config.A2POConfig | None = Nonetrain_dataset = Noneeval_dataset = Noneprocessing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = Nonecallbacks = Noneoptimizers = (None, None) )

パラメータ

  • model (PreTrainedModel または str) — 学習対象のモデル、または from_pretrained に渡すモデル識別子(文字列)。
  • reward_funcs (Callable または list[Callable]) — 報酬関数です。各関数は prompts と completions(およびデータセットの列をキーワード引数として)を受け取り、浮動小数点数の報酬のリストを返します。複数の関数が指定された場合、それらの加重和(A2POConfig.reward_weights を参照)がスカラー報酬 r となり、A*-PO はこれが二値({0, 1} の範囲)であると仮定します。
  • args (experimental.a2po.A2POConfig、任意) — このトレーナーの設定です。None の場合、デフォルトの設定が使用されます。
  • train_dataset (Dataset、任意) — 学習用データセット。"prompt"カラムを含む必要があります。
  • eval_dataset (Dataset、任意) — 評価用データセット。
  • processing_class (PreTrainedTokenizerBase、任意) — データを処理するために使用される処理クラスです。None の場合、モデル名から from_pretrained を使用して読み込まれます。
  • callbacks (list[~transformers.TrainerCallback]、任意) — トレーニングループをカスタマイズするためのコールバックのリスト。
  • optimizers (tuple[~torch.optim.Optimizer, ~torch.optim.lr_scheduler.LambdaLR]、optional、デフォルトは(None, None)) — オプティマイザーと学習率スケジューラーを含むタプルです。

Accelerating RL for LLM Reasoning with Optimal Advantage Regression で紹介された A*-PO (Optimal Advantage Regression) 手法用の Trainer です。

A*-POは2段階で実行されます:

  1. オフラインの価値推定。学習開始前に、すべての学習プロンプトに対して参照ポリシーからnum_value_samples個の補完がサンプリングされ、reward_funcsでスコアリングされます。最適な価値はV*(x) = beta1 * log(mean_i exp(r(x, y_i) / beta1))として推定され、プロンプトごとにキャッシュされます。
  2. オンポリシー回帰。 学習中、現在のポリシーからプロンプトごとに1つの補完が生成されます。 損失は、暗黙の報酬 beta2 * log(pi(y|x) / pi_ref(y|x)) と最適なアドバンテージ推定値 r(x, y) - V*(x) の間の二乗誤差です。

train

< >

( *args**kwargs )

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 にアップロードします。

A2POConfig

class trl.experimental.a2po.A2POConfig

< >

( output_dir: str | None = Noneper_device_train_batch_size: int = 8num_train_epochs: float = 3.0max_steps: int = -1learning_rate: float = 5e-05lr_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 = Falselabel_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 | None = Nonetrust_remote_code: bool = Falsemax_prompt_length: int | None = 512max_completion_length: int | None = 256temperature: float = 1.0top_p: float = 1.0top_k: int | None = Nonenum_value_samples: int = 8beta1: float = 0.5filter_all_incorrect: bool = Truebeta2: float = 0.001reward_weights: list[float] | None = None )

モデルと参照モデルを制御するパラメータ

  • model_init_kwargs (dict[str, Any], 省略可) — model 引数が文字列として experimental.a2po.A2POTrainer に渡された場合、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.

データ前処理を制御するパラメータ

  • remove_unused_columns (bool、任意、デフォルトは False) — データセットで "prompt" 列のみを保持するかどうか。"prompts" と "completions" 以外の列を必要とするカスタムの報酬関数を使用する場合は、この値を False に設定してください。

生成を制御するパラメータ

  • max_prompt_length (int または None、任意、デフォルトは 512) — プロンプトの最大長です。プロンプトがこの長さを超える場合、左側から切り詰められます。
  • max_completion_length (int または None、任意、デフォルトは 256) — 生成される補完の最大長。
  • temperature (float、任意、デフォルトは 1.0) — Stage 1 と Stage 2 の両方の生成で使用するサンプリング温度です。
  • top_p (float、任意、デフォルトは 1.0) — 考慮する上位トークンの累積確率を制御する浮動小数点数です。値は (0, 1] の範囲でなければなりません。すべてのトークンを考慮するには 1.0 を設定してください。
  • top_k (int または None、任意) — 保持する最高確率の語彙トークンの数。None の場合、トップkフィルタリングは無効になります。

Stage 1(オフライン最適値推定)を制御するパラメータ

  • num_value_samples (int、任意、デフォルトは8) — V*を推定するために、プロンプトごとに参照ポリシーからサンプリングするサンプル数。
  • beta1 (float、任意、デフォルトは0.5) — Stage 1 でV*を推定するために使用される KL 温度です。
  • filter_all_incorrect (bool、省略可能、デフォルトはTrue) — すべてのリファレンスサンプルが正しくないプロンプトを除外するかどうかを指定します。

Stage 2(オンポリシー回帰)を制御するパラメータ

  • beta2 (float、任意、デフォルトは1e-3) — Stage 2 の回帰ターゲットで使用する KL 温度です。
  • reward_weights (list[float], 任意) — 各報酬関数に対する重み。報酬関数の数と一致する必要があります。None の場合、すべての報酬が重み 1.0 で等しく重み付けされます。

experimental.a2po.A2POTrainer用の設定クラスです。

このクラスには、A2PO学習に固有のパラメータのみが含まれています。学習引数の完全なリストについては、TrainingArgumentsのドキュメントを参照してください。なお、このクラスのデフォルト値は、TrainingArgumentsのものと異なる場合があります。

Update on GitHub