# 论文索引

> [!TIP]
> 以下每篇论文都链接到其 Hugging Face 论文页面。你也可以通过 `hf` CLI 在终端中阅读其中任意一篇，例如 `hf papers read 2402.03300` —— 这对编码代理来说尤其方便。

## Group Relative Policy Optimization

与 [GRPOTrainer](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOTrainer) 相关的论文。

### DeepSeekMath：推动开源语言模型数学推理的极限

**📜 论文**: https://huggingface.co/papers/2402.03300

引入了组相对策略优化（GRPO），并展示了以数学为中心的预训练加上组相对 PPO 风格优化所带来的显著数学推理能力提升。在 TRL 中通过 [GRPOTrainer](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOTrainer) 使用。

```python
from trl import GRPOConfig, GRPOTrainer

# The paper doesn't specify its hyperparameters, so here we provide hyperparameters from "DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning" instead.
training_args = GRPOConfig(
    loss_type="grpo",
    beta=0.001,  # "the KL coefficient to 0.001"
    epsilon=10.0, # "the GRPO clip ratio ϵ to 10"
    num_generations=16,  # "For each question, we sample 16 outputs..."
    max_completion_length=32_768,  # "...with a maximum length of 32,768"
    steps_per_generation=16,  # "To accelerate training, each rollout generates 8,192 outputs, which are randomly split into 16 minibatches"
    # "resulting in a training batch size of 512". One way to achieve this setting with 1 device is per_device_train_batch_size=4, gradient_accumulation_steps=128
    per_device_train_batch_size=4,
    gradient_accumulation_steps=128,  
)
trainer = GRPOTrainer(
    ...,
    args=training_args,
)
```

### DeepSeek-R1：通过强化学习激励大语言模型的推理能力

**📜 论文**: https://huggingface.co/papers/2501.12948

DeepSeek-R1 通过一个多阶段流程实现了与 OpenAI-o1 相当的推理性能，该流程从纯强化学习（RL）逐步过渡到经过精调、与人类偏好对齐的模型。与其前代 DeepSeek-R1-Zero 不同，后者在基础模型上使用了纯 RL，R1 遵循了结构化的四阶段演进：
1. 冷启动：基础模型在一组高质量、长思维链（CoT）数据上进行微调，以提供稳定的起点。
2. 面向推理的强化学习：应用大规模强化学习来提升数学、编码和逻辑方面的性能，并使用基于规则的奖励以及语言一致性奖励来减少语言混杂。
3. 拒绝采样 & SFT：RL 检查点通过拒绝采样生成 60 万个推理样本，并将其与 20 万个非推理（通用）样本合并，以创建用于第二轮监督微调的新数据集。
4. 适用于所有场景的强化学习：最终的强化学习阶段使模型在所有领域中对齐人类偏好（有用性和无害性），同时保持推理能力。

蒸馏：赋能小模型

该论文的一项关键贡献在于证明，可以将推理模式从大模型（DeepSeek-R1）蒸馏到更小的稠密模型（例如 Qwen 和 Llama 系列）中。研究发现，对于小模型而言，蒸馏比从头开始使用纯 RL 进行训练更为有效。

你可以使用 GRPOTrainer 来复现此流水线中推理密集的阶段。
```python
from trl import GRPOConfig, GRPOTrainer

# Example configuration for a reasoning-oriented GRPO stage
# Based on the Open-R1 recipe for Qwen-7B
training_args = GRPOConfig(
    learning_rate=4.0e-5,
    max_completion_length=32768, # Support for long Chain-of-Thought
    num_generations=16,          # Sample 16 outputs per prompt for group relative advantage
    beta=0.001,                  # KL coefficient
    use_vllm=True,               # Use vLLM backend for accelerated rollout generation
)

trainer = GRPOTrainer(
    model=model,
    args=training_args,
    train_dataset=dataset,
    reward_funcs=[accuracy_reward, format_reward], # R1-Zero used rule-based rewards
)

trainer.train()
```

### Group Sequence Policy Optimization

**📜 论文**: https://huggingface.co/papers/2507.18071

GSPO 是 GRPO 的一种变体，它在序列级别而非逐 token 级别计算重要性采样权重。要复现论文中的设置，请使用此配置：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    importance_sampling_level="sequence",
    loss_type="grpo",
    beta=0.0,  # GSPO set KL regularization to zero: https://github.com/volcengine/verl/pull/2775#issuecomment-3131807306
    epsilon=3e-4,  # GSPO paper (v2), section 5.1
    epsilon_high=4e-4,  # GSPO paper (v2), section 5.1
    gradient_accumulation_steps=1,
    steps_per_generation=4,  # partition rollout batch into 4 mini-batches. GSPO paper (v2), section 5.1. Must be 4 times gradient_accumulation_steps
)
```

请注意，此方法仅在训练略微偏离策略时才会产生效果——例如，当 `steps_per_generation > gradient_accumulation_steps` 或 `num_iterations > 1` 时。否则，它实际上等同于未做任何修改。

TRL 在 v1.13 之前发布了一个实验性的 GSPO-token 实现；它已不再属于该库的一部分，但仍可在 git 历史中获取。仅当优势值随 \\( t \\) 变化时，它与上述序列级目标存在差异，而 TRL 目前并不生成此类优势值。

#### 策略比率：GRPO 与 GSPO

在 GSPO 中，策略比率在序列级别上定义。换句话说，它是当前策略生成某个序列的概率与旧策略生成同一序列的概率之比。

序列似然定义为：

$$ \pi_\theta (o_i | q) = \prod_{t=1}^{|o_i|} \pi_\theta  (o_{i,t} | q, o_{i, < t} ), $$

其中 \\( \pi_\theta \\) 是参数为 \\(\theta\\) 的策略 \\( \pi \\)，\\( o_i \\) 是第 \\( i \\) 个输出序列 \\( o \\)，\\(o_{i,t}\\) 是该序列中的第 \\( t \\) 个 token，\\( q \\) 是输入查询。序列似然比 \\( s_i (\theta) \\) 定义为：

$$ s_i (\theta) = \left(\frac{\pi_\theta (o_i | q)}{\pi_{\theta_{old}} (o_i | q)} \right)^{\frac{1}{|o_i|}} $$

指数 \\( \frac{1}{|o_i|} \\) 表示序列长度归一化，用于最小化序列长度对序列似然的影响。换言之，它计算的是 token 概率的几何平均值，从而确保不同长度的序列之间能够进行公平比较。

虽然 GSPO 在序列级别定义策略比率，但 GRPO 在 token 级别进行操作。具体来说，GRPO 为序列中的每个 token 计算一个重要性比率：

$$ w_{i,t}(\theta) = \frac{\pi_\theta (o_{i,t} | q, o_{i,< t})}{\pi_{\theta_{\text{old}}} (o_{i,t} | q, o_{i,< t})} $$

该 token 级比率随后与共享优势 \\( \hat{A}_i \\) 相结合，GRPO 目标函数会对序列中的每个 token 独立地进行裁剪和优化。

### 几何平均策略优化

**📜 论文**: https://huggingface.co/papers/2507.20673

几何均值策略优化（GMPO）是 GRPO 的一种变体，它最大化的是 token 级重要性比值的*几何*均值，而非算术均值。几何均值对异常比值的敏感度远低于算术均值，因此策略更新更加稳定，并能容忍更宽的裁剪范围。裁剪在 token 级别、对数空间中进行，并且根据优势值的符号进行单侧裁剪（即标准的 PPO 信任域）——关键在于，这一操作发生在计算几何均值*之前*。这正是 GMPO 与 GSPO（`importance_sampling_level="sequence"`）的区别所在，后者是在求平均*之后*才对序列级比值进行裁剪。

GMPO 目标将 GRPO 的逐 token 算术平均值替换为（裁剪后的）token 比值的几何平均值：

$$ \mathcal{J}_{\text{GMPO}}(\theta) = \mathbb{E}_{q, \{o_i\}} \left[ \frac{1}{G} \sum_{i=1}^{G} \left( \prod_{t=1}^{|o_i|} \min\left[ w_{i,t}(\theta)^{\operatorname{sgn}(\hat{A}_i)},\ \operatorname{clip}\left(w_{i,t}(\theta)^{\operatorname{sgn}(\hat{A}_i)}, \epsilon_1, \epsilon_2\right) \right]^{\operatorname{sgn}(\hat{A}_i)} \right)^{\frac{1}{|o_i|}} \hat{A}_i \right] $$

其中 \\( w_{i,t}(\theta) \\) 是逐 token 的重要性比率。在实际操作中，乘积和裁剪均在 log 空间中计算，以确保数值稳定性，并且裁剪范围 \\( (\epsilon_1, \epsilon_2) = (e^{-0.4}, e^{0.4}) \\) 明显宽于 GRPO/DAPO，以鼓励探索。

TRL 提供了一个实验性实现，请参阅 [实验性 - GMPO](gmpo)：

```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,
)
```

### DAPO：大规模开源 LLM 强化学习系统

**📜 论文**: https://huggingface.co/papers/2503.14476

DAPO 算法包含 5 个关键组件：

- 超长过滤
- Clip-Higher
- Soft Overlong Punishment
- Token 级损失
- 动态采样（⚠️ TRL 不支持）

要复现论文中的设置，请使用此配置：

```python
from trl import GRPOConfig, GRPOTrainer

training_args = GRPOConfig(
    # Overlong Filtering
    mask_truncated_completions=True,
    # Token-level Loss
    loss_type="dapo",
    # Clip-Higher
    epsilon_high=0.28, # DAPO paper: section 4.1
    epsilon=0.2, # DAPO paper: section 4.1
    # Other parameters used
    per_device_train_batch_size=512, # mini-batch size for training in the paper, DAPO paper: section 4.1
    num_generations=16, # number of sample responses in the paper, DAPO paper: section 4.1
    max_completion_length=20480, #  maximum number of tokens for generation in the paper, DAPO paper: section 4.1
    beta=0.0, # section 2.3, DAPO paper

)
# Soft Overlong Punishment
sop_reward = get_soft_overlong_punishment(max_completion_len=20480, soft_punish_cache=4096) # DAPO paper: section 4.1
trainer = GRPOTrainer(
    ...,
    args=training_args,
    reward_funcs=[..., sop_reward],
)
```

### 揭秘大语言模型中的长思维链推理

**📜 论文**: https://huggingface.co/papers/2502.03373

本文研究了长思维链强化学习，并引入了两种互补的规则奖励：

- 一种**余弦长度缩放奖励**（[get_cosine_scaled_reward()](/docs/trl/v1.18.1/zh/rewards#trl.rewards.get_cosine_scaled_reward)，附录 C.1），它根据补全长度对正确性奖励进行缩放：正确的补全越短，获得的奖励越高；而错误的补全越长，受到的惩罚越小（以保留探索空间）。
- 一种 **n-gram 重复惩罚**（[get_repetition_penalty_reward()](/docs/trl/v1.18.1/zh/rewards#trl.rewards.get_repetition_penalty_reward)，附录 C.2），用于抑制在长度整形下作为奖励黑客策略而出现的退化、重复性补全。

两者被设计为配合使用：

```python
from trl import GRPOTrainer
from trl.rewards import get_cosine_scaled_reward, get_repetition_penalty_reward

# max_len should match the generation budget (in tokens)
cosine_scaled_reward = get_cosine_scaled_reward(max_len=4096)
# Penalize repeated 3-grams, down to -1.0 for fully repetitive completions
repetition_penalty = get_repetition_penalty_reward(ngram_size=3, max_penalty=-1.0)
trainer = GRPOTrainer(
    ...,
    reward_funcs=[cosine_scaled_reward, repetition_penalty],
)
```

### INTELLECT-2：通过全球去中心化强化学习训练的推理模型

**📜 论文**: https://huggingface.co/papers/2505.07291

INTELLECT-2 是首个在全球范围内分布式进行的强化学习训练，针对一个 320 亿参数的语言模型，利用完全异步的 RL 在一个由无许可计算贡献者组成的动态、异构集群上运行。作者提出了对标准 GRPO 训练方案的修改，包括用于提高训练稳定性的双向 GRPO 裁剪。要复现论文中的设置，请使用此配置：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    delta=4,  # δ in section 4.1 of the paper
    epsilon=0.2,  # ε in section 4.1 of the paper
    beta=0.001,  # KL divergence coefficient in section 4.1 of the paper
    num_generations=16,  # responses per prompt in section 4.1 of the paper
    learning_rate=3e-7,  # section 4.1 of the paper
)
```

### Skywork-OR1：开放推理模型

**📜 论文**: https://huggingface.co/papers/2505.22312

Skywork-OR1 是一组使用 GRPO 训练的开放推理模型。该论文引入了**自适应熵控制**：在 GRPO 目标函数中添加了一个熵正则化项 `−α·H(π_θ)`，并且系数 `α` 会在每个优化器步骤中自动调整。当模型的平均每 token 熵降至目标值或以下时，`α` 会递增以鼓励更多的探索；否则递减。该奖励仅在熵处于目标值或以下时应用。要复现这种自适应熵控制，请使用以下配置：

