transformers-Generation with LLMs

news2025/2/25 18:06:28

https://huggingface.co/docs/transformers/main/en/llm_tutorialicon-default.png?t=N7T8https://huggingface.co/docs/transformers/main/en/llm_tutorial停止条件是由模型决定的,模型应该能够学习何时输出一个序列结束(EOS)标记。如果不是这种情况,则在达到某个预定义的最大长度时停止生成。

from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1", device_map="auto", load_in_4bit=True
)
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left")
model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to("cuda")
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'A list of colors: red, blue, green, yellow, orange, purple, pink,'
tokenizer.pad_token = tokenizer.eos_token  # Most LLMs don't have a pad token by default
model_inputs = tokenizer(
    ["A list of colors: red, blue", "Portugal is"], return_tensors="pt", padding=True
).to("cuda")
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
['A list of colors: red, blue, green, yellow, orange, purple, pink,',
'Portugal is a country in southwestern Europe, on the Iber']

生成策略有很多,

生成结果太短或太长

如果在GenerationConfig文件中未指定,则默认情况下generate返回最多20个标记。建议在generate调用中手动设置max_new_tokens来控制它可以返回的最大新标记数。请注意,LLM(更精确地说是仅解码器模型)还将输入提示作为输出的一部分返回。

model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to("cuda")

# By default, the output will contain up to 20 tokens
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'A sequence of numbers: 1, 2, 3, 4, 5'

# Setting `max_new_tokens` allows you to control the maximum length
generated_ids = model.generate(**model_inputs, max_new_tokens=50)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,'

生成模式不正确

默认情况下,generate在每次迭代中选择最可能的标记(greedy decoding),除非在GenerationConfig文件中指定。

# Set seed or reproducibility -- you don't need this unless you want full reproducibility
from transformers import set_seed
set_seed(42)

model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to("cuda")

# LLM + greedy decoding = repetitive, boring output
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'I am a cat. I am a cat. I am a cat. I am a cat'

# With sampling, the output becomes more creative!
generated_ids = model.generate(**model_inputs, do_sample=True)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'I am a cat.  Specifically, I am an indoor-only cat.  I'

边缘填充错误

LLM是仅解码器架构,这意味着它们会继续对输入提示进行迭代。如果您的输入长度不相同,那么它们需要被填充。由于LLM没有被训练以从填充标记继续生成,因此输入需要进行左填充。确保还记得将注意力掩码传递给generate函数!

# The tokenizer initialized above has right-padding active by default: the 1st sequence,
# which is shorter, has padding on the right side. Generation fails to capture the logic.
model_inputs = tokenizer(
    ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt"
).to("cuda")
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'1, 2, 33333333333'

# With left-padding, it works as expected!
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left")
tokenizer.pad_token = tokenizer.eos_token  # Most LLMs don't have a pad token by default
model_inputs = tokenizer(
    ["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt"
).to("cuda")
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'1, 2, 3, 4, 5, 6,'

错误的prompt

一些模型和任务需要特定的输入提示格式才能正常工作。如果未使用该格式,性能可能会出现悄然下降:模型可以运行,但效果不如按照预期的提示进行操作。

tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha")
model = AutoModelForCausalLM.from_pretrained(
    "HuggingFaceH4/zephyr-7b-alpha", device_map="auto", load_in_4bit=True
)
set_seed(0)
prompt = """How many helicopters can a human eat in one sitting? Reply as a thug."""
model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
input_length = model_inputs.input_ids.shape[1]
generated_ids = model.generate(**model_inputs, max_new_tokens=20)
print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])
"I'm not a thug, but i can tell you that a human cannot eat"
# Oh no, it did not follow our instruction to reply as a thug! Let's see what happens when we write
# a better prompt and use the right template for this model (through `tokenizer.apply_chat_template`)

