搜索引擎竞价广告,灰色词seo排名,杭州网站公司设计,云浮市住房城乡建设信息网网站internLM-Chat-7B FastApi 部署调用
环境准备
在autodl平台中租一个3090等24G显存的显卡机器#xff0c;如下图所示镜像选择PyTorch–1.11.0–3.8(ubuntu20.04)–11.3 接下来打开刚刚租用服务器的JupyterLab#xff0c;并且打开其中的终端开始环境配置、模型下…internLM-Chat-7B FastApi 部署调用
环境准备
在autodl平台中租一个3090等24G显存的显卡机器如下图所示镜像选择PyTorch–1.11.0–3.8(ubuntu20.04)–11.3 接下来打开刚刚租用服务器的JupyterLab并且打开其中的终端开始环境配置、模型下载和运行demo。 pip换源和安装依赖包
# 升级pip
python -m pip install --upgrade pip
# 更换 pypi 源加速库的安装
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simplepip install fastapi0.104.1
pip install uvicorn0.24.0.post1
pip install requests2.25.1
pip install modelscope1.9.5
pip install transformers4.35.2
pip install streamlit1.24.0
pip install sentencepiece0.1.99
pip install accelerate0.24.1模型下载
使用 modelscope 中的snapshot_download函数下载模型第一个参数为模型名称参数cache_dir为模型的下载路径。
在 /root/autodl-tmp 路径下新建 download.py 文件并在其中输入以下内容粘贴代码后记得保存文件如下图所示。并运行 python /root/autodl-tmp/download.py执行下载模型大小为 14 GB下载模型大概需要 10~20 分钟
import torch
from modelscope import snapshot_download, AutoModel, AutoTokenizer
import os
model_dir snapshot_download(Shanghai_AI_Laboratory/internlm-chat-7b, cache_dir/root/autodl-tmp, revisionmaster)代码准备
在/root/autodl-tmp路径下新建api.py文件并在其中输入以下内容粘贴代码后记得保存文件。下面的代码有很详细的注释大家如有不理解的地方欢迎提出issue。
from fastapi import FastAPI, Request
from transformers import AutoTokenizer, AutoModelForCausalLM
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(): # 检查是否可用CUDAwith 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) # 获取请求中的提示history json_post_list.get(history) # 获取请求中的历史记录max_length json_post_list.get(max_length) # 获取请求中的最大长度top_p json_post_list.get(top_p) # 获取请求中的top_p参数temperature json_post_list.get(temperature) # 获取请求中的温度参数# 调用模型进行对话生成response, history model.chat(tokenizer,prompt,historyhistory,max_lengthmax_length if max_length else 2048, # 如果未提供最大长度默认使用2048top_ptop_p if top_p else 0.7, # 如果未提供top_p参数默认使用0.7temperaturetemperature if temperature else 0.95 # 如果未提供温度参数默认使用0.95)now datetime.datetime.now() # 获取当前时间time now.strftime(%Y-%m-%d %H:%M:%S) # 格式化时间为字符串# 构建响应JSONanswer {response: response,history: history,status: 200,time: time}# 构建日志信息log [ time ] , prompt: prompt , response: repr(response) print(log) # 打印日志torch_gc() # 执行GPU内存清理return answer # 返回响应# 主函数入口
if __name__ __main__:# 加载预训练的分词器和模型tokenizer AutoTokenizer.from_pretrained(/root/autodl-tmp/Shanghai_AI_Laboratory/internlm-chat-7b, trust_remote_codeTrue)model AutoModelForCausalLM.from_pretrained(/root/autodl-tmp/Shanghai_AI_Laboratory/internlm-chat-7b, trust_remote_codeTrue).to(torch.bfloat16).cuda()model.eval() # 设置模型为评估模式# 启动FastAPI应用# 用6006端口可以将autodl的端口映射到本地从而在本地使用apiuvicorn.run(app, host0.0.0.0, port6006, workers1) # 在指定端口和主机上启动应用Api 部署
在终端输入以下命令启动api服务
cd /root/autodl-tmp
python api.py默认部署在 6006 端口通过 POST 方法进行调用可以使用curl调用如下所示
curl -X POST http://127.0.0.1:6006 \-H Content-Type: application/json \-d {prompt: 你好, history: []}也可以使用python中的requests库进行调用如下所示
import requests
import jsondef get_completion(prompt):headers {Content-Type: application/json}data {prompt: prompt, history: []}response requests.post(urlhttp://127.0.0.1:6006, headersheaders, datajson.dumps(data))return response.json()[response]if __name__ __main__:print(get_completion(你好))得到的返回值如下所示
{response:你好有什么可以帮助你的吗,history:[[你好,你好有什么可以帮助你的吗]],status:200,time:2023-11-19 20:08:40
}