```python
from trl import GRPOConfig, GRPOTrainer

training_args = GRPOConfig(
    use_adaptive_entropy=True,   # enable adaptive entropy control (Section 3.3 of the paper)
    entropy_coef=0.01,           # initial entropy regularization coefficient
    entropy_target=5.0,          # target mean per-token entropy (nats); tune for your model
    entropy_coef_delta=0.005,    # step size for coefficient updates per optimizer step
)
trainer = GRPOTrainer(
    ...,
    args=training_args,
)
```

### 超越 80/20 法则：高熵少数 Token 驱动大语言模型推理的有效强化学习

**📜 论文**: https://huggingface.co/papers/2506.01939

在 CoT 路径中，少数高熵 token 充当推理“分叉点”，推动探索并为 RLVR 带来性能提升；而占多数的低熵 token 贡献甚微，甚至可能阻碍学习。RLVR 主要调整高熵 token，在很大程度上保留了基础模型的整体熵分布模式。因此，遵循 80/20 法则，仅使用熵最高的 20% token 进行训练，对于 Qwen3 模型而言，其效果与全梯度更新相当甚至更优。

该论文的主要结果使用的是原生 DAPO（⚠️ TRL 不支持动态采样）。要复现主要结果，请使用以下配置：

```python
from trl import GRPOConfig, GRPOTrainer
from trl.rewards import get_soft_overlong_punishment

training_args = GRPOConfig(
    # --- vanilla DAPO parameters (80/20 rule: section 5.2) --- #
    # Overlong Filtering
    mask_truncated_completions=True,
    # Token-level Loss
    loss_type="dapo",
    # Clip-Higher
    epsilon_high=0.28, # DAPO paper: section 4.1
    epsilon=0.2, # DAPO paper: section 4.1
    # Other parameters used
    per_device_train_batch_size=512, # mini-batch size for training in the paper, DAPO paper: section 4.1
    num_generations=16, # number of sample responses in the paper, DAPO paper: section 4.1
    max_completion_length=20480, #  maximum number of tokens for generation in the paper, DAPO paper: section 4.1
    beta=0.0, # section 2.3, DAPO paper
    # --- Gradients on the highest entropy tokens --- #
    top_entropy_quantile=0.2
)
# Soft Overlong Punishment
sop_reward = get_soft_overlong_punishment(max_completion_len=20480, soft_punish_cache=4096) # DAPO paper: section 4.1
trainer = GRPOTrainer(
    ...,
    args=training_args,
    reward_funcs=[..., sop_reward],
)
```

### Dr. GRPO：理解 R1-Zero 式训练：一种批判性视角

**📜 论文**: https://huggingface.co/papers/2503.20783

对 R1-Zero 训练的研究揭示了预训练对强化学习性能的影响，并提出了 Dr. GRPO 以提升 token 效率，在 AIME 2024 上取得了更高的准确率。要复现该论文的设置，请使用此配置：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    loss_type="dr_grpo",
    per_device_train_batch_size=1, # train_batch_size_per_device in the Training section of the repository
    num_generations=8, #  num_samples in the Training section of the repository
    max_completion_length=3000, # generate_max_length in the Training section of the repository
    beta=0.0, # β in the Training section of the repository
)
```

### 第一部分：技巧还是陷阱？深入探讨用于 LLM 推理的 RL（Lite PPO）

**📜 论文**: https://huggingface.co/papers/2508.08221

该论文的作者发现，以下组合

1. 按整个批次计算的标准差对奖励进行缩放，
2. 在总 token 数量上聚合损失

可以解锁无评论家策略的学习能力，同时使用标准的 PPO 损失。他们的结果表明，这种简单的组合能持续提升性能，超越了 GRPO 和 [DAPO](https://huggingface.co/papers/2503.14476) 等策略。

TRL 支持利用这些学习成果来训练 GRPO 模型，具体方式为：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...
    scale_rewards="batch",
    loss_type="dapo",
    # Other parameters used
    beta=0.0,  # = init_kl_coef in the paper
    top_p=0.99,
    top_k=100,
    temperature=0.99,
    num_generations=8, # = num_return_sequences in the paper
    num_iterations=1,  # = ppo_epochs in the paper
    per_device_train_batch_size=4,
    gradient_accumulation_steps=32,
    steps_per_generation=8,  # (rollout_batch_size*num_return_sequences) / (per_device_train_batch_size*gradient_accumulation_steps)
)
```

请注意，在使用梯度累积时，损失是在批次的总 token 数上进行聚合的，而不是在累积的批次上进行聚合。有关更多详细信息，请参阅 [GRPO Trainer - Loss types](grpo_trainer#loss-types)。

### 截断重要性采样

**📰 博客**：https://fengyao.notion.site/off-policy-rl

**📜 论文**: https://huggingface.co/papers/1606.02647

在线策略学习方法通常使用与训练后端分离的优化推理框架（例如 vLLM）来生成 rollout。这会导致 rollout 与训练之间的不匹配，以下 PPO 目标函数即为示例：

$$ \small{ \mathbb{E}_{a\sim\textcolor{red}{\pi_{\text{inference}}}(\theta_{\mathrm{old}})} \Bigl[ \min\Bigl( \frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}\,\hat A, \;\mathrm{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})},\,1-\epsilon,\,1+\epsilon\bigr)\,\hat A \Bigr) \Bigr] } $$

尽管 \\( \textcolor{red}{\pi_{\text{inference}}} \\) 和 \\( \textcolor{blue}{\pi_{\text{training}}} \\) 共享相同的模型参数 \\( \theta \\)，它们仍可能产生显著不同的 token 概率。这种出乎意料的行为隐式地破坏了 on-policy 假设，并悄无声息地将训练转变为 off-policy。

截断重要性采样（TIS）通过重要性采样校正来调整模型更新，从而解决这一问题。上述 PPO 目标的梯度计算变为

$$ \small{ \mathbb{E}_{a\sim\textcolor{red}{\pi_{\text{inference}}}(\theta_{\mathrm{old}})} \Bigl[ \underbrace{\text{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}{\textcolor{red}{\pi_{\text{inference}}}(a, \theta_{\mathrm{old}})}, C_{\min}, C_{\max}\bigr)}_{截断的重要性比率} \cdot \nabla_\theta \min\Bigl( \frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}\,\hat A, \;\mathrm{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})},\,1-\epsilon,\,1+\epsilon\bigr)\,\hat A \Bigr) \Bigr] } $$

其中 \\( C_{\min} \\) 和 \\( C_{\max} \\) 是超参数。TIS 在 GRPO 中实现，通过选择包含 `truncate` 一词的 `vllm_importance_sampling_mode` 变体来启用，例如 `"sequence_truncate"` 或 `"token_truncate"`。

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...
    use_vllm=True,
    vllm_importance_sampling_correction=True, # default True
    vllm_importance_sampling_mode="sequence_truncate", # or "token_truncate"
    vllm_importance_sampling_clip_max=2.0, # hyper-parameter C_max
)
```

### 掩码重要性采样

**📰 博客**：https://ringtech.notion.site/icepop

**📜 论文**: https://huggingface.co/papers/2510.18855

**📰 博客**：https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda

掩码重要性采样（MIS）解决了与[截断重要性采样](#truncated-importance-sampling)相同的问题，但用掩码替代了截断。MIS 采取了更果断的立场，直接丢弃差异超出范围 \\( [C_{\min}, C_{\max}] \\) 的更新。

$$ \small{ \mathbb{E}_{a\sim\textcolor{red}{\pi_{\text{inference}}}(\theta_{\mathrm{old}})} \Bigl[ \underbrace{\mathbf{1}\left[ C_{\min} \le \frac{\pi_{\text{training}}(a, \theta_{\mathrm{old}})} {\pi_{\text{inference}}(a, \theta_{\mathrm{old}})} \le C_{\max} \right] \cdot \frac{\pi_{\text{training}}(a, \theta_{\mathrm{old}})} {\pi_{\text{inference}}(a, \theta_{\mathrm{old}})}}_{\text{masked importance ratio}} \cdot \nabla_\theta \min\Bigl( \frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})}\,\hat A, \;\mathrm{clip}\bigl(\frac{\textcolor{blue}{\pi_{\text{training}}}(a, \theta)}{\textcolor{blue}{\pi_{\text{training}}}(a, \theta_{\mathrm{old}})},\,1-\epsilon,\,1+\epsilon\bigr)\,\hat A \Bigr) \Bigr] } $$

MIS 已针对 GRPO 实现，通过选择包含 `"mask"` 一词的 `vllm_importance_sampling_mode` 变体来启用，例如 `"sequence_mask"` 或 `"token_mask"`。

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...
    use_vllm=True,
    vllm_importance_sampling_correction=True, # default True
    vllm_importance_sampling_mode="sequence_mask", # or "token_mask"
    vllm_importance_sampling_clip_max=2.0, # hyper-parameter C_max
    vllm_importance_sampling_clip_min=0.5, # hyper-parameter C_min
)
```

