# GMPO

Trong bài báo [Geometric-Mean Policy Optimization](https://huggingface.co/papers/2507.20673), các tác giả đề xuất một biến thể của GRPO, tối đa hóa trung bình *nhân* của các tỷ lệ quan trọng ở cấp độ token thay vì trung bình cộng. Vì trung bình nhân ít nhạy cảm hơn nhiều với các tỷ lệ ngoại lai, việc cập nhật chính sách sẽ ổn định hơn và cho phép một khoảng cắt (clipping) rộng hơn đáng kể. Việc cắt được áp dụng cho từng token, trong không gian log, và một chiều theo dấu của lợi thế (trust region chuẩn của PPO) — quan trọng là, *trước* khi lấy trung bình nhân.

Để sử dụng GMPO, bạn có thể dùng lớp [experimental.gmpo.GMPOTrainer](/docs/trl/v1.18.1/vi/gmpo#trl.experimental.gmpo.GMPOTrainer) trong `trl.experimental.gmpo`.

## Cách sử dụng

```python
from trl.experimental.gmpo import GMPOConfig, GMPOTrainer

training_args = GMPOConfig(
    epsilon=0.4,  # log-space clip range -> ratios clipped to (exp(-0.4), exp(0.4)); paper, Sec. 4
    beta=0.0,
)
trainer = GMPOTrainer(
    model="Qwen/Qwen3-0.6B",
    reward_funcs=...,
    train_dataset=...,
    args=training_args,
)
trainer.train()
```

Trong GMPO, việc cắt (clipping) được áp dụng cho các tỷ lệ quan trọng theo từng token *log* (tức là trong không gian log) trước khi lấy trung bình hình học, do đó `epsilon` và `epsilon_high` được biểu diễn trong không gian log: phạm vi cắt tỷ lệ hiệu dụng là `(exp(-epsilon), exp(epsilon_high))`. Bài báo đề xuất một phạm vi rộng hơn đáng kể so với GRPO/DAPO, `(exp(-0.4), exp(0.4))`, nhằm khuyến khích khám phá.

## GMPOTrainer[[trl.experimental.gmpo.GMPOTrainer]]

#### trl.experimental.gmpo.GMPOTrainer[[trl.experimental.gmpo.GMPOTrainer]]

```python
trl.experimental.gmpo.GMPOTrainer(model, reward_funcs, args = None, **kwargs)
```

[Nguồn](https://github.com/huggingface/trl/blob/v1.18.1/trl/experimental/gmpo/gmpo_trainer.py#L22)

Trainer cho tối ưu hóa chính trị trung bình hình học (GMPO).

GMPO (https://huggingface.co/papers/2507.20673) là một biến thể của GRPO, tối đa hóa trung bình *hình học* của các tỷ lệ quan trọng ở cấp độ token thay vì trung bình số học. Do trung bình hình học ít nhạy cảm hơn nhiều với các tỷ lệ ngoại lai, việc cập nhật chính sách ổn định hơn và có thể sử dụng phạm vi cắt (clipping) rộng hơn rất nhiều.

Điểm khác biệt duy nhất so với [GRPOTrainer](/docs/trl/v1.18.1/vi/grpo_trainer#trl.GRPOTrainer) là `_compute_loss`. Mọi thứ khác (sinh nội dung, tính phần thưởng, đồng bộ trọng số, ghi log chỉ số) đều được kế thừa không thay đổi

#### train[[trl.experimental.gmpo.GMPOTrainer.train]]

```python
train(resume_from_checkpoint: str | bool | None = None, trial: optuna.Trial | dict[str, Any] | None = None, ignore_keys_for_eval: list[str] | None = None)
```

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

**Tham số:**

resume_from_checkpoint (`str` hoặc `bool`, *tùy chọn*) : Nếu là `str`, đường dẫn cục bộ đến checkpoint đã lưu bởi một phiên `Trainer` trước đó. Nếu là `bool` và bằng `True`, nạp checkpoint cuối cùng trong *args.output_dir* do một phiên `Trainer` trước đó lưu lại. Nếu có, quá trình huấn luyện sẽ tiếp tục từ trạng thái model/optimizer/scheduler được nạp tại đây.

trial (`optuna.Trial` hoặc `dict[str, Any]`, *tùy chọn*) : Chạy thử nghiệm hoặc từ điển siêu tham số cho việc tìm kiếm siêu tham số.

ignore_keys_for_eval (`list[str]`, *tùy chọn*) : Một danh sách các khóa trong đầu ra của mô hình của bạn (nếu nó là một từ điển) cần được bỏ qua khi thu thập các dự đoán để đánh giá trong quá trình huấn luyện.

**Trả về:** `~trainer_utils.TrainOutput`

Đối tượng chứa số bước toàn cục, tổn thất huấn luyện và các chỉ số.

Điểm vào chính cho quá trình huấn luyện.

#### save_model[[trl.experimental.gmpo.GMPOTrainer.save_model]]

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

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

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.gmpo.GMPOTrainer.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.18.1/transformers/trainer.py#L4337)

**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`.

## GMPOConfig[[trl.experimental.gmpo.GMPOConfig]]

#### trl.experimental.gmpo.GMPOConfig[[trl.experimental.gmpo.GMPOConfig]]

```python
trl.experimental.gmpo.GMPOConfig(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 = 1e-06, 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 | None = 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[str, typing.Any] | str | None = None, trust_remote_code: bool = False, router_aux_loss_coef: float | None = None, disable_dropout: bool = False, cast_lm_head_to_fp32: bool = False, num_generations: int | None = 8, num_generations_eval: int | None = None, max_completion_length: int | None = 512, ds3_gather_for_generation: bool = True, shuffle_dataset: bool | None = True, pad_to_multiple_of: int | str | None = 'auto', generation_batch_size: int | None = None, steps_per_generation: int | None = None, temperature: float = 1.0, top_p: float = 1.0, top_k: int = 0, min_p: float | None = None, generation_kwargs: dict | str | None = None, chat_template_kwargs: dict | str | None = None, repetition_penalty: float = 1.0, cache_implementation: str | None = None, use_vllm: bool = False, vllm_mode: str = 'colocate', vllm_model_impl: str = 'vllm', vllm_enable_sleep_mode: bool = False, vllm_structured_outputs_regex: str | None = None, vllm_server_base_url: str | None = None, vllm_server_host: str = '0.0.0.0', vllm_server_port: int = 8000, vllm_server_timeout: float = 240.0, vllm_group_port: int = 51216, vllm_gpu_memory_utilization: float = 0.3, vllm_max_model_length: int | None = None, vllm_tensor_parallel_size: int = 1, beta: float = 0.0, num_iterations: int = 1, epsilon: float = 0.4, delta: float | None = None, epsilon_high: float | None = None, sapo_temperature_neg: float = 1.05, sapo_temperature_pos: float = 1.0, vespo_k_pos: float = 2.0, vespo_lambda_pos: float = 3.0, vespo_k_neg: float = 3.0, vespo_lambda_neg: float = 2.0, importance_sampling_level: str = 'token', reward_weights: list[float] | None = None, multi_objective_aggregation: str = 'sum_then_normalize', scale_rewards: str = 'group', loss_type: str = 'dapo', mask_truncated_completions: bool = False, sync_ref_model: bool = False, ref_model_mixup_alpha: float = 0.6, ref_model_sync_steps: int = 512, top_entropy_quantile: float = 1.0, entropy_coef: float = 0.0, use_adaptive_entropy: bool = False, entropy_coef_min: float = 0.0, entropy_coef_max: float = 1.0, entropy_coef_delta: float = 0.005, entropy_target: float = 0.2, max_tool_calling_iterations: int | None = None, vllm_importance_sampling_correction: bool = True, vllm_importance_sampling_mode: str = 'sequence_mask', vllm_importance_sampling_clip_max: float | None = 3.0, vllm_importance_sampling_clip_min: float | None = None, off_policy_mask_threshold: float | None = None, use_bias_correction_kl: bool = True, log_completions: bool = False, log_multimodal: bool = True, num_completions_to_print: int | None = None, log_unique_prompts: bool = False, log_completions_hub_repo: str | None = None, use_transformers_continuous_batching: bool = False, transformers_continuous_batching_config: dict | str | None = None, use_transformers_paged: bool = False, vllm_importance_sampling_cap: float | None = None)
```

[Nguồn](https://github.com/huggingface/trl/blob/v1.18.1/trl/experimental/gmpo/gmpo_config.py#L21)

**Tham số:**

epsilon (`float`, *optional*, mặc định là `0.4`) : Giá trị cắt dưới, biểu diễn trong không gian log. Giới hạn dưới của tỷ lệ quan trọng trên mỗi token là `exp(-epsilon)`.

epsilon_high (`float`, *optional*) : Giá trị cắt trên, biểu diễn trong không gian log. Nếu là `None`, giá trị mặc định sẽ là giá trị của `epsilon`. Giới hạn trên của tỷ lệ quan trọng trên mỗi token là `exp(epsilon_high)`.

Lớp cấu hình cho [experimental.gmpo.GMPOTrainer](/docs/trl/v1.18.1/vi/gmpo#trl.experimental.gmpo.GMPOTrainer).

[experimental.gmpo.GMPOConfig](/docs/trl/v1.18.1/vi/gmpo#trl.experimental.gmpo.GMPOConfig) kế thừa mọi tham số từ [GRPOConfig](/docs/trl/v1.18.1/vi/grpo_trainer#trl.GRPOConfig); nó chỉ thay đổi ý nghĩa và giá trị mặc định của khoảng cắt (clipping range). Trong GMPO, việc cắt được áp dụng cho các tỷ lệ quan trọng *log* trên mỗi token (tức là trong không gian log) trước khi lấy trung bình hình học, do đó `epsilon` và `epsilon_high` được biểu diễn trong không gian log: khoảng cắt hiệu dụng của tỷ lệ là `(exp(-epsilon), exp(epsilon_high))`. Bài báo [GMPO paper](https://huggingface.co/papers/2507.20673) khuyến nghị một khoảng rộng hơn đáng kể so với GRPO/DAPO, `(exp(-0.4), exp(0.4))`, để khuyến khích khám phá.

