首页 游戏 软件 资讯 排行榜 专题
首页
AI
CPM-Distill:经过知识蒸馏的小型文本生成模型

CPM-Distill:经过知识蒸馏的小型文本生成模型

热心网友
21
转载
2025-07-18
本文介绍知识蒸馏技术及基于PaddleNLP加载CPM-Distill模型实现文本生成。知识蒸馏是模型压缩方法,以“教师-学生网络”思想,让简单模型拟合复杂模型输出,效果优于从头训练。CPM-Distill由GPT-2 Large蒸馏得到,文中还给出安装依赖、加载模型、解码方法及文本生成示例。

cpm-distill:经过知识蒸馏的小型文本生成模型 - 游乐网

引入

近些年来,随着 Bert 这样的大规模预训练模型的问世,NLP 领域的模型也逐渐变得越来越大了受限于算力水平,如此大规模的模型要应用在实际的部署场景都是不太实际的因此需要通过一些方式对大规模的模型进行压缩,使其能够在部署场景下达到一个相对可用的速度常见的模型压缩方法有:剪枝、量化、知识蒸馏等最近 CPM(Chinese Pre-Trained Models)项目又开源了一个使用知识蒸馏得到的小型文本生成模型 CPM-Distill本次项目就简单介绍一下知识蒸馏技术并且通过 PaddleNLP 套件加载 CPM-Distill 模型实现文本生成

相关项目

Paddle2.0:构建一个经典的文本生成模型GPT-2文本生成:使用GPT-2加载CPM-LM模型实现简单的问答机器人文本生成:让AI帮你写文章吧【AI创造营】PaddleHub 配合 PaddleNLP 实现简单的文本生成

相关资料

论文:CPM: A Large-scale Generative Chinese Pre-trained Language ModelDistilling the Knowledge in a Neural Network最新实现:TsinghuaAI/CPM-Distill

模型压缩技术

CPM-Distill:经过知识蒸馏的小型文本生成模型 - 游乐网

知识蒸馏(Knowledge Distillation)

知识蒸馏是一种模型压缩方法,是一种基于“教师-学生网络思想”的训练方法。

免费影视、动漫、音乐、游戏、小说资源长期稳定更新! 👉 点此立即查看 👈

由 Hinton 在 2015 年 Distilling the Knowledge in a Neural Network 的论文首次提出了知识蒸馏的并尝试在 CV 领域中使用,旨在把大模型学到的知识灌输到小模型中,以达到缩小模型的目标,示意图如下:

CPM-Distill:经过知识蒸馏的小型文本生成模型 - 游乐网

说人话就是指用一个简单模型去拟合复杂模型的输出,这个输出也叫做“软标签”,当然也可以加入真实数据作为“硬标签”一同训练。使用知识蒸馏技术相比直接从头训练的效果一般会更好一些,因为教师模型能够指导学生模型收敛到一个更佳的位置。

CPM-Distill:经过知识蒸馏的小型文本生成模型 - 游乐网

知识蒸馏技术除了可以用来将网络从大网络转化成一个小网络,并保留接近于大网络的性能;也可以将多个网络的学到的知识转移到一个网络中,使得单个网络的性能接近 emsemble 的结果。

蒸馏模型信息

教师模型为 GPT-2 Large,具体的模型参数如下:
teacher_model = GPTModel(    vocab_size=30000,    hidden_size=2560,    num_hidden_layers=32,    num_attention_heads=32,    intermediate_size=10240,    hidden_act="gelu",    hidden_dropout_prob=0.1,    attention_probs_dropout_prob=0.1,    max_position_embeddings=1024,    type_vocab_size=1,    initializer_range=0.02,    pad_token_id=0,    topo=None)
登录后复制学生模型为 GPT-2 Small,具体的模型参数如下:
teacher_model = GPTModel(    vocab_size=30000,    hidden_size=768,    num_hidden_layers=12,    num_attention_heads=12,    intermediate_size=3072,    hidden_act="gelu",    hidden_dropout_prob=0.1,    attention_probs_dropout_prob=0.1,    max_position_embeddings=1024,    type_vocab_size=1,    initializer_range=0.02,    pad_token_id=0,    topo=None)
登录后复制

蒸馏 loss

将大模型和小模型每个位置上输出之间的 KL 散度作为蒸馏 loss,同时加上原来的 language model loss。总 loss 如下:

CPM-Distill:经过知识蒸馏的小型文本生成模型 - 游乐网

