[大模型] BlueLM-7B-Chat WebDemo 部署

news2025/5/31 15:25:05

BlueLM-7B-Chat WebDemo 部署

模型介绍

BlueLM-7B 是由 vivo AI 全球研究院自主研发的大规模预训练语言模型,参数规模为 70 亿。BlueLM-7B 在 C-Eval 和 CMMLU 上均取得领先结果,对比同尺寸开源模型中具有较强的竞争力(截止11月1号)。本次发布共包含 7B 模型的 Base 和 Chat 两个版本。

模型下载链接见:

基座模型对齐模型
🤗 BlueLM-7B-Base🤗 BlueLM-7B-Chat
🤗 BlueLM-7B-Base-32K🤗 BlueLM-7B-Chat-32K
🤗 BlueLM-7B-Chat-4bits

环境准备

在 autodl 平台中租赁一个 3090 等 24G 显存的显卡机器,如下图所示镜像选择 PyTorch–>1.11.0–>3.8(ubuntu20.04)–>11.3,Cuda版本在11.3以上都可以。

在这里插入图片描述

接下来打开刚刚租用服务器的 JupyterLab(也可以使用vscode ssh远程连接服务器),并且打开其中的终端开始环境配置、模型下载和运行 demo。

pip 换源加速下载并安装依赖包

# 升级pip
python -m pip install --upgrade pip
# 设置pip镜像源
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 安装软件依赖
pip install modelscope==1.11.0
pip install transformers==4.37.0
pip install streamlit==1.24.0
pip install sentencepiece==0.1.99
pip install accelerate==0.24.1
pip install transformers_stream_generator==0.0.4

模型下载

使用Modelscope API 下载BlueLM-7B-Chat模型,模型路径为/root/autodl-tmp。在 /root/autodl-tmp 下创建model_download.py文件内容如下:

from modelscope import snapshot_download
model_dir = snapshot_download("vivo-ai/BlueLM-7B-Chat", cache_dir='/root/autodl-tmp', revision="master")

代码准备

/root/autodl-tmp路径下新建 chatBot.py 文件并在其中输入以下内容:

# 导入所需的库
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, TextStreamer
import torch
import streamlit as st

# 在侧边栏中创建一个标题和一个链接
with st.sidebar:
    st.markdown("## BlueLM-7B-Chat")
    "[开源大模型食用指南 self-llm](https://github.com/datawhalechina/self-llm.git)"
    # 创建一个滑块,用于选择最大长度,范围在0到1024之间,默认值为512
    max_length = st.slider("max_length", 0, 1024, 512, step=1)

# 创建一个标题和一个副标题
st.title("💬 BlueLM Chatbot")
st.caption("🚀 A streamlit chatbot powered by Self-LLM")

# 定义模型路径
mode_name_or_path = '/root/autodl-tvivo-ai/BlueLM-7B-Chat'

# 定义一个函数,用于获取模型和tokenizer
@st.cache_resource
def get_model():
    # 从预训练的模型中获取tokenizer
    tokenizer = AutoTokenizer.from_pretrained(mode_name_or_path, trust_remote_code=True)
    # 从预训练的模型中获取模型,并设置模型参数
    model = AutoModelForCausalLM.from_pretrained(mode_name_or_path, trust_remote_code=True,torch_dtype=torch.bfloat16,  device_map="auto")
    # 从预训练的模型中获取生成配置
    model.generation_config = GenerationConfig.from_pretrained(mode_name_or_path)
    # 设置生成配置的pad_token_id为生成配置的eos_token_id
    model.generation_config.pad_token_id = model.generation_config.eos_token_id
    # 设置模型为评估模式
    model.eval()  
    return tokenizer, model

# 加载BlueLM的model和tokenizer
tokenizer, model = get_model()

def build_prompt(messages, prompt):
    """
    构建会话提示信息。

    参数:
    messages - 包含会话历史的元组列表,每个元组是(用户查询,AI响应)。
    prompt - 当前用户输入的文本。

    返回值:
    res - 构建好的包含会话历史和当前用户提示的字符串。
    """
    res = ""
    # 遍历历史消息,构建会话历史字符串
    for query, response in messages:
        res += f"[|Human|]:{query}[|AI|]:{response}</s>"
    # 添加当前用户提示
    res += f"[|Human|]:{prompt}[|AI|]:"
    return res


class BlueLMStreamer(TextStreamer):
    """
    BlueLM流式处理类,用于处理模型的输入输出流。

    参数:
    tokenizer - 用于分词和反分词的tokenizer实例。
    """
    def __init__(self, tokenizer: "AutoTokenizer"):
        self.tokenizer = tokenizer
        self.tokenIds = []
        self.prompt = ""
        self.response = ""
        self.first = True

    def put(self, value):
        """
        添加token id到流中。

        参数:
        value - 要添加的token id。
        """
        if self.first:
            self.first = False
            return
        self.tokenIds.append(value.item())
        # 将token ids解码为文本
        text = tokenizer.decode(self.tokenIds, skip_special_tokens=True)

    def end(self):
        """
        结束流处理,将当前流中的文本作为响应,并重置流状态。
        """
        self.first = True
        # 将token ids解码为文本
        text = tokenizer.decode(self.tokenIds, skip_special_tokens=True)
        self.response = text
        self.tokenIds = []