在 [AsyncGRPOTrainer](/docs/trl/v1.18.1/zh/async_grpo_trainer#trl.AsyncGRPOTrainer) 中，旧的 log-probabilities 来自采样器，因此比率直接取训练后的策略与采样器之间，并且位于 \\( [C_{\min}, C_{\max}] \\) 之外的 token 会从损失中丢弃。此功能默认开启：

```python
from trl import AsyncGRPOConfig

training_args = AsyncGRPOConfig(
    ...,
    vllm_importance_sampling_clip_min=0.5,  # hyper-parameter C_min
    vllm_importance_sampling_clip_max=5.0,  # hyper-parameter C_max
)
```

### 序列级重要性采样

**📰 博客**：https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda

从理论上讲，纠正训练与推理之间分布偏移的合理方法是重要性采样，如上述两篇论文[截断重要性采样](#truncated-importance-sampling)和[掩码重要性采样](#masked-importance-sampling)中所介绍。然而，公式的选择对于保持梯度无偏并确保训练稳定至关重要。

这项工作表明，序列级重要性采样是解决训练-推理不匹配问题的可靠方法。尽管令牌级重要性采样比序列级比率具有更低的方差，但它会引入偏差，因此被认为不适用于自回归模型。令牌级梯度估计器是

$$ \mathbb{E}_{x\sim\mathcal{D},\, y\sim \pi^{\text{inference}}_\theta(\cdot|x)} \Bigg[ R(x,y)\,\cdot\, \sum_{t=0}^{|y|-1} \frac{\pi^{\text{training}}_\theta(y_t\,|\,x, y_{<t})} {\pi^{\text{inference}}_\theta(y_t\,|\,x, y_{<t})} \,\nabla_\theta \log \pi^{\text{training}}_\theta(y_t\,|\,x, y_{<t}) \Bigg] $$ 正确且无偏的策略梯度估计器在整个生成的序列（轨迹）\\( y \\) 上应用单个重要性比率。序列级 IS 估计器的形式如下：

$$ \mathbb{E}_{x\sim\mathcal{D},\, y\sim \pi^{\text{inference}}_\theta(\cdot|x)} \Bigg[ \frac{\pi^{\text{training}}_\theta(y|x)} {\pi^{\text{inference}}_\theta(y|x)} \, R(x,y)\, \nabla_\theta \log \pi^{\text{training}}_\theta(y|x) \Bigg] $$

TRL 通过 `vllm_importance_sampling_mode` 配置参数暴露重要性采样的粒度级别，其中 `"sequence_*"` 模式实现序列级别的重要性采样比率，而 `"token_*"` 则实现逐 token 的比率。

### 扩展强化学习的艺术

**📜 论文**: https://huggingface.co/papers/2510.13786

一项系统性研究，旨在定义一个用于分析和预测大语言模型中强化学习扩展性的框架，识别影响计算效率的关键设计选择，并提出一种名为 ScaleRL 的最佳实践方案。

您可以使用以下配置，通过 [GRPOTrainer](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOTrainer) 部分复现 ScaleRL 配方：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    loss_type="cispo",
    epsilon_high=5.0,
    num_generations=16,
    scale_rewards="batch",
    cast_lm_head_to_fp32=True
)
```

### 缺一不可：你的 GRPO 其实是 DPO

**📜 论文**: https://huggingface.co/papers/2510.00977

表明 GRPO 的有效性源于隐式对比目标，而非通过大组规模实现的精确优势估计。这建立了 GRPO 与 DPO 之间的正式联系，其中组规模仅影响对比目标的蒙特卡洛估计器。作者引入了 2-GRPO——仅使用两个 rollout——其在显著降低训练成本的情况下，性能与 16-GRPO 相当。在 TRL 中通过 [GRPOTrainer](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOTrainer) 配合 `num_generations=2` 使用。要复现论文的设置，请使用此配置：

```python
from trl import GRPOConfig, GRPOTrainer

training_args = GRPOConfig(
    num_generations=2,  # minimal two-rollout case (2-GRPO) from the paper
    loss_type="grpo",
)
trainer = GRPOTrainer(
    ...,
    args=training_args,
)
```

### Soft Adaptive Policy Optimization

**📜 论文**: https://huggingface.co/papers/2511.20347

Soft Adaptive Policy Optimization (SAPO) 用一种平滑的、温度可控的门控机制取代了硬截断，该机制在保留有用学习信号的同时，自适应地衰减离策略更新。与 GSPO 和 GRPO 相比，SAPO 兼具序列一致性和 token 级自适应性。与 GSPO 类似，SAPO 保持了序列级别的一致性，但其软门控形成了一个连续的信任域，从而避免了 GSPO 中使用的脆弱的硬截断区间。

要复现论文中的设置，请使用此配置：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    loss_type="sapo",
    sapo_temperature_pos=1.0,  # default value
    sapo_temperature_neg=1.05,  # default value
    scale_rewards="group",
    ...
)
```

### DeepSeek-V3.2：推动开源大语言模型的前沿

**📜 论文**: https://huggingface.co/papers/2512.02556

DeepSeek-V3.2 技术报告介绍了多种用于提升 GRPO 性能的技术。在 TRL 中，我们实现了：

- **无偏 KL 估计**，它修正了 K3 估计器（原始 GRPO 实现中所使用的），利用当前策略 \\( \pi_\theta \\) 与行为策略 \\( \pi_{\text{old}} \\) 之间的重要性采样比率，获得无偏的 KL 估计。

$$ \mathrm{D}_{\mathrm{KL}}\!\left(\pi_\theta(o_{i,t}) \,\|\, \pi_{\text{ref}}(o_{i,t})\right) = \textcolor{red}{\frac{\pi_\theta(o_{i,t}\mid q, o_{i,<t})}{\pi_{\text{old}}(o_{i,t}\mid q, o_{i,<t})}} \left( \frac{\pi_{\text{ref}}(o_{i,t}\mid q, o_{i,<t})}{\pi_\theta(o_{i,t}\mid q, o_{i,<t})} - \log \frac{\pi_{\text{ref}}(o_{i,t}\mid q, o_{i,<t})}{\pi_\theta(o_{i,t}\mid q, o_{i,<t})}
  - 1
\right). $$

此功能默认启用（[GRPOConfig](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOConfig) 中的 `use_bias_correction_kl=True`），因此您只需设置 `beta > 0`：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...,
    beta=0.001,  # the paper doesn't specify the value used, so we use the value from "DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning"
)
```

- **Off-Policy Masking** 通过忽略策略表现不佳（负优势）**且**与旧策略存在显著偏差（高 KL 散度）的序列，来稳定训练。

离策略二元掩码 \\(\textcolor{red}{M_{i,t}}\\) 定义为：

$$ \textcolor{red}{M_{i,t}} = \begin{cases} 0 & \text{if } \hat{A}_{i,t} < 0 \quad \text{and} \quad \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \log \frac{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i, \textcolor{blue}{\delta} \\ 1 & \text{otherwise} \end{cases} $$

然后，该掩码按以下方式应用于 GRPO 损失：

$$ \mathcal{L}_{\text{GRPO}}(\theta) = -\frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \left[ \min \left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})} \hat{A}_{i,t}, \, \text{clip}\left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})}, 1 - \epsilon, 1 + \epsilon \right) \hat{A}_{i,t} \right) \textcolor{red}{M_{i,t}} - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right] \right] $$

要启用此功能，请在 [GRPOConfig](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOConfig) 中使用 `off_policy_mask_threshold`（对应 \\( \textcolor{blue}{\delta} \\))：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...,
    off_policy_mask_threshold=0.5,
)
```

虽然论文未指定所使用的 \\( \textcolor{blue}{\delta} \\) 值，但一个不错的起点可以是 \\( \textcolor{blue}{\delta} = 0.5 \\)。如果训练显得过于保守，或者被掩码的序列过多，您可以增大该值。作为参考，\\( \textcolor{blue}{\delta} = 1.0 \\) 对应于每个 token 平均 1 nat 的对数比率散度，即在该阈值被超过的序列上，旧策略生成这些 token 的平均概率是当前策略的 \\( e^1 \approx 2.7 \\) 倍。

