TRL documentation

A2PO

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)을 미세 조정하는 강력한 도구로 부상했습니다. 그러나 최첨단 정책 최적화 방법은 프롬프트당 여러 번의 생성이 필요하고 현재 정책의 크리틱 네트워크나 이점(advantage) 추정치에 의존해야 하기 때문에 주로 높은 계산 오버헤드와 메모리 소비 문제를 겪습니다. 본 논문에서는 최적의 이점 함수를 직접 근사하고 추론 작업을 위한 LLM의 효율적인 학습을 가능하게 하는 새로운 2단계 정책 최적화 프레임워크인 A*-PO를 제안합니다. 첫 번째 단계에서는 참조 정책의 오프라인 샘플링을 활용하여 최적의 가치 함수 V*를 추정함으로써 비용이 높은 온라인 가치 추정의 필요성을 제거합니다. 두 번째 단계에서는 프롬프트당 단 하나의 생성만을 사용하여 간단한 최소제곱 회귀 손실로 온-폴리시(on-policy) 업데이트를 수행합니다. 이론적으로, 성능 보장을 확립하고 복잡한 탐색 전략이 필요하지 않고도 KL-정규화 강화 학습 목적 함수를 최적화할 수 있음을 증명합니다. 실증적으로, A*-PO는 다양한 수학적 추론 벤치마크에서 경쟁력 있는 성능을 달성하는 동시에 PPO, GRPO, REBEL과 비교하여 학습 시간을 최대 2배, 피크 메모리 사용량을 30% 이상 줄입니다.

사용

A*-PO는 이진, 검증 가능한 보상(r ∈ {0, 1})을 가정하며 두 단계로 실행됩니다:

  1. 오프라인 가치 추정. 학습 전에 모든 프롬프트에 대해 참조 정책에서 num_value_samples개의 완성본을 샘플링하고 reward_funcs로 점수를 매깁니다. 최적 가치 V*(x) = β₁·log(mean_i exp(r(x, yᵢ)/β₁))는 프롬프트별로 추정되어 캐시에 저장됩니다.
  2. 온-폴리시 회귀. 학습 중에는 현재 정책에서 프롬프트당 하나의 완성본이 생성됩니다. 손실은 암시적 보상 β₂·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(그리고 데이터셋 컬럼을 키워드 인수로)를 받아 float 보상 목록을 반환합니다. 여러 함수가 제공되면, 가중 합( A2POConfig.reward_weights 참조)이 스칼라 보상 r이 되며, A*-PO는 이를 이진값({0, 1} 범위)으로 가정합니다.
  • args (experimental.a2po.A2POConfig, 선택) — 이 trainer에 대한 설정입니다. 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], 선택 사항, 기본값 (None, None)) — 옵티마이저와 학습률 스케줄러를 포함하는 튜플입니다.

최적 이점 회귀를 통한 LLM 추론 RL 가속에서 소개된 A*-PO(최적 이점 회귀) 방법의 Trainer입니다.

A*-PO는 두 단계로 실행됩니다:

  1. 오프라인 가치 추정. 학습 시작 전, 모든 학습 프롬프트에 대해 참조 정책에서 num_value_samples개의 완성본을 샘플링하고 reward_funcs로 점수를 매깁니다. 최적의 가치는 V*(x) = beta1 * log(mean_i exp(r(x, y_i) / beta1))로 추정되며 프롬프트별로 캐시됩니다.
  2. 온-폴리시 회귀. 학습 중에는 현재 정책에서 프롬프트당 하나의 완성본이 생성됩니다. 손실은 암시적 보상 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()를 사용하여 다시 로드할 수 있습니다.

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를 🤗 모델 허브에 업로드합니다.

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) — 생성된 completion의 최대 길이입니다.
  • temperature (float, 선택 사항, 기본값 1.0) — Stage 1 및 Stage 2 생성 모두에서 사용되는 샘플링 온도입니다.
  • top_p (float, 선택 사항, 기본값 1.0) — 고려할 상위 토큰의 누적 확률을 제어하는 값입니다. 값은 (0, 1] 범위에 있어야 합니다. 모든 토큰을 고려하려면 1.0으로 설정하세요.
  • top_k (int 또는 None, 선택 사항) — 유지할 가장 높은 확률의 어휘 토큰 수입니다. None인 경우 top-k 필터링이 비활성화됩니다.

Stage 1(오프라인 최적 가치 추정)을 제어하는 매개변수

  • num_value_samples (int, 선택 사항, 기본값 8) — 각 프롬프트에 대해 V*를 추정하기 위해 참조 정책(reference policy)에서 추출할 샘플의 수입니다.
  • beta1 (float, 선택 사항, 기본값 0.5) — Stage 1에서 V*를 추정하는 데 사용되는 KL temperature입니다.
  • filter_all_incorrect (bool, 선택 사항, 기본값 True) — 모든 참조 샘플이 잘못된 프롬프트를 제거할지 여부입니다.

Stage 2(on-policy regression)를 제어하는 매개변수

  • beta2 (float, 선택 사항, 기본값 1e-3) — Stage 2 회귀 목표에 사용되는 KL 온도입니다.
  • reward_weights (list[float], 선택 사항) — 각 보상 함수에 대한 가중치입니다. 보상 함수의 수와 일치해야 합니다. None인 경우, 모든 보상은 1.0의 동일한 가중치로 적용됩니다.

experimental.a2po.A2POTrainer의 구성 클래스입니다.

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

Update on GitHub