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壁挂和桌面洗衣机 洗涤烘干双变频方案 热泵烘…

python前端通过API接口调用与后端进行数据交互前端如何调用api接口通过关键词获取电商平台热销商品数据

要在Python前端通过API接口调用与后端进行数据交互并通过关键词获取电商平台热销商品数据&#xff0c;可以通过封装好的api接口通过链接直接请求获取数据&#xff0c;以下是接入api的请求示例&#xff1a; # coding:utf-8 """ Compatible for python2.x and py…

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…

游戏行业如何利用隐私计算技术增强玩家体验

PrimiHub一款由密码学专家团队打造的开源隐私计算平台&#xff0c;专注于分享数据安全、密码学、联邦学习、同态加密等隐私计算领域的技术和内容。 在游戏行业&#xff0c;玩家体验的个性化是提升用户粘性和满意度的关键。随着技术的发展&#xff0c;游戏公司现在可以利用大量的…

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

本篇文章将介绍存内计算技术对于数据经济的提升&#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 …

Vue3记录校验工具类:validata.ts

在vue文件使用&#xff1a; import { validateNull } from //utils/validata; validateNull(需要校验的数据)validata.ts文件&#xff1a; /*** 判断是否为空* param val 数据*/ export const validateNull (val: any) > {if (typeof val boolean) {return false;}if (t…

C++核心编程——4.7 多态

4.7.1 多态的基本概念 多态是C面向对象三大特性之一 多态表示提供一个公共的函数接口&#xff0c;当传入不同参数对象时&#xff0c;执行不同的函数实现。 语法 virtual 返回值类型 函数名() {} 分类 静态多态 动态多态&#xff08;加“virtual“&#xff09; 函数重载 和 …

基于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;成都科成博…

js Ajax函数封装及使用

直接上代码 一、ajax函数封装 /*** ajax函数* param {Object} options 请求传入的对象参数*/ function ajax(options {}) {// 1. 参数校验// 校验请求地址必传,而只能是字符串类型if (!options.url || typeof (options.url) ! string) throw Error(url必传,只能是字符串);//…

每天发布1000个视频SOP之账号管理:抖音可用的上传管理账号的浏览器安装包23个

企业抖音运营&#xff1a; 全流程整套操作SOP&#xff0c; 每天发布1000个视频工作管理体系&#xff1a; &#xff08;因为上传限制&#xff0c;分成3个压缩包资源上传&#xff09; 这是其中的&#xff1a;SOP矩阵划管理登录抖音平台账号&#xff0c;上传管理运营账号&#…

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

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

设计模式 16 解释器模式 Interpreter Design Pattern

设计模式 16 解释器模式 Interpreter Design Pattern 1.定义 解释器模式 (Interpreter Design Pattern) 是一种行为型设计模式&#xff0c;它定义了一种语法表示&#xff0c;并提供了一种解释器来解释该语法表示的句子。 核心概念&#xff1a; 语法表示 (Grammar): 定义了…

如何使用 jQuery 库来删除 HTML 页面中指定的元素下的所有子元素,但是保留其中一个特定的子元素

如何使用 jQuery 库来删除 HTML 页面中指定的元素下的所有子元素&#xff0c;但是保留其中一个特定的子元素 示例如下&#xff1a; 假设我们有以下的 HTML 代码&#xff1a; <div id"container"><div id"header">Header</div><div…

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

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

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

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