qwen+Fastapi搭建本地知识库

参考链接:https://blog.csdn.net/xiaobing259/article/details/139998673

https://download.pytorch.org/whl/cu124/torch-2.4.1%2Bcu124-cp39-cp39-win_amd64.whl

https://pytorch.org/get-started/previous-versions/?spm=a2c6h.12873639.article-detail.13.281c5bdfwUad0k

https://blog.csdn.net/qq_43874102/article/details/123164105?spm=a2c6h.12873639.article-detail.11.281c5bdfwUad0k

https://www.bilibili.com/read/cv35427548/?jump_opus=1

内存不多,用这个qwen/Qwen2-7B-Instruct,差不多20G,2.5要百G,没那么多内存。。。

环境准备

创建虚环境

正好前面补充了虚环境的知识,这里我们直接创建一个.qwen的虚环境

python -m venv .qwen

image-20240928221426863

安装依赖

下面我们下载一下需要用到的包

pip install fastapi==0.104.1 uvicorn==0.24.0.post1 requests==2.25.1 modelscope==1.11.0 transformers==4.41.0 streamlit==1.24.0 sentencepiece==0.1.99 accelerate==0.24.1 transformers_stream_generator==0.0.4

image-20240928221505464

模型下载

这里用博主给的脚本,稍作修改即可,也可以用官网的教程下载https://modelscope.cn/models/Qwen/Qwen2-7B-Instruct/files

modelscope download --model Qwen/Qwen2-7B-Instruct

但这个不会把文件保存到当前目录,用脚本可以指定缓存目录使用参考

import torch
from modelscope import snapshot_download

# snapshot_download函数用于下载模型
model_dir = snapshot_download(
'qwen/Qwen2-7B-Instruct', # 模型名称
cache_dir='./autodl-tmp', # 缓存目录
revision='master' # 版本号
)

但不懂为什么下载会停住

image-20240928222819389

看了下任务管理器,pyton还是有占用网络资源的的

image-20240928222917899

等了一会,进度条动了,所以遇到这种情况可以等一等,可能是还没显示

image-20240928223007931

下载好后,大概有个15G左右

image-20240928233227573

代码准备

安装fastapi库

https://fastapi.org.cn/tutorial/first-steps/

./autodl-tmp路径下创建fastapi_Demo.py文件,编写FastAPI应用代码,用于加载模型并提供API服务

#encoding="utf-8"
from fastapi import FastAPI, Request
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
import uvicorn
import json
import datetime
import torch

# 设置设备参数
DEVICE = "cuda" # 使用CUDA
DEVICE_ID = "0" # CUDA设备ID,如果未设置则为空
CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE # 组合CUDA设备信息

# 清理GPU内存函数
def torch_gc():
if torch.cuda.is_available(): # 检查是否可用CUDA
with torch.cuda.device(CUDA_DEVICE): # 指定CUDA设备
torch.cuda.empty_cache() # 清空CUDA缓存
torch.cuda.ipc_collect() # 收集CUDA内存碎片

# 创建FastAPI应用
app = FastAPI()

# 处理POST请求的端点
@app.post("/")
async def create_item(request: Request):
global model, tokenizer # 声明全局变量以便在函数内部使用模型和分词器
json_post_raw = await request.json() # 获取POST请求的JSON数据
json_post = json.dumps(json_post_raw) # 将JSON数据转换为字符串
json_post_list = json.loads(json_post) # 将字符串转换为Python对象
prompt = json_post_list.get('prompt') # 获取请求中的提示

messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]

# 调用模型进行对话生成
input_ids = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
model_inputs = tokenizer([input_ids], return_tensors="pt").to('cuda')
generated_ids = model.generate(model_inputs.input_ids,max_new_tokens=512)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
now = datetime.datetime.now() # 获取当前时间
time = now.strftime("%Y-%m-%d %H:%M:%S") # 格式化时间为字符串
# 构建响应JSON
answer = {
"response": response,
"status": 200,
"time": time
}
# 构建日志信息
log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"'
print(log) # 打印日志
torch_gc() # 执行GPU内存清理
return answer # 返回响应

# 主函数入口
if __name__ == '__main__':
# 加载预训练的分词器和模型
model_name_or_path = './qwen/Qwen2-7B-Instruct'
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=False)
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, device_map="auto", torch_dtype=torch.bfloat16)

# 启动FastAPI应用
# 用6006端口可以将autodl的端口映射到本地,从而在本地使用api
uvicorn.run(app, host='0.0.0.0', port=6006, workers=1) # 在指定端口和主机上启动应用

执行的时候可能会报错

Errot

AssertionError: Torch not compiled with CUDA enabled

https://blog.csdn.net/moyong1572/article/details/119438286

import torch
print(torch.__version__)
print(torch.cuda.is_available())

image-20240929205938728

