昇思25天学习打卡营第16天|文本解码原理——以MindNLP为例

在大模型中,文本解码通常是指在自然语言处理(NLP)任务中使用的大型神经网络模型(如Transformer架构的模型)将编码后的文本数据转换回可读的原始文本的过程。这些模型在处理自然语言时,首先将输入文本(如一段话或一个句子)编码成高维空间中的向量表示,这些向量能够捕捉到文本的语义和上下文信息。

在编码过程中,模型通过多层神经网络将文本的每个字符、单词或标记(token)转换成对应的向量。这些向量随后在模型的解码阶段被处理,以生成或选择最合适的序列来表示原始文本的含义。例如,在机器翻译任务中,解码阶段会生成目标语言的文本;在文本摘要任务中,解码阶段会生成原文的摘要;在问答系统中,解码阶段会生成问题的答案。

 一、自回归语言模型:

1、根据前文预测下一个单词:

2、一个文本序列的概率分布可以分解为每个词基于其上文的条件概率的乘积 :

  • w_0:初始上下文单词序列
  • T:时间步
  • 当生存ESO标签时停止生成 

3、MindNLP/huggingface Transformers提供的文本生成方法:

 二、环境准备:

首先还是需要下载MindSpore,相关教程可以参考我昇思25天学习打卡营第1天|快速入门这篇博客,之后就需要使用pip命令在终端卸载mindvision和mindinsight包之后,下载mindnlp:

pip uninstall mindvision -y
pip uninstall mindinsight -ypip install mindnlp

相关依赖下载完成之后,就可以开始我们下面的实验了!

三、Greedy Search:

在每个时间步𝑡都简单地选择概率最高的词作为当前输出词:

wt = argmax_w P(w|w(1:t-1))

按照贪心搜索输出序列("The","nice","woman") 的条件概率为:0.5 x 0.4 = 0.2

缺点: 错过了隐藏在低概率词后面的高概率词,如:dog=0.5, has=0.9 ![image.png](attachment:image.png =600x600)

from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')# generate text until the output length (which includes the context length) reaches 50
greedy_output = model.generate(input_ids, max_length=50)print("Output:\n" + 100 * '-')
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))

四、Beam Search:

Beam search通过在每个时间步保留最可能的 num_beams 个词,并从中最终选择出概率最高的序列来降低丢失潜在的高概率序列的风险。如图以 num_beams=2 为例:

("The","dog","has") : 0.4 * 0.9 = 0.36

("The","nice","woman") : 0.5 * 0.4 = 0.20

优点:一定程度保留最优路径

缺点:1. 无法解决重复问题;2. 开放域生成效果差

from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')# activate beam search and early_stopping
beam_output = model.generate(input_ids, max_length=50, num_beams=5, early_stopping=True
)print("Output:\n" + 100 * '-')
print(tokenizer.decode(beam_output[0], skip_special_tokens=True))
print(100 * '-')# set no_repeat_ngram_size to 2
beam_output = model.generate(input_ids, max_length=50, num_beams=5, no_repeat_ngram_size=2, early_stopping=True
)print("Beam search with ngram, Output:\n" + 100 * '-')
print(tokenizer.decode(beam_output[0], skip_special_tokens=True))
print(100 * '-')# set return_num_sequences > 1
beam_outputs = model.generate(input_ids, max_length=50, num_beams=5, no_repeat_ngram_size=2, num_return_sequences=5, early_stopping=True
)# now we have 3 output sequences
print("return_num_sequences, Output:\n" + 100 * '-')
for i, beam_output in enumerate(beam_outputs):print("{}: {}".format(i, tokenizer.decode(beam_output, skip_special_tokens=True)))
print(100 * '-')

 

缺点的具体表现:

重复性高,这个看我生成的例子就可以很清楚的看到,着几句话几乎一模一样,还有就是开放域的问题,可以看下图:

 

五、超参数:

由于普通的默认索引均存在着难以克服的问题,人们通常会使用各种超参数来减小索引缺陷的影响。

1、n_gram惩罚:

将出现过的候选词的概率设置为 0

设置no_repeat_ngram_size=2 ,任意 2-gram 不会出现两次

Notice: 实际文本生成需要重复出现

 2、Sample:

根据当前条件概率分布随机选择输出词w_t

优点:文本生成多样性高

缺点:生成文本不连续

import mindspore
from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')mindspore.set_seed(0)
# activate sampling and deactivate top_k by setting top_k sampling to 0
sample_output = model.generate(input_ids, do_sample=True, max_length=50, top_k=0
)print("Output:\n" + 100 * '-')
print(tokenizer.decode(sample_output[0], skip_special_tokens=True))

 

3、Temperature:

降低softmax 的temperature使 P(w∣w1:t−1​)分布更陡峭,以增加高概率单词的似然并降低低概率单词的似然。

 

import mindspore
from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')mindspore.set_seed(1234)
# activate sampling and deactivate top_k by setting top_k sampling to 0
sample_output = model.generate(input_ids, do_sample=True, max_length=50, top_k=0,temperature=0.7
)print("Output:\n" + 100 * '-')
print(tokenizer.decode(sample_output[0], skip_special_tokens=True))

 

