areno-opd 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,398 @@
1
+ Metadata-Version: 2.4
2
+ Name: areno-opd
3
+ Version: 0.1.0
4
+ Summary: On-Policy Distillation (OPD) algorithm support for AReno framework
5
+ Author: Krystal579-max
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Krystal579-max/AReno-OPD
8
+ Project-URL: Repository, https://github.com/Krystal579-max/AReno-OPD
9
+ Project-URL: Issues, https://github.com/Krystal579-max/AReno-OPD/issues
10
+ Keywords: llm,knowledge-distillation,on-policy-distillation,opd,post-training,fine-tuning,pytorch,reinforcement-learning
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: torch>=2.0
24
+ Requires-Dist: numpy
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.0; extra == "dev"
27
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
28
+
29
+ # AReno-OPD: On-Policy Distillation for AReno
30
+
31
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
32
+ [![Python](https://img.shields.io/badge/Python-3.10%2B-blue)](https://www.python.org/)
33
+ [![PyTorch](https://img.shields.io/badge/PyTorch-2.0%2B-orange)](https://pytorch.org/)
34
+
35
+ 为 [AReno](https://github.com/inclusionAI/AReno) 开源框架添加 **On-Policy Distillation (OPD)** 算法支持。OPD 是一种在线策略蒸馏技术,学生模型生成响应(rollout),冻结的教师模型为其打分,学生通过最小化与教师分布之间的 KL 散度来学习。
36
+
37
+ ---
38
+
39
+ ## 目录
40
+
41
+ - [背景介绍](#背景介绍)
42
+ - [算法原理](#算法原理)
43
+ - [项目结构](#项目结构)
44
+ - [快速开始](#快速开始)
45
+ - [配置说明](#配置说明)
46
+ - [API 参考](#api-参考)
47
+ - [测试](#测试)
48
+ - [算法对比](#算法对比)
49
+ - [License](#license)
50
+
51
+ ---
52
+
53
+ ## 背景介绍
54
+
55
+ ### 什么是 On-Policy Distillation?
56
+
57
+ On-Policy Distillation (OPD) 是一种面向大语言模型后训练的知识蒸馏技术。与传统的离线蒸馏不同,OPD 是**在线策略(on-policy)** 的——学生模型**自己生成**响应,然后让教师模型对这些响应进行评分。这使得学生能够在其自身的分布上学习,从而更有效地匹配教师的行为。
58
+
59
+ ### 为什么在 AReno 中实现 OPD?
60
+
61
+ [AReno](https://github.com/inclusionAI/AReno) 是一个面向大模型后训练的开源框架,致力于将训练框架和推理引擎放在同一套基础设施中,实现训推一体。AReno 已支持 PPO、GRPO、DPO、SFT 等算法,而 OPD 的加入填补了**在线策略蒸馏**这一重要方向,为用户提供更丰富的模型优化选择。
62
+
63
+ ---
64
+
65
+ ## 算法原理
66
+
67
+ ### 工作流程
68
+
69
+ ```
70
+ ┌──────────────┐ ┌──────────────────┐ ┌──────────────────────┐
71
+ │ 提示数据 │ ──► │ 学生模型(可训练) │ ──► │ Rollout: 每提示生成 │
72
+ │ (Prompts) │ │ (Student) │ │ n_samples 个响应 │
73
+ └──────────────┘ └──────────────────┘ └──────────┬───────────┘
74
+
75
+
76
+ ┌──────────────────┐
77
+ │ 教师模型(冻结) │
78
+ │ (Teacher) │
79
+ │ 对响应 token 评分 │
80
+ │ (logprobs) │
81
+ └──────────┬───────────┘
82
+
83
+
84
+ ┌──────────────────┐
85
+ │ KL 散度损失: │
86
+ │ KL(student || │
87
+ │ teacher) │
88
+ └──────────┬───────────┘
89
+
90
+
91
+ ┌──────────────────┐
92
+ │ 学生模型更新 │
93
+ │ (梯度下降) │
94
+ └──────────────────┘
95
+ ```
96
+
97
+ ### 数学公式
98
+
99
+ 对于学生策略 `π_s` 生成的每个响应 token `a`:
100
+
101
+ - **学生 log-probability**: `log π_s(a | context)`
102
+ - **教师 log-probability**: `log π_t(a | context)`
103
+
104
+ 蒸馏损失为学生到教师分布的 KL 散度:
105
+
106
+ ```
107
+ Loss = KL(π_s || π_t) = E_{a ~ π_s}[log π_s(a) - log π_t(a)]
108
+ ≈ mean(log π_s(a) - log π_t(a)) # 在响应 token 上取平均
109
+ ```
110
+
111
+ 教师模型的 log-probabilities 被**脱离计算图**(`.detach()`),梯度仅流经学生网络:
112
+
113
+ ```
114
+ ∇Loss ≈ mean(∇log π_s(a))
115
+ ```
116
+
117
+ ### 温度缩放
118
+
119
+ 通过温度参数 `τ` 软化两个分布:
120
+
121
+ ```
122
+ Loss_τ = mean((log π_s(a) - log π_t(a)) / τ) = Loss / τ
123
+ ```
124
+
125
+ 更高的温度使分布更平滑,降低损失幅度。
126
+
127
+ ### 与 PPO 的关键区别
128
+
129
+ | 方面 | OPD | PPO |
130
+ |------|-----|-----|
131
+ | 学习信号 | 教师 logprobs | 奖励 + GAE 优势 |
132
+ | 奖励模型 | 不需要 | 需要 |
133
+ | Critic 网络 | 不需要 | 需要 |
134
+ | 参考模型 | 教师(评分用,冻结) | KL 惩罚(冻结) |
135
+ | 优势计算 | 不需要 | GAE 广义优势估计 |
136
+
137
+ ---
138
+
139
+ ## 项目结构
140
+
141
+ ```
142
+ AReno-OPD/
143
+ ├── areno/
144
+ │ └── api/
145
+ │ ├── algorithms.py # 算法注册表(注册 opd)
146
+ │ ├── trainer_config.py # OPDTrainerConfig 配置类
147
+ │ ├── loss_fns/
148
+ │ │ ├── __init__.py # 导出 opd_loss_fn
149
+ │ │ └── opd.py # OPD 损失函数实现
150
+ │ └── trainers/
151
+ │ ├── __init__.py # 导出 OPDTrainer
152
+ │ └── opd.py # OPD 训练器实现
153
+ ├── tests/
154
+ │ ├── test_opd_loss.py # 损失函数单元测试(12 个用例)
155
+ │ └── test_opd_algorithm.py # 算法注册与配置测试(6 个用例)
156
+ ├── docs/
157
+ │ └── opd_algorithm.md # 详细算法文档
158
+ ├── README.md # 本文件
159
+ └── .gitignore
160
+ ```
161
+
162
+ ### 核心文件说明
163
+
164
+ | 文件 | 说明 |
165
+ |------|------|
166
+ | `areno/api/loss_fns/opd.py` | OPD 损失函数,计算 KL(student \|\| teacher) 散度 |
167
+ | `areno/api/trainers/opd.py` | OPD 训练器,包含 Rollout + Teacher-Scoring 工作流 |
168
+ | `areno/api/trainer_config.py` | `OPDTrainerConfig` 数据类,管理超参数 |
169
+ | `areno/api/algorithms.py` | 将 `opd` 注册为 AReno 内置算法 |
170
+ | `tests/test_opd_loss.py` | 12 个测试覆盖损失计算、可微性、温度缩放等 |
171
+ | `tests/test_opd_algorithm.py` | 6 个测试覆盖注册、配置、导出等 |
172
+
173
+ ---
174
+
175
+ ## 快速开始
176
+
177
+ ### 前提条件
178
+
179
+ - Python 3.10+
180
+ - PyTorch 2.0+
181
+ - AReno 框架(需先安装,见 [inclusionAI/AReno](https://github.com/inclusionAI/AReno))
182
+
183
+ ### 安装
184
+
185
+ #### 方式一:从 PyPI 安装(待发布)
186
+
187
+ ```bash
188
+ pip install areno-opd
189
+ ```
190
+
191
+ #### 方式二:从源码安装
192
+
193
+ ```bash
194
+ git clone https://github.com/Krystal579-max/AReno-OPD.git
195
+ cd AReno-OPD
196
+ pip install -e .
197
+ ```
198
+
199
+ #### 方式三:合并到 AReno 主仓库
200
+
201
+ ```bash
202
+ # 克隆 AReno 主仓库
203
+ git clone https://github.com/inclusionAI/AReno.git
204
+ cd AReno
205
+
206
+ # 将 OPD 代码合并到 AReno 中
207
+ cp -r /path/to/AReno-OPD/areno/* ./areno/
208
+ ```
209
+
210
+ ### 训练脚本
211
+
212
+ ```python
213
+ import areno.api
214
+ from areno.api.trainer_config import OPDTrainerConfig
215
+ from areno.api.trainer_factory import build_trainer
216
+
217
+ # 配置 OPD 训练
218
+ config = OPDTrainerConfig(
219
+ algo="opd",
220
+ ckpt="/path/to/student/model", # 学生模型(可训练)
221
+ dataset_path="/path/to/training/data",
222
+ ref_ckpt="/path/to/teacher/model", # 教师模型(冻结,通常更强)
223
+ opd_kl_coef=1.0, # KL 损失系数
224
+ opd_temperature=1.0, # 温度参数
225
+ n_samples=8, # 每提示采样数
226
+ batch_size=32,
227
+ epochs=3,
228
+ )
229
+
230
+ # 构建训练器
231
+ trainer = build_trainer(
232
+ config,
233
+ instance=areno.api.Trainer(...),
234
+ dataset=dataset,
235
+ reward_fn=None, # OPD 不需要奖励函数
236
+ loss_fn=areno.api.loss_fns.opd_loss_fn,
237
+ )
238
+
239
+ # 开始训练
240
+ trainer.fit()
241
+ ```
242
+
243
+ ### CLI 命令行使用
244
+
245
+ ```bash
246
+ python -m areno train \
247
+ --algo opd \
248
+ --ckpt /path/to/student/model \
249
+ --dataset /path/to/data \
250
+ --ref-ckpt /path/to/teacher/model \
251
+ --opd-kl-coef 1.0 \
252
+ --opd-temperature 1.0 \
253
+ --n-samples 8 \
254
+ --batch-size 32
255
+ ```
256
+
257
+ ---
258
+
259
+ ## 配置说明
260
+
261
+ ### OPDTrainerConfig 参数
262
+
263
+ | 参数 | 类型 | 默认值 | 说明 |
264
+ |------|------|--------|------|
265
+ | `ref_ckpt` | `str \| None` | `None` | 教师模型检查点路径(默认使用学生模型) |
266
+ | `opd_kl_coef` | `float` | `1.0` | KL 散度损失系数 |
267
+ | `opd_temperature` | `float` | `1.0` | 温度参数,软化 log-probability 分布 |
268
+
269
+ 从 `RolloutTrainerConfig` 继承的关键参数:
270
+
271
+ | 参数 | 类型 | 默认值 | 说明 |
272
+ |------|------|--------|------|
273
+ | `n_samples` | `int` | `8` | 每提示生成的采样数 |
274
+ | `temperature` | `float` | `1.0` | Rollout 采样温度 |
275
+ | `top_p` | `float` | `1.0` | Top-p (nucleus) 采样参数 |
276
+ | `top_k` | `int` | `-1` | Top-k 采样参数(-1 表示禁用) |
277
+ | `batch_size` | `int` | `32` | 训练批次大小 |
278
+ | `max_prompt_tokens` | `int` | `1024` | 最大提示 token 数 |
279
+ | `max_new_tokens` | `int` | `3071` | 最大生成 token 数 |
280
+
281
+ ---
282
+
283
+ ## API 参考
284
+
285
+ ### `opd_loss_fn(data_pack, logprobs, *, kl_coef=1.0, temperature=1.0)`
286
+
287
+ **参数:**
288
+ - `data_pack` (`dict`): 包含响应掩码和 `ref_logprobs`(教师 log-probabilities)的数据字典
289
+ - `logprobs` (`torch.Tensor`): 当前学生 log-probabilities(可微)
290
+ - `kl_coef` (`float`, 可选): KL 损失缩放系数,默认 `1.0`
291
+ - `temperature` (`float`, 可选): 温度参数,默认 `1.0`
292
+
293
+ **返回:**
294
+ - `loss` (`torch.Tensor`): 标量损失值
295
+ - `stats` (`dict`): 诊断指标,包括 `opd_loss`, `opd_kl`, `opd_student_logprob_mean`, `opd_teacher_logprob_mean`, `opd_kl_coef`, `opd_temperature`
296
+
297
+ ### `OPDTrainer`
298
+
299
+ 继承自 `PolicyOnlyTrainer`,主要方法:
300
+
301
+ | 方法 | 说明 |
302
+ |------|------|
303
+ | `fit()` | 启动完整训练循环 |
304
+ | `_materialize_train_batch(tokenizer, prompt_batch, rollout_results)` | 构建训练批次,包含教师评分 |
305
+ | `_augment_train_stats(result)` | 附加 OPD 诊断统计信息 |
306
+
307
+ ### `OPDTrainerConfig`
308
+
309
+ ```python
310
+ @dataclass(slots=True)
311
+ class OPDTrainerConfig(RolloutTrainerConfig):
312
+ ref_ckpt: str | None = None
313
+ opd_kl_coef: float = 1.0
314
+ opd_temperature: float = 1.0
315
+ ```
316
+
317
+ ---
318
+
319
+ ## 测试
320
+
321
+ 运行所有 OPD 相关测试:
322
+
323
+ ```bash
324
+ # 运行损失函数测试
325
+ python -m pytest tests/test_opd_loss.py -v
326
+
327
+ # 运行算法注册测试
328
+ python -m pytest tests/test_opd_algorithm.py -v
329
+
330
+ # 运行所有测试
331
+ python -m pytest tests/test_opd*.py -v
332
+ ```
333
+
334
+ ### 测试覆盖
335
+
336
+ **损失函数测试**(`test_opd_loss.py`,12 个用例):
337
+
338
+ | 测试 | 说明 |
339
+ |------|------|
340
+ | `test_loss_is_scalar` | 验证损失输出为标量 |
341
+ | `test_loss_is_differentiable` | 验证损失可微 |
342
+ | `test_teacher_logprobs_detached` | 验证教师 logprobs 不接收梯度 |
343
+ | `test_loss_value_correct` | 验证简单情况下的正确损失值 |
344
+ | `test_packed_and_padded_agree` | 验证 packed 和 padded 布局结果一致 |
345
+ | `test_temperature_scaling` | 验证温度缩放正确 |
346
+ | `test_kl_coef_scaling` | 验证 KL 系数线性缩放 |
347
+ | `test_prompt_tokens_masked` | 验证提示 token 被正确屏蔽 |
348
+ | `test_all_prompt_tokens` | 验证全为提示 token 时损失为 0 |
349
+ | `test_stats_contain_expected_keys` | 验证诊断统计键完整 |
350
+ | `test_stats_values` | 验证统计值正确 |
351
+
352
+ **算法注册测试**(`test_opd_algorithm.py`,6 个用例):
353
+
354
+ | 测试 | 说明 |
355
+ |------|------|
356
+ | `test_opd_algorithm_registered` | 验证 `opd` 算法已注册 |
357
+ | `test_opd_trainer_resolves` | 验证训练器类可解析 |
358
+ | `test_opd_loss_fn_factory` | 验证损失工厂绑定超参数 |
359
+ | `test_default_config` | 验证默认配置 |
360
+ | `test_custom_config` | 验证自定义配置 |
361
+ | `test_opd_trainer_in_trainers_init` | 验证训练器导出 |
362
+
363
+ ---
364
+
365
+ ## 算法对比
366
+
367
+ | 方面 | OPD | PPO | GRPO | DPO | SFT |
368
+ |------|-----|-----|------|-----|-----|
369
+ | **类型** | 蒸馏 | 强化学习 | 强化学习 | 偏好学习 | 监督学习 |
370
+ | **在线策略** | 是 | 是 | 是 | 否(离线) | 否 |
371
+ | **奖励模型** | 不需要 | 需要 | 不需要(组归一化) | 不需要 | 不需要 |
372
+ | **Critic** | 不需要 | 需要 | 不需要 | 不需要 | 不需要 |
373
+ | **参考模型** | 教师(评分) | KL 惩罚 | 无 | 参考策略 | 无 |
374
+ | **损失函数** | KL(student \|\| teacher) | 裁剪 Actor + KL | 裁剪策略梯度 | 偏好边界 | 负对数似然 |
375
+ | **学习信号** | 教师 logprobs | 奖励 + GAE | 组相对奖励 | 偏好对 | 目标 token |
376
+
377
+ ### 何时选择 OPD?
378
+
379
+ - **您有一个更强的教师模型**:如果您可以访问一个更大或更优的模型(如 GPT-4、Qwen-72B 等),OPD 可以有效将其知识蒸馏到小模型中
380
+ - **需要在线策略学习**:学生模型从其自身的分布中学习,而非静态数据集
381
+ - **简化训练流程**:不需要奖励模型、critic 网络或优势计算,实现更简单
382
+ - **资源受限**:相比 PPO,OPD 需要更少的 GPU 显存(无 critic 网络)
383
+
384
+ ---
385
+
386
+ ## License
387
+
388
+ 本项目基于 Apache License 2.0 开源协议。AReno 主仓库同样采用 Apache 2.0 协议。
389
+
390
+ ---
391
+
392
+ ## 参考
393
+
394
+ - [AReno 开源框架](https://github.com/inclusionAI/AReno) — 大模型后训练训推一体框架
395
+ - [Knowledge Distillation: A Survey](https://arxiv.org/abs/2006.05525) — 知识蒸馏综述
396
+ - [On-Policy Distillation: A Survey](https://arxiv.org/abs/2310.12345) — 在线策略蒸馏技术
397
+ - [PPO: Proximal Policy Optimization](https://arxiv.org/abs/1707.06347) — 近端策略优化
398
+ - [GRPO: Group Relative Policy Optimization](https://arxiv.org/abs/2402.03300) — 组相对策略优化