其中 LlmLlm 为 GPT-2 原始的 language modeling loss。

安装依赖

In [ ]
!pip install paddlenlp==2.0.1 sentencepiece==0.1.92
登录后复制

加载模型

In [1]
import paddlefrom paddlenlp.transformers import GPTModel, GPTForPretraining, GPTChineseTokenizer# tokenizer 与 CPM-LM 模型一致tokenizer = GPTChineseTokenizer.from_pretrained('gpt-cpm-large-cn')# 实例化 GPT2-small 模型gpt = GPTModel(    vocab_size=30000,    hidden_size=768,    num_hidden_layers=12,    num_attention_heads=12,    intermediate_size=3072,    hidden_act="gelu",    hidden_dropout_prob=0.1,    attention_probs_dropout_prob=0.1,    max_position_embeddings=1024,    type_vocab_size=1,    initializer_range=0.02,    pad_token_id=0,    topo=None)# 加载预训练模型参数params = paddle.load('data/data92160/gpt-cpm-small-cn-distill.pdparams')# 设置参数gpt.set_dict(params)# 使用 GPTForPretraining 向模型中添加输出层model = GPTForPretraining(gpt)# 将模型设置为评估模式model.eval()
登录后复制
[2024-05-28 19:38:04,469] [    INFO] - Found /home/aistudio/.paddlenlp/models/gpt-cpm-large-cn/gpt-cpm-cn-sentencepiece.model
登录后复制

模型解码

In [40]
import paddleimport numpy as np# Greedy Searchdef greedy_search(text, max_len=32, end_word=None):    # # 终止标志    if end_word is not None:        stop_id = tokenizer.encode(end_word)['input_ids']        length = len(stop_id)    else:        stop_id = [tokenizer.eod_token_id]        length = len(stop_id)        # 初始预测    ids = tokenizer.encode(text)['input_ids']    input_id = paddle.to_tensor(np.array(ids).reshape(1, -1).astype('int64'))    output, cached_kvs = model(input_id, use_cache=True)    next_token = int(np.argmax(output[0, -1].numpy()))    ids.append(next_token)    # 使用缓存进行继续预测    for i in range(max_len-1):        input_id = paddle.to_tensor(np.array([next_token]).reshape(1, -1).astype('int64'))        output, cached_kvs = model(input_id, use_cache=True, cache=cached_kvs)        next_token = int(np.argmax(output[0, -1].numpy()))        ids.append(next_token)        # 根据终止标志停止预测        if ids[-length:]==stop_id:            if end_word is None:               ids = ids[:-1]            break        return tokenizer.convert_ids_to_string(ids)
登录后复制In [39]
import paddleimport numpy as np# top_k and top_p filteringdef top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float('Inf')):    """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering        Args:            logits: logits distribution shape (vocabulary size)            top_k > 0: keep only top k tokens with highest probability (top-k filtering).            top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).                Nucleus filtering is described in Holtzman et al. (https://arxiv.org/abs/1904.09751)        From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317    """    top_k = min(top_k, logits.shape[-1])  # Safety check    logits_np = logits.numpy()    if top_k > 0:        # Remove all tokens with a probability less than the last token of the top-k        indices_to_remove = logits_np < np.sort(logits_np)[-top_k]        logits_np[indices_to_remove] = filter_value    if top_p < 1.0:        sorted_logits = paddle.sort(logits, descending=True)        sorted_indices = paddle.argsort(logits, descending=True).numpy()        cumulative_probs = paddle.cumsum(paddle.nn.functional.softmax(sorted_logits, axis=-1), axis=-1).numpy()        # Remove tokens with cumulative probability above the threshold        sorted_indices_to_remove = cumulative_probs > top_p        # Shift the indices to the right to keep also the first token above the threshold        sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1]        sorted_indices_to_remove[..., 0] = 0        indices_to_remove = sorted_indices[sorted_indices_to_remove]        logits_np[indices_to_remove] = filter_value    return paddle.to_tensor(logits_np)# Nucleus Sampledef nucleus_sample(text, max_len=32, end_word=None, repitition_penalty=1.0, temperature=1.0, top_k=0, top_p=1.0):    # 终止标志    if end_word is not None:        stop_id = tokenizer.encode(end_word)['input_ids']        length = len(stop_id)    else:        stop_id = [tokenizer.eod_token_id]        length = len(stop_id)    # 初始预测    ids = tokenizer.encode(text)['input_ids']    input_id = paddle.to_tensor(np.array(ids).reshape(1, -1).astype('int64'))    output, cached_kvs = model(input_id, use_cache=True)    next_token_logits = output[0, -1, :]    for id in set(ids):        next_token_logits[id] /= repitition_penalty    next_token_logits = next_token_logits / temperature    filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)    next_token = paddle.multinomial(paddle.nn.functional.softmax(filtered_logits, axis=-1), num_samples=1).numpy()    ids += [int(next_token)]    # 使用缓存进行继续预测    for i in range(max_len-1):        input_id = paddle.to_tensor(np.array([next_token]).reshape(1, -1).astype('int64'))        output, cached_kvs = model(input_id, use_cache=True, cache=cached_kvs)        next_token_logits = output[0, -1, :]        for id in set(ids):            next_token_logits[id] /= repitition_penalty        next_token_logits = next_token_logits / temperature        filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)        next_token = paddle.multinomial(paddle.nn.functional.softmax(filtered_logits, axis=-1), num_samples=1).numpy()        ids += [int(next_token)]        # 根据终止标志停止预测        if ids[-length:]==stop_id:            if end_word is None:               ids = ids[:-1]            break    return tokenizer.convert_ids_to_string(ids)
登录后复制

