huggingface 笔记:聊天模型

news2024/10/6 10:30:28

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 pipeline

import os
os.environ["HF_TOKEN"] = '...'
#申请llama 3的访问权限,使用huggingface的personal token


pipe = 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.coloradmin.cn/o/1707592.html

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

相关文章

企业文件加密实现数据泄露防护

在数字化时代&#xff0c;数据成为企业最宝贵的资产之一。然而&#xff0c;数据泄露事件频发&#xff0c;给企业带来了巨大的经济损失和声誉风险。为了保护企业的核心利益&#xff0c;实现数据泄露防护&#xff0c;企业必须采取有效的文件加密措施。 一、数据泄露的严重性 数据…

基于STM32实现智能交通灯控制系统

目录 引言环境准备智能交通灯控制系统基础代码示例&#xff1a;实现智能交通灯控制系统 GPIO控制交通灯定时器配置与使用红外传感器检测车辆用户界面与显示应用场景&#xff1a;城市交通管理与自动化控制问题解决方案与优化收尾与总结 1. 引言 本教程将详细介绍如何在STM32嵌…

汽车大灯中擎耀智能控制器在车灯智能化配置下的创新与分析

随着科技的飞速发展&#xff0c;汽车工业也在不断地进行着革新。其中&#xff0c;车灯作为汽车的重要组成部分&#xff0c;其智能化配置已经成为汽车行业的一大趋势。这种趋势不仅为消费者带来了更加安全、便捷的驾驶体验&#xff0c;同时也为商家提供了丰富的商业机会。汽车工…

JS中运算符详解

一&#xff1a;赋值运算符 1 类型 、、-、*、/等 2 如何运行 &#xff0c;是将等号右边的数赋值给左边以为例&#xff0c;let num 5&#xff1b;num2等价于numnum2 二&#xff1a;一元运算符 1 自增运算符 什么是一元运算符 只需要一个操作数就可以运算的运算符 &#x…

开源数据库同步工具DBSyncer

前言&#xff1a; 这么实用的工具&#xff0c;竟然今天才发现&#xff0c;相见恨晚呀&#xff01;&#xff01;&#xff01;&#xff01; DBSyncer&#xff08;英[dbsɪŋkɜː]&#xff0c;美[dbsɪŋkɜː 简称dbs&#xff09;是一款开源的数据同步中间件&#xff0c;提供M…

解读vue3源码-1

提示&#xff1a;看到我 请让滚去学习 vue3渲染流程 文章目录 vue3渲染流程vue3的3个核心&#xff1a;1.响应式模块(Reactivity Module)--创建响应式数据2.编译模块(Compiler Module)--模版编译器将html转换为一个渲染函数3.渲染模块(Renderer Module) 渲染流程&#xff1a;1.首…

【御控工业物联网】 Java JSON结构转换、JSON结构重构、JSON结构互换(17):数组To对象——键值互换属性重组

文章目录 一、JSON结构转换是什么&#xff1f;二、核心构件之转换映射三、案例之《JSON数组 To JSON对象》四、代码实现五、在线转换工具六、技术资料 一、JSON结构转换是什么&#xff1f; JSON结构转换指的是将一个JSON对象或JSON数组按照一定规则进行重组、筛选、映射或转换…

2024第三届AIGC开发者大会圆桌论坛:AI Agent中国落地发展现状及多模态结合具身智能的发展展望

在2024年第三届AIGC开发者大会上&#xff0c;多位业内专家齐聚一堂&#xff0c;共同探讨了AI Agent在中国的落地发展现状以及多模态结合具身智能的发展前景。本次圆桌论坛的嘉宾包括&#xff1a; Fast JP作者于金龙Agent创始人莫西莫必胜作者秦瑞January Agent创始人李晨 多模…

JavaEE:Servlet创建和使用及生命周期介绍

目录 ▐ Servlet概述 ▐ Servlet的创建和使用 ▐ Servlet中方法介绍 ▐ Servlet的生命周期 ▐ Servlet概述 • Servlet是Server Applet的简称&#xff0c;意思是 用Java编写的服务器端的程序&#xff0c;Servlet被部署在服务器中&#xff0c;而服务器负责管理并调用Servle…

【第5章】SpringBoot整合Druid

