一个网站有个前端后端怎么做,seo网站自动发布外链工具,浙江省信息港入口,酒泉网站建设有哪些Qwen2的web搭建(streamlit)
千问2前段时间发布了#xff0c;个人觉得千问系列是我用过最好的中文开源大模型#xff0c;所以这里基于streamlit进行一个千问2的web搭建#xff0c;来进行模型的测试
一、硬件要求
该文档中使用的千问模型为7B-Instruct#xff0c;需要5g以…Qwen2的web搭建(streamlit)
千问2前段时间发布了个人觉得千问系列是我用过最好的中文开源大模型所以这里基于streamlit进行一个千问2的web搭建来进行模型的测试
一、硬件要求
该文档中使用的千问模型为7B-Instruct需要5g以上的显存如果是轻薄本不建议进行本地测试下图为测试时的实际显存占用 二、环境准备
对于环境的基本要求
transformers
torch
streamlit
sentencepiece
accelerate
transformers_stream_generator上述是基础的环境准备可以用conda创建一个新的环境来进行配置。在下载库时可以使用清华大学的镜像进行加速如下所示
pip install transformers -i https://pypi.tuna.tsinghua.edu.cn/simple三、模型下载
这里推荐使用huggingface镜像网站进行下载因为在下载中断后再次请求时会从上次中断的地方继续而不是重新下载。
https://hf-mirror.com
以千问为例在终端的下载请求为
huggingface-cli download --resume-download Qwen/Qwen2-7B-Instruct --local-dir ./qwen2四、web代码编写
from transformers import AutoTokenizer,AutoModelForCausalLM
import torch
import streamlit as st#在侧边栏创建标题
with st.sidebar:st.markdown(qwen2)hello world#创建滑块默认值为512范围在0到1024之间max_length st.slider(max_length,0,1024,512,step1)#创建标题和副标题
st.title(qwen2 chatbot)
st.caption(test)#你下载到本地的模型路径
model_path ../models/qwen2-1.5b-Instruct#streamlit.cache_resource 是一个用于缓存昂贵或频繁调用的资源如大型文件、网络资源、或数据库连接的装饰器。这个装饰器可以帮助你提高应用的性能通过缓存那些不经常变更但加载需要大量时间或计算资源的数据。
#定义的函数来获取tokenizer和model
st.cache_resource
def get_model():tokenizer AutoTokenizer.from_pretrained(model_path,use_fastFalse)model AutoModelForCausalLM.from_pretrained(model_path,torch_dtypetorch.float16,device_mapauto)return tokenizer,modeltokenizer,model get_model()#如果没有消息则创建默认的消息列表
if messages not in st.session_state:st.session_state[messages] [{role:assistant,content:有什么可以帮到您}]#便利session_state中的消息并显示在聊天界面上
for msg in st.session_state.messages:st.chat_message(msg[role]).write(msg[content])
## 如果用户在聊天输入框中输入了内容则执行下述操作
if prompt : st.chat_input():#将用户输入添加到message列表中st.session_state.messages.append({role:user,content:prompt})#在聊天界面上显示用户输入st.chat_message(user).write(prompt)#构建输入input_ids tokenizer.apply_chat_template(st.session_state.messages,tokenizeFalse,add_generation_promptTrue)model_inputs tokenizer([input_ids],return_tensorspt).to(cuda)#模型生成输出idgenerated_ids model.generate(model_inputs.input_ids,max_new_tokens512)generated_ids [output_ids[len(input_ids):] for input_ids,output_ids in zip(model_inputs.input_ids,generated_ids)]#将生成的id转换成文字response tokenizer.batch_decode(generated_ids,skip_special_tokensTrue)[0]st.session_state.messages.append({role:assistant,content:response})#在界面上显示输出st.chat_message(assistant).write(response)由于qwen2模型并没有自带流式输出函数会报错AttributeError: Qwen2Model object has no attribute stream_chat后续改进考虑对其进行流式输出增强用户可读性 五、终端启动
在该文件目录下终端输入
streamlit run your_file_name.py之后就会进入web界面
六、调试
streamlit这样的web形式不能直接通过打断点进行debug所以需要进行一些处理 红框中进行下图配置script框中的路径是你配置的模型环境中streamlit所在的绝对路径parameters框就是run your_file_name.py这样处理后就是终端输入streamlit run your_file_name.py的效果之后就能进行断点调试了 Reference
[1] qwen官方文档
[2] qwen2 webDemo部署
[3] streamlit断点调试