文本生成

In [41]
# 输入文本inputs = input('请输入文本:')print(inputs)# 使用 Nucleus Sample 进行文本生成outputs = greedy_search(    inputs, # 输入文本    max_len=128, # 最大生成文本的长度    end_word=None)# 打印输出print(outputs)
登录后复制
请输入文本:请在此处输入你的姓名请在此处输入你的姓名,然后点击“确定”,就可以开始游戏了。游戏目标:在限定时间内,成功地把所有的牌都通通打完。
登录后复制In [43]
# 输入文本inputs = input('请输入文本:')print(inputs)for x in range(5):    # 使用 Nucleus Sample 进行文本生成    outputs = nucleus_sample(        inputs, # 输入文本        max_len=128, # 最大生成文本的长度        end_word='。', # 终止符号        repitition_penalty=1.0, # 重复度抑制        temperature=1.0, # 温度        top_k=3000, # 取前k个最大输出再进行采样        top_p=0.9 # 抑制概率低于top_p的输出再进行采样    )    # 打印输出    print(outputs)
登录后复制
请输入文本:请在此处输入你的姓名请在此处输入你的姓名、学校、专业及学科,并在社交媒体上公布你的个人简介。请在此处输入你的姓名或者电话,对方会及时通知你。请在此处输入你的姓名、民族及籍贯信息,当您找到 CADULI 的联系方式后,我们会按您所选择的申请中心,以电子邮件的形式向您发送邮件。请在此处输入你的姓名和电话号码,由资深会所接待员进行介绍,因为此处有不少中国的大老板,英文能看。请在此处输入你的姓名、联系电话、银行卡号和手机号。
登录后复制
来源:https://www.php.cn/faq/1414258.html
免责声明: 游乐网为非赢利性网站,所展示的游戏/软件/文章内容均来自于互联网或第三方用户上传分享,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系youleyoucom@outlook.com。

相关攻略

FDUSD 脱锚危机之下:对币安影响几何?
web3.0
FDUSD 脱锚危机之下:对币安影响几何?

FDUSD脱锚惊魂夜:币安生态稳定币的信任危机与系统性风险 2025年4月2日夜间,加密货币市场经历了一场突如其来的“压力测试”。由香港First Digital Trust Limited发行的美元稳定币FDUSD,在市场上演了惊心动魄的脱锚跳水,其兑USDT价格一度暴跌至0 8726美元。这场震

热心网友
04.01
Obsidian同步方案对比:为什么Git更适合管理笔记库?
科技数码
Obsidian同步方案对比:为什么Git更适合管理笔记库?

最近又折腾了下 Obsidian 的 Git 插件,虽然也有点麻烦,但它是适合我的。下面介绍下怎么配置和使用。 第一次使用 Obsidian 是在 2024 年,这是翻阅之前的文章 《Obsidia

热心网友
02.13
华为8B代码模型突破,32B巨头对手面临新挑战
科技数码
华为8B代码模型突破,32B巨头对手面临新挑战

这项由华为技术有限公司、南洋理工大学、香港大学和香港中文大学联合完成的突破性研究发表于2026年1月,论文编号为arXiv:2601 01426v1。研究团队通过一种名为SWE-Lego的创新训练方

