ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

BlueLM-7B-Chat WebDemo 部署指南:基于 Streamlit 构建可交互聊天界面(self-llm 实战)

BlueLM-7B-Chat WebDemo 部署指南:基于 Streamlit 构建可交互聊天界面(self-llm 实战) BlueLM-7B-Chat WebDemo 部署指南基于 Streamlit 构建可交互聊天界面self-llm 实战【免费下载链接】self-llm《开源大模型食用指南》针对中国宝宝量身打造的基于Linux环境快速微调全参数/Lora、部署国内外开源大模型LLM/多模态大模型MLLM教程项目地址: https://gitcode.com/datawhalechina/self-llm本篇技术指南以 BlueLM-7B-Chat WebDemo 部署 文档为主体完整讲解如何在 Linux 单卡 24G 显存环境下基于 Hugging Face Transformers 与 Streamlit 将 vivo 蓝心大模型 BlueLM-7B-Chat 部署为带流式输出、多轮记忆的网页聊天应用。读完本文你将掌握镜像环境准备、ModelScope 模型下载、chatBot.py逐模块实现原理对话模板拼接、流式生成器、会话状态管理以及端口映射与访问调试的完整实战流程并可直接迁移到自研模型的 WebDemo 部署场景。BlueLM-7B-Chat 模型简介BlueLM-7B 是 vivo AI 全球研究院自主研发的大规模预训练语言模型参数规模为 70 亿。该模型在 C-Eval 与 CMMLU 两项中文评测基准上均取得领先结果截至发布时点 11 月 1 日在同等参数规模的开源模型中具有较强的竞争力。本次发布共包含 7B 规模的Base基座与Chat对话对齐两个版本其中类型基座模型对齐模型标准版BlueLM-7B-BaseBlueLM-7B-Chat长上下文版BlueLM-7B-Base-32KBlueLM-7B-Chat-32K量化版—BlueLM-7B-Chat-4bits本文部署的vivo-ai/BlueLM-7B-Chat为 7B 对话对齐版本支持通过 Transformerstrust_remote_codeTrue方式从远程代码仓库加载是后续 FastApi、LangChain、Lora 微调等系列教程见 support_model.md 中的 BlueLM 章节共用的基础模型。对话模板BlueLM 的多轮会话格式理解 BlueLM 的对话模板是写出正确 WebDemo 的前提。从仓库中多份源码可以交叉印证其对话格式本文 WebDemo 的build_prompt函数将历史消息拼为[|Human|]:{query}[|AI|]:{response}/s当前输入拼为[|Human|]:{prompt}[|AI|]:FastApi 部署 中构造输入为f[|Human|]:{prompt}[|AI|]:LangChain 接入 的自定义 LLM 类同样使用f[|Human|]:{prompt}[|AI|]:Lora 微调代码 中指令与回答以[|Human|]:... [|AI|]:...组织回答后追加eos_token_id对应/s。可见[|Human|]与[|AI|]是 BlueLM 系列通用的角色分隔标记/s是句子结束符WebDemo 中的模板与训练阶段保持一致保证了推理输入分布与训练分布对齐。环境准备1. 租赁 GPU 实例并选择镜像在 AutoDL 平台租赁一台配备 RTX 3090 等24G 显存的显卡机器24G 显存足以容纳 7B 规模模型以 bf16 精度加载推理按 2 字节/参数估算70 亿参数权重约占 14GB 显存剩余空间可容纳 KV Cache 与激活。创建实例时镜像选择PyTorch -- 1.11.0 -- 3.8(ubuntu20.04) -- 11.3CUDA 版本在 11.3 以上均可满足要求2. 打开终端实例启动后打开 JupyterLab也可以使用 VSCode SSH 远程连接服务器在其中打开终端后续的环境配置、模型下载与 demo 运行都在该终端中进行。3. pip 换源加速并安装依赖# 升级pip python -m pip install --upgrade pip # 设置pip镜像源 pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple # 安装软件依赖 pip install modelscope1.11.0 pip install transformers4.37.0 pip install streamlit1.24.0 pip install sentencepiece0.1.99 pip install accelerate0.24.1 pip install transformers_stream_generator0.0.4各依赖在本场景中的作用依赖版本作用modelscope1.11.0从 ModelScope 下载模型权重transformers4.37.0加载模型与 Tokenizer、执行生成streamlit1.24.0Web 界面框架sentencepiece0.1.99BlueLM 词表的 SentencePiece 分词后端accelerate0.24.1支撑device_mapauto自动设备分配transformers_stream_generator0.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, revisionmaster)执行python model_download.py后模型权重会缓存到/root/autodl-tmp目录按 ModelScope 默认目录结构实际权重路径为/root/autodl-tmp/vivo-ai/BlueLM-7B-Chat。下载完成后可通过ls /root/autodl-tmp/vivo-ai/BlueLM-7B-Chat确认config.json、分词器文件与权重文件均已就位。代码准备chatBot.py 逐模块实现在/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, step1) # 创建一个标题和一个副标题 st.title( BlueLM Chatbot) st.caption( A streamlit chatbot powered by Self-LLM) # 定义模型路径 mode_name_or_path /root/autodl-tmp/vivo-ai/BlueLM-7B-Chat # 定义一个函数用于获取模型和tokenizer st.cache_resource def get_model(): # 从预训练的模型中获取tokenizer tokenizer AutoTokenizer.from_pretrained(mode_name_or_path, trust_remote_codeTrue) # 从预训练的模型中获取模型并设置模型参数 model AutoModelForCausalLM.from_pretrained(mode_name_or_path, trust_remote_codeTrue,torch_dtypetorch.bfloat16, device_mapauto) # 从预训练的模型中获取生成配置 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_tokensTrue) def end(self): 结束流处理将当前流中的文本作为响应并重置流状态。 self.first True # 将token ids解码为文本 text tokenizer.decode(self.tokenIds, skip_special_tokensTrue) 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(tokenizertokenizer) # 构建当前会话的提示信息 prompt build_prompt(messagesmessages, promptprompt_text) # 将提示信息编码为模型输入 inputs_tensor tokenizer(prompt, return_tensorspt) inputs_tensor inputs_tensor.to(cuda:0) input_ids inputs_tensor[input_ids] # 通过模型生成响应 outputs model.generate(input_idsinput_ids, max_new_tokensmax_length, streamerstreamer) # 将模型的响应显示给用户 st.chat_message(assistant).write(streamer.response) # 更新会话历史 st.session_state.messages.append((prompt_text, streamer.response))1. 侧边栏与界面骨架st.sidebar区域展示模型名称并放置max_length滑块范围 01024默认 512步长 1用于控制每次生成的最大新 token 数。主区域通过st.title与st.caption展示应用标题。这里的max_length后续会作为model.generate(max_new_tokensmax_length)的参数传入直接决定回答长度上限。注意原文档此处侧边栏链接指向 self-llm 仓库同时需要提醒的是模型路径必须填写为实际下载目录/root/autodl-tmp/vivo-ai/BlueLM-7B-Chat本文已按 ModelScope 默认缓存结构修正原文档中该处的笔误路径错误会导致from_pretrained找不到本地模型。2. 模型加载get_model()get_model使用st.cache_resource装饰Streamlit 会缓存加载好的模型对象页面每次交互重跑脚本时不会重复加载权重。加载要点AutoTokenizer.from_pretrained(mode_name_or_path, trust_remote_codeTrue)加载分词器trust_remote_codeTrue允许执行模型仓库中的自定义代码BlueLM 需要远程代码支撑AutoModelForCausalLM.from_pretrained(..., torch_dtypetorch.bfloat16, device_mapauto)以bf16 半精度加载因果语言模型device_mapauto由 accelerate 自动将各层分配到可用设备model.generation_config GenerationConfig.from_pretrained(mode_name_or_path)从模型目录加载官方生成配置model.generation_config.pad_token_id model.generation_config.eos_token_id将 pad_token_id 对齐到 eos_token_id。BlueLM 的生成配置若未显式声明 pad token在 batch 解码如启用 padding 的 DataCollator时会因 pad token 缺失而报错此处赋值是最常见的规避手段——该做法与 FastApi 部署 中的设置完全一致model.eval()切换为评估模式关闭 dropout 等训练期行为。3. 多轮会话构造build_prompt()build_prompt接收两个参数messages形如[(用户输入, AI回答), ...]的会话历史列表和prompt当前用户输入。拼接规则历史轮次[|Human|]:{query}[|AI|]:{response}/s每轮以/s收尾当前轮次[|Human|]:{prompt}[|AI|]:以[|AI|]:结尾引导模型续写回答。这样模型看到的输入是完整的多轮对话序列从而获得对话记忆能力。注意首条欢迎消息(, 你好有什么可以帮助你吗)也会被拼入历史因此模型在真正对话前已经见过一次空的用户轮次这也解释了首次提问时模型能够衔接上下文。4. 流式输出BlueLMStreamerBlueLMStreamer继承自transformers.TextStreamer通过回调机制接收generate过程中逐步产出的 tokenput(value)每个新 token 产出时被调用。其中if self.first:分支会跳过第一个 token 并置firstFalse——跳过的是生成序列中的首 token避免把输入提示的起始 token 计入回答此后收集 token id 到self.tokenIds列表put内的decode结果在当前版本实现中并未使用最终回答以end中的解码结果为准end()生成结束时被调用将收集到的 token ids 以skip_special_tokensTrue解码跳过/s等特殊 token赋值给self.response并重置状态。重要使用细节streamer.response必须在model.generate(...)返回之后再读取因为回答文本是在end()阶段才最终写回self.response。文中代码的顺序先generate再st.chat_message(assistant).write(streamer.response)正是基于这一时序约束。5. 会话状态与交互主循环st.session_state.messages首次运行时初始化为空列表并追加欢迎语后续每次脚本重跑时保持不变实现多轮记忆历史渲染遍历st.session_state.messages每条以st.chat_message(assistant)气泡展示WebDemo 中所有历史统一以 assistant 身份展示属于演示简化处理输入处理st.chat_input()捕获用户输入:(walrus)运算符在非空时进入生成流程——调用build_prompt拼接完整提示、tokenizer编码为 tensor 并搬到cuda:0、model.generate(input_ids..., max_new_tokensmax_length, streamerstreamer)执行生成收尾显示回答并把(prompt_text, streamer.response)追加进会话历史供下一轮构建提示使用。运行 demo在终端中运行以下命令启动 Streamlit 服务streamlit run /root/autodl-tmp/chatBot.py --server.address 127.0.0.1 --server.port 6006随后按照 AutoDL 平台的端口映射说明将 6006 端口映射到本地在浏览器中打开http://localhost:6006/即可看到聊天界面。运行效果如下界面左侧边栏展示模型名与max_length滑块右侧主区域为对话气泡区欢迎语、多轮问答均以气泡呈现底部输入框支持键入问题并发送。整个应用实现了「多轮记忆 可调生成长度 网页交互」的完整 WebDemo 能力。同系列部署方案对照BlueLM-7B-Chat 在 self-llm 仓库中同时提供了四种部署形态方便在不同场景间选择方案适用场景关键差异FastApi 部署后端 API 服务以uvicorn起 HTTP 服务通过 POST 返回 JSON含torch_gc显存清理LangChain 接入构建 LLM 应用链路继承LangChain.llms.base.LLM自定义BlueLM类重写_callWebDemo本文浏览器交互演示Streamlit 流式生成 多轮会话 UILora 微调领域微调基于 PEFT 对q/k/v/o/gate/up/down_proj注入 LoRA 适配器四种方案共享同一套对话模板[|Human|]/[|AI|]//s与同一份模型权重这也是本仓库将该模型系列教程组织在一起的原因——从模型下载、对话格式到部署形态全部打通读者可按需将本文的build_prompt模板直接复用到 FastApi 或 LangChain 场景中。常见问题与注意事项模型路径务必正确下载后权重位于/root/autodl-tmp/vivo-ai/BlueLM-7B-ChatchatBot.py中的mode_name_or_path必须与该路径一致否则加载失败trust_remote_codeTrue不可省略BlueLM 依赖模型仓库内的自定义实现代码加载 tokenizer 与模型时均需开启显存要求7B 模型 bf16 加载约需 14GB 权重显存推荐 24G 显存显卡如 RTX 3090CUDA 版本 11.3 及以上若显存紧张可参考 4bits 量化版模型BlueLM-7B-Chat-4bits端口映射务必先在 AutoDL 控制台完成 6006 端口的对外映射否则本地浏览器无法访问首次启动较慢首次加载需读取完整权重并构建缓存耐心等待日志输出st.cache_resource保证后续交互不重复加载模型生成超长回答若回答被截断或偏短可通过侧边栏max_length滑块调高上限该值即generate的max_new_tokens。通过以上步骤你已完整掌握 BlueLM-7B-Chat 的 WebDemo 部署全流程如需进一步扩展可基于 FastApi 部署 将该模型以 API 形式对外服务或通过 LangChain 接入 集成到上层应用链路中。【免费下载链接】self-llm《开源大模型食用指南》针对中国宝宝量身打造的基于Linux环境快速微调全参数/Lora、部署国内外开源大模型LLM/多模态大模型MLLM教程项目地址: https://gitcode.com/datawhalechina/self-llm创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表