False,说明当前的pytorch版本无法使用显卡,先安装cuda

  1. 查看自己显卡驱动程序的版本

image-20240929210039119

  1. 下载对应的cuda

查看需要下载的版本:https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html

image-20240929210626909

我们需要下载12.5的版本,但GA喝update有什么区别,搞不懂

https://wenku.csdn.net/answer/f6694262edc811ed9e3dfa163eeb3507#:~:text=%E8%80%8C%E5%9C%A8CUDA%E4%B8%AD%EF%BC%8CGA

下载地址:https://developer.nvidia.com/cuda-toolkit-archive

image-20240929210802209

进入下载页面,选择对应的操作系统,中间有一步我选择local了,怕网络不好

image-20240929210855880

选完,这里会有对应的版本给你下载,这个下载指引挺有意思的

image-20240929210948888

下载好后就可以安装了:https://blog.csdn.net/weixin_34409703/article/details/93226830

双击安装下载的.exe文件,然后选择解压路径,如下图,解压到哪里无所谓,安装成功会自动删除;

image-20240929211712678

image-20240929211951860

这里我先继续试试

image-20240929212014051

解压完成后,得到如下图:

  • 精简:安装所有CUDA模块,并覆盖掉当前的NVIDIA驱动程序;(说实话,容易出问题)
  • 自定义:选择自己想要安装的模块,此处选择这里;

image-20240929212028303

下面几个模块准确具体有什么用,不能100%确定,但能大概才出来:

  • CUDA:这个是必须的,下面有CUDA Runntime、Samples一些东西;
  • NVIDIA GeForce Experience:这个好像是为了更好的游戏体验,之前安装显卡驱动程序时也提示是否安装,果断拒绝了;
  • Other components:这里的PhysX好像也是为了游戏体验来的;
  • Driver components:这个就要慎重了,意思就是重新安装显卡驱动程序;如果之前已经成功安装驱动程序,这里就不用选了;如果之前没安装驱动程序,建议还是去官网上单独下载驱动程序进行安装吧

根据这个,我也是只保留了第一个选项

image-20240929212132253

image-20240929212141125

这里我修改到其它路径了,而且这里我只有一个选项。。。

image-20240929212610431

安装完成后配置一下环境变量

F:/Nvida/lib/x64添加的系统变量的path中;

然后nvcc -V即可

image-20240929213109888

  1. 还需要安装对应的CuDNN

下载网址 https://developer.nvidia.com/rdp/cudnn-archive

下载对应CUDA版本的CuDNN

下载完成后,解压得到一个名为cudnn-windows-x86_64-8.9.7.29_cuda12-archive的文件夹;

该文件夹下的文件复制到上一步安装的CUDA中;注意对应的文件夹;
./cuda/bin/.dll 复制到 ./NVIDIA GPU Computing Tookit/CUDA/v8.0/bin/
./cuda/include/.dll 复制到 ./NVIDIA GPU Computing Tookit/CUDA/v8.0/include/
./cuda/lib/x64/**.dll 复制到 ./NVIDIA GPU Computing Tookit/CUDA/v8.0/lib/x64/

这里根据实际情况来操作,cudnn就是原来的扩充,直接把对应的动态链接库dll,要包含的头文件*.h和要用的lib库,给补充到原拉的cuda中即可

安装好后测试Pytorch是否可以使用,运行刚刚的检查脚本,还是False/。。。

原文链接:https://blog.csdn.net/moyong1572/article/details/119438286

还有一种情况也会发生错误Torch not compiled with CUDA enabled,那就是安装的pytorch是cpu版本。。。

访问链接:https://pytorch.org/get-started/locally/#supported-windows-distributions,选择相应的版本

image-20240929220037638

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124

image-20240929220306521

有点大啊,我看看能不能手动安装,复制下载链接,IDM+手动设置代理

image-20240929220903447

确实快的多,下载完放到相应的位置即可,就是大小有点对不上,他的2.5应该值得是解压后的,whl是一个压缩文件,下载好后,给他放到虚环境下的./qwen/Lib/site-packages,然后再pip一下

pip install F:\qwen\.qwen\lib\site-packages\torch-2.4.1+cu124-cp39-cp39-win_amd64.whl

image-20240929221803376

测试是否安装成功

image-20240929222109947

但还是有问题

image-20240929224415158

感觉靠谱i的解释如下,但这个慢点,好像慢的有点多

image-20240929224520750

image-20240929225706044

我试着换个版本

https://download.pytorch.org/whl/cu121/torch-2.1.2%2Bcu121-cp39-cp39-win_amd64.whl

image-20240929231604190

这次也是挺慢的,但没有报错了

image-20240929233328129

image-20240929225304370

这个错误,DEVICE_ID得设置成0,https://blog.csdn.net/qq_38614074/article/details/139499410#:~:text=RuntimeErr