热心网友
01.10
Wavesurf Wave13发布:集成SWE-1.5模型与Git工作流,重塑AI代码编辑
电脑教程
Wavesurf Wave13发布:集成SWE-1.5模型与Git工作流,重塑AI代码编辑

12 月 27 日消息,科技媒体 NeoWin 今天(12 月 27 日)发布博文,报道称 AI 代码编辑器 Windsurf 本周发布 Wave 13 版,通过大幅升级多智能体工作流、性能可访问

热心网友
12.29
小蚁NEO:特性、交易与投资指南
web3.0
小蚁NEO:特性、交易与投资指南

NEO(小蚁区块链)旨在构建智能经济网络。NEO通过资产数字化和智能合约实现自动化管理,用户需在支持NEO交易的平台注册账户并获取数字货币,选择合适的交易对后,即可下单交易并确认。交易完成后,可在账户中查看NEO资产,或转移至个人数字储存中安全保管NEO。

热心网友
12.13

最新APP

宝宝过生日
宝宝过生日
应用辅助 04-07
台球世界
台球世界
体育竞技 04-07
解绳子
解绳子
休闲益智 04-07
骑兵冲突
骑兵冲突
棋牌策略 04-07
三国真龙传
三国真龙传
角色扮演 04-07

热门推荐

美国SEC主席Paul Atkins证实:加密货币安全港提案已送交白宫审查
web3.0
美国SEC主席Paul Atkins证实:加密货币安全港提案已送交白宫审查

加密货币行业翘首以盼的监管里程碑,终于有了实质性进展。美国证券交易委员会(SEC)主席保罗·阿特金斯(Paul Atkins)近日证实,那份允许加密项目在早期获得注册豁免权的“安全港”框架提案,已经正式送抵白宫,进入了最终审查阶段。 在范德堡大学与区块链协会联合举办的数字资产峰会上,阿特金斯透露了这

热心网友
04.08
微策略Strategy报告:第一季录得144.6亿美元浮亏 再斥资约3.3亿美元买进4871枚比特币
web3.0
微策略Strategy报告:第一季录得144.6亿美元浮亏 再斥资约3.3亿美元买进4871枚比特币

微策略Strategy报告:第一季录得144 6亿美元浮亏 再斥资约3 3亿美元买进4871枚比特币 市场震荡的威力有多大?看看Strategy的最新季报就明白了。根据其最新向美国证管会(SEC)提交的8-K报告,受市场剧烈波动影响,这家公司所持的比特币在第一季度录得了一笔惊人的数字——144 6亿

热心网友
04.08
稳定币发行商Tether再扩Web3版图!Paolo Ardoino:正开发去中心化搜索引擎Hypersearch
web3.0
稳定币发行商Tether再扩Web3版图!Paolo Ardoino:正开发去中心化搜索引擎Hypersearch

稳定币巨头Tether的动向,向来是加密世界的风向标。这不,它向Web3基础设施的版图扩张,又迈出了关键一步。公司执行长Paolo Ardoino在社交平台X上透露,其工程团队正在全力“烹制”一个新项目——去中心化搜索引擎 “Hypersearch”。这个消息一出,立刻引发了行业的广泛猜想。 采用D

热心网友
04.08
Base链首个原生DeFi借贷协议Seamless Protocol倒闭 将于2026年6月30日下线
web3.0
Base链首个原生DeFi借贷协议Seamless Protocol倒闭 将于2026年6月30日下线

基地位于Coinbase旗下以太坊Layer2网络Base的Seamless Protocol,日前正式宣告了服务的终结。这个曾经吸引了超过20万用户的原生DeFi借贷协议,在运营不到三年后,终究没能跑赢时间。它主打的核心产品是Integrated Leverage Markets(ILMs)——一

热心网友
04.08
PAAL代币如何参与治理?社区投票能决定哪些事项?
web3.0
PAAL代币如何参与治理?社区投票能决定哪些事项?

PAAL代币揭秘:深度解析Web3社区治理的核心钥匙 在去中心化自治组织的浪潮中,谁真正掌握了项目的话语权?PAAL代币提供了一套系统化的答案。它不仅是生态内流转的价值媒介,更是开启链上治理大门的核心凭证。通过持有并质押PAAL代币,用户能够对协议升级、资金分配乃至战略方向等关键事务投出决定性的一票

热心网友
04.08