面向学生自生成序列的在线知识蒸馏训练器
DistillationTrainer 让学生模型在自己生成的补全上对齐教师模型的下一词分布,采用分块 Jensen-Shannon 散度损失避免完整展开教师分布,并支持 vLLM 加速生成、工具调用轨迹训练与视觉语言模型蒸馏。
# 蒸馏训练员 [](https://huggingface.co/models?other=distillation,trl) ## 概览 消化训练员执行政策知识提炼,如 [语文模式的政策扭曲:从自发错误中学习](https://huggingface.co/papers/2306.13649) 由 [里沙布·阿加尔瓦尔](https://huggingface.co/agarwl)尼诺·维耶拉尔德 周永考 [皮奥特·斯坦奇克(Piotr Stanczyk)](https://huggingface.co/PiotrStanczyk)萨贝拉·拉莫斯, [马蒂厄·盖斯特(Matthieu Geist)](https://huggingface.co/matthieu-geist),以及 [奥利维尔·巴切姆](https://huggingface.co/bachem). 本文的抽象内容如下: > 知识衍射(KD)被广泛用于通过培训一个较小的学生模型来压缩一个教师模型以减少其推论成本和记忆足迹,然而,目前用于自动递归序列模型的KD方法在培训期间看到的输出序列和学生在推论期间产生的输出序列之间的分配不匹配.为了解决这个问题,我们引入了通用知识分解(GKD ) 。 GKD 并非完全依赖一组固定的输出序列,而是通过借助老师对此类序列的反馈,对学生进行自我生成输出序列的培训.与受监督的KD方法不同,GKD还提供了在学生和教师之间使用替代损失函数的灵活性,当学生缺乏模仿教师分布的表达力时,这种功能可能有用. 那个... `DistillationTrainer` 培训一个较小的学生模式,以匹配教师在学生自己决策的几代人身上的近亲分布。它生成学生在政策上的完成率(可选的 vLLM 动力) , 并将教师在其全部近亲分布上与记忆高效的块Jensen-Shannon 差异损失相匹配,因此教师密集分布从未完全实现。 这个训练员是来自 [卡洛斯·米格尔·帕蒂尼奥](https://huggingface.co/cmpatino). 对于一个将一代人与培训脱钩的同步对应方, 并且对一个教师的分数超过HTTP, 而不是本地的前进通道, 参见 [`AsyncDistillationTrainer`](<https://github.com/huggingface/trl/blob/HEAD/docs/source/async_distillation_trainer>). ## 快速启动 这个例子说明如何使用蒸馏法培训一个模型。 [Qwen 2.5 0.5B 指令型号](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) 调自 a [Qwen 2.5 1.5B 指导教师](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct) 以示警告, [UltraFeedback 快速数据集](https://huggingface.co/datasets/trl-lib/ultrafeedback-prompt)您可以在此查看数据集中的数据 : [查看原文媒体](<https://huggingface.co/datasets/trl-lib/ultrafeedback-prompt/embed/viewer/default/train?row=0>) 下面是训练模型的脚本. ```python # train_distillation.py from datasets import load_dataset from trl import DistillationTrainer dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train") trainer = DistillationTrainer( model="Qwen/Qwen2.5-0.5B-Instruct", teacher_model="Qwen/Qwen2.5-1.5B-Instruct", train_dataset=dataset, ) trainer.train() ``` 使用以下命令执行脚本 : ```bash torchrun --nproc_per_node 8 train_distillation.py ``` ## 更深入地研究蒸馏方法 政策知识提炼培训学生在完成学业时复制教师的下一手分配,而不是在固定的教师产出上。从自己的几代人那里学习,让学生纠正自己的错误,这些错误一般会超越政策外的提炼。本节分解其实际运作方式,包括两个关键步骤: **生成补全** 财务报告和财务报告 **计算损失**. ### 生成完成数 每个培训步骤,学生都会为抽查的提示产生一批完成的成绩. ### 计算损失 损失是... **詹森-沙农差异(JSD )** 在学生分配之间 \\( p_S \\)和教师分布 \\( p_T \\在生成的完成符上,由 `beta` 定义为: $$ \mathcal{L}_\beta = \beta \, \mathbb{D}_{\mathrm{KL}}\!\left[ p_T \| p_M \right] + (1 - \beta) \, \mathbb{D}_{\mathrm{KL}}\!\left[ p_S \| p_M \right], \qquad p_M = (1 - \beta) \, p_S + \beta \, p_T, $$ 地点 \\( p_M \\即为: \\(\beta) (中文(简体) ). \\) - 两个分布的混合。终点缩小为纯差: `beta=0.0` 给出前进的 KL \\(\ mathbb{ D}_{\ mathrm{ KL } 左转!\ 左转[ p_T \| p_S 对] \\和(或) `beta=1.0` 倒转 KL \\(\ mathbb{ D}_{\ mathrm{ KL } 左转!\ 左转[ p_S \| p_T 对] \\). 在实践中,对词汇日志的投影和差异用块计算,所以峰值激活内存不会与完整的词汇x序列长的日志伸缩。参见 [减少内存使用](<https://github.com/huggingface/trl/blob/HEAD/docs/source/reducing_memory_usage>). ### 预期数据集类型 数据集应为: [prompt-only](<https://github.com/huggingface/trl/blob/HEAD/docs/source/dataset_formats#prompt-only>) 数据集,在任意 [标准](<https://github.com/huggingface/trl/blob/HEAD/docs/source/dataset_formats#standard>) 或 时 间 [对话](<https://github.com/huggingface/trl/blob/HEAD/docs/source/dataset_formats#conversational>) 格式。学生在政策上产生自己的完成,所以只需要提示: ```python {"prompt": [{"role": "user", "content": "What color is the sky?"}]} ``` ## 逻辑衡量标准 在培训和评估方面,我们记录了以下衡量标准: - `num_tokens`: 迄今已处理的令牌总数, 包括提示和补全。 当使用工具时, 仅计算非工具令牌 。 - `step_time`:每个训练步骤(包括一代)的平均时间(秒). - `completions/mean_length`:生成补全的平均长度。在使用工具时,只计算非工具符号。 - `completions/min_length`:生成完成的最小长度。使用工具时,只计算非工具符号。 - `completions/max_length`:生成完成的最大长度。在使用工具时,只计算非工具符号。 - `completions/mean_terminated_length`: 以 EOS 终止的生成完成的平均长度 。 当使用工具时, 仅计算非工具符号 。 - `completions/min_terminated_length`: 以 EOS 终止的生成完成的最小长度. 使用工具时,只计算非工具符号. - `completions/max_terminated_length`: 以 EOS 终止的生成完成的最大长度. 使用工具时,只计算非工具符号. - `completions/clipped_ratio`: 截断(clipped)完成的比例. - `tools/call_frequency`: 生成批次中每完成一个工具调用的平均次数。仅在 `tools` 已提供。 - `tools/failure_frequency`: 失败的工具调用( 找不到工具, 升起例外, 或调用类型不支持) 。 是 。 `0.0` 当没有调用工具时。仅在 `tools` 已提供。 - `rewards/{EnvironmentClass}/mean`: 环境返回的平均值 `get_reward` 仅记录于 `environment_factory` 定义 `get_reward`,在损失中从未使用。 - `rewards/{EnvironmentClass}/std`: 返回值的标准偏差 `get_reward`,通过同样的推出。 - `entropy`: 整个生成的完成值(nats)的令牌预测值的平均 en值. - `teacher/<id>/jsd`: 对教师的每只脚平均差异 `<id>`,或 NaN 当没有向它提供示例时。只有在几个教师通过时才登录。 - `teacher/<id>/token_frac`: 教师打出的完成符的分数 `<id>`。只有在几位教师通过时才进行登录。 ## 自定义 ### 以 vLLM 发电加速培训 在以政策方法进行培训时,世代常常是主要的瓶颈。 要加快世代,可以使用 [vLLM 数据](https://github.com/vllm-project/vllm),用于 LLMs 的高通量低纬度推导引擎。要启用它,首先将软件包安装在 ```shell pip install trl[vllm] ``` 我们支持在培训期间使用VLLM的两种方法: **焦距模式** 财务报告和财务报告 **服务器模式**. #### 选项 1: 凝胶模式 在此模式下,vLLM运行在教练器进程内部,并与训练模型共享GPU内存,这避免了单独启动服务器,可以提高GPU的利用率,但可能导致训练GPU的内存争议,这是默认模式. ```python from trl import DistillationConfig training_args = DistillationConfig( ..., use_vllm=True, # vllm_mode="colocate" by default ) ``` #### 选项 2: 服务器模式 在这个模式中,vLLM运行在一个单独的进程(并使用单独的GPU)中,并通过HTTP与教练员进行交流. 如果您有专门的GPU进行推论,这是理想的. 1. **启动 vLLM 服务器**: ```bash VLLM_SERVER_DEV_MODE=1 vllm serve <model_name> --gpu-memory-utilization 0.9 \ --weight-transfer-config '{"backend": "nccl"}' \ --logprobs-mode processed_logprobs \ --max-logprobs -1 ``` 2. **在培训脚本中启用服务器模式**: ```python from trl import DistillationConfig training_args = DistillationConfig( ..., use_vllm=True, vllm_mode="server", ) ``` > [!WARNING] > 确定服务器使用不同的 GPU 而不是训练器, 否则您可能会遇到 NCCL 错误 。 您可以指定 GPU 使用 。 `CUDA_VISIBLE_DEVICES` 环境变量。 > [!TIP] > 根据模型大小以及培训的总体GPU内存要求,您可能需要调整 `vllm_gpu_memory_utilization` 参数在 [`DistillationConfig`] 以避免使用不足或out-of-memory错误。 更多信息见: [加快使用vLLM的培训](<https://github.com/huggingface/trl/blob/HEAD/docs/source/speeding_up_training#vllm-for-fast-generation-in-online-methods>). ### 带有 PEFT 的列车适配器 我们赞成与 QQ PEFT 库进行紧密的整合, 让你训练适配器, 并分享到Hub上, 而不是训练整个学生。 ```python from datasets import load_dataset from trl import DistillationTrainer from peft import LoraConfig dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train") trainer = DistillationTrainer( model="Qwen/Qwen2.5-0.5B-Instruct", teacher_model="Qwen/Qwen2.5-1.5B-Instruct", train_dataset=dataset, peft_config=LoraConfig(), ) trainer.train() ``` > [!WARNING] > 蒸馏损失是: `lm_head.weight` 直接和运行学生骨干 不经过 `PeftModel.forward()`。适配器打开 `lm_head` (通过) `target_modules`因此,拒绝采用即时学习方法(PromptTuning、PrefixTuning、P-Tuning),因为这些方法会被默默忽略。 `modules_to_save=["lm_head"]` 换句话说。 ### 多名教师 将几个冷冻域专家(如数学专家和密码专家)提炼成一个单一的学生,如: [MOPD](https://huggingface.co/papers/2606.30406),将一个词典映射教师的ID传递给教师,而不是一个单一的教师。每个实例通过一个 `teacher_id` 。每个教师必须分享学生的词汇,并且准备得像一名教师,因此,DeepSpeed ZeRO-3 shards(和可选卸载)是每个教师的。FSDP不支持教师绘图。 ```python from datasets import Dataset from trl import DistillationConfig, DistillationTrainer dataset = Dataset.from_dict( { "prompt": [ [{"role": "user", "content": "What is the derivative of x^2?"}], [{"role": "user", "content": "Write a function that reverses a string."}], ], "teacher_id": ["math", "code"], } ) trainer = DistillationTrainer( model="Qwen/Qwen2.5-0.5B-Instruct", teacher_model={ "math": "Qwen/Qwen2.5-Math-1.5B-Instruct", "code": "Qwen/Qwen2.5-Coder-1.5B-Instruct", }, args=DistillationConfig(output_dir="mopd-student", teacher_model_init_kwargs={"code": {"dtype": "bfloat16"}}), train_dataset=dataset, ) trainer.train() ``` ## 代理培训 [`DistillationTrainer`] 支持 **代理人培训**:学生在一代中调用工具,并在产生的轨迹上被蒸馏. 工具-结果符号被掩盖在损失中,因此学生只接受它自己产生的符号的培训. ### 工具 那个... `tools` 参数预期定义代理工具的 Python 函数列表 : ```python from trl import DistillationTrainer trainer = DistillationTrainer( tools=[tool1, tool2], ..., ) ``` 每个工具必须是标准的 Python 函数, 带有 **键入参数和返回类型**,加上一个 **Google 风格的剂量字符串** 描述其目的、参数和返回值。 详细情况见: [传阅工具指南](https://huggingface.co/docs/transformers/en/chat_extras#passing-tools). > [!TIP] > 工具调用循环需要聊天模板 *prefix-preserving* 对于已知的模型家族(如Qwen3,DeepSeek-V3),在工具启用时,TRL在补丁的训练模板中自动互换。 [聊天模板](<https://github.com/huggingface/trl/blob/HEAD/docs/source/chat_templates#training-templates>) 完整名单。 使用( U) `max_tool_calling_iterations` 输入 [`DistillationConfig`] 以限制工具调用转弯的次数。默认情况下,没有限制,当学生生成一个响应转弯,没有工具调用,完成(全部转弯和工具结果)到达时,生成停止 `max_completion_length` 符号,或当整个序列达到模型的最大长度时(`vllm_max_model_length` 与 `vllm_mode="colocate"`模特儿们的 `max_position_embeddings` (除此以外) 示例: ```python from trl import DistillationTrainer def multiply(a: int, b: int) -> int: """ Multiplies two integers. Args: a: The first integer. b: The second integer. Returns: The product of the two integers. """ return a * b trainer = DistillationTrainer( tools=[multiply], ..., ) ``` > [!WARNING] > Async 工具尚未被支持——通过同步函数. ### 环境 您也可通过下列方式提供工具: `environment_factory`。在此模式下, [`DistillationTrainer`] 每次推出时都会创建一个环境实例,并暴露环境的公共方法作为工具。 学生会针对自己的情况运行多回合的插曲, 老师会将整个插曲( 包括工具结果) 产生的每个符号评分为上下文, 工具结果符号会被掩盖在损失中。 > [!IMPORTANT] > `environment_factory` 要求 `transformers>=5.2.0`. > [!NOTE] > 训练员每推出一代就保留一个环境实例,所以 `per_device_train_batch_size × gradient_accumulation_steps × num_processes` 各个进程同时存在实例(如果 `per_device_eval_batch_size` 如果每个实例都会在远程环境服务器上打开一个会话(如: [OpenEnv](<https://github.com/huggingface/trl/blob/HEAD/docs/source/openenv>)),该服务器必须接受许多并行的会话。 [服务器货币](<https://github.com/huggingface/trl/blob/HEAD/docs/source/openenv#server-concurrency>). 每次推出时,训练员会抽取一排 `train_dataset`,使用其 `"prompt"` 栏作为提示,并将行中的其他列传递到 `reset()` 作为关键词参数,因此环境会从数据集读取任务. ```python from datasets import Dataset from trl import DistillationConfig, DistillationTrainer # Each row carries the prompt and the task data (here, the counter target to reach). targets = [i % 6 + 1 for i in range(64)] dataset = Dataset.from_dict( { "prompt": [[{"role": "user", "content": f"Increment the counter to {t}."}] for t in targets], "target": targets, } ) class IncrementEnv: # Reserved methods def reset(self, target, **kwargs) -> str | None: # required; the row's `target` column arrives as a keyword argument self.counter = 0 self.target = target return None # a returned string is appended to the last user message def get_reward(self) -> float: # optional: logged, never used in the loss return float(self.counter == self.target) # Public methods (exposed as tools) def increment(self, step: int) -> int: """ Increment the internal counter. Args: step: Value to add to the counter. Returns: The updated counter value. """ self.counter += step return self.counter trainer = DistillationTrainer( model="Qwen/Qwen3-0.6B", teacher_model="Qwen/Qwen3-4B", args=DistillationConfig(max_tool_calling_iterations=4, chat_template_kwargs={"enable_thinking": False}), train_dataset=dataset, environment_factory=IncrementEnv, ) trainer.train() ``` 计数器任务在一个工具调用中解决, 因此它只显示 API 。 对于一个后一个转弯很重要的任务, 请参见 。 [`distillation_data_analysis_env`](https://github.com/huggingface/trl/tree/main/examples/distillation_data_analysis_env) 例及其将整个剧集与第一回合的比较。 环境类有两种保留方法: `reset` 财务报告和财务报告 `get_reward`与任何其他公共方法不同,这些方法不作为工具与模型接触。 - `reset` 启动时称为( 需要) 。 也可以返回 。 `None` 或字符串。在蒸馏中,当它返回字符串时,该字符串被附加到最后一个用户消息中。 - `get_reward` (可选)不需要参数返回 a `float`抖音没有奖赏,所以每次完成推出时,只用记录该集的分数为: `rewards/{EnvironmentClass}/mean`,这有利于跟踪任务的成功,同时减少损失。它也让环境释放出每集的资源。它运行在每次推出时,所以费用昂贵。 `get_reward` (例如运行一个测试套房的)增加了每一步的时间. > [!IMPORTANT] > 有了工具, `max_completion_length` 预算为 **整个剧集**:每个模型转动加上每个工具结果。工具结果被掩盖在损失中,但仍在计算中,它们可以占据大部分,例如当工具返回表格或追踪时,如在数据库中。 [`distillation_data_analysis_env`](https://github.com/huggingface/trl/tree/main/examples/distillation_data_analysis_env) 例。该集的大小,而不是一个单一的答案。一个将超过预算的工具结果被放弃,该集将在那里结束。 在一个运行中混合多个环境,将一个词典映射环境名称传递到工厂,并添加一个 `environment` 到数据集的列,截至 [`GRPOTrainer`](<https://github.com/huggingface/trl/blob/HEAD/docs/source/grpo_trainer#multiple-environments>):每次推出都只看到自身环境的工具, `environment` 字段未转发到 `reset`,也不是 `teacher_id` 字段为 [多名教师](#multiple-teachers)实例被跨步骤重复使用(在间隔间重置),所以费用昂贵 `__init__` 已经付了一次钱。 [`distillation_data_analysis_env`](https://github.com/huggingface/trl/tree/main/examples/distillation_data_analysis_env) 示例在 OpenEnv 的数据分析环境中提取一个数据分析剂. > [!WARNING] > Async环境方法(工具或 `get_reward`)尚未支持,而且 `train_dataset` 需要: 环境不能像拥有数据一样拥有数据 [`GRPOTrainer`]. ### 多式联运工具对策 工具可以通过返回一个内容块列表来返回图像与文本并列。这对VLM代理培训有用,因为工具提供视觉反馈(例如截图,图案,相机捕获). ```python from PIL import Image def take_screenshot() -> list: """ Takes a screenshot of the current screen. Returns: The screenshot image with a description. """ img = Image.open("screenshot.png") return [{"type": "image", "image": img}, {"type": "text", "text": "Here is the screenshot."}] ``` 返回的图像会自动注入到对话中,并传递到VLM,用于后续的一代转折. ## 培训远景语言模式 [`DistillationTrainer`] 支持在包含文本和图像的多模式数据集上对VLMs进行蒸馏。作为学生和教师通过一个 VLM ,并提供一个带有任意一种的快速专用数据集。 `image` 列(每个样本的单一图像)或一个 `images` 列(每个样本的图像列表)。关于预期数据集结构的更多信息,请参见 [数据集格式——远景数据集](<https://github.com/huggingface/trl/blob/HEAD/docs/source/dataset_formats#vision-datasets>) 节。 试验过: - **Gemma 3 (英语).** — e.g., `google/gemma-3-4b-it` - **LLAVA - NeXT (英语).** — e.g., `llava-hf/llava-v1.6-mistral-7b-hf` - **Quen2- VL (中文(简体) ).** — e.g., `Qwen/Qwen2-VL-2B-Instruct` - **Qwen2.5-VL** — e.g., `Qwen/Qwen2.5-VL-3B-Instruct` > [!TIP] > 与所有VLM的兼容性没有保证。 如果您认为一个模型应该被支持, 请随意在 GitHub 上打开一个问题, 或者更好一点, 提交一个带有所需修改的拉动请求 。 ## 命令行接口 使用该 [`trl distillation` CLI](<https://github.com/huggingface/trl/blob/HEAD/docs/source/clis>) 从命令行中启动蒸馏训练。它通过标准支持全面训练和LoRA。 `ModelConfig` 旗帜。 ```bash # Full training: trl distillation \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ --dataset_name trl-lib/ultrafeedback-prompt \ --learning_rate 2e-5 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir distilled-model \ --num_train_epochs 1 ``` ```bash # LoRA: trl distillation \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ --dataset_name trl-lib/ultrafeedback-prompt \ --learning_rate 2e-4 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir distilled-model \ --num_train_epochs 1 \ --use_peft \ --lora_r 64 \ --lora_alpha 16 ``` ## DistillationTrainer [[自动doc]] DistillationTrainer - 火车 - save_model - push_to_hub ## DistillationConfig [[自动doc]] DistillationConfig
查看原始来源