set_seed(0)
messages = [
    {
        "role": "system",
        "content": "You are a friendly chatbot who always responds in the style of a thug",
    },
    {"role": "user", "content": "How many helicopters can a human eat in one sitting?"},
]
model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to("cuda")
input_length = model_inputs.shape[1]
generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=20)
print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])
'None, you thug. How bout you try to focus on more useful questions?'
# As we can see, it followed a proper thug style 😎

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

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

相关文章

天软特色因子看板(2023.10 第14期)

该因子看板跟踪天软特色因子A05005(近一月单笔流通金额占比(%),该因子为近一个月单笔流通金额占比因子,用以刻画股票在收盘时,主力资金在总交易金额中所占的比重。 今日为该因子跟踪第14期,跟踪其在SW801160 (申万公用事业) 中的表…

go-gin-vue3-elementPlus带参手动上传文件

文章目录 一. 总体代码流程1.1 全局Axios部分样例1.2 上传业务 二. 后端部分三. 测试样例 go的mvc层使用gin框架. 总的来说gin的formFile封装的不如springboot的好.获取值有很多的坑. 当然使用axios的formData也有不少坑.现给出较好的解决办法 以下部分仅贴出关键代码 一. 总…

阅读PDF文档优选操作

这样就是左侧标题 右侧单页文章内容

4G物联模组产品

4G物联模组产品 文章目录 4G物联模组产品1.功能2.优势3.规格参数3.1.额定最大值3.2.尺寸规格 4.内部实物图5.产品功能说明5.1.通信功能5.2.GPS定位5.3.充放电管理5.4.告警和保护5.5.软件升级5.6.软件调测 6.通信协议6.1流程6.2.消息定义6.2.1.应用下发到云6.2.2.云下发到设备6.…

量化交易-应对市场闪崩

金融交易世界虽然提供了无与伦比的机会,但也并非没有陷阱。其中一个陷阱是闪崩现象,尤其是在算法交易领域。这些快速且常常无法解释的市场下跌可能会在几分钟内消除数十亿美元的价值。了解它们的起源、影响和预防策略对于参与算法交易的任何人都至关重要。本文深入研究了闪存…

0基础学习PyFlink——事件时间和运行时间的窗口

大纲 定制策略运行策略Reduce完整代码滑动窗口案例参考资料 在 《0基础学习PyFlink——时间滚动窗口(Tumbling Time Windows)》一文中,我们使用的是运行时间(Tumbling ProcessingTimeWindows)作为窗口的参考时间: reducedkeyed.window(TumblingProcess…

通过Xpath解析尝试多种方法提取文本

from lxml import etree# XML文档内容 xml_data <root><element attribute"value1">Text 1</element><element attribute"value2">Text 2</element><element attribute"value3">Text 3</element> &…

文件批量改名:字母随机重命名文件,高效又轻松

在日常工作中&#xff0c;我们经常需要处理大量的文件&#xff0c;其中最繁琐的任务之一就是给文件重命名。如果手动一个一个地重命名&#xff0c;不仅耗时而且容易出错。为了解决这个问题&#xff0c;我们可以使用云炫文件管理器批量改名&#xff0c;用字母随机重命名文件&…

猪八戒、程序员客栈、码市哪个更好用?

最近有很多程序员伙伴在用接单平台线上兼职&#xff0c;问题也来了&#xff1a;到底哪个更好用嘞? 选取了几个问的比较多的&#xff1a;猪八戒、程序员客栈、码市。进行了一下简单的比较。 优点: 猪八戒 第一&#xff0c;猪八戒的名气是毋庸置疑的。无论是它成立至今的时间…

【移远QuecPython】EC800M物联网开发板的GPIO流水灯配置

【移远QuecPython】EC800M物联网开发板的GPIO流水灯配置 文章目录 GPIO初始化GPIO配置GPIO流水灯附录&#xff1a;列表的赋值类型和py打包列表赋值BUG复现代码改进优化总结 py打包 GPIO初始化 GPIO库&#xff1a; from machine import Pin初始化函数&#xff1a; class mac…

数据结构笔记(一)绪论

&#x1f600;前言 本人是根据bi站王卓老师视频学习并且做了相关笔记希望可以帮助到大家 &#x1f3e0;个人主页&#xff1a;尘觉主页 &#x1f9d1;个人简介&#xff1a;大家好&#xff0c;我是尘觉&#xff0c;希望我的文章可以帮助到大家&#xff0c;您的满意是我的动力&a…

PHP 人才招聘管理系统mysql数据库web结构layUI布局apache计算机软件工程网页wamp

一、源码特点 PHP 人才招聘管理系统是一套完善的web设计系统 layUI技术布局 &#xff0c;对理解php编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。 php人才招聘管理系统 代码 https://download.csdn.net/download/qq_4…

Http代理与socks5代理有何区别?如何选择?(一)

了解SOCKS和HTTP代理之间的区别对于优化您的在线活动至关重要&#xff0c;无论您是技术娴熟的个人、现代互联网用户还是企业所有者。在使用代理IP时&#xff0c;您需要先了解这两种协议之间的不同。 一、了解HTTP代理 HTTP&#xff08;超文本传输协议&#xff09;代理专门设计…

RoCEv2网络部署----Mellanox网卡配置

Mellanox 网卡配置RoCEv2步骤&#xff0c; 1. 设置RDMA CM 模式v2 cma_roce_mode -d mlx5_1 -p 1 -m 2 检查RDMA CM的RoCE模式 2. 开启 DCQCN 在priority 3 echo 1 > /sys/class/net/ens1np0/ecn/roce_np/enable/3 echo 1 > /sys/class/net/ens1np0/ecn/roce_rp/enable…

实现右键出现菜单选项功能

文章目录 需求分析需求 实现鼠标右键显示菜单的功能 分析 分析该需求,流程如下 写一个 div 作为右键弹出的菜单选项——> 监听鼠标右键事件——> 得到坐标位置——> 在该位置对写好的 菜单选项 进行展示——> 选择完毕后关闭菜单——> 鼠标左键其他位置 点…

无需使用jadx-gui和mac电脑获取app备案公钥的方法

由于2023年&#xff0c;国家要求上架的app必须备案&#xff0c;因此app备案成为了很多公司迫切的需求。 备案的时候&#xff0c;需要填写app公钥&#xff0c;MD5值等参数&#xff0c;这些参数对于不熟悉加密技术的人来说&#xff0c;简直是无从下手&#xff0c;因为目前的开发…

王道408模拟8套卷(六)

紫色标记是认为有一定的思维难度或重点总结 红色标记是这次模拟做错的 橙色代表自己&#xff0c;对题目的看法和命题的失误之处 蓝色代表自己后续检查时检查出失误并改正的题 分数用时 选择部分 72/8045min25min大题部分40/70110min总分112155min25min&#xff08;检查&#x…

上班族如何做日程自律清单实现逆袭呢?电脑日程管理软件助力高效办公

越来越多的上班族都表示自己每天的工作任务非常多&#xff0c;经常从早忙到晚也无法按时完成工作&#xff0c;导致工作的拖延完成&#xff0c;这应该怎么办呢&#xff1f;其实对于职场人士来说&#xff0c;想要在工作中提升效率&#xff0c;就需要提前做好每天的工作日程安排&a…

概念解析 | 神经网络中的位置编码(Positional Encoding)

注1:本文系“概念解析”系列之一,致力于简洁清晰地解释、辨析复杂而专业的概念。本次辨析的概念是:Positional Encoding 神经网络中的位置编码(Positional Encoding) A Gentle Introduction to Positional Encoding in Transformer Models, Part 1 1.背景介绍 在自然语言处理任…

柯桥专升本学校,自考本科文凭的价值如何?

自考本科文凭的价值如何&#xff1f; 自考本科学历是通过独立学习和考试获得的一种本科学历。对于自考本科学历的价值&#xff0c;很多人感到困惑&#xff0c;那么究竟自考本科学历有多大的价值呢? 首先&#xff0c;在就业市场上&#xff0c;自考本科学历具有一定的竞争力。随…