# 初始化session状态,如果messages不存在则初始化为空,并添加欢迎信息
if "messages" not in st.session_state:
    st.session_state.messages = []
    st.session_state.messages.append(("", "你好,有什么可以帮助你吗?"))


# 遍历并显示历史消息
for msg in st.session_state.messages:
    st.chat_message("assistant").write(msg[1])


# 处理用户输入
if prompt_text := st.chat_input():
    prompt_text = prompt_text.strip()
    st.chat_message("user").write(prompt_text)
    messages = st.session_state.messages
    # 使用BlueLMStreamer处理流式模型输入
    streamer = BlueLMStreamer(tokenizer=tokenizer)
    # 构建当前会话的提示信息
    prompt = build_prompt(messages=messages, prompt=prompt_text)
    # 将提示信息编码为模型输入
    inputs_tensor = tokenizer(prompt, return_tensors="pt")
    inputs_tensor = inputs_tensor.to("cuda:0")
    input_ids = inputs_tensor["input_ids"]
    # 通过模型生成响应
    outputs = model.generate(input_ids=input_ids, max_new_tokens=max_length, streamer=streamer)
    # 将模型的响应显示给用户
    st.chat_message("assistant").write(streamer.response)
    # 更新会话历史
    st.session_state.messages.append((prompt_text, streamer.response))

运行 demo

在终端中运行以下命令,启动streamlit服务,并按照 autodl 的指示将端口映射到本地,然后在浏览器中打开链接 http://localhost:6006/ ,即可看到聊天界面。

streamlit run /root/autodl-tmp/chatBot.py --server.address 127.0.0.1 --server.port 6006

如下所示:

在这里插入图片描述

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

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

相关文章

Golang | Leetcode Golang题解之第25题K个一组翻转链表

题目&#xff1a; 题解&#xff1a; func reverseKGroup(head *ListNode, k int) *ListNode {hair : &ListNode{Next: head}pre : hairfor head ! nil {tail : prefor i : 0; i < k; i {tail tail.Nextif tail nil {return hair.Next}}nex : tail.Nexthead, tail my…

微信小程序兼容iphone适配安全区域

背景&#xff1a; 小程序页面底部在ios中会有小黑条遮挡 上代码&#xff1a; padding-bottom: constant(safe-area-inset-bottom); /* 兼容 iOS < 11.2 */ padding-bottom: env(safe-area-inset-bottom); /* 兼容 iOS > 11.2 */ 项目描述&#xff1a; 微信小程序是通过…

DonkeyDocker-v1-0渗透思路

MY_BLOG https://xyaxxya.github.io/2024/04/13/DonkeyDocker-v1-0%E6%B8%97%E9%80%8F%E6%80%9D%E8%B7%AF/ date: 2024-04-13 19:15:10 tags: 内网渗透Dockerfile categories: 内网渗透vulnhub 靶机下载地址 https://www.vulnhub.com/entry/donkeydocker-1,189/ 靶机IP&a…

补充continue,break

一&#xff0c;continue 该关键字用于立即跳出本次循环&#xff0c;继续下一次循环 二&#xff0c;break 退出循环&#xff0c;不再执行

gma 2.0.8 (2024.04.12) 更新日志

安装 gma 2.0.8 pip install gma2.0.8网盘下载&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1P0nmZUPMJaPEmYgixoL2QQ?pwd1pc8 提取码&#xff1a;1pc8 注意&#xff1a;此版本没有Linux版&#xff01; 编译gma的Linux虚拟机没有时间修复&#xff0c;本期Linux版继…

Redis入门到通关之String命令

文章目录 ⛄1 String 介绍⛄2 命令⛄3 对应 RedisTemplate API❄️❄️ 3.1 添加缓存❄️❄️ 3.2 设置过期时间(单独设置)❄️❄️ 3.3 获取缓存值❄️❄️ 3.4 删除key❄️❄️ 3.5 顺序递增❄️❄️ 3.6 顺序递减 ⛄4 以下是一些常用的API⛄5 应用场景 ⛄1 String 介绍 Stri…

康耐视visionpro-CogCaliperTool操作工具详细说明

CogCaliperTool]功能说明:卡尺工具,用于测量距离 ◆CogCaliperTool操作说明: ①.打开工具栏,双击或点击鼠标拖拽添加CogCaliperTool ②.添加输入图像,右键“链接到”或以连线拖拽的方式选择相应输入源 ③.拖动屏幕上的矩形框到需要测量的位置。卡尺的搜索框角度与边缘不…