4、Topk Sample:

选出概率最大的 K 个词,重新归一化,最后在归一化后的 K 个词中采样,确定就是:将采样池限制为固定大小 K 导致在分布比较尖锐的时候产生胡言乱语和在分布比较平坦的时候限制模型的创造力。

 

import mindspore
from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')mindspore.set_seed(0)
# activate sampling and deactivate top_k by setting top_k sampling to 0
sample_output = model.generate(input_ids, do_sample=True, max_length=50, top_k=50
)print("Output:\n" + 100 * '-')
print(tokenizer.decode(sample_output[0], skip_special_tokens=True))

5、Top_P Sample:

在累积概率超过概率 p 的最小单词集中进行采样,重新归一化,缺点就是:采样池可以根据下一个词的概率分布动态增加和减少。

import mindspore
from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')mindspore.set_seed(0)# deactivate top_k sampling and sample only from 92% most likely words
sample_output = model.generate(input_ids, do_sample=True, max_length=50, top_p=0.92, top_k=0
)print("Output:\n" + 100 * '-')
print(tokenizer.decode(sample_output[0], skip_special_tokens=True))

 6、Top_k_Top_p:

import mindspore
from mindnlp.transformers import GPT2Tokenizer, GPT2LMHeadModeltokenizer = GPT2Tokenizer.from_pretrained("iiBcai/gpt2", mirror='modelscope')# add the EOS token as PAD token to avoid warnings
model = GPT2LMHeadModel.from_pretrained("iiBcai/gpt2", pad_token_id=tokenizer.eos_token_id, mirror='modelscope')# encode context the generation is conditioned on
input_ids = tokenizer.encode('I enjoy walking with my cute dog', return_tensors='ms')mindspore.set_seed(0)
# set top_k = 50 and set top_p = 0.95 and num_return_sequences = 3
sample_outputs = model.generate(input_ids,do_sample=True,max_length=50,top_k=5,top_p=0.95,num_return_sequences=3
)print("Output:\n" + 100 * '-')
for i, sample_output in enumerate(sample_outputs):print("{}: {}".format(i, tokenizer.decode(sample_output, skip_special_tokens=True)))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1473006.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

长沙(市场调研公司)源点 企业如何决定是否需要开展市场调研?

长沙源点调研咨询认为:对于一个特定问题,管理者在面临几种解决问题的方案时,不应该凭直觉草率开展应用性市场调研。事实上,首先需要做的决策是是否需要开展调研。在下述情况下,最好不要做调研: *缺乏资源。…

重大更新来袭!!《植物大战僵尸杂交版V2.1+修改器+融合版》

大家好!每个软件更新总是令人兴奋不已。前段时间介绍的《植物大战僵尸》系列以其独特的策略玩法和丰富的植物角色,赢得了很多玩家的喜爱。而在今天,这款经典游戏全网最新版本——《植物大战僵尸:杂交版V2.1》正式推出,…

ASUS/华硕枪神4 G532L G732L系列 原厂win10系统 工厂文件 带F12 ASUS Recovery恢复

华硕工厂文件恢复系统 ,安装结束后带隐藏分区,一键恢复,以及机器所有驱动软件。 系统版本:Windows10 原厂系统下载网址:http://www.bioxt.cn 需准备一个20G以上u盘进行恢复 请注意:仅支持以上型号专用…

【Redis】真行,原来是这样啊! --Redis自动序列化和手动序列化的区别(存储结构、内存开销,实际写法)

对于Redis有两种序列化和反序列化的方式, 方式一: 一种是通过 注入RedisTemplate 对象,找个对象,通过配置类进行一定的配置,使得使用RedisTemplate 对象时,便会使用配置的那些键、值的序列化方式&#xff…

有哪些有效的策略可以提升独立站的外链数量?

有哪些有效的策略可以提升独立站的外链数量?提升独立站的外链数量并不难,难得是不被谷歌惩罚把你的网站判定为作弊,正因如此,了解并应用GNB自然外链策略是个不错的开始,GNB外链的核心价值在于它提高了网站外链资源的自…

opencv概念以及安装方法

#opencv相关概念介绍 Open Source Computer Vision Library 缩写 opencv 翻译:开源的计算机视觉库 ,英特尔公司发起并开发,支持多种编程语言(如C、Python、Java等),支持计算机视觉和机器学习等众多算法&a…

Android车载开发中调试app与bat结合的丝滑小妙招

项目场景: 做Android车载的小伙伴调试app的时候常年就是手动adb命令三连,例如我常用的adb推送apk的命令 adb root adb remount adb push D:\workspace_atc\XSP3-10A\AutoSystemUIPlugin\app\release\CarSystemUI.apk /system/priv-app/CarSystemUI …

【qt】如何获取网卡的IP地址?

网卡相当于是一个翻译官,可以将数据转换成网络信号. 同时也可以将网络信号转换成数据. 我们要用到网卡类QNetmorkInterface 我们获取网卡的所有地址用静态函数allAddresses() 返回的还是一个QhostAddress的容器. QList<QHostAddress> addrList QNetworkInterface::allA…

