ChatGLM3在Docker環境部署

ChatGLM3 docker部署

1. 下載項目到本地

git clone https://github.com/THUDM/ChatGLM3
cd ChatGLM3

這目錄ChatGLM3下應該還需要包含chatglm3-6b-32k HuggingFace 或者 ModelScope ,需要手動下載。

2.製作Docker鏡像

1)配置基礎的Dockerfile:

#基於的基礎鏡像
FROM python:3.11.6
# 設置工作目錄
WORKDIR /LLM
# 拷貝應用程序文件到容器中
COPY ./chatglm3-6b-32k/ /models/
COPY ./ChatGLM3/ /LLM/
# 安裝支持
RUN pip install  -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
RUN pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple

2)打包生成鏡像

docker build -t dmx:easy .

3.啓動容器

 docker run --restart=always -itd --name dmxApp3 -p 8000:8000 -w /LLM --gpus device=2 dmx:easy python LLM_Server.py

4.查看運行日誌

docker logs -t dmxApp3

在這裏插入圖片描述

5. LLM_Server.py

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from transformers import AutoTokenizer, AutoModel
from utils import load_model_on_gpus
import uvicorn, json, datetime
import os

import torch


DEVICE = "cuda"
DEVICE_ID = "0"
CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE


def torch_gc():
    if torch.cuda.is_available():
        with torch.cuda.device(CUDA_DEVICE):
            torch.cuda.empty_cache()
            torch.cuda.ipc_collect()


app = FastAPI()  # 創建API實例
app.add_middleware(
    CORSMiddleware,
    # 允許跨域的源列表,例如 ["http://www.example.org"] 等等,["*"] 表示允許任何源
    allow_origins=["*"],
    # 跨域請求是否支持 cookie,默認是 False,如果爲 True,allow_origins 必須爲具體的源,不可以是 ["*"]
    allow_credentials=False,
    # 允許跨域請求的 HTTP 方法列表,默認是 ["GET"]
    allow_methods=["*"],
    # 允許跨域請求的 HTTP 請求頭列表,默認是 [],可以使用 ["*"] 表示允許所有的請求頭
    # 當然 Accept、Accept-Language、Content-Language 以及 Content-Type 總之被允許的
    allow_headers=["*"],
    # 可以被瀏覽器訪問的響應頭, 默認是 [],一般很少指定
    # expose_headers=["*"]
    # 設定瀏覽器緩存 CORS 響應的最長時間,單位是秒。默認爲 600,一般也很少指定
    # max_age=1000
)


@app.post("/")
async def create_item(request: Request):
    global model, tokenizer
    json_post_raw = await request.json()
    json_post = json.dumps(json_post_raw)
    json_post_list = json.loads(json_post)
    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')
    temperature = json_post_list.get('temperature')
    response, history = model.chat(tokenizer,
                                   prompt,
                                   history=history,
                                   max_length=max_length if max_length else 32760,
                                   top_p=top_p if top_p else 0.7,
                                   #top_p=top_p if top_p else 0.1,
                                   temperature=temperature if temperature else 0.95)
                                   #temperature=temperature if temperature else 0.1)

    now = datetime.datetime.now()
    time = now.strftime("%Y-%m-%d %H:%M:%S")
    answer = {
        "response": response,
        "history": history,
        "status": 200,
        "time": time
    }
    log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"'
    print(log)
    torch_gc()
    return answer

if __name__ == '__main__':
    modelPath="models/"
    tokenizer = AutoTokenizer.from_pretrained(modelPath, trust_remote_code=True)
    model = AutoModel.from_pretrained(modelPath, trust_remote_code=True).cuda()
    model.eval()
    uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章