2026年7月2日 周四晚上19:30,报名腾讯会议了解“如何构建自进化的动态知识库(Brain)”(限30人)
免费POC, 零成本试错
FDE知识库

FDE知识库

学习大模型的前沿技术与行业落地应用


收藏

Reasoning模型蒸馏实践:用大模型提升小模型能力

发布日期:2025-05-23 19:35:39 浏览次数: 2555
作者:魔搭ModelScope社区

微信搜一搜,关注“魔搭ModelScope社区”

推荐语

模型蒸馏技术,让小模型也能获得大模型的知识精华!

核心内容:
1. 模型蒸馏技术介绍:如何让小模型学习大模型的知识
2. 三步速成法:构造蒸馏数据、特训小模型、考试验收
3. Python代码示例:从高质量开源数学数据集中获取蒸馏数据

杨芳贤
53AI创始人/腾讯云(TVP)最具价值专家
01


前言



DeepSeek-R1的爆火让更多开发者注意到模型蒸馏技术——这种让小模型也能"开小灶"习得大模型知识精华的秘诀。今天我们就用Qwen2.5-1.5B小模型(相当于AI界的初中生)来进行实践!



? 什么是模型蒸馏?

就像普通学生跟着学霸学解题思路:

-教师模型 = 学霸本霸(比如DeepSeek-R1)
-学生模型 = 需要进步的Qwen2.5-1.5B
-蒸馏数据 = 学霸的解题笔记

? 三步速成法:

制造"学霸笔记"(构造蒸馏数据)

-让学霸模型处理大量题目
-记录它的解题过程和参考答案
-整理成适合小模型学习的训练集


特训小模型(训练阶段)

-重点模仿学霸的解题思路


考试验收(模型评测)

-准备数学题等测试卷
-对比特训前后的考试成绩
-观察逻辑推理能力的提升效果


跟着这个流程,小模型也能获得学霸的真传!不需要昂贵硬件,用常规显卡就能训练,赶紧试试这个AI界的"开小灶"秘籍吧~


02


构造蒸馏数据



为了让小模型也有合适的学习资料,我们需要从高质量开源数学数据集,例如AI-MO/NuminaMath-CoT中获取蒸馏数据

AI-MO/NuminaMath-CoT:

https://www.modelscope.cn/datasets/AI-MO/NuminaMath-CoT/summary