文章目录 前言一、启动器二、配置1.JDBC 配置2.连接池配置3. 监控配置 三、配置多数据源1. 添加配置2. 创建数据源 四、配置 Filter1. 配置Filter2. 可配置的Filter 五、获取 Druid 的监控数据六、案例1. 问题2. 引入库3. 配置4. 配置类5. 测试类6. 测试结果 七、案例 ( 推荐 )…

vivo X100 Ultra自称销售额破5亿,真实销量成谜?

文/张诗雨 5月28日9点&#xff0c;vivo 正式启动了其旗舰新机vivo X100 Ultra的全渠道销售工作。这款新机&#xff0c;早在5月13日就已正式亮相&#xff0c;并推出了三种存储容量的版本&#xff0c;分别是12GB256GB、16GB512GB以及16GB1TB&#xff0c;而相应的售价也不低&…

短道速滑短视频:四川京之华锦信息技术公司

短道速滑短视频&#xff1a;冰雪激情的视觉盛宴 随着冬奥会的热度不断攀升&#xff0c;短道速滑作为其中一项紧张刺激、充满观赏性的运动&#xff0c;受到了越来越多人的关注。而在社交媒体和短视频平台的助力下&#xff0c;短道速滑短视频成为了人们了解、欣赏这项运动的新窗…

vxe-form-design 表单设计器的使用

vxe-form-design 在 vue3 中表单设计器的使用 查看官网 https://vxeui.com 安装 npm install vxe-pc-ui // ... import VxeUI from vxe-pc-ui import vxe-pc-ui/lib/style.css // ...// ... createApp(App).use(VxeUI).mount(#app) // ...使用 github vxe-form-design 用…

Linux软硬链接详解

软链接&#xff1a; ln -s file1 file2//file1为目标文件&#xff0c;file2为软链接文件 演示&#xff1a; 从上图可以得出&#xff1a; 软链接本质不是同一个文件&#xff0c;因为inode不同。 作用&#xff1a; 软连接就像是Windows里的快捷方式&#xff0c;里面存放的是目标…

Llama模型家族训练奖励模型Reward Model技术及代码实战(二)从用户反馈构建比较数据集

LlaMA 3 系列博客 基于 LlaMA 3 LangGraph 在windows本地部署大模型 &#xff08;一&#xff09; 基于 LlaMA 3 LangGraph 在windows本地部署大模型 &#xff08;二&#xff09; 基于 LlaMA 3 LangGraph 在windows本地部署大模型 &#xff08;三&#xff09; 基于 LlaMA…

DES加密算法笔记

【DES加密算法&#xff5c;密码学&#xff5c;信息安全】https://www.bilibili.com/video/BV1KQ4y127AT?vd_source7ad69e0c2be65c96d9584e19b0202113 根据此视频学习 DES是对称密码中的分组加密算法 (分组加密对应流加密算法) 流加密算法就是一个字节一个字节加密 分组加…

Mybatis枚举类型转换

Mybatis枚举类型转换 类型转换器源码分析 在Mybatis的TypeHandlerRegistry中&#xff0c;添加了常用的类转换器&#xff0c;其中默认的枚举类型转换器是EnumTypeHandler。 public final class TypeHandlerRegistry {....public TypeHandlerRegistry(Configuration configura…

第 8 章 机器人平台设计之传感器(自学二刷笔记)

重要参考&#xff1a; 课程链接:https://www.bilibili.com/video/BV1Ci4y1L7ZZ 讲义链接:Introduction Autolabor-ROS机器人入门课程《ROS理论与实践》零基础教程 8.6.1 传感器_激光雷达简介 激光雷达是现今机器人尤其是无人车领域及最重要、最关键也是最常见的传感器之一&…

opencv c++编程基础

1、图片的本质 图像在 OpenCV 中的本质 在 OpenCV 中&#xff0c;图像被表示为一个多维数组&#xff0c;其中每个元素对应于图像中的单个像素。图像的维度取决于其通道数和像素数。 **通道数&#xff1a;**图像可以有多个通道&#xff0c;每个通道存储图像的不同信息。例如&…

RabbitMQ 发布订阅

RabbitMQ 发布订阅视频学习地址&#xff1a; 简单模式下RabbitMQ 发布者发布消息 消费者消费消息 Publist/Subscribe 发布订阅 在 RabbitMQ 中&#xff0c;发布订阅模式是一种消息传递方式&#xff0c;其中发送者&#xff08;发布者&#xff09;不会将消息直接发送到特 定的…