- **Keep Sampling Mask** 策略可确保 top-k/top-p 采样保持无偏。采样器从截断后的支撑集 \\( \textcolor{red}{\mathcal{S}_{i,t}} \\（即截断后保留的 token）中抽取每个 token，因此策略的对数概率会在该相同的支撑集上进行重新归一化：

$$ \log \pi_\theta(o_{i,t} \mid q, o_{i,<t}) = z_{o_{i,t}} - \log \sum_{v \in \textcolor{red}{\mathcal{S}_{i,t}}} e^{z_v}. $$

若缺少该机制，重要性比率会偏低，梯度会持续将概率质量推向采样器从未采样的 token，从而导致训练崩溃。[AsyncGRPOTrainer](/docs/trl/v1.18.1/zh/async_grpo_trainer#trl.AsyncGRPOTrainer) 支持此功能：当 `top_p < 1.0`、`top_k > 0` 或 `min_p > 0.0` 时，rollout worker 会记录 vLLM 中每个 token 的支持集（>= 0.28，需通过 `--return-sampling-mask --enable-scale-out` 启用），随后 trainer 会在该支持集上进行重新归一化：

```python
from trl import AsyncGRPOConfig

training_args = AsyncGRPOConfig(
    ...,
    top_p=0.95,
    top_k=512,
)
```

在 vLLM 的 colocate 模式（>= 0.28）下，[GRPOTrainer](/docs/trl/v1.18.1/zh/grpo_trainer#trl.GRPOTrainer) 也支持此功能：当 `top_k > 0` 且启用了重要性采样校正（默认设置）时，vLLM 会返回每个 token 的支持集，训练器会对其进行重新归一化：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...,
    use_vllm=True,
    top_p=0.95,
    top_k=512,
)
```

### GDPO：面向多奖励强化学习优化的组奖励解耦归一化策略优化

**📜 论文**: https://huggingface.co/papers/2601.05242

GDPO 是一种专为多奖励训练设计的强化学习优化方法。尽管现有方法在多奖励场景中通常采用 Group Relative Policy Optimization (GRPO)，但作者指出这会导致奖励优势坍缩，从而降低训练信号的分辨率，并引发不稳定的收敛或训练失败。GDPO 通过解耦各个奖励的归一化过程来解决此问题，保留它们之间的相对差异，从而实现更忠实的偏好优化。要在多奖励强化学习训练中启用 GDPO，只需设置：

对于一组\\( N \\)个奖励和每组\\( G \\)个样本，GDPO 独立地对每个奖励进行归一化：

$$ A_n^{(i,j)} = \frac{r_n^{(i,j)} - \text{mean}\{r_n^{(i,1)}, \ldots, r_n^{(i,G)}\}}{\text{std}\{r_n^{(i,1)}, \ldots, r_n^{(i,G)}\} + \epsilon} $$

然后，归一化的组优势会在奖励上进行聚合：

$$ A^{(i,j)} = \sum_{n=1}^{N} w_n A_n^{(i,j)} $$

最终的按批次归一化产生：

$$ \hat{A}^{(i,j)} = \frac{A^{(i,j)} - \text{mean}_{i',j'}\{A^{(i',j')}\}}{\text{std}_{i',j'}\{A^{(i',j')}\} + \epsilon} $$

此处，\\( \text{mean}_{i',j'}\{A^{(i',j')}\} \\) 和 \\( \text{std}_{i',j'}\{A^{(i',j')}\} \\) 表示对批次中所有组计算的统计量。

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    ...,
    multi_objective_aggregation="normalize_then_sum",
)
```

请注意，此方法仅在训练涉及多个奖励函数时才会生效。

作者提供了一个易于使用且无需 Slurm 的训练示例，使社区能够快速验证 GDPO 相较于 GRPO 的有效性，参见 [实验——“顿悟”时刻](https://github.com/NVlabs/GDPO/tree/main/trl-GDPO)。

### 无长度偏差的序列策略优化：揭示并控制 RLVR 中的响应长度变化

**📜 论文**: https://huggingface.co/papers/2602.05261

长度无偏序列策略优化（LUSPO）通过按序列长度缩放每个序列的损失来修改 GSPO。这纠正了 GSPO 中惩罚较长响应的梯度偏差。要复现论文中的设置，请使用此配置：

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    loss_type="luspo",
    importance_sampling_level="sequence",
    epsilon=2e-3, # section 5.1 of the paper
    epsilon_high=2.5e-3, # section 5.1 of the paper
)
```

### VESPO：用于稳定离策略大语言模型训练的变化序列级软策略优化

**📜 论文**: https://huggingface.co/papers/2602.10693

VESPO 解决了离策略强化学习中由策略陈旧、异步更新以及训练与推理不匹配所导致的训练不稳定问题。与依赖启发式的 token 级裁剪（GRPO）或序列长度归一化（GSPO）不同，VESPO 从变分框架中推导出了一个有原则的重塑核。在实践中，这产生了一个平滑且非对称的 Gamma 加权函数，能够优雅地抑制极端的序列级重要性权重，同时不会引入长度偏差。

$$ \mathcal{L}_{\text{VESPO}}(\theta) = - \mathbb{E}_{\tau \sim \mu} \left[ \underbrace{W(\tau)^{k} \cdot \exp\left(\lambda (1 - W(\tau))\right)}_{\phi(W) \text{ 已分离 }} \cdot \mathcal{A}(\tau) \cdot \log \pi_\theta(\tau) \right] $$

其中 \\( W(\tau) = \frac{\pi_\theta(\tau)}{\mu(\tau)} \\) 为序列级重要性比率，且 \\( \phi(W) \\) 从计算图中分离，用作梯度缩放系数。

```python
from trl import GRPOConfig

training_args = GRPOConfig(
    loss_type="vespo",
    use_vllm=True,  # or False if not using any token-level `vllm_importance_sampling_correction` methods
    vllm_importance_sampling_mode="token_truncate",  # default correction mode for VESPO, `token_mask` also supported
    vespo_k_pos=2.0,  # power exponent (c1 in paper Section 3.4) for positive advantages
    vespo_lambda_pos=3.0,  # decay factor (c2 in paper Section 3.4) for positive advantages
    vespo_k_neg=3.0,  # power exponent (c1 in paper Section 3.4) for negative advantages
    vespo_lambda_neg=2.0,  # decay factor (c2 in paper Section 3.4) for negative advantages
)
```

### 分数中心化稳定了离策略强化学习

**📜 论文**: https://huggingface.co/papers/2609.20807

在训练-推理不匹配的情况下，分数 \\( \nabla_\theta \log \pi_\theta \\) 在采样器 \\( \mu \\) 下不会平均为零，因此每次更新都会使策略向采样器漂移，漂移量随优势值增大而增大。分数中心化在每个位置减去该期望值，因此恒定的优势值不再使策略发生移动：

$$ \nabla_\theta \mathcal{L} = - \mathbb{E}_{o \sim \mu} \left[ \hat{A} \left( f(r_t) \nabla_\theta \log \pi_\theta(o_t) - \mathbb{E}_{v \sim \mu} \left[ f(r_v) \nabla_\theta \log \pi_\theta(v) \right] \right) \right], \quad r_v = \frac{\pi_\theta(v)}{\mu(v)}, $$

其中 \\( f \\) 为 [Masked Importance Sampling](#masked-importance-sampling) 的重要性权重：在 \\( [C_{\min}, C_{\max}] \\) 内为 \\( f(r) = r \\)，在区间外为 \\( 0 \\)。内部期望是在采样器于每个位置报告的对数概率所对应的最可能 token 上计算的；对于词表中的其余部分，将采样器视为经过重新缩放以匹配剩余概率质量的已训练策略。

这是 [AsyncGRPOTrainer](/docs/trl/v1.18.1/zh/async_grpo_trainer#trl.AsyncGRPOTrainer) 的默认目标，其 rollout worker 会向 vLLM 请求每个生成 token 的 top log-probabilities：

```python
from trl import AsyncGRPOConfig

training_args = AsyncGRPOConfig(
    ...,
    score_centering=True,  # default; `False` trains with the clipped objective instead
    vllm_importance_sampling_clip_min=0.5,  # hyper-parameter C_min
    vllm_importance_sampling_clip_max=5.0,  # hyper-parameter C_max
    num_sampler_logprobs=8,  # tokens per position the expectation is taken over
)
```

## 最优优势回归

与 [experimental.a2po.A2POTrainer](/docs/trl/v1.18.1/zh/a2po_trainer#trl.experimental.a2po.A2POTrainer) 相关的论文。

### 使用最优优势回归加速大语言模型推理中的强化学习

**📜 论文**: https://huggingface.co/papers/2505.20686

A\*-PO（Optimal Advantage Regression，最优优势回归）是一种用于 LLM 推理的两阶段强化学习方法，它既避免了在线 critic，也避免了多采样组 rollout。第一阶段从参考策略的样本中离线估计最优价值 `V*(x) = β·log E_{y∼π_ref}[exp(r(x, y)/β)]`；第二阶段使用每个提示词单次生成的方式，通过平方误差回归损失 `(β·log(π(y|x)/π_ref(y|x)) − (r(x, y) − V*(x)))²` 执行 on-policy 更新。与 PPO/GRPO/REBEL 相比，该方法具有更快的训练速度和更低的峰值内存。该方法假设奖励是二元的可验证奖励，且无法超越参考策略的 Pass@K。参见 [A2PO](a2po_trainer)。官方代码可在 [ZhaolinGao/A-PO](https://github.com/ZhaolinGao/A-PO) 中找到。

```python
from trl.experimental.a2po import A2POConfig, A2POTrainer

# Hyperparameters from the paper (Qwen2.5, GSM8K/MATH)
training_args = A2POConfig(
    beta1=0.5,  # KL temperature for offline V* estimation
    beta2=1e-3,  # KL temperature for the on-policy regression target
    num_value_samples=8,  # N samples per prompt from the reference policy
)
trainer = A2POTrainer(
    model=...,
    reward_funcs=...,  # should return a binary reward in {0, 1}
    args=training_args,
    train_dataset=...,
)
trainer.train()
```

## 直接偏好优化

与 [DPOTrainer](/docs/trl/v1.18.1/zh/dpo_trainer#trl.DPOTrainer) 相关的论文

### 直接偏好优化：你的语言模型其实是一个隐藏的奖励模型

**📜 论文**: https://huggingface.co/papers/2305.18290

直接偏好优化（DPO）通过基于人类偏好直接优化策略训练，与基于人类反馈的强化学习（RLHF）相比，能够更高效地微调语言模型，并带来更好的性能。要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="sigmoid", # losses in Appendix B of the paper
    per_device_train_batch_size=64, #  batch size in Appendix B of the paper
    learning_rate=1e-6, # learning rate in Appendix B of the paper
    beta=0.1, # β in Appendix B of the paper
)
```

### SLiC-HF：基于人类反馈的序列似然校准

**📜 论文**: https://huggingface.co/papers/2305.10425

序列似然校准（SLiC）被证明是语言模型中从人类偏好学习的一种有效且更简单的替代方案，可替代基于人类反馈的强化学习（RLHF）。要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="hinge", # Section 2 of the paper
    per_device_train_batch_size=512, #  batch size in Section 3.2 of the paper
    learning_rate=1e-4, # learning rate in Section 3.2 of the paper
)
```

这些参数仅出现在[已发布版本](https://openreview.net/pdf?id=0qSOodKmJaN)中

### 统计拒绝采样可提升偏好优化

**📜 论文**: https://huggingface.co/papers/2309.06657

提出**RSO**，通过统计拒绝采样选择更强的偏好对以提升离线偏好优化；作为 DPO/SLiC 的补充。他们还引入了一个新损失，定义为：

$$ \mathcal{L}_{\text{hinge-norm}}(\pi_\theta) = \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \max\left(0,\; 1 - \left[\gamma \log \frac{\pi_\theta(y_w \mid x)}{\pi_\text{ref}(y_w \mid x)} - \gamma \log \frac{\pi_\theta(y_l \mid x)}{\pi_\text{ref}(y_l \mid x)}\right]\right) \right] $$

要使用 RSO 过滤后的数据和 hinge-norm 损失进行训练，您可以使用以下代码：

```python
from trl import DPOConfig, DPOTrainer

dataset = ...

def rso_accept(example):  # replace with your actual filter/score logic
    return example["rso_keep"]

train_dataset = train_dataset.filter(rso_accept)

training_args = DPOConfig(
    loss_type="hinge",
    beta=0.05,  # correspond to γ in the paper
)

trainer = DPOTrainer(
    ...,
    args=training_args,
    train_dataset=train_dataset,
)
trainer.train()
```

### 超越反向 KL：通过多样化散度约束泛化直接偏好优化

**📜 论文**: https://huggingface.co/papers/2309.16240

提出了 \(( f \\)-DPO，通过用通用的 \(( f \\)-散度替换 DPO 中常用的反向 KL 正则项来扩展 DPO，从而允许你在模式寻求（mode-seeking）与质量覆盖（mass-covering）行为之间进行权衡（例如前向 KL、JS、 \(( \alpha \\)-散度）。唯一的改动是将 DPO 的对数比率边际替换为 **f′ 分数**：

$$ \mathcal{L}_{f\text{-DPO}}(\pi_\theta) = \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ -\log \sigma\left( \beta \textcolor{red}{f'}\textcolor{red}{\Big(}\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)}\textcolor{red}{\Big)} - \beta \textcolor{red}{f'}\textcolor{red}{\Big(}\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\textcolor{red}{\Big)} \right) \right] $$

其中 \\( f' \\) 是定义所选 \(( f \\)-散度的凸函数的导数。

要复现：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="sigmoid",
    beta=0.1,
    f_divergence_type="js_divergence",  # or "reverse_kl" (default), "forward_kl", "js_divergence", "alpha_divergence"
    f_alpha_divergence_coef=0.5,  # only used if f_divergence_type="alpha_divergence"
)
```

### 理解从人类偏好中学习的通用理论范式

**📜 论文**: https://huggingface.co/papers/2310.12036

从人类偏好中学习可以表述为针对成对偏好概率的单一 KL 正则化目标，

$$ \max_\pi ;\mathbb{E}\big[\Psi\left(p^*(y \succ y' \mid x)\right)\big] - \tau\mathrm{KL}(\pi||\pi_{\text{ref}}), $$

这揭示了 RLHF 和 DPO 是 \\( \Psi \\) 的 logit 选择所对应的特例。该论文表明，这种 logit 变换会放大近乎确定性的偏好，并有效削弱 KL 正则化，从而解释了过拟合现象。使用 **恒等变换（IPO）** 可以直接优化偏好，而无需假设 Bradley–Terry 奖励模型，从而避免了这一病理现象。要复现论文中的设置，请使用以下配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="ipo",  # Section 5.1 of the paper
    per_device_train_batch_size=90,  #  mini-batch size in Section C.1 of the paper
    learning_rate=1e-2,  # learning rate in Section C.1 of the paper
)
```

这些参数仅出现在[已发布版本](https://proceedings.mlr.press/v238/gheshlaghi-azar24a/gheshlaghi-azar24a.pdf)中

### 面向语言模型对齐的高效且精确优化

**📜 论文**: https://huggingface.co/papers/2402.00856

该论文表明，DPO 等直接偏好方法优化了错误的 KL 方向，导致偏好捕捉模糊，并提出了 EXO 作为一种高效方法，通过利用反向 KL 概率匹配而非前向 KL 近似，来精确优化人类偏好对齐目标。要复现论文的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="exo_pair", # Section 3.2 of the paper
    # From Section B of the paper
    per_device_train_batch_size=64,
    learning_rate=1e-6,
    beta=0.1,
)
```

### 使用显式奖励对语言模型进行噪声对比对齐

**📜 论文**: https://huggingface.co/papers/2402.05369

该论文将语言模型对齐重新定义为*噪声对比分类*问题，提出 InfoNCA 通过匹配由奖励（或偏好）诱导的响应目标分布，从显式奖励（或偏好）中学习策略，并证明 DPO 是其特殊的二分类情形。随后，论文引入了 NCA，通过添加绝对似然项来防止纯相对（对比）目标中出现的似然坍缩现象。

对于成对偏好，将 chosen/rejected 视为 \\( K=2 \\)，定义分数 \\( r=\beta(\log\pi_\theta-\log\pi_{\text{ref}}) \\)，并应用 NCA 偏好损失 \\( -\log\sigma(r_w)-\tfrac12\log\sigma(-r_w)-\tfrac12\log\sigma(-r_l) \\)。

要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="nca_pair",
    # From Section C of the paper
    per_device_train_batch_size=32,
    learning_rate=5e-6,
    beta=0.01,
)
```

### 可证明鲁棒的 DPO：使用噪声反馈对齐语言模型

**📜 论文**: https://huggingface.co/papers/2403.00409

DPO 在存在噪声的人类偏好下会失效，因为标签翻转会使目标函数产生偏差。Robust DPO 通过在一个简单的噪声模型下对 DPO 损失进行解析去偏来解决这一问题，并提供了可证明的保证。

$$ \mathcal{L}_{\text{robust}}(\pi_\theta) = \frac{(1-\varepsilon)\mathcal{L}_{\text{DPO}}(y_w, y_l) - \varepsilon\mathcal{L}_{\text{DPO}}(y_l, y_w)} {1-2\varepsilon} $$

其中 \\( \mathcal{L}_{\text{DPO}} \\) 是 [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](#direct-preference-optimization-your-language-model-is-secretly-a-reward-model) 中定义的 DPO 损失，\\( \varepsilon \\) 是标签翻转的概率。

这一项修正可将带有噪声的偏好数据转化为干净 DPO 目标的无偏估计量。

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="robust",
    per_device_train_batch_size=16,  # batch size in Section B of the paper
    learning_rate=1e-3,  # learning rate in Section B of the paper
    beta=0.1,  # β in Section B of the paper,
    max_length=512,  # max length in Section B of the paper
    label_smoothing=0.1  # label smoothing $\varepsilon$ in Section 6 of the paper
)
```

### 用于大语言模型对齐的二分类器优化

**📜 论文**: https://huggingface.co/papers/2404.04656

理论分析和一种新算法——二元分类器优化（Binary Classifier Optimization）——解释并增强了使用二元反馈信号对大语言模型进行对齐的过程。要复现论文中的设置，请使用此配置：

BCO 将语言模型对齐重新定义为从最优奖励加权分布中进行行为克隆，从而得出简单的监督目标，在保持理论依据的同时避免了强化学习。它支持非配对奖励数据和成对偏好数据，并采用一种对奖励偏移具有不变性的公式，在偏好设置下可简化为 DPO 风格的损失函数。

在成对偏好设置中，BCO 损失定义为：

$$ \mathcal{L}_{\text{bco\_pair}}(\pi_\theta) = \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ -\log \sigma\Big( \beta[(\log\pi_\theta-\log\pi_{\text{ref}})(y_w) - (\log\pi_\theta-\log\pi_{\text{ref}})(y_l)] \Big) \right] $$

要在此设置中复现该论文，请使用以下配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="bco_pair",
    # From Section C of the paper
    per_device_train_batch_size=128,
    learning_rate=5e-7,
    beta=0.01,
)
```

### 深入学习你的参考模型，以实现真正的良好对齐

**📜 论文**: https://huggingface.co/papers/2404.09656

Trust Region DPO (TR-DPO) 在训练过程中更新参考策略，在 Anthropic HH 和 TLDR 数据集上展现出优于 DPO 的效果，通过 GPT-4 自动评估衡量，性能最高提升 19%，并在连贯性、正确性、细节程度、有用性和无害性方面均有改善。要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    sync_ref_model=True,  # enable TR-DPO (Section 3 of the paper)
    ref_model_mixup_alpha=0.6,  # α soft update weight (Table 1 of the paper)
    ref_model_sync_steps=512,  # τ update frequency in steps (Table 1 of the paper)
    beta=0.05,  # β temperature (Table 1 of the paper)
    learning_rate=1e-6,  # learning rate (Table 2 of the paper)
    num_train_epochs=1,  # Table 2 of the paper
    max_length=1024,  # max tokens length (Table 2 of the paper)
    max_grad_norm=2,  # max gradient norm (Table 2 of the paper)
    warmup_steps=100,  # warm-up steps (Table 2 of the paper)
)
```

### 迭代推理偏好优化

**📜 论文**: https://huggingface.co/papers/2404.19733

迭代式 RPO 通过反复生成思维链候选项、基于正确与错误答案构建偏好对，并使用 DPO + NLL 目标进行训练，从而提升推理能力。额外的 NLL 项对于学习实际生成获胜轨迹至关重要。

TRL 可以通过混合 `"sigmoid"`（DPO）和 `"sft"`（NLL）来表达 DPO + NLL 目标：

```python
from trl import DPOConfig, DPOTrainer

training_args = DPOConfig(
    loss_type=["sigmoid", "sft"],
    loss_weights=[1.0, 1.0],  # alpha in the paper, recommended value is 1.0
)
trainer = DPOTrainer(
    ...,
    args=training_args,
)
```

请注意，该论文采用迭代循环：每次迭代都会使用当前模型重新生成 CoT 候选项，然后在新的偏好对上重新训练。TRL 不会为您自动执行该循环。