下面展示使用ModelScope的在线模型推理服务(https://www.modelscope.cn/docs/model-service/API-Inference/intro),用DeepSeek-R1作为教师模型,通过prompt构造的方式获取一个数学题的解题过程和参考答案。以下是Python代码示例:

from openai import OpenAIimport ossystem_prompt = (        'A conversation between User and Assistant. The user asks a question, and the Assistant solves it. '        'The assistant first thinks about the reasoning process in the mind and then provides the user '        'with the answer. The reasoning process and answer are enclosed '        'within <think> </think> and <answer> </answer> tags, respectively, '        'i.e., <think> reasoning process here </think> <answer> answer here </answer>.')prompt_template = r'{question}\nPlease reason step by step, and put your final answer within \boxed{{}}.'question = 'Find all real numbers \( x, y, z \) such that \[ x + y + z = 3, \quad x^2 + y^2 + z^2 = 3, \quad x^3 + y^3 + z^3 = 3 \]'client = OpenAI(    api_key=os.getenv("MODELSCOPE_SDK_TOKEN"), # 请替换成您的 ModelScope SDK Token    base_url="https://api-inference.modelscope.cn/v1/")response = client.chat.completions.create(    model="deepseek-ai/DeepSeek-R1", # ModleScope Model-Id    messages=[        {            'role': 'system',            'content': system_prompt        },        {            'role': 'user',            'content': prompt_template.format(question=question)        }    ],    stream=True)for chunk in response:    if hasattr(chunk.choices[0].delta, 'reasoning_content'):        print(chunk.choices[0].delta.reasoning_content, end='', flush=True)    if hasattr(chunk.choices[0].delta, 'content'):        print(chunk.choices[0].delta.content, end='', flush=True)
输出:
Okay, so I need to solve this system of equations:x + y + z = 3,x² + y² + z² = 3,x³ + y³ + z³ = 3.Hmm, let's see. These are symmetric equations, so maybe I can use some symmetric properties or formulas. Let me recall that for symmetric equations, using variables like sums and products might help. Let me denote S = x + y + z, which is given as 3. Then, the sum of squares is given by x² + y² + z² = 3. I also know that the sum of squares can be related to S and the pairwise products. The formula is:x² + y² + z² = (x + y + z)² - 2(xy + yz + zx).Plugging in the known values, 3 = (3)² - 2(xy + yz + zx). So, 3 = 9 - 2(xy + yz + zx). Let's solve for the sum of products:2(xy + yz + zx) = 9 - 3 = 6 ⇒ xy + yz + zx = 3.Okay, so now I have S = 3, and the sum of products is also 3. Now, moving on to the third equation, which is the sum of cubes: x³ + y³ + z³ = 3. There's a formula for the sum of cubes in terms of S, the sum of products, and the product xyz. The formula is:x³ + y³ + z³ = (x + y + z)³ - 3(x + y + z)(xy + yz + zx) + 3xyz.Plugging in the known values:3 = 3³ - 3*3*3 + 3xyz.Calculating each term:3³ is 27,3*3*3 is 27,So,3 = 27 - 27 + 3xyz ⇒ 3 = 0 + 3xyz ⇒ 3xyz = 3 ⇒ xyz = 1.So now I have S = 3, sum of products = 3, and product = 1. These are the elementary symmetric sums. Therefore, the monic cubic polynomial whose roots are x, y, z is:t³ - S t² + (xy + yz + zx) t - xyz = 0 ⇒ t³ - 3t² + 3t - 1 = 0.So, solving this cubic equation should give me all real numbers x, y, z. Let me try to factor this cubic. Maybe it has rational roots? By Rational Root Theorem, possible roots are ±1. Let's test t=1:1³ - 3*1² + 3*1 -1 = 1 -3 +3 -1 = 0. Yes, t=1 is a root. So, we can factor out (t -1). Let's perform polynomial division or use synthetic division.Dividing t³ -3t² +3t -1 by (t -1):Using synthetic division:1 | 1  -3   3   -1           1  -2    1       1  -2    1    0So, the quadratic factor is t² - 2t +1. Which factors further as (t -1)².Therefore, the cubic factors as (t -1)³ = 0. So, all three roots are 1. Therefore, the solution is x = y = z =1.Wait, but let me check if there could be other solutions. Suppose the cubic factors into (t-1)^3, which means that all three variables are 1. Let me verify if this satisfies the original equations.First equation: 1 +1 +1 =3, yes.Second: 1² +1² +1² =3, yes.Third:1³ +1³ +1³=3, yes. So that works.But wait, maybe there are other real solutions where variables are not all 1? Let's see. Since the cubic equation only has t=1 as a triple root, that's the only solution. Therefore, the only real solution is x=y=z=1.But let me think again. Suppose that two variables are equal to 1 and the third is different. Let me test that. Suppose x =1, y=1, then z =3 -1 -1=1. So, z=1. So that's still all ones. Alternatively, if one variable is not 1, would that work?Wait, suppose that x, y, z are all 1, which works. Suppose, for example, x=2, y=0, z=1. Then x+y+z=3. Check the sum of squares: 4 +0 +1=5 ≠3. So that doesn't work. Alternatively, maybe some other combination. But given that the cubic equation only has 1 as a root, multiplicity three, that suggests that all three variables must be 1.Alternatively, perhaps complex roots, but the problem asks for real numbers. So, since the only real root is 1 with multiplicity three, the only real solution is x=y=z=1. Therefore, the answer is all variables equal to 1.<answer>The only real solution is \( x = y = z = 1 \). Thus, the numbers are \(\boxed{1}\), \(\boxed{1}\), and \(\boxed{1}\).Alternatively, since all variables are the same, it can be written as \(\boxed{1}\) for each variable.**Final Answer**The real numbers are \(\boxed{1}\), \(\boxed{1}\), and \(\boxed{1}\).</answer>

03


训练模型



我们已经处理了一批数学题,生成了一个包含4000个样本的蒸馏数据集。每个样本包含题目、解题过程和参考答案。我们将其保存为JSONL格式,方便后续使用,数据集预览:https://www.modelscope.cn/datasets/modelscope/MathR/dataPeview。


接下来,我们将使用ms-swift(https://github.com/modelscope/ms-swift)模型训练框架,用这批数据对Qwen2.5-1.5B模型进行训练。


训练样本示例:

[  {    "role": "user",    "content": "A set of consecutive positive integers beginning with $1$ is written on a blackboard. One number is erased. The average (arithmetic mean) of the remaining numbers is $35\\frac{7}{17}$. What number was erased? \n$\\textbf{(A)}\\ 6\\qquad  \\textbf{(B)}\\ 7 \\qquad  \\textbf{(C)}\\ 8 \\qquad  \\textbf{(D)}\\  9\\qquad  \\textbf{(E)}\\ \\text{cannot be determined}$\nPlease reason step by step, and put your final answer within \boxed{}."  },  {    "role": "assistant",    "content": "\nOkay, let's see. I need to figure out which ....... Answer is B.\n\n**Final Answer**\n\\boxed{B}\n\n\nGiven a set of consecutive positive integers starting ...... Average of remaining numbers: \\(\\frac{2408}{68} = \\frac{602}{17} = 35 \\frac{7}{17}\\)\n\nThus, the number erased is \\(\\boxed{B}\\)."  }]


注意:受限于显存,我们使用LoRA技术对Qwen2.5-1.5B进行微调。LoRA是一种高效的模型微调方法,能够在不改变原始模型参数的情况下,通过添加低秩矩阵来实现模型的适应性调整。这样可以大幅降低训练成本和时间。如果有更强的显卡,可以考虑使用更多的训练数据以及全量参数微调。


下面的命令中我们还使用了Swanlab(https://github.com/SwanHubX/SwanLab)进行训练过程的可视化,可以方便的查看训练过程中loss等指标的变化情况,请替换下面的YOUR_SWANLAB_TOKEN

!CUDA_VISIBLE_DEVICES=0 \ swift sft \    --model Qwen/Qwen2.5-1.5B-Instruct \    --train_type lora \    --lora_rank 16 \    --torch_dtype bfloat16 \    --dataset 'modelscope/MathR:clean' \    --split_dataset_ratio 0 \    --max_length 4096 \    --num_train_epochs 1 \    --per_device_train_batch_size 1 \    --learning_rate 1e-5 \    --gradient_accumulation_steps 16 \    --save_steps 100 \    --save_total_limit 10 \    --logging_steps 5 \    --report_to swanlab \    --swanlab_token YOUR_SWANLAB_TOKEN \    --swanlab_mode cloud

在控制台运行下面的命令,可以与训练后的模型进行对话,了解模型效果:

注意:把adapters参数替换成你训练好的模型路径,--stream参数设置为true表示使用流式推理,--infer_backend参数设置为pt表示使用PyTorch作为推理后端,--temperature参数设置为0表示不引入随机性,--max_new_tokens参数设置为2048表示生成的最大token数。

swift infer \--adapters 'output/Qwen2.5-1.5B-Instruct/v11-20250415-120200/checkpoint-81' \--stream true \--infer_backend pt \--temperature 0 \--max_new_tokens 2048

04


模型性能前后对比



在训练完成后,我们使用一组新的数学题对模型进行评测。这里我们使用gsm8k数据集(数学题数据集)来进行评测,可以在这里查看数据集(https://www.modelscope.cn/datasets/modelscope/gsm8k/dataPeview)

from evalscope import run_task, TaskConfigtask_config = TaskConfig(    model="Qwen/Qwen2.5-1.5B-Instruct",  # 原始模型    datasets=["gsm8k"],  # 数据集名称    dataset_args={        "gsm8k": {"few_shot_num": 0},  # few_shot_num: 0表示不使用few-shot    },    generation_config={        "max_new_tokens": 4096,  # 生成的最大token数        "temperature": 0,  # 生成的温度系数,0表示贪婪搜索    },    eval_batch_size=10,  # 评测时的batch size    limit=100   # 评测数据集的大小,抽取前100条数据进行评测)run_task(task_config)

结果如下:


为了评测训练之后的模型,需要运行下面的命令将我们训练的lora参数合并回原始模型,得到一个新的模型Qwen2.5-1.5B-Instruct,并将其保存到checkpoint-xxx-merged目录下。

!swift export \    --adapters /mnt/data/data/user/maoyunlin.myl/tools/course/distill/output/Qwen2.5-1.5B-Instruct/v11-20250415-120200/checkpoint-81 \    --merge_lora true

# 测试蒸馏训练后的模型from evalscope import run_task, TaskConfig# 记得替换下面的model路径task_config = TaskConfig(    model="/mnt/data/data/user/maoyunlin.myl/tools/course/distill/output/Qwen2.5-1.5B-Instruct/v11-20250415-120200/checkpoint-81-merged",    datasets=["gsm8k"],    dataset_args={        "gsm8k": {"few_shot_num": 0},    },    generation_config={        "max_new_tokens": 4096,        "temperature": 0,    },    eval_batch_size=10,    limit=100)run_task(task_config)

结果如下:


可视化结果

通过训练结果可以看到模型的回答准确率提升了12%,进步还是很可观的。我们还可以使用可视化工具来进一步分析模型的推理过程,帮助我们更好地理解模型的决策逻辑。

import osos.environ['GRADIO_ROOT_PATH'] = f"/{os.environ['JUPYTER_NAME']}/proxy/7860"print(os.environ['GRADIO_ROOT_PATH'])
!evalscope app

05


总结



在这个教程中,我们详细演示了如何利用一个教师模型来蒸馏一个小模型的完整流程。内容涵盖三个关键环节:数据构造、模型训练和模型评测。通过这一方法,您可以高效地训练出属于自己的小模型。希望本教程能帮助您掌握这一技术,并灵活运用于实际项目中!

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询

扫码登录
登录即表示您同意《53AI网站服务协议》
服务协议

欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。

在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。

一、 定义

本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。

会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。

知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。

二、 账号注册与登录

登录方式:本网站支持以下登录方式,您可根据实际情况选择:

微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。

手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。

账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。

实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。

未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。

三、 服务内容与规范

知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。

服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。

禁止行为:您在使用服务时不得实施以下行为:

利用技术手段批量爬取、下载、转存知识库内容;

将知识库内容用于商业目的或未经授权地向第三方传播;

干扰本网站正常运行或侵犯其他用户合法权益;

发布违法违规信息或从事违反公序良俗的活动。

四、 知识产权声明

权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。

有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。

侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。

五、 个人信息保护

我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。

您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。

您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。

六、 免责声明

内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。

不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。

第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。

七、 违约责任

如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。

如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。

八、 法律适用与争议解决

本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。

因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。

九、 其他

本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。

本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。

我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。


已查阅