学习基于pytorch的VGG图像分类 day5

注&#xff1a;本系列博客在于汇总CSDN的精华帖&#xff0c;类似自用笔记&#xff0c;不做学习交流&#xff0c;方便以后的复习回顾&#xff0c;博文中的引用都注明出处&#xff0c;并点赞收藏原博主. 目录 VGG的数据集处理 1.数据的分类 2.对数据集的处理 VGG的分类标签设置 …

C++从入门到精通——类和对象(下篇)

1. 再谈构造函数 1.1 构造函数体赋值 在创建对象时&#xff0c;编译器通过调用构造函数&#xff0c;给对象中各个成员变量一个合适的初始值。 class Date { public:Date(int year, int month, int day){_year year;_month month;_day day;} private:int _year;int _mont…

SpringBoot项目如何国际化操作,让你可以随意切换语言

1.前言 最近接触的项目需要中文/英文或者其他国家语言的切换&#xff0c;在后台的时候有一个选择&#xff0c;你可以选择中文还是英文&#xff0c;或者其他语言&#xff0c;选择完毕界面语言就都变了&#xff0c;咱不知道前端怎么操作的&#xff0c;但是后台在处理提示语的时候…

matplotlib画圆

参考博客&#xff1a; https://zhuanlan.zhihu.com/p/658373265 实现1 import matplotlib.pyplot as plt import numpy as np# 设置圆的半径和圆心坐标 radius 1.0 x_center, y_center 0, 0# 生成圆的点 theta np.linspace(0, 2*np.pi, 100) x radius * np.cos(theta) x…

JavaScript中的Blob、Buffer、ArrayBuffer和TypedArray详解

文章的更新路线&#xff1a;JavaScript基础知识-Vue2基础知识-Vue3基础知识-TypeScript基础知识-网络基础知识-浏览器基础知识-项目优化知识-项目实战经验-前端温习题&#xff08;HTML基础知识和CSS基础知识已经更新完毕&#xff09; 正文 摘要&#xff1a;本文详细介绍了JavaS…

基于PyTorch神经网络进行温度预测——基于jupyter实现

导入环境 import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.optim as optim import warnings warnings.filterwarnings("ignore") %matplotlib inline读取文件 ### 读取数据文件 features pd.read_csv(temps.…

蓝桥杯-数组分割

问题描述 小蓝有一个长度为 N 的数组 A 「Ao,A1,…,A~-1]。现在小蓝想要从 A 对应的数组下标所构成的集合I 0,1,2,… N-1 中找出一个子集 民1&#xff0c;那么 民」在I中的补集为Rz。记S∑reR 4&#xff0c;S2∑rERA,&#xff0c;我们要求S、和 S,均为偶数&#xff0c;请问在这…

如何访问远程服务器?

在现代技术时代&#xff0c;随着信息化的快速发展&#xff0c;远程访问服务器已经成为了不可或缺的一种需求。无论是企业还是个人用户&#xff0c;都需要通过远程访问来管理、传输和获取数据。本文将介绍一种名为【天联】的工具&#xff0c;它能够通过私有通道进行远程服务器访…

iptables/ebtables学习笔记

目录 一、前言 二、Netfilter 构成 三、Netfilter 转发框架 四、Netfilter 与 iptables 五、Netfilter 与 ebtables 一、前言 Netfilter 是 Linux 内核的数据包处理框架&#xff0c;由 Rusty Russell 于 1998 年开发&#xff0c; 旨在改进以前的 ipchains&#xff08;Lin…

【排序 贪心】3107. 使数组中位数等于 K 的最少操作数

算法可以发掘本质&#xff0c;如&#xff1a; 一&#xff0c;若干师傅和徒弟互有好感&#xff0c;有好感的师徒可以结对学习。师傅和徒弟都只能参加一个对子。如何让对子最多。 二&#xff0c;有无限多1X2和2X1的骨牌&#xff0c;某个棋盘若干格子坏了&#xff0c;如何在没有坏…

centos编译安装nginx1.24

nginx编译1.24&#xff0c;先下载安装包 机器通外网的话配置nginx的yum源直接yum安装 vim /etc/yum.repos.d/nginx.repo [nginx-stable] namenginx stable repo baseurlhttp://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck1 enabled1 gpgkeyhttps://nginx.org…

前端实现自动获取农历日期:探索JavaScript的跨文化编程

&#x1f31f; 前言 欢迎来到我的技术小宇宙&#xff01;&#x1f30c; 这里不仅是我记录技术点滴的后花园&#xff0c;也是我分享学习心得和项目经验的乐园。&#x1f4da; 无论你是技术小白还是资深大牛&#xff0c;这里总有一些内容能触动你的好奇心。&#x1f50d; &#x…

嵌入式学习52-ARM1

知识零散&#xff1a; 1.flash&#xff1a; nor flash 可被寻地址 …