# A2PO

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

TRL hỗ trợ A\*-PO (Hồi quy Lợi thế Tối ưu) như được mô tả trong bài báo [Accelerating RL for LLM Reasoning with Optimal Advantage Regression](https://huggingface.co/papers/2505.20686) của Kianté Brantley, Mingyu Chen, Zhaolin Gao, Jason D. Lee, Wen Sun, Wenhao Zhan và Xuezhou Zhang.

Tóm tắt từ bài báo như sau:

> Học tăng cường (RL) đã nổi lên như một công cụ mạnh mẽ để tinh chỉnh các mô hình ngôn ngữ lớn (LLM), nhằm cải thiện khả năng suy luận phức tạp. Tuy nhiên, các phương pháp tối ưu hóa chính sách tiên tiến thường gặp phải chi phí tính toán và mức tiêu thụ bộ nhớ cao, chủ yếu do nhu cầu tạo ra nhiều lần cho mỗi prompt và sự phụ thuộc vào các mạng critic hoặc các ước lượng lợi thế của chính sách hiện tại. Trong bài báo này, chúng tôi đề xuất A\*-PO, một khung tối ưu hóa chính sách hai giai đoạn mới, cho phép xấp xỉ trực tiếp hàm lợi thế tối ưu và hỗ trợ huấn luyện hiệu quả các LLM cho các tác vụ suy luận. Ở giai đoạn đầu, chúng tôi tận dụng việc lấy mẫu ngoại tuyến từ một chính sách tham chiếu để ước lượng hàm giá trị tối ưu V\*, loại bỏ nhu cầu ước lượng giá trị trực tuyến tốn kém. Ở giai đoạn thứ hai, chúng tôi thực hiện các cập nhật on-policy bằng cách sử dụng một tổn thất hồi quy bình phương tối thiểu đơn giản, chỉ với một lần tạo duy nhất cho mỗi prompt. Về mặt lý thuyết, chúng tôi thiết lập các đảm bảo về hiệu suất và chứng minh rằng mục tiêu RL có điều chỉnh KL có thể được tối ưu hóa mà không cần đến các chiến lược khám phá phức tạp. Về mặt thực nghiệm, A\*-PO đạt được hiệu suất cạnh tranh trên một loạt các bộ chuẩn đánh giá suy luận toán học, đồng thời giảm thời gian huấn luyện lên đến 2 lần và mức sử dụng bộ nhớ đỉnh hơn 30% so với PPO, GRPO và REBEL.

## Cách sử dụng

A\*-PO giả định một **phần thưởng nhị phân, có thể kiểm chứng** (`r ∈ {0, 1}`) và chạy theo hai giai đoạn:

1. **Ước lượng giá trị ngoại tuyến.** Trước khi huấn luyện, `num_value_samples` hoàn thành được lấy mẫu từ chính sách tham chiếu cho mỗi prompt và được chấm điểm bằng `reward_funcs`. Giá trị tối ưu `V*(x) = β₁·log(mean_i exp(r(x, yᵢ)/β₁))` được ước lượng và lưu đệm cho từng prompt.
2. **Quy hồi on-policy.** Trong quá trình huấn luyện, một hoàn thành duy nhất được tạo ra cho mỗi prompt từ chính sách hiện tại. Tổn thất là sai số bình phương giữa phần thưởng ngầm `β₂·log(π(y|x)/π_ref(y|x))` và lợi thế tối ưu `r(x, y) − V*(x)`.

```python
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ì `V*` được ước lượng hoàn toàn từ các mẫu của chính sách tham chiếu, A\*-PO không thể vượt quá Pass@K của chính sách tham chiếu. Bản triển khai chính thức có thể tìm thấy tại [ZhaolinGao/A-PO](https://github.com/ZhaolinGao/A-PO).

## A2POTrainer[[trl.experimental.a2po.A2POTrainer]]

#### trl.experimental.a2po.A2POTrainer[[trl.experimental.a2po.A2POTrainer]]

```python
trl.experimental.a2po.A2POTrainer(model: transformers.modeling_utils.PreTrainedModel | str, reward_funcs: collections.abc.Callable[..., list[float]] | list[collections.abc.Callable[..., list[float]]], args: trl.experimental.a2po.a2po_config.A2POConfig | None = None, train_dataset = None, eval_dataset = None, processing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = None, callbacks = None, optimizers = (None, None))
```

[Nguồn](https://github.com/huggingface/trl/blob/v1.19.0/trl/experimental/a2po/a2po_trainer.py#L48)

**Tham số:**

model (`PreTrainedModel` hoặc `str`) : Mô hình cần được huấn luyện, hoặc một định danh mô hình (chuỗi) được truyền vào [from_pretrained](https://huggingface.co/docs/transformers/v5.24.1/en/model_doc/auto#transformers.AutoModelForCausalLM.from_pretrained).

reward_funcs (`Callable` hoặc `list[Callable]`) : Hàm phần thưởng. Mỗi hàm nhận `prompts` và `completions` (cùng các cột của tập dữ liệu dưới dạng tham số từ khóa) và trả về một danh sách các phần thưởng dạng float. Khi cung cấp nhiều hàm, tổng có trọng số của chúng (xem `A2POConfig.reward_weights`) là phần thưởng vô hướng `r`, mà A*-PO giả định là nhị phân (trong `{0, 1}`).

args ([experimental.a2po.A2POConfig](/docs/trl/v1.19.0/vi/a2po_trainer#trl.experimental.a2po.A2POConfig), *tùy chọn*) : Cấu hình cho trainer này. Nếu là `None`, một cấu hình mặc định sẽ được sử dụng.

train_dataset ([Dataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset), *tùy chọn*) : Bộ dữ liệu huấn luyện. Phải chứa cột `"prompt"`.

eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset), *tùy chọn*) : Bộ dữ liệu đánh giá.

processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.24.1/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), *optional*) : Lớp xử lý được dùng để xử lý dữ liệu. Nếu là `None`, nó sẽ được tải từ tên mô hình bằng [from_pretrained](https://huggingface.co/docs/transformers/v5.24.1/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained).

callbacks (`list[~transformers.TrainerCallback]`, *tùy chọn*) : Danh sách các callback để tùy chỉnh vòng lặp huấn luyện.

optimizers (`tuple[~torch.optim.Optimizer, ~torch.optim.lr_scheduler.LambdaLR]`, *tùy chọn*, mặc định là `(None, None)`) : Bộ tuple chứa optimizer và trình lập lịch tốc độ học.

Trainer cho phương pháp A*-PO (Hồi quy Lợi thế Tối ưu), được giới thiệu trong [Accelerating RL for LLM Reasoning with Optimal Advantage Regression](https://huggingface.co/papers/2505.20686).

A*-PO chạy theo hai giai đoạn:

1. **Ước lượng giá trị ngoại tuyến.** Trước khi huấn luyện, `num_value_samples` hoàn thành được lấy mẫu từ chính sách tham chiếu cho mỗi prompt huấn luyện và được chấm điểm bằng `reward_funcs`. Giá trị tối ưu được ước lượng là `V*(x) = beta1 * log(mean_i exp(r(x, y_i) / beta1))` và được lưu đệm theo từng prompt.
2. **Quy hồi on-policy.** Trong quá trình huấn luyện, một hoàn thành duy nhất được tạo ra cho mỗi prompt từ chính sách hiện tại. Tổn thất là sai số bình phương giữa phần thưởng ẩn `beta2 * log(pi(y|x) / pi_ref(y|x))` và ước lượng lợi thế tối ưu `r(x, y) - V*(x)`.

#### train[[trl.experimental.a2po.A2POTrainer.train]]

```python
train(*args, **kwargs)
```

[Nguồn](https://github.com/huggingface/trl/blob/v1.19.0/trl/experimental/a2po/a2po_trainer.py#L371)

#### save_model[[trl.experimental.a2po.A2POTrainer.save_model]]

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

[Nguồn](https://github.com/huggingface/trl/blob/v1.19.0/transformers/trainer.py#L4085)

Sẽ lưu mô hình, để bạn có thể tải lại bằng `from_pretrained()`.

Chỉ lưu từ tiến trình chính.

#### push_to_hub[[trl.experimental.a2po.A2POTrainer.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)
```

[Nguồn](https://github.com/huggingface/trl/blob/v1.19.0/transformers/trainer.py#L4345)

**Tham số:**

commit_message (`str`, *tùy chọn*, mặc định là `"End of training"`) : Thông điệp để commit khi đẩy lên.

blocking (`bool`, *tùy chọn*, mặc định là `True`) : Xác định xem hàm có nên chỉ trả về khi `git push` đã hoàn tất hay không.

token (`str`, *tùy chọn*, mặc định là `None`) : Token có quyền ghi để ghi đè lên các đối số gốc của Trainer.

revision (`str`, *tùy chọn*) : Bản sửa git để commit từ. Mặc định là đầu của nhánh "main".

private (`bool`, *tùy chọn*) : Xác định xem có làm cho kho riêng tư khi nó được tạo hay không. Mặc định là `args.hub_private_repo`. Không có hiệu lực nếu kho đã tồn tại.

kwargs (`dict[str, Any]`, *tùy chọn*) : Các đối số từ khóa bổ sung được truyền đến `~Trainer.create_model_card`.

**Trả về:**

URL của kho lưu trữ nơi mô hình đã được đẩy lên nếu `blocking=False`, hoặc một đối tượng `Future` theo dõi tiến trình của lệnh commit nếu `blocking=True`.

Tải `self.model` và `self.processing_class` lên 🤗 model hub tại repo `self.args.hub_model_id`.

## A2POConfig[[trl.experimental.a2po.A2POConfig]]

#### trl.experimental.a2po.A2POConfig[[trl.experimental.a2po.A2POConfig]]

```python
trl.experimental.a2po.A2POConfig(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 = 5e-05, 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 = False, 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 | None = None, trust_remote_code: bool = False, max_prompt_length: int | None = 512, max_completion_length: int | None = 256, temperature: float = 1.0, top_p: float = 1.0, top_k: int | None = None, num_value_samples: int = 8, beta1: float = 0.5, filter_all_incorrect: bool = True, beta2: float = 0.001, reward_weights: list[float] | None = None)
```

[Nguồn](https://github.com/huggingface/trl/blob/v1.19.0/trl/experimental/a2po/a2po_config.py#L21)

**Các tham số kiểm soát mô hình và mô hình tham chiếu:**

model_init_kwargs (`dict[str, Any]`, *tùy chọn*) : Các đối số từ khóa cho [from_pretrained](https://huggingface.co/docs/transformers/v5.24.1/en/model_doc/auto#transformers.AutoModelForCausalLM.from_pretrained), được sử dụng khi đối số `model` của [experimental.a2po.A2POTrainer](/docs/trl/v1.19.0/vi/a2po_trainer#trl.experimental.a2po.A2POTrainer) được cung cấp dưới dạng chuỗi. Giá trị `revision` cũng được sử dụng khi nạp lớp xử lý.

trust_remote_code (`bool`, *tuỳ chọn*, mặc định là `False`) : Cho phép tải các model và tokenizer có kèm theo mã Python tùy chỉnh từ Hub hay không. Tham số này được chuyển tiếp đến [from_pretrained](https://huggingface.co/docs/transformers/v5.24.1/en/model_doc/auto#transformers.AutoModelForCausalLM.from_pretrained) và [from_pretrained](https://huggingface.co/docs/transformers/v5.24.1/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained).

**Các tham số kiểm soát tiền xử lý dữ liệu:**

remove_unused_columns (`bool`, *tùy chọn*, mặc định là `False`) : Có nên chỉ giữ lại cột `"prompt"` trong bộ dữ liệu hay không. Nếu bạn sử dụng một hàm thưởng tùy chỉnh yêu cầu bất kỳ cột nào khác ngoài `"prompts"` và `"completions"`, bạn nên giữ giá trị này là `False`.

**Các tham số kiểm soát quá trình sinh:**

max_prompt_length (`int` hoặc `None`, *tùy chọn*, mặc định là `512`) : Độ dài tối đa của prompt. Nếu prompt dài hơn giá trị này, nó sẽ bị cắt bớt từ phía bên trái.

max_completion_length (`int` hoặc `None`, *tùy chọn*, mặc định là `256`) : Độ dài tối đa của phần hoàn thành được tạo ra.

temperature (`float`, *tùy chọn*, mặc định là `1.0`) : Nhiệt độ lấy mẫu, được sử dụng trong cả giai đoạn 1 và giai đoạn 2 của quá trình tạo.

top_p (`float`, *optional*, mặc định là `1.0`) : Giá trị kiểm soát xác suất tích lũy của các token hàng đầu cần xem xét. Phải nằm trong khoảng (0, 1]. Đặt thành `1.0` để xem xét tất cả các token.

top_k (`int` hoặc `None`, *tùy chọn*) : Số lượng token từ vựng có xác suất cao nhất cần giữ lại. Nếu là `None`, lọc top-k sẽ bị tắt.

**Các tham số kiểm soát Giai đoạn 1 (ước lượng giá trị tối ưu ngoại tuyến):**

num_value_samples (`int`, *tuỳ chọn*, mặc định là `8`) : Số lượng mẫu được lấy từ chính sách tham chiếu cho mỗi prompt để ước lượng `V*`.

beta1 (`float`, *tuỳ chọn*, mặc định là `0.5`) : KL temperature được sử dụng để ước lượng `V*` trong Giai đoạn 1.

filter_all_incorrect (`bool`, *tùy chọn*, mặc định là `True`) : Có nên loại bỏ các prompt mà tất cả các mẫu tham chiếu đều không chính xác hay không.

**Các tham số kiểm soát Giai đoạn 2 (hồi quy on-policy):**

beta2 (`float`, *tùy chọn*, mặc định là `1e-3`) : KL temperature được sử dụng trong mục tiêu hồi quy của Giai đoạn 2.

reward_weights (`list[float]`, *optional*) : Trọng số cho mỗi hàm phần thưởng. Phải khớp với số lượng các hàm phần thưởng. Nếu là `None`, tất cả các phần thưởng được gán trọng số bằng nhau với trọng số `1.0`.

Lớp cấu hình cho [experimental.a2po.A2POTrainer](/docs/trl/v1.19.0/vi/a2po_trainer#trl.experimental.a2po.A2POTrainer).

Lớp này chỉ bao gồm các tham số đặc thù cho huấn luyện A2PO. Để xem danh sách đầy đủ các đối số huấn luyện, vui lòng tham khảo tài liệu [TrainingArguments](https://huggingface.co/docs/transformers/v5.24.1/en/main_classes/trainer#transformers.TrainingArguments). Lưu ý rằng các giá trị mặc định trong lớp này có thể khác với các giá trị trong [TrainingArguments](https://huggingface.co/docs/transformers/v5.24.1/en/main_classes/trainer#transformers.TrainingArguments).