相关技术 太阳能热水器循环水泵制作技术

网盘 https://pan.baidu.com/s/1oAKwUEGkKnEgxE-F4znKow?pwdidxd 双温区蓄能供热型太阳能热水系统及其工作方法.pdf 双罐叠压节能恒温型太阳能热水机组.pdf 基于傅科电流的循环式风能热水器.pdf 基于太阳能利用的建筑冷热电联产系统及工作方法.pdf 基于太阳能和热泵的双蓄式热…

剪画小程序:自媒体工具推荐:视频文案提取!

各位小伙伴&#xff0c;你们好啊&#xff01; 上周五观看《歌手 2024》第八期时&#xff0c;我再次被何炅老师幽默风趣的主持风格所折服。他的每一句话都仿佛带着魔力&#xff0c;让现场气氛热烈非凡&#xff0c;实在令人羡慕不已&#xff01; 何炅老师的口才之所以如此出色&a…

7月6日 VueConf 技术大会即将在深圳举办

7月6日&#xff0c;VueConf 2024 即将在深圳召开&#xff0c;本次大会正值 Vue.js 十周年&#xff0c;旨在聚焦 Vue.js 社区的成员&#xff0c;分享最新的技术动态、经验以及创新实践。 本次参与 VueConf 大会的是来自全球 Vue.js 核心团队成员、行业专家及前端开发者。其中&a…

# Sharding-JDBC从入门到精通(7)- Sharding-JDBC 公共表 与 读写分离

Sharding-JDBC从入门到精通&#xff08;7&#xff09;- Sharding-JDBC 公共表 与 读写分离 一、Sharding-JDBC 公共表 1、公共表 公共表属于系统中数据量较小&#xff0c;变动少&#xff0c;而且属于高频联合查询的依赖表。参数表、数据字典表等属于此类型。可以将这类表在每…

芯片基识 | 掰开揉碎讲 FIFO(同步FIFO和异步FIFO)

文章目录 一、什么是FIFO二、为什么要用FIFO三、什么时候用FIFO四、FIFO分类五、同步FIFO1. 同步FIFO电路框图2. 同步FIFO空满判断3. 同步FIFO设计代码4. 同步FIFO仿真结果 六、异步FIFO1、异步FIFO的电路框图2 、亚稳态3、打两拍4、格雷码5、如何判断异步FIFO的空满&#xff0…

外泌体相关基因肝癌临床模型预测——2-3分纯生信文章复现——4.预后相关外泌体基因确定单因素cox回归(2)

内容如下&#xff1a; 1.外泌体和肝癌TCGA数据下载 2.数据格式整理 3.差异表达基因筛选 4.预后相关外泌体基因确定 5.拷贝数变异及突变图谱 6.外泌体基因功能注释 7.LASSO回归筛选外泌体预后模型 8.预后模型验证 9.预后模型鲁棒性分析 10.独立预后因素分析及与临床的…

全端面试题15(canvas)

在前端开发领域&#xff0c;<canvas> 元素和相关的 API 是面试中经常被提及的主题。下面是一些常见的关于 HTML5 Canvas 的面试问题及解答示例&#xff1a; 1. 什么是 <canvas> 元素&#xff1f; <canvas> 是 HTML5 引入的一个用于图形渲染的标签。它本身并…

win11如何关闭自动更新,延长暂停更新时间

网上有很多关闭自动更新的方法&#xff0c;今天给大家带来另一种关闭win11自动更新的方法。 1.winR打开运行窗口&#xff0c;输入regedit打开注册表 2.定位到以下位置&#xff1a; 计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings 3.右键右边空白&…

昇思25天学习打卡营第13天|linchenfengxue

Diffusion扩散模型 关于扩散模型&#xff08;Diffusion Models&#xff09;有很多种理解&#xff0c;本文的介绍是基于denoising diffusion probabilistic model &#xff08;DDPM&#xff09;&#xff0c;DDPM已经在&#xff08;无&#xff09;条件图像/音频/视频生成领域取得…

理解机器学习中的潜在空间(Understanding Latent Space in Machine Learning)

1、什么是潜在空间&#xff1f; If I have to describe latent space in one sentence, it simply means a representation of compressed data. 如果我必须用一句话来描述潜在空间&#xff0c;它只是意味着压缩数据的表示。 想象一个像上面所示的手写数字&#xff08;0-9&…

什么是OSPFv2 ?

什么是OSPF ? 开放式最短路径优先 OSPF&#xff08;Open Shortest Path First&#xff09;是IETF组织开发的一个基于链路状态的内部网关协议&#xff08;Interior Gateway Protocol&#xff09;。 目前针对IPv4协议使用的是OSPF Version 2&#xff08;RFC2328&#xff09;&a…

c进阶篇(三):字符串函数

1.strlen: strlen - C Reference strlen 函数是一个标准库函数&#xff0c;用于计算以 null 结尾的字符串的长度&#xff0c;也就是字符串中实际字符的数量&#xff0c;不包括最后的 null 终止符 \0。它定义在 <string.h> 头文件中。 函数原型:size_t strlen(const ch…