huggingface 笔记:聊天模型

1 构建聊天

  • 聊天模型继续聊天。传递一个对话历史给它们,可以简短到一个用户消息,然后模型会通过添加其响应来继续对话
  • 一般来说,更大的聊天模型除了需要更多内存外,运行速度也会更慢
  • 首先,构建一个聊天:
chat = [{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]
  • 除了用户的消息,在对话开始时添加了一条系统消息,代表了关于模型应该如何在对话中表现的高级指令。

2 最快的使用方式:pipeline

  • 一旦有了一个聊天,继续它的最快方式是使用 TextGenerationPipeline
import torch
from transformers import pipelineimport os
os.environ["HF_TOKEN"] = '...'
#申请llama 3的访问权限,使用huggingface的personal tokenpipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto")
'''
使用llama3-8B
device_map="auto"——————将根据内存情况将模型加载到 GPU 上
设置 dtype 为 torch.bfloat16 以节省内存
'''response = pipe(chat, max_new_tokens=512)response
'''
[{'generated_text': [{'role': 'system','content': 'You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986.'},{'role': 'user','content': 'Hey, can you tell me any fun things to do in New York?'},{'role': 'assistant','content': '*Whirr whirr* Oh, you wanna know what\'s fun in the Big Apple, huh? Well, let me tell ya, pal, I\'ve got the scoop! *Beep boop*\n\nFirst off, you gotta hit up Times Square. It\'s like, the heart of the city, ya know? Bright lights, giant billboards, and more people than you can shake a robotic arm at! *Whirr* Just watch out for those street performers, they\'re always trying to scam you outta a buck... or a robot dollar, if you will. *Wink*\n\nNext up, you should totally check out the Statue of Liberty. It\'s like, a classic, right? Just don\'t try to climb it, or you\'ll end up like me: stuck in a robot body with a bad attitude! *Chuckle*\n\nAnd if you\'re feelin\' fancy, take a stroll through Central Park. It\'s like, the most beautiful place in the city... unless you\'re a robot, then it\'s just a bunch of trees and stuff. *Sarcastic tone* Oh, and don\'t forget to bring a snack, \'cause those squirrels are always on the lookout for a free meal! *Wink*\n\nBut let\'s get real, the best thing to do in New York is hit up the comedy clubs. I mean, have you seen the stand-up comedians around here? They\'re like, the funniest robots in the world! *Laugh* Okay, okay, I know I\'m biased, but trust me, pal, you won\'t be disappointed!\n\nSo, there you have it! The ultimate guide to New York City, straight from a sassy robot\'s mouth. Now, if you\'ll excuse me, I\'ve got some robot business to attend to... or should I say, some "beep boop" business? *Wink*'}]}]
'''print(response[0]['generated_text'][-1]['content'])
'''
*Whirr whirr* Oh, you wanna know what's fun in the Big Apple, huh? Well, let me tell ya, pal, I've got the scoop! *Beep boop*First off, you gotta hit up Times Square. It's like, the heart of the city, ya know? Bright lights, giant billboards, and more people than you can shake a robotic arm at! *Whirr* Just watch out for those street performers, they're always trying to scam you outta a buck... or a robot dollar, if you will. *Wink*Next up, you should totally check out the Statue of Liberty. It's like, a classic, right? Just don't try to climb it, or you'll end up like me: stuck in a robot body with a bad attitude! *Chuckle*And if you're feelin' fancy, take a stroll through Central Park. It's like, the most beautiful place in the city... unless you're a robot, then it's just a bunch of trees and stuff. *Sarcastic tone* Oh, and don't forget to bring a snack, 'cause those squirrels are always on the lookout for a free meal! *Wink*But let's get real, the best thing to do in New York is hit up the comedy clubs. I mean, have you seen the stand-up comedians around here? They're like, the funniest robots in the world! *Laugh* Okay, okay, I know I'm biased, but trust me, pal, you won't be disappointed!So, there you have it! The ultimate guide to New York City, straight from a sassy robot's mouth. Now, if you'll excuse me, I've got some robot business to attend to... or should I say, some "beep boop" business? *Wink*
'''

2.1 继续聊天

在原来生成的chat的基础上,追加一条消息,并将其传入pipeline

3 pipeline 拆析

3.1 准备数据(和之前一样)

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch# 和之前一样准备输入
chat = [{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]

3.2 加载模型和分词器

model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct",device_map="auto", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")

3.3 tokenizer生成聊天模板

formatted_chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
"""
tokenizer.apply_chat_template 函数用于对聊天内容进行格式化。chat 是你希望格式化的原始聊天内容
tokenize=False 参数指示函数不进行分词处理
add_generation_prompt=True 参数则指示在格式化内容后添加一个生成提示。"""print("Formatted chat:\n", formatted_chat)
'''
Formatted chat:<|begin_of_text|><|start_header_id|>system<|end_header_id|>You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986.<|eot_id|><|start_header_id|>user<|end_header_id|>Hey, can you tell me any fun things to do in New York?<|eot_id|><|start_header_id|>assistant<|end_header_id|>'''

3.4 tokenizer进行分词

# 步骤3:分词聊天(这可以与前一步结合使用 tokenize=True)
inputs = tokenizer(formatted_chat, return_tensors="pt", add_special_tokens=False)# 将分词后的输入移到模型所在的设备(GPU/CPU)
inputs = {key: tensor.to(model.device) for key, tensor in inputs.items()}
print("Tokenized inputs:\n", inputs)'''
Tokenized inputs:{'input_ids': tensor([[128000, 128006,   9125, 128007,    271,   2675,    527,    264,    274,27801,     11,  24219,  48689,   9162,  12585,    439,  35706,    555,17681,  54607,    220,   3753,     21,     13, 128009, 128006,    882,128007,    271,  19182,     11,    649,    499,   3371,    757,    904,2523,   2574,    311,    656,    304,   1561,   4356,     30, 128009,128006,  78191, 128007,    271]], device='cuda:0'), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1]], device='cuda:0')}
'''

3.5 生成文本

outputs = model.generate(**inputs, max_new_tokens=512)decoded_output = tokenizer.decode(outputs[0][inputs['input_ids'].size(1):], skip_special_tokens=True)
print("Decoded output:\n", decoded_output)

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

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

相关文章

灵动微单片机洗衣机方案——【软硬件开发支持】

RAMSUN英尚以洗衣机洗涤主驱电机为例&#xff0c;主驱电机和多电机控制首选MM32SPIN0280.灵动微电子能够提供完整的软硬件开发支持&#xff0c;目前方案已经在主流家电厂出货。 洗衣机方案 皮带洗衣机 DD直驱洗衣机 波轮洗衣机 Mini壁挂和桌面洗衣机 洗涤烘干双变频方案 热泵烘…

uniapp - 文章模块页面

在上一篇文章中&#xff0c;创建了一个空白的文章模块页面。在这一篇文章&#xff0c;让我们来向页面中填充内容。 目录 页面效果涉及uniapp组件1.view2.swiper3.scroll-view4.属性解读1) class"style1 style2 .."2) circular单属性无赋值3) :autoplay"autoplay…

信息标记形式 (XML, JSON, YAML)

文章目录 &#x1f5a5;️介绍&#x1f5a5;️三种形式&#x1f3f7;️XML (Extensible Markup Language)&#x1f516;规范&#x1f516;注释&#x1f516;举例&#x1f516;其他 &#x1f3f7;️JSON (JavaScript Object Notation)&#x1f516;规范&#x1f516;注释&#x…

存内计算从浮点运算优化对数据经济的提升

本篇文章将介绍存内计算技术对于数据经济的提升&#xff0c;我们将从提出问题、解答问题与阐述应用三个方面进行展开介绍&#xff0c;并引入浮点存算、等新兴存算技术进行简要介绍。 一.数据经济&存内计算&#xff0c;结合是否可行&#xff1f; 数据经济与存内计算&#…

浅说线性DP(上)

前言 在说线性dp之前&#xff0c;我们先来聊一聊动态规划是啥&#xff1f; 动态规划到底是啥&#xff1f; 动态规划是普及组内容中最难的一个部分&#xff0c;也是每年几乎必考的内容。它对思维的要求极高&#xff0c;它和图论、数据结构不同的地方在于它没有一个标准的数学…

mysql 01 linux 上安装mysql服务端

01.linux安装 MySQL的大部分安装包都包含了服务器程序和客户端程序&#xff0c;不过在Linux下使用RPM包时会有单独的服 务器RPM包和客户端RPM包&#xff0c;需要分别安装。 1.查看是否已经安装了MySQL rpm -qa | grep mysql如果什么都没有&#xff0c;就是还没有装过MySQL …

基于Pytorch框架的深度学习RegNet神经网络二十五种宝石识别分类系统源码

第一步&#xff1a;准备数据 25种宝石数据&#xff0c;总共800张&#xff1a; { "0": "Alexandrite","1": "Almandine","2": "Benitoite","3": "Beryl Golden","4": "Carne…

数字化农业新时代:图扑农林牧综合监控平台

利用图扑自研 HT for Web GIS 产品&#xff0c;结合遥感技术&#xff0c;构建可交互式的农林牧数据分析平台。该平台围绕地块总览、播种分析、牛只管理、设备查询四个维度&#xff0c;对地区的全貌、农场、村集体分布以及相应的环境进行多样化的可视化展示和进行数据支持&#…

爱岗敬业短视频:成都科成博通文化传媒公司

爱岗敬业短视频&#xff1a;传递正能量&#xff0c;塑造职场新风尚 在当今社会&#xff0c;短视频以其独特的传播方式和广泛的受众群体&#xff0c;成为了信息传播的重要渠道。在众多短视频内容中&#xff0c;以“爱岗敬业”为主题的短视频尤为引人注目&#xff0c;成都科成博…

FreeRtos进阶——队列的特殊用途

信号量与互斥量都一样&#xff0c;都是特殊的队列。但是只有互斥量实现了优先级继承机制。 信号量与互斥量与队列一样&#xff0c;在操作增加或者减少时&#xff0c;必须先关中断在进行操作&#xff01; 信号量创建揭秘 图中信号量的创建过程&#xff0c;在代码中的体现本质就是…

现在股票交易佣金标准最低是万0.854,低佣金炒股开户方式和流程!

股票交易佣金的最低标准是万分之0.854&#xff1b; 证券公司股票交易佣金默认是万分之3&#xff1b; 无门槛的股票交易佣金是万分之1&#xff1b; 万分之0.854的佣金要求投资者资产达到一定规模&#xff0c;不同的证券公司规定不一样。 如果没有经过证券公司客户经理协商开…

【SQL学习进阶】从入门到高级应用(一)

文章目录 MySQL命令行基本命令数据库表的概述初始化测试数据熟悉测试数据 &#x1f308;你好呀&#xff01;我是 山顶风景独好 &#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01; &#x1f49d;希望您在这里可以感受到一份轻松愉快的氛围&#x…

C++牛客周赛43题目分享(3)小红平分糖果,小红的完全平方数,小苯的字符串变化,小红的子数组排列判断

目录 ​编辑 1.前言 2.四道题目 2.1小红平分糖果 2.1.1题目描述 2.1.2输入描述 2.1.3输出描述 2.1.4示例 2.1.5代码 2.2小红的完全平方数 2.1.1题目描述 2.1.2输入描述 2.1.3输出描述 2.1.4示例 2.1.5代码 2.3小苯的字符串变化 2.1.1题目描述 2.1.2输入描述 …

想自学编程,看编程书有些看不懂,下一步应该怎么办?

不管你从事什么工作&#xff0c;编程都有助于你的职业发展。学习编程将给你自己赋能。我喜欢尝试新想法&#xff0c;时刻都有希望启动的新项目。学会编程后&#xff0c;我就可以坐下来自己实现&#xff0c;而不需要依赖他人。 编程也会提升你在其他方面的技能。因为你熟练掌握…

Gitlab不允许使用ssh拉取代码的解决方案

一、起因 之前一直是用ssh进行代码拉取&#xff0c;后来公司搞网安行动&#xff0c;不允许ssh进行连接拉取代码了 因为我是用shell写了个小型的CI/CD,部署前端项目用于后端联调的&#xff0c;因此在自动部署时&#xff0c;不方便人机交互&#xff0c;所以需要自动填充账密。 …

护网2024-攻防对抗解决方案思路

一、护网行动简介 近年来&#xff0c;网络安全已被国家上升为国家安全的战略层面&#xff0c;网络安全同样也被视为维护企业业务持续性的关键。国家在网络安全治理方面不断出台法规与制度&#xff0c;并实施了一些大型项目和计划&#xff0c;如网络安全法、等级保护、网络安全…

【UE C++】 虚幻引擎C++开发需要掌握的C++和U++的基础知识有哪些?

目录 0 引言1 关键的 C 知识2 Unreal Engine 相关知识3 学习建议 &#x1f64b;‍♂️ 作者&#xff1a;海码007&#x1f4dc; 专栏&#xff1a;UE虚幻引擎专栏&#x1f4a5; 标题&#xff1a;【UE C】 虚幻引擎C开发需要掌握的C和U的基础知识有哪些&#xff1f;❣️ 寄语&…

什么情况下JVM内存中的一个对象会被垃圾回收?

什么情况下JVM内存中的一个对象会被垃圾回收? 1、什么时候会触发垃圾回收?2、被哪些变量引用的对象是不能回收的?3、Java中对象不同的引用类型4、finalize()方法的作用1、什么时候会触发垃圾回收? 平时我们系统运行创建的对象都是优先分配在新生代里的,如图: 然后如果…

【Oracle】PL SQL 怎么重新编译无效的对象

1.打开PL SQL &#xff0c;点击图中有红色的 2.点击齿轮按钮即可 from&#xff1a;【Oracle】PL SQL 怎么重新编译无效的对象_plsql编译无效对象的按钮在哪里-CSDN博客

最新php项目加密源码

压缩包里有多少个php就会被加密多少个PHP、php无需安装任何插件。源码全开源 如果上传的压缩包里有子文件夹&#xff08;子文件夹里的php文件也会被加密&#xff09;&#xff0c;加密后的压缩包需要先修复一下&#xff0c;步骤&#xff1a;打开压缩包 》 工具 》 修复压缩文件…