mirror of
https://github.com/datawhalechina/self-llm.git
synced 2026-09-19 01:36:47 +08:00
Update internLM api
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
# internLM-Chat-7B FastApi 部署调用
|
||||
|
||||
## 环境准备
|
||||
|
||||
在[autodl](https://www.autodl.com/)平台中租一个3090等24G显存的显卡机器,如下图所示镜像选择`PyTorch`-->`1.11.0`-->`3.8(ubuntu20.04)`-->`11.3`
|
||||
|
||||

|
||||
|
||||
接下来打开刚刚租用服务器的`JupyterLab`,并且打开其中的终端开始环境配置、模型下载和运行`demo`。
|
||||
|
||||

|
||||
|
||||
pip换源和安装依赖包
|
||||
|
||||
```shell
|
||||
# 升级pip
|
||||
python -m pip install --upgrade pip
|
||||
# 更换 pypi 源加速库的安装
|
||||
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
|
||||
pip install fastapi==0.104.1
|
||||
pip install uvicorn==0.24.0.post1
|
||||
pip install requests==2.25.1
|
||||
pip install modelscope==1.9.5
|
||||
pip install transformers==4.35.2
|
||||
pip install streamlit==1.24.0
|
||||
pip install sentencepiece==0.1.99
|
||||
pip install accelerate==0.24.1
|
||||
```
|
||||
## 模型下载
|
||||
|
||||
使用 `modelscope` 中的`snapshot_download`函数下载模型,第一个参数为模型名称,参数`cache_dir`为模型的下载路径。
|
||||
|
||||
在 `/root/autodl-tmp` 路径下新建 `download.py` 文件并在其中输入以下内容,粘贴代码后记得保存文件,如下图所示。并运行 `python /root/autodl-tmp/download.py`执行下载,模型大小为 14 GB,下载模型大概需要 10~20 分钟
|
||||
|
||||
```python
|
||||
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', revision='master')
|
||||
```
|
||||

|
||||
|
||||
## 代码准备
|
||||
|
||||
在`/root/autodl-tmp`路径下新建`api.py`文件并在其中输入以下内容,粘贴代码后记得保存文件。下面的代码有很详细的注释,大家如有不理解的地方,欢迎提出issue。
|
||||
|
||||
```python
|
||||
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(): # 检查是否可用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') # 获取请求中的提示
|
||||
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,
|
||||
history=history,
|
||||
max_length=max_length if max_length else 2048, # 如果未提供最大长度,默认使用2048
|
||||
top_p=top_p if top_p else 0.7, # 如果未提供top_p参数,默认使用0.7
|
||||
temperature=temperature if temperature else 0.95 # 如果未提供温度参数,默认使用0.95
|
||||
)
|
||||
now = datetime.datetime.now() # 获取当前时间
|
||||
time = now.strftime("%Y-%m-%d %H:%M:%S") # 格式化时间为字符串
|
||||
# 构建响应JSON
|
||||
answer = {
|
||||
"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_code=True)
|
||||
model = AutoModelForCausalLM.from_pretrained("/root/autodl-tmp/Shanghai_AI_Laboratory/internlm-chat-7b", trust_remote_code=True).to(torch.bfloat16).cuda()
|
||||
model.eval() # 设置模型为评估模式
|
||||
# 启动FastAPI应用
|
||||
# 用6006端口可以将autodl的端口映射到本地,从而在本地使用api
|
||||
uvicorn.run(app, host='0.0.0.0', port=6006, workers=1) # 在指定端口和主机上启动应用
|
||||
```
|
||||
|
||||
## Api 部署
|
||||
|
||||
在终端输入以下命令启动`api`服务
|
||||
|
||||
```shell
|
||||
cd /root/autodl-tmp
|
||||
python api.py
|
||||
```
|
||||
|
||||
默认部署在 6006 端口,通过 POST 方法进行调用,可以使用`curl`调用,如下所示:
|
||||
```shell
|
||||
curl -X POST "http://127.0.0.1:6006" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"prompt": "你好", "history": []}'
|
||||
```
|
||||
|
||||
也可以使用python中的requests库进行调用,如下所示:
|
||||
|
||||
```python
|
||||
import requests
|
||||
import json
|
||||
|
||||
def get_completion(prompt):
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
data = {"prompt": prompt, "history": []}
|
||||
response = requests.post(url='http://127.0.0.1:6006', headers=headers, data=json.dumps(data))
|
||||
return response.json()['response']
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(get_completion('你好'))
|
||||
```
|
||||
|
||||
得到的返回值如下所示:
|
||||
|
||||
```json
|
||||
{
|
||||
"response":"你好!有什么可以帮助你的吗?",
|
||||
"history":[["你好","你好!有什么可以帮助你的吗?"]],
|
||||
"status":200,
|
||||
"time":"2023-11-19 20:08:40"
|
||||
}
|
||||
```
|
||||
@@ -46,9 +46,9 @@
|
||||
|
||||
### 已支持模型
|
||||
|
||||
- InternLM
|
||||
- [InternLM](https://github.com/InternLM/InternLM.git)
|
||||
- [ ] InternLM-Chat-7B Transformers 部署调用 @小罗 ddl=11.26
|
||||
- [ ] InternLM-Chat-7B FastApi 部署调用
|
||||
- [x] [InternLM-Chat-7B FastApi 部署调用](InternLM/02-internLM-Chat-7B%20FastApi.md)
|
||||
- [x] [InternLM-Chat-7B WebDemo](InternLM/03-InternLM-Chat-7B.md) @不要葱姜蒜
|
||||
- [x] [Lagent+InternLM-Chat-7B-V1.1 WebDemo](InternLM/04-Lagent+InternLM-Chat-7B-V1.1.md) @不要葱姜蒜
|
||||
- [x] [浦语灵笔图文理解&创作 WebDemo](InternLM/05-浦语灵笔图文理解&创作.md) @不要葱姜蒜
|
||||
@@ -57,7 +57,7 @@
|
||||
- [ ] InternLM-Chat-7B ptuning 微调
|
||||
- [ ] InternLM-Chat-7B 全量微调
|
||||
|
||||
- ChatGLM
|
||||
- [ChatGLM3](https://github.com/THUDM/ChatGLM3.git)
|
||||
- [ ] ChatGLM3-6B Transformers 部署调用 @丁悦 ddl=12.2
|
||||
- [ ] ChatGLM3-6B FastApi 部署调用 @丁悦 ddl=12.2
|
||||
- [x] [ChatGLM3-6B chat WebDemo](ChatGLM/03-ChatGLM3-6B-chat.md) @不要葱姜蒜
|
||||
@@ -66,7 +66,7 @@
|
||||
- [ ] ChatGLM3-6B Lora 微调 @ Hongru0306 ddl=11.26
|
||||
- [ ] ChatGLM3-6B ptuning 微调 @ Hongru0306 ddl=11.26
|
||||
- [ ] ChatGLM3-6B 全量微调
|
||||
- Qwen
|
||||
- [Qwen](https://github.com/QwenLM/Qwen.git)
|
||||
- [ ] Qwen-7B-chat Transformers 部署调用 @娇娇 ddl=12.2
|
||||
- [ ] Qwen-7B-chat FastApi 部署调用 @娇娇 ddl=12.2
|
||||
- [ ] Qwen-7B-chat WebDemo @娇娇 ddl=12.2
|
||||
|
||||
Reference in New Issue
Block a user