### 用于语言模型对齐的自博弈偏好优化

**📜 论文**: https://huggingface.co/papers/2405.00675

一种名为 SPPO 的自博弈方法用于语言模型对齐，通过在零和博弈设定下近似纳什均衡策略，以有限的数据实现了最先进的性能，优于其他方法。要复现论文中的设定，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="sppo_hard",
    # From Section 5 of the paper
    beta=0.001,  # β = η^−1
    per_device_train_batch_size=64,
    learning_rate=5e-7,
)
```

### 可证明地缓解 RLHF 中的过度优化：你的 SFT 损失函数隐式地充当了对抗正则化器

**📜 论文**: https://huggingface.co/papers/2405.16436

正则化偏好优化（RPO）通过将 DPO 损失与 SFT 损失融合，缓解了 RLHF 中的过度优化问题，并可在理论上防止策略选择具有虚假高代理奖励的动作。要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type=["sigmoid", "sft"],  # RPO loss = DPO + SFT (Section 5 of the paper)
    loss_weights=[1.0, 0.005],  # η=0.005 SFT weight in Appendix E.1 of the paper
    beta=0.01,  # β in Appendix E.1 of the paper
    learning_rate=5e-7,  # learning rate in Appendix E.1 of the paper
    num_train_epochs=1,  # Appendix E.1 of the paper
)
```

### 通过最优传输实现大语言模型的分布偏好对齐

**📜 论文**: https://huggingface.co/papers/2406.05882

基于最优传输的对齐（AOT）通过对正样本和负样本分布之间随机占优的违反进行惩罚，在分布层面实现大语言模型的对齐，并在对齐基准测试中达到了最先进的性能。要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="aot",
    beta=0.01,  # from the caption of Figure 2
)
```

或者，对于非配对版本：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="aot_unpaired",
    beta=0.01,  # from the caption of Figure 2
)
```

论文中没有额外的超参数。

### 利用大语言模型发现偏好优化算法

**📜 论文**: https://huggingface.co/papers/2406.08414

一种由 LLM 驱动的方法能够自动发现高效的偏好优化算法，由此产生了一种名为 DiscoPOP 的新算法，该算法融合了逻辑损失和指数损失。要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="discopop",
    per_device_train_batch_size=64,  # batch size in Section B.1 of the paper
    learning_rate=5e-7,  # learning rate in Section B.1 of the paper
    beta=0.05,  # β in Section B.1 of the paper,
    discopop_tau=0.05  # τ in Section E of the paper
)
```

### WPO：通过加权偏好优化增强 RLHF

**📜 论文**: https://huggingface.co/papers/2406.11827

WPO 根据策略概率对偏好对进行重新加权，以减少 DPO 风格训练中的离策略差距。损失函数为：

$$ \mathcal{L}_{\text{WPO}} = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \left[ \textcolor{red}{w(x, y_w) w(x, y_l)} \log p(y_w \succ y_l \mid x) \right] $$

其中权重 \\( w(x, y) \\) 定义为：

$$ w(x, y) = \exp\left(\frac{1}{|y|}\sum_{t=1}^{|y|} \log \frac{\pi_\theta(y_t \mid x, y_{<t})}{\sum_{v \in \mathcal{V}} \pi_\theta(v \mid x, y_{<t})^2}\right) $$

要复现论文中的设置，请使用此配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="sigmoid",  # DPO loss used in the paper
    beta=0.01,  # Section 4 of the paper
    use_weighting=True,
)
```

### 基于锚点的偏好优化与对比修订：解决对齐中的欠指定问题

**📜 论文**: https://huggingface.co/papers/2408.06266

CLAIR 和 APO 通过引入更多对比偏好对和受控的对齐目标来增强 LLM 的对齐效果，使模型性能接近 GPT4-turbo。要复现论文中的设置，请使用以下配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="apo_zero",  # Section 4 of the paper
    per_device_train_batch_size=64,  # batch size in Section B.1 of the paper
    learning_rate=2e-7,  # learning rate in Section 5.2 of the paper
    beta=0.1,  # β in Section 5.2 of the paper,
)
```

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="apo_down",  # Section 4 of the paper
    per_device_train_batch_size=64,  # batch size in Section B.1 of the paper
    learning_rate=2e-7,  # learning rate in Section 5.2 of the paper
    beta=0.1,  # β in Section 5.2 of the paper,
)
```

这些参数仅出现在[已发布版本](https://aclanthology.org/2025.tacl-1.22.pdf)中

### 直接偏好优化中的长度脱敏

**📜 论文**: https://huggingface.co/papers/2409.06411

表明标准 DPO 本质上对长度敏感，这往往会促使模型生成过长或冗余的内容。该论文提出了 LD-DPO，它通过修改序列对数概率的聚合方式来应对这一问题：将较长的响应拆分为共享前缀（直至较短响应的长度）和多余的尾部，然后使用因子 \\( \alpha \in [0,1] \\) 对尾部进行降权：

$$ \log \pi_\theta(y_{\text{long}}|x) = \log \pi_\theta(y_{1:l_p}|x) + \alpha \cdot \log \pi_\theta(y_{l_p+1:l}|x, y_{1:l_p}), \quad l_p=\min(|y_w|,|y_l|). $$

设置 \\( \alpha=1 \\) 可恢复标准 DPO；较小的 \\( \alpha \\) 值可在保持偏好质量的同时减少冗余。最优的 \\( \alpha \\) 取决于模型系列以及你训练的是基础模型还是指令模型，但论文建议将 \\( \alpha=0.5 \\) 作为强有力的默认起点。

```python
from trl import DPOConfig

training_args = DPOConfig(
    ld_alpha=0.5,
)
```

### 通过混合偏好优化增强多模态大语言模型的推理能力

**📜 论文**: https://huggingface.co/papers/2411.10442

引入混合偏好优化（MPO）以提升多模态大语言模型（MLLM）的多模态推理能力，解决标准预训练和监督微调（SFT）后出现的分布偏移以及较弱的思维链（CoT）问题。该论文的贡献包括：(1) MMPR，一个用于生成高质量多模态偏好数据的自动化流水线；以及 (2) MPO，一种组合偏好目标（成对 + BCO 风格 + SFT），能够增强 CoT。InternVL2-8B-MPO 在 MathVista 上达到 67.0 分（比 InternVL2-8B 高 8.7 分），与规模大 10 倍的 InternVL2-76B 相当。在 TRL 中通过 [DPOConfig](/docs/trl/v1.18.1/zh/dpo_trainer#trl.DPOConfig) 使用复合损失来实现。要复现论文中的设置，请使用以下配置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type=["sigmoid", "bco_pair", "sft"],  # ℒ = w_p·ℒ_p + w_q·ℒ_q + w_g·ℒ_g (Section 3.2 of the paper)
    loss_weights=[0.8, 0.2, 1.0],  # w_p, w_q, w_g loss weights (Section 7 of the paper)
    learning_rate=5e-6,  # learning rate (Section 7 of the paper)
)
```

### TÜLU 3：推动开放语言模型后训练的前沿

**📜 论文**: https://huggingface.co/papers/2411.15124

长度归一化 Sigmoid 损失通过将 chosen 和 rejected 的对数比率分数分别除以各自的补全长度，再计算 Bradley-Terry 损失，从而解决了 DPO 中的长度偏差问题。这种逐 token 的归一化方法在 [SimPO](https://huggingface.co/papers/2405.14734)（附录 I “DPO w/ LN” 消融实验）中作为无参考设置下的平均对数概率奖励被提出，随后在 [Tülu 3](https://huggingface.co/papers/2411.15124)（第 4.3 节）等基于标准参考模型的 DPO 后训练方案中被采用。该损失函数为：

$$ \mathcal{L}_{\text{sigmoid\_norm}} = -\log\sigma\!\left(\beta \left({\color{red}\frac{1}{|y_w|}}\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - {\color{red}\frac{1}{|y_l|}}\log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\right)\right), $$ 可以通过以下方式设置：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="sigmoid_norm",
)
```

### 使用噪声偏好对大语言模型进行无偏对齐

**📜 论文**: https://huggingface.co/papers/2607.03248

该论文将偏好噪声建模为以概率 \\( \varepsilon \\) 翻转的标签，并反转此转换过程，使得在含噪偏好上训练的策略与在干净偏好上训练的策略具有相同的最优解。TRL 实现了由此得到的无偏 DPO（UDPO）损失的归一化形式，论文中称之为 α-UDPO：

$$ \mathcal{L}_{\text{UDPO}} = -\alpha \log \frac{e^{z} + a}{e^{z} + 1}, \quad z = \beta \left( \log \frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \log \frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)} \right), \quad a = \frac{\varepsilon}{1 - \varepsilon}, \quad \alpha = \frac{1 + \sqrt{a}}{1 - \sqrt{a}}, $$

这是 \\( a = 0 \\) 时的 DPO 损失。常数 \\( \alpha \\) 将最大梯度幅度保持在 1，与 DPO 相同。与 [Robust DPO](#provably-robust-dpo-aligning-language-models-with-noisy-feedback) 不同，论文表明，当真实的翻转概率低于假设的 \\( \varepsilon \\) 时（推论 4.7），最优解保持无偏，因此 \\( \varepsilon \\) 无需精确估计。在 TRL 中，\\( \varepsilon \\) 通过 `label_smoothing` 设置。要使用 \\( a = 0.8 \\)，即论文建议从业者采用的值：

```python
from trl import DPOConfig

training_args = DPOConfig(
    loss_type="udpo",
    label_smoothing=4 / 9,  # flip probability ε, for a = ε / (1 - ε) = 0.8 as recommended in Appendix B.1 of the paper
    beta=0.1,  # 0.1 for HH and UltraFeedback, 0.5 for TL;DR (Appendix B.1 of the paper)
    learning_rate=5e-6,  # 5e-6 for Llama-3.2-3B and Qwen3-1.7B, 1e-6 for 8B models (Appendix B.1 of the paper)
    num_train_epochs=3,  # Appendix B.1 of the paper
    per_device_train_batch_size=16,  # total batch size of 128 on 8 GPUs (Appendix B.1 of the paper)
    max_grad_norm=10.0,  # Appendix B.1 of the paper
    warmup_ratio=0.1,  # Appendix B.1 of the paper
)
```

## Kahneman–Tversky 优化

与 [KTOTrainer](/docs/trl/v1.18.1/zh/kto_trainer#trl.KTOTrainer) 相关的论文

### KTO：将模型对齐视为前景理论优化

**📜 论文**: https://huggingface.co/papers/2402.01306

KTO 从前景理论中推导出一个对齐目标，并直接基于**二元**人类反馈（喜欢/不喜欢）进行学习，其效果与 DPO 风格方法相当或更优，同时能很好地处理不平衡或含噪声的信号。若要复现论文中的设置，您可以使用 [KTOTrainer](/docs/trl/v1.18.1/zh/kto_trainer#trl.KTOTrainer) 的默认配置：

```python
from trl import KTOConfig, KTOTrainer
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)

trainer = KTOTrainer(
    model=model,
    processing_class=tokenizer,
    args=KTOConfig(),
    train_dataset=...,
)
trainer.train()
```

## 监督微调

与 [SFTTrainer](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTTrainer) 相关的论文

### TailSFT：过滤微调可提升后训练性能

**📜 论文**: https://huggingface.co/papers/2608.25756

TailSFT 通过筛选相对于初始策略在长度归一化损失上改善最多的序列，来保留后续强化学习所需的响应覆盖度。[`tail_sft_gsm8k`](https://github.com/huggingface/trl/tree/main/examples/tail_sft_gsm8k) 示例通过子类化 [SFTTrainer](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTTrainer) 实现了论文中分布式选择批次的过滤机制。它在训练前记录每个序列的初始策略损失，并在每个选择批次中独立地过滤样本。

```sh
python examples/tail_sft_gsm8k/tail_sft.py
```

### 无延迟的 EMA：偏差校正的迭代平均方案

**📜 论文**: https://huggingface.co/papers/2508.00180

偏差校正指数移动平均（BEMA）通过降低随机性并消除偏差，提升了语言模型微调的稳定性和效率。要按照论文中的描述将 BEMA 与 SFT 结合使用，您可以使用 [BEMACallback](/docs/trl/v1.18.1/zh/bema_for_reference_model#trl.BEMACallback)：

```python
from trl import BEMACallback, SFTTrainer

trainer = SFTTrainer(
    ...
    callbacks=[BEMACallback()],
)
```

### SFT 的泛化：基于奖励校正的强化学习视角

**📜 论文**: https://huggingface.co/papers/2508.05629

动态微调（DFT）通过动态重新缩放梯度来提升大语言模型（LLM）的泛化能力，其表现优于标准的监督微调（SFT），并在离线强化学习中展现出具有竞争力的结果。

$$ \mathcal{L}_{\text{DFT}}(\theta) = \mathbb{E}_{(x,y) \sim \mathcal{D}} \left[ - \sum_{t=1}^{|y|} \textcolor{red}{\text{sg}\big(\pi_\theta(y_t \mid y_{<t}, x)\big)} \; \log \pi_\theta(y_t \mid y_{<t}, x) \right] $$

其中 \\( \text{sg}(\cdot) \\) 是停止梯度算子。要按照论文中的描述将 DFT 与 SFT 结合使用，您可以使用 `loss_type="dft"` 参数：

```python
from trl import SFTConfig

training_args = SFTConfig(
    loss_type="dft",
    ...
)
```

为了与论文的设置保持一致，您可以使用以下配置（参见第 4.1 节）。作者还提到，超参数并不十分敏感（第 4.3 节）：

```python
SFTConfig(
    loss_type="dft",
    learning_rate=5e-5,
    max_length=2048,
    # Target batch size 256; achieved via per-device batch 8 * grad accumulation 32
    per_device_train_batch_size=8,
    gradient_accumulation_steps=32,
)
```

### 减少截断可提升语言建模效果

**📜 论文**: https://huggingface.co/papers/2404.10830

该论文表明，用于 LLM 训练的标准“先拼接后拆分”预处理（`packing_strategy="wrapped"`）会导致许多文档被任意截断，从而损害学习效果。它提出使用 Best-Fit Decreasing 装箱算法将文档块打包到上下文窗口中，在保持高 token 利用率的同时大幅减少截断，并提升模型性能。TRL 将此实现为 [SFTConfig](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTConfig) 中的 `"bfd_split"` 打包策略。有关打包的更多详细信息，请参阅 [SFT 文档](sft_trainer#packing)。

```python
from trl import SFTConfig

training_args = SFTConfig(
    packing=True,
    packing_strategy="bfd_split",
    max_length=4096,
)
```

### 探索统一文本到文本 Transformer 在迁移学习中的极限

**📜 论文**: https://huggingface.co/papers/1910.10683

T5 论文提出了一种用于迁移学习的统一文本到文本框架，并引入了**序列打包**（第 3.5.2 节）：将多个短序列分组为固定长度的块，以减少填充并提高训练效率。TRL 通过 [SFTConfig](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTConfig) 和 [SFTTrainer](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTTrainer) 支持打包功能。要在 TRL 中启用打包，请使用以下配置：

```python
from trl import SFTConfig

training_args = SFTConfig(
    packing=True,  # enable sequence packing (Section 3.5.2 of the paper)
    max_length=512,  # packed sequence length (Section 3.5.2 of the paper)
)
```

### 重参数化均匀扩散模型：留一法去噪器

**📜 论文**: https://huggingface.co/papers/2605.22765

对于均匀离散扩散模型，常规的即插即用交叉熵学习到的并非朴素的去噪器 \\( \mathbb{E}[X_0 \mid X_t] \\)，而是留一法（LOO）后验，后者在预测每个 token 时不使用其自身的损坏值。该论文推导了去噪器、LOO 后验和 score 之间的精确转换关系，因此可以使用相同的交叉熵将网络训练为任意一种参数化形式。给定 logits \\( f_\theta \\)，其 softmax 参数化了 LOO 后验，则损失函数中使用的去噪器为

$$ d_\theta(x_t, t)^\ell = \mathrm{softmax}\!\left( f_\theta(x_t, t)^\ell + \log\!\left(1 + \frac{K\,\alpha_t}{1 - \alpha_t}\, x_t^\ell\right) \right), $$

即对观测 token 的 logit 进行加性修正，其中 \\( K \\) 为词表大小，\\( \alpha_t \\) 为均匀前向过程保留干净 token 的概率。论文报告指出，LOO 参数化能持续改善生成效果。块扩散 SFT 示例 [`examples/sft_diffusion_gemma/sft_diffusion_gemma.py`](https://github.com/huggingface/trl/blob/main/examples/sft_diffusion_gemma/sft_diffusion_gemma.py) 通过 `--model_prediction_type` 暴露了这两种参数化（`mean` 对应普通去噪器，与发布的检查点一致；或 `mean_loo` 对应 LOO 后验）：

```bash
torchrun --nproc_per_node 8 examples/sft_diffusion_gemma/sft_diffusion_gemma.py \
    --deepspeed examples/deepspeed_configs/zero3.json \
    --use_peft \
    --gradient_checkpointing \
    --model_prediction_type mean_loo \
    --output_dir diffusiongemma-26B-A4B-it-gsm8k-lora
```

### 减少大型 Transformer 模型中的激活重计算

**📜 论文**: https://huggingface.co/papers/2205.05198

完整的激活检查点会在反向传播期间重新计算检查点区域内的所有操作，包括注意力机制，尽管只有少数操作（其中包含注意力机制）相对于其内存占用而言，占据了大部分的重计算成本。该论文中的选择性激活重计算仅针对这些高成本操作进行检查点，而非整个区域。TRL 将此实现为 [SFTTrainer](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTTrainer) 的选择性激活检查点（SAC），在正向传播过程中保存注意力输出，从而避免在反向传播中重新计算它：

```python
from trl import SFTConfig

training_args = SFTConfig(
    gradient_checkpointing=True,
    gradient_checkpointing_kwargs={"selective": True},
)
```

## 参数高效微调（PEFT）

有关使用 PEFT 与 TRL 的一般详细信息，请参阅 [PEFT 集成](peft_integration) 指南。

### LoRA：大型语言模型的秩适应

**📜 论文**: https://huggingface.co/papers/2106.09685

低秩适应（LoRA）在保持或提升下游任务性能的同时，减少了大规模预训练模型中可训练参数的数量和 GPU 内存占用。TRL 通过 [PEFT 库](https://huggingface.co/docs/peft/index)集成 LoRA，只需将 `LoraConfig` 传递给 `peft_config` 参数，即可轻松在任何 TRL 训练器中启用。以下是使用 LoRA 与 [SFTTrainer](/docs/trl/v1.18.1/zh/sft_trainer#trl.SFTTrainer) 的示例：

```python
from trl import SFTTrainer
from peft import LoraConfig

trainer = SFTTrainer(
    ...,
    peft_config=LoraConfig(),
)
```

### DoRA：权重分解的低秩适配

**📜 论文**: https://huggingface.co/papers/2402.09353

权重分解低秩适应（DoRA）可以提升 LoRA 的性能，尤其是在低秩情况下。DoRA 将预训练权重分解为两个分量：幅度和方向。方向由标准的 LoRA 处理，而幅度则是可学习参数。TRL 通过 [PEFT 库](https://huggingface.co/docs/peft/index)集成 DoRA，只需将 `LoraConfig` 中的 `use_dora=True` 设置为 True 即可轻松启用。

``` python
from peft import LoraConfig

config = LoraConfig(use_dora=True, ...)
```

## Reinforce Leave-One-Out

与 [RLOOTrainer](/docs/trl/v1.18.1/zh/rloo_trainer#trl.RLOOTrainer) 相关的论文

### 回归基础：重新审视用于大语言模型人类反馈学习的 REINFORCE 风格优化

**📜 论文**: https://huggingface.co/papers/2402.14740

RLOO 是 REINFORCE 的一种变体，通过使用留一法基线来降低方差。它通过将每个样本与批次中所有其他样本的平均值进行比较来计算奖励，从而提供比标准 REINFORCE 更稳定的梯度。要复现论文中的设置，请使用此配置：

```python
from trl import RLOOConfig

training_args = RLOOConfig(
    per_device_train_batch_size=512,  # section C Training Detail of the paper
    steps_per_generation=2,  # section C Training Detail of the paper
    beta=0.03,  # section C Training Detail of the paper
    num_generations=2,  # experiments of paper different num_generations={2,4}
    learning_rate=1e-6,  # section C Training Detail of the paper
)
```

### REINFORCE++：一种用于对齐大语言模型的简单高效方法

**📜 论文**: https://huggingface.co/papers/2501.03262

REINFORCE++ 是经典 REINFORCE 算法的增强变体，它融合了 PPO 中的关键优化技术，同时消除了对 critic 网络的需求。通过在整批数据上进行全局优势归一化，它实现了更高的简洁性、更强的训练稳定性以及更低的计算开销。若要使用 [RLOOTrainer](/docs/trl/v1.18.1/zh/rloo_trainer#trl.RLOOTrainer) 来近似论文中的设置，请使用以下配置：

```python
from trl import RLOOConfig

training_args = RLOOConfig(
    normalize_advantages=True,  # global advantage normalization, core of REINFORCE++
)
```

## Odds Ratio Preference Optimization

与 [experimental.orpo.ORPOTrainer](/docs/trl/v1.18.1/zh/orpo_trainer#trl.experimental.orpo.ORPOTrainer) 相关的论文

### ORPO：无需参考模型的单体偏好优化

**📜 论文**: https://huggingface.co/papers/2403.07691

引入无需参考模型的整体式赔率比偏好优化算法（ORPO），可在监督微调过程中增强偏好对齐，并在关键评估中超越更大的模型。要复现论文中的设置，请使用此配置：

```python
from trl.experimental.orpo import ORPOConfig

training_args = ORPOConfig(
    beta=0.1,  # λ odds ratio loss weight (Table 7 of the paper, Mistral-ORPO-β)
    learning_rate=5e-6,  # learning rate (Appendix C of the paper)
    lr_scheduler_type="inverse_sqrt",  # scheduler (Appendix C of the paper)
    num_train_epochs=5,  # Appendix C of the paper
    warmup_steps=200,  # warm-up steps (Appendix C of the paper)
    per_device_train_batch_size=8,  # batch size (Appendix C of the paper)
)
```

## 对比偏好优化

与 [experimental.cpo.CPOTrainer](/docs/trl/v1.18.1/zh/cpo_trainer#trl.experimental.cpo.CPOTrainer) 相关的论文

### 对比偏好优化：推动大语言模型在机器翻译中的性能边界

**📜 论文**: https://huggingface.co/papers/2401.08417

介绍了对比偏好优化（Contrastive Preference Optimization，CPO），这是一种基于偏好的机器翻译方法，它训练模型避免生成“合格但不完美”的译文，而不是像 SFT 那样模仿参考译文。该论文分析了 SFT 在机器翻译中的局限性（包括参考译文质量问题），并表明仅使用 22K 条平行句对将 CPO 应用于 ALMA 即可得到 ALMA-R，其在 WMT'21–WMT'23 上的表现达到或超过了 WMT 竞赛冠军及 GPT-4。在 TRL 中通过 [experimental.cpo.CPOTrainer](/docs/trl/v1.18.1/zh/cpo_trainer#trl.experimental.cpo.CPOTrainer) 使用。要复现论文中的设置，请使用此配置：

```python
from trl.experimental.cpo import CPOConfig

training_args = CPOConfig(
    loss_type="sigmoid",  # preference learning loss (Section 3 of the paper)
    cpo_alpha=1.0,  # NLL regularizer weight (Section 3 of the paper)
    beta=0.1,  # β temperature (Section 4.2 of the paper)
    learning_rate=1e-4,  # learning rate (official code)
    lr_scheduler_type="inverse_sqrt",  # scheduler (official code)
    num_train_epochs=1,  # Section 4.2 of the paper
    warmup_ratio=0.01,  # warm-up ratio (Section 4.2 of the paper)
    max_length=512,  # max sequence length (Section 4.2 of the paper)
)
```

### SimPO：基于无参考奖励的简单偏好优化

**📜 论文**: https://huggingface.co/papers/2405.14734

SimPO 是一种更简单但更有效的偏好优化方法，它使用序列的平均对数概率作为隐式奖励，从而无需参考模型。它在 Bradley-Terry 目标中引入了目标奖励间隔，以鼓励获胜响应和失败响应之间产生更大的间隔。要复现论文中的设置，请使用此配置：

```python
from trl.experimental.cpo import CPOConfig

training_args = CPOConfig(
    loss_type="simpo",  # SimPO loss (Section 3 of the paper)
    cpo_alpha=0.0,  # no BC regularizer for SimPO
    beta=2.5,  # β in Appendix B of the paper
    simpo_gamma=1.375,  # γ target reward margin, from γ/β=0.55 in Appendix B of the paper
    learning_rate=1e-6,  # learning rate in Appendix B of the paper
    num_train_epochs=1,  # Appendix B of the paper
)
```

### AlphaPO -- 奖励形状对 LLM 对齐很重要

**📜 论文**: https://huggingface.co/papers/2501.03884

AlphaPO 是一种新的直接对齐算法（DAAs）方法，它利用 alpha 参数来改变奖励函数的形状，使其超越标准的对数奖励。AlphaPO 有助于对似然位移和过度优化保持细粒度的控制。要复现论文中的设置，请使用此配置：

```python
from trl.experimental.cpo import CPOConfig

# Mistral-Instruct from Table 3 of the paper
training_args = CPOConfig(
    loss_type="alphapo",
    alpha=0.25,
    beta=2.5,
    simpo_gamma=0.1,
    learning_rate=7e-7,
    ...
)
```

## 三重偏好优化

### 三重偏好优化：通过单步优化实现更好的对齐

**📜 论文**: https://huggingface.co/papers/2405.16681

引入了三重偏好优化（Triple Preference Optimization，TPO），这是一种偏好学习方法，可在单个优化步骤中使大语言模型（LLM）与每个提示词对应的三个响应保持一致：一个黄金（`reference`）补全、一个优选（`chosen`）补全和一个劣选（`rejected`）补全。TPO 将 (chosen, rejected) 对上的对比目标与黄金响应上的监督 NLL 项相结合，从而无需单独的 SFT 阶段以及 DPO 中使用的参考模型。TRL 在 v1.16 及之前版本中提供了 `TPOTrainer` 的实现；该实现已不再包含在库中，但仍可在 git 历史记录中找到。

## 基于人类反馈的纳什学习

### 基于人类反馈的纳什学习

**📜 论文**: https://huggingface.co/papers/2312.00886

介绍了 Nash-MD，这是一种标准 RLHF 的替代方案，它学习一个以两个输入为条件的偏好模型，并找到纳什均衡处的策略。与针对奖励模型进行优化不同，Nash-MD 生成的策略能够持续产生优于任何竞争策略的响应。该算法基于镜像下降原理。TRL 在 v1.13 及之前版本中提供了 `NashMDTrainer` 的实现；它已不再属于该库的一部分，但仍可在 git 历史记录中找到。

## 奖励建模

与 [RewardTrainer](/docs/trl/v1.18.1/zh/reward_trainer#trl.RewardTrainer) 相关的论文

### 帮助还是从众？奖励模型集成能缓解但无法消除奖励作弊

**📜 论文**: https://huggingface.co/papers/2312.09244

该论文提出了一种辅助损失函数，旨在直接学习一个居中的奖励模型。该辅助损失最小化奖励的平方和，从而鼓励模型自然地产生均值为零的输出，进而解决欠定问题。

$$ \mathcal{L}(\theta) = - \mathbb{E}_{(x,y^+,y^-) \sim \mathcal{D}} \left[ \log \sigma(r_\theta(x, y^+) - r_\theta(x, y^-)) \textcolor{red}{- \eta \cdot (r_\theta(x, y^+) + r_\theta(x, y^-))^2} \right]. $$

要在[RewardTrainer](/docs/trl/v1.18.1/zh/reward_trainer#trl.RewardTrainer)中使用此辅助损失，可以按照以下方式在[RewardConfig](/docs/trl/v1.18.1/zh/reward_trainer#trl.RewardConfig)中使用`center_rewards_coefficient`参数：

```python
from trl import RewardConfig

training_args = RewardConfig(
    center_rewards_coefficient=0.01,  # η in the paper
    ...
)
```

### Llama 2：开放的基础模型和微调后的对话模型

**📜 论文**: https://huggingface.co/papers/2307.09288

在本文中，作者提出利用其偏好评分被分解为四点量表（例如，_显著更好_）这一特性，为奖励模型提供更具信息量的反馈。具体做法是在损失函数中加入一个间隔项，以鼓励奖励模型为具有更高偏好评分的样本对分配更大的分数差距。

$$ \mathcal{L}(\theta) = - \mathbb{E}_{(x,y^+,y^-,\textcolor{red}{m}) \sim \mathcal{D}} \left[ \log \sigma(r_\theta(x, y^+) - r_\theta(x, y^-) \textcolor{red}{- m}) \right]. $$

您可以通过在数据集中添加 `margin` 列来为损失函数添加边距。以下示例展示了如何设置论文中的“Margin Small”配置。

```python
def add_margin(example):
    preference_to_margin = {
        "significantly better": 1.0,
        "better": 2.0/3.0,
        "slightly better": 1.0/3.0,
        "negligibly better / unsure": 0.0,
    }
    return {"margin": preference_to_margin[example["preference_label"]]}

dataset = dataset.map(add_margin)
```

## 在线直接偏好优化

与 [experimental.online_dpo.OnlineDPOTrainer](/docs/trl/v1.18.1/zh/online_dpo_trainer#trl.experimental.online_dpo.OnlineDPOTrainer) 相关的论文

### 直接从在线 AI 反馈进行语言模型对齐

**📜 论文**: https://huggingface.co/papers/2402.04792

Online DPO 通过提供来自模型的实时反馈，改进了基于偏好的直接对齐方法，其性能优于 DPO 和 PPO 方法。

要使用 Online DPO，您可以使用 [experimental.online_dpo.OnlineDPOTrainer](/docs/trl/v1.18.1/zh/online_dpo_trainer#trl.experimental.online_dpo.OnlineDPOTrainer)。

### 探索性偏好优化：利用隐式 Q* 近似实现样本高效的 RLHF

**📜 论文**: https://huggingface.co/papers/2405.21046

XPO 通过引入一种新颖且基于原则的探索奖励来增强 DPO 目标，使算法能够探索初始模型和人类反馈数据支持范围之外的区域。它是对在线 DPO 的一行代码修改，可证明具有样本效率，并收敛到接近最优的语言模型策略。TRL 在 v1.13 及之前版本中提供了 `XPOTrainer` 的实现；它已不再属于该库的一部分，但仍可在 git 历史记录中找到。

## 蒸馏

与借助教师模型训练学生模型相关的论文。

### 语言模型的在线策略蒸馏：从自生成错误中学习

**📜 论文**: https://huggingface.co/papers/2306.13649

介绍了广义知识蒸馏（GKD），该方法通过让模型在自身生成的输出上接受教师反馈进行训练，而非使用固定的序列集合，从而解决了自回归模型中知识蒸馏的分布不匹配问题。GKD 支持灵活的损失函数（例如，当学生模型无法匹配教师模型时，可以使用 KL 散度以外的损失函数），并与强化学习微调（RLHF）集成。论文报告了在摘要生成、翻译、算术推理和指令微调上的结果。在 TRL 中通过 [experimental.gkd.GKDTrainer](/docs/trl/v1.18.1/zh/gkd_trainer#trl.experimental.gkd.GKDTrainer) 使用，该组件暴露了论文中的 on/off-policy 混合参数（`lmbda`）。[DistillationTrainer](/docs/trl/v1.18.1/zh/distillation_trainer#trl.DistillationTrainer) 实现了相同的广义 JSD 目标，用于始终处于 on-policy 的情况。要复现论文的设置，请使用此配置：

```python
from trl.experimental.gkd import GKDConfig

# XSum summarization task (Table A.1 of the paper)
training_args = GKDConfig(
    lmbda=0.5,  # λ student data fraction (Section 3 of the paper)
    beta=0.5,  # β Generalized JSD interpolation, 0=KL, 1=reverse KL (Section 3 of the paper)
    temperature=1.0,  # student training temperature (Appendix A of the paper)
    max_steps=40000,  # training steps (Table A.1 of the paper)
    learning_rate=3e-4,  # learning rate (Table A.1 of the paper)
    per_device_train_batch_size=32,  # batch size (Table A.1 of the paper)
    warmup_steps=2000,  # warm-up steps (Table A.1 of the paper)
    max_new_tokens=64,  # max output tokens (Table A.1 of the paper)
)
```

### MOPD：用于 LLM 后训练能力整合的多教师在线策略蒸馏

**📜 论文**: https://huggingface.co/papers/2606.30406

将后训练结构化为三个阶段：通用 SFT、针对每个领域独立训练一个专家模型的 RL 训练（例如，用于数学的可验证答案 RL，用于软件工程的沙盒智能体 RL），以及一个最终的 MOPD 阶段，该阶段将冻结的领域专家融合为一个统一的学生模型。在最终阶段，学生模型为每个提示生成一条轨迹，每条轨迹被分派给其对应的领域教师（绝不在多个教师之间进行平均或集成），并通过最小化沿该轨迹相对于该单一教师分布的逐 token 反向 KL 散度来更新学生模型。在 TRL 中通过 [experimental.async_distillation.AsyncDistillationTrainer](/docs/trl/v1.18.1/zh/async_distillation_trainer#trl.experimental.async_distillation.AsyncDistillationTrainer) 使用，该实现器实现了第三个融合阶段：在 `teacher_server_urls` 中传入多个条目即可启用 MOPD，其中每一行的 `teacher_id` 列用于选择由哪个（已训练好的）教师对其进行评分。使用 `beta=1.0` 以匹配论文中的反向 KL 目标。

### 关于在线策略蒸馏中的位置偏差

**📜 论文**: https://huggingface.co/papers/2606.22600

引入了重要性加权在线策略蒸馏（Importance-Weighted On-Policy Distillation，IW-OPD），该方法通过根据累积的教师-学生前缀差异对采样 token 的蒸馏更新进行重新加权，来解决 OPD 中的位置偏差问题。早期 token 保留较大的权重，而高漂移之后的后期 token 权重会被降低。在 TRL 中，通过 [experimental.iw_opd.IWOPDTrainer](/docs/trl/v1.18.1/zh/iw_opd_trainer#trl.experimental.iw_opd.IWOPDTrainer) 配合 `distillation_objective="iw_opd"` 使用。

该论文采用带裁剪的策略梯度设置（verl）和 vLLM 推演来优化 IW-OPD。`IWOPDTrainer` 暴露了以下对应的蒸馏和推演设置；论文中的策略优化设置，例如裁剪范围 `0.2`、双裁剪常数 `3.0`、内部 PPO 轮数、熵系数、KL 奖励惩罚、辅助 KL 以及推演重要性校正，均不是 `IWOPDConfig` 参数。

```python
from trl.experimental.iw_opd import IWOPDConfig

# Table 6 and Algorithm 1 of the paper, mapped to IWOPDConfig where available.
training_args = IWOPDConfig(
    distillation_objective="iw_opd",
    iw_opd_gamma=0.5,  # γ amplification, Algorithm 1 and Appendix C.3
    lmbda=1.0,  # fully on-policy rollouts
    learning_rate=1e-5,  # Table 6
    per_device_train_batch_size=1,  # Table 6 uses PPO micro-batch size 1 per GPU
    gradient_accumulation_steps=32,  # with 32 GPUs, this gives the paper's 1024-prompt batch
    num_generations=1,  # Table 6 rollout samples per prompt
    temperature=1.0,  # Table 6 training decoding temperature
    top_p=1.0,  # Table 6 training decoding top-p
    max_prompt_length=2048,  # Table 6
    max_completion_length=16384,  # Table 6
    warmup_ratio=0.0,  # Table 6
    use_vllm=True,  # Table 6 uses vLLM rollouts
    vllm_sync_frequency=1,  # refresh rollout policy after each update
    save_steps=10,  # Table 6 checkpoint frequency
    eval_steps=10,  # Table 6 validation frequency
)
```

### On-Policy 蒸馏

**📰 博客**：https://thinkingmachines.ai/blog/on-policy-distillation/

On-Policy Distillation 涉及学生模型为每个训练数据批次生成 rollout。随后，我们从学生模型和教师模型中分别获取 rollout 中每个 token 的概率分布。接着，优化学生模型以最小化其自身 token 分布与教师模型 token 分布之间的负 Kullback-Leibler (KL) 散度。

| 方法                  | 采样   | 奖励信号 |
|-------------------------|------------|---------------|
| 监督微调   | off-policy | dense         |
| 强化学习  | on-policy  | 稀疏        |
| On-policy 蒸馏  | on-policy  | dense         |

On-Policy Distillation 已被证明优于 SFT 和 GRPO，并且可用于恢复在 SFT 过程中丢失的泛化能力。

此外，在策略蒸馏在计算效率上更高，并且在有限数据上训练时更不容易过拟合。

要在 TRL 中使用在线策略蒸馏训练模型，您可以使用以下配置，其中包含 [DistillationTrainer](/docs/trl/v1.18.1/zh/distillation_trainer#trl.DistillationTrainer) 和 [DistillationConfig](/docs/trl/v1.18.1/zh/distillation_trainer#trl.DistillationConfig)：

```python
from trl import DistillationConfig

training_args = DistillationConfig(
    beta=1.0,  # to ensure reverse-kl as the loss function
    teacher_model_name_or_path="teacher-model",  # specify the teacher model
)
```

或者，您可以使用 [experimental.gkd.GKDTrainer](/docs/trl/v1.18.1/zh/gkd_trainer#trl.experimental.gkd.GKDTrainer) 和 [experimental.gkd.GKDConfig](/docs/trl/v1.18.1/zh/gkd_trainer#trl.experimental.gkd.GKDConfig)：

```python
from trl.experimental.gkd import GKDConfig

training_args = GKDConfig(
    lmbda=1.0,  # student produces rollouts for all batches
    beta=1.0,  # to ensure reverse-kl as the loss function
    teacher_model_name_or_path="teacher-model",  # specify the teacher model
)
```

您还可以使用 [experimental.gold.GOLDTrainer](/docs/trl/v1.18.1/zh/gold_trainer#trl.experimental.gold.GOLDTrainer) 进行在线策略蒸馏；请参阅 [Unlocking On-Policy Distillation for Any Model Family](#unlocking-on-policy-distillation-for-any-model-family)。

### 解锁任意模型系列的在线策略蒸馏

**🌐 项目**: https://huggingface.co/spaces/HuggingFaceH4/general-on-policy-logit-distillation

引入了通用在线对数几率蒸馏（General Online Logit Distillation，GOLD），该方法将在线策略蒸馏扩展至具有不同分词器和模型族的师生模型对。GOLD 能够跨分词器对齐文本片段，并可应用通用对数几率蒸馏（Universal Logit Distillation，ULD），以确保补全 token 不被丢弃。在 TRL 中通过 [experimental.gold.GOLDTrainer](/docs/trl/v1.18.1/zh/gold_trainer#trl.experimental.gold.GOLDTrainer) 使用。

```python
from trl.experimental.gold import GOLDConfig

training_args = GOLDConfig(
    lmbda=1.0,  # student produces rollouts for all batches
    beta=1.0,  # to ensure reverse-kl as the loss function
    use_uld_loss=True,  # Universal Logit Distillation for cross-tokenizer pairs
)
```

### X-Token：投影引导的跨分词器知识蒸馏

**📜 论文**: https://huggingface.co/papers/2605.21699

X-Token 将 GOLD 蒸馏框架扩展至**不共享分词器**的学生-教师模型对。这是一种**离策略**方法（`lmbda=0`）：数据集提供补全文本，学生和教师均在该文本上执行前向传播，并在它们的 logits 之间计算跨分词器 KD 损失。无需进行策略内的学生 rollout。预计算的稀疏投影矩阵 W ∈ ℝ^{V_s × V_t} 将每个学生 token 映射到其最可能对应的教师 token，从而将学生分布投影到教师词表空间中，以便直接比较两者。在 TRL 中通过 [experimental.gold.GOLDTrainer](/docs/trl/v1.18.1/zh/gold_trainer#trl.experimental.gold.GOLDTrainer) 使用，并设置 `xtoken_loss_type="p_kl"` 或 `"h_kl"`。

提供了两种损失函数形式：

| 变体 | `xtoken_loss_type` | 描述 |
|---------|-------------------|-------------|
| P-KL | `"p_kl"` | 通过 W 将完整的 student 分布投影到 teacher 词表，并在全局 top-k 子集上计算前向 KL。实现了论文中的公式 (4)。 |
| H-KL | `"h_kl"` | 混合：在放宽的公共集合（top-1 投影权重 ≥ 0.6）上对重归一化分布计算前向 KL，对不常见 token 计算排序 L1。实现公式 (3)，并采用公式 (5) 中的映射。 |

与参考实现一样，H-KL 将完整词表的对数概率切片到公共集合，而 P-KL 对每个 span 的教师对数概率取平均而不进行重新归一化，因此 KD 项可能为负值。CE 和 KD 在每个累积窗口上使用独立的 token 计数和对齐 span 计数。动态 CE/KD 平衡和 P-KL top-k 选择按 microbatch 计算。

此实现使用冻结的投影矩阵。该论文还联合学习了 P-KL 的矩阵；此处未实现该变体。

首先使用 `examples/xtoken/` 中的预处理脚本构建投影矩阵。步骤 1 会使用教师分词器重新标记学生词汇表；可选的 `--runtime-top-k` 标志随后会一次性对矩阵进行排序和裁剪（等效于之后运行 `sort_and_cut_projection_matrix.py`）：

```bash
python examples/xtoken/build_projection_matrix.py \
    --student-model meta-llama/Llama-3.2-1B-Instruct \
    --teacher-model Qwen/Qwen3-4B \
    --runtime-top-k 4 \
    --output-dir cross_tokenizer_data
```

然后使用示例脚本进行训练（off-policy，无需 vLLM）：

```bash
python examples/xtoken/xtoken.py \
    --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \
    --teacher_model_name_or_path Qwen/Qwen3-4B \
    --dataset_name trl-lib/chatbot_arena_completions \
    --xtoken_loss_type p_kl \
    --xtoken_projection_matrix_path cross_tokenizer_data/projection_map_Llama-3.2_to_Qwen3_multitoken_top_32_double_special_top4.pt \
    --lmbda 0.0
```

或直接传入 [experimental.gold.GOLDConfig](/docs/trl/v1.18.1/zh/gold_trainer#trl.experimental.gold.GOLDConfig) 的路径：

```python
from trl.experimental.gold import GOLDConfig

config = GOLDConfig(
    lmbda=0.0,  # "off-policy knowledge distillation"
    xtoken_temperature=1.0,  # "temperature τ=1.0"
    xtoken_dynamic_scaling=True,  # Eq. (7): stop-gradient CE/KD balance
    xtoken_loss_type="p_kl",
    xtoken_projection_matrix_path="cross_tokenizer_data/projection_map_Llama-3.2_to_Qwen3_multitoken_top_32_double_special_top4.pt",
    teacher_tokenizer_name_or_path="Qwen/Qwen3-4B",
)
```

### 大语言模型的知识蒸馏

**📜 论文**: https://huggingface.co/papers/2306.08543

MiniLLM 是首个基于策略的知识蒸馏方法，它通过强化学习来最小化教师模型与学生模型之间的序列级反向 KLD。

它是[Think Machine Lab 的 On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/)的广义版本，支持添加分布级单步蒸馏信号（例如当`beta=1`时的 GKD）以及长上下文反向 KLD 信号。

TRL 在 v1.14 及之前版本中提供了 `MiniLLMTrainer` 的实现；该实现已不再包含在库中，但仍可在 git 历史记录中找到。

### 通过自蒸馏进行强化学习

**📜 论文**: https://huggingface.co/papers/2601.20802

自蒸馏策略优化（SDPO）通过将丰富的文本反馈（例如运行时错误、评审评估）转化为密集的学习信号，从而增强基于可验证奖励的强化学习，且无需任何外部教师或显式奖励模型。SDPO 将基于反馈条件化的当前模型视为自教师，并将其受反馈影响的下一词元预测蒸馏回策略中。值得注意的是，在仅返回标量反馈的标准 RLVR 环境中，SDPO 通过使用成功的 rollout 作为失败尝试的隐式反馈，同样优于基线方法。

```python
from trl.experimental.sdpo import SDPOConfig, SDPOTrainer

training_args = SDPOConfig(
    distillation_alpha=0.5,                # Jensen-Shannon divergence (recommended)
    distillation_mode="topk_logits",       # Explicitly select top-K logit distillation
    distillation_topk=100,                 # Required for top-K logit distillation
    distillation_is_clip=2.0,              # Importance sampling clipping
    distillation_weight=1.0,               # Convex weight: (1-w)*policy + w*distillation; 1.0 = pure distillation
    use_successful_as_teacher=True,        # Use successful rollouts as teacher
    teacher_model_kind="ema",              # Supported: "base", "live", "ema"
    teacher_update_rate=0.05,              # EMA update rate
    include_environment_feedback=True,     # required to use the dataset's privileged_context (defaults to False)
)

trainer = SDPOTrainer(
    model="Qwen/Qwen2.5-1.5B-Instruct",
    reward_funcs=...,
    args=training_args,
    train_dataset=...,
)
trainer.train()
```

预期的数据集列：

- `prompt`
- `privileged_context` 用于可选的环境反馈

有关更多详细信息，请参阅 [SDPO Trainer 文档](sdpo_trainer)。

### 自蒸馏实现持续学习

**📜 论文**: https://huggingface.co/papers/2601.19897

自蒸馏微调（SDFT）通过在训练过程中生成补全，然后将这些相同补全的显式教师条件视图蒸馏回学生模型，从而执行在策略自蒸馏。教师模型由 `teacher_model_kind` 选择：`"base"`（初始学生）、`"live"`（当前学生）或 `"ema"`（指数移动平均教师）。教师提示在内部由学生 `prompt` 加上数据集 `privileged_context` 组成。

```python
from datasets import Dataset

from trl.experimental.sdft import SDFTConfig, SDFTTrainer

dataset = Dataset.from_dict(
    {
        "prompt": [[{"role": "user", "content": "Solve 2+2."}]],
        "privileged_context": ["Example answer: 4."],
    }
)

training_args = SDFTConfig(
    distillation_alpha=0.5,
    distillation_mode="topk_logits",
    distillation_topk=5,
    max_completion_length=64,
)

trainer = SDFTTrainer(
    model="Qwen/Qwen2.5-1.5B-Instruct",
    args=training_args,
    train_dataset=dataset,
)
trainer.train()
```

预期的数据集列：

- `prompt`
- 仅包含额外教师专用信息的`privileged_context`

有关更多详细信息，请参阅 [SDFT Trainer 文档](sdft_trainer)。

### 简单到令人尴尬的自蒸馏方法提升了代码生成

**📜 论文**: https://huggingface.co/papers/2604.01193

简单自蒸馏（SSD）通过在训练时以特定温度和截断配置从模型中采样补全，然后使用标准交叉熵损失在这些原始且未经验证的样本上进行微调，从而提升代码生成能力。该方法无需奖励模型、验证器、教师模型或强化学习。SSD 以依赖上下文的方式重塑 token 分布：在“锁定”位置（即语法歧义极小的位置）抑制干扰尾部，同时在“分叉”位置（即存在多种有效续写的位置）保留多样性。

TRL 在 v1.15 及之前版本中提供了 `SSDTrainer` 的实现；该实现已不再包含在库中，但仍可在 git 历史记录中找到。

### Softmax 和交叉熵的修复

**📜 论文**: https://huggingface.co/papers/2610.31642

识别高置信度预测中的 softmax 坍缩，以及当学生模型与教师模型的 logits 几乎一致时发生的抵消现象。TRL 的分块对数概率和蒸馏头采用排除目标的归一化方法以及对数空间中的概率差，以保留微小的梯度。这些数值修复会自动应用，包括 [DistillationTrainer](/docs/trl/v1.18.1/zh/distillation_trainer#trl.DistillationTrainer) 中的前向 KL、反向 KL 和广义 JSD。

[Entropy-preserving reinforcement learning](https://huggingface.co/papers/2603.11682) 的附录 B.4 此前已识别出高置信度策略梯度失效问题，并提出了在 FP64 中选择性重新计算梯度的方案。TRL 的内核使用稳定的 FP32 公式来保留这些梯度。

附录 B.1 中讨论的 FSDP2 独立输出类型转换问题已通过 [Accelerate #4403](https://github.com/huggingface/accelerate/pull/4403) 解决。旧版 Accelerate 需要使用 `output_dtype=None` 的混合精度策略，才能保留 FP32 内核输出。

以下示例将第 7 节中报告的超参数映射到 TRL 的前向 KL 目标，该目标与软目标交叉熵共享学生模型的梯度。它展示的是语言模型蒸馏，而非复现论文中的模运算实验。论文使用教师模型的权重来初始化学生模型；在构建模型时必须处理这一点，且独立于配置。其他训练器默认值保持不变。

```python
from trl import DistillationConfig

training_args = DistillationConfig(
    beta=0.0,  # Forward KL has the same student gradient as soft-target cross-entropy.
    temperature=4.0,  # "distillation temperature T=4"
    learning_rate=2e-3,  # "eta=2 x 10^-3"
    lr_scheduler_type="constant",
    optim="adamw_torch",  # AdamW with zero weight decay has the same updates as Adam.
    weight_decay=0.0,  # "lambda=0"
    adam_epsilon=1e-8,  # "epsilon=10^-8"
    max_steps=2000,  # "2,000 steps of Adam"
)
```

## 分布式训练

### ZeRO：面向训练万亿参数模型的内存优化

**📜 论文**: https://huggingface.co/papers/1910.02054

ZeRO (Zero Redundancy Optimizer) 通过在设备间分区优化器状态、梯度和参数，同时保持低通信量和高的计算粒度，消除了数据并行和模型并行训练中的内存冗余。这使得能够高效训练那些原本无法装入 GPU 内存的大型模型。

TRL 通过 [DeepSpeed 集成](deepspeed_integration)支持 ZeRO。要使用它，请提供一个包含所需设置的 DeepSpeed 配置文件，

```json
{
  "zero_optimization": {"stage": 3},
  "bf16": {"enabled": "auto"},
  "train_batch_size": "auto",
  "train_micro_batch_size_per_gpu": "auto"
}
```

在训练配置中设置 `deepspeed="zero3.json"`，并使用 torchrun 启动训练脚本。

```sh
torchrun --nproc_per_node 2 train.py
```

