目前絕大多數LLM模型都是python實現的,運行速度有限(包括ChatGLM2-6b),幸好有大神將其用C++重寫了一遍,讓運行速度大大提高。
項目地址:li-plus/chatglm.cpp: C++ implementation of ChatGLM-6B & ChatGLM2-6B (github.com)
部署過程如下(環境:WSL 2 ubuntu 22.04,顯卡: N卡RTX 4060) - 注:無顯卡,純CPU也行
1、克隆項目
git clone --recursive https://github.com/li-plus/chatglm.cpp.git && cd chatglm.cpp
2、編譯
注:執行下面操作前,請先確保ubuntu環境裏有make, cmake環境(沒有請自行google或baidu)
純CPU環境:
cmake -B build cmake --build build -j --config Release
有(nvidia cuda) GPU 環境:
cmake -B build -DGGML_CUBLAS=ON && cmake --build build -j --config Release
3、模型轉換
原生的ChatGLM2-6B模型無法直接使用,需要將其轉換成ggml的bin文件,假如我們已提前下載了 THUDM/chatglm2-6b-int4 · Hugging Face,放在windows主系統的e:\chatglm2-6b-in4目錄
python3 convert.py -i /mnt/e/chatglm2-6b-int4 -t q4_0 -o chatglm2-6b-int4.bin
執行完後,將在當前目錄下,得到1個名爲chatglm2-6b-int4.bin
4、CLI 驗證
./build/bin/main -m /home/jimmy/code/models/chatglm2-6b-int4.bin -i
有顯卡的情況下,c++版本與python版本速度的區別不太明顯,但在純CPU環境下,c++版本明顯快很多。
5、python綁定
純CPU環境:
pip install -U chatglm-cpp
nvidia CUDA環境:
CMAKE_ARGS="-DGGML_CUBLAS=ON" pip install -U chatglm-cpp
Mac環境:
CMAKE_ARGS="-DGGML_METAL=ON" pip install -U chatglm-cpp
安裝好以後,cd examples目錄:
- CLI模式驗證
python cli_chat.py -m /home/jimmy/code/models/chatglm2-6b-int4.bin -i
- web_demo
- api-demo
先安裝
pip install 'chatglm-cpp[api]'
然後就可以驗證了:
MODEL=/home/jimmy/code/models/chatglm2-6b-int4.bin uvicorn api_demo:app --host 127.0.0.1 --port 8080
MODEL=後面的路徑,大家根據情況換成模型的實際路徑,這裏的api_demo.app,實際是在examples/api_demo.py裏指定的
同時從源碼裏可以看到,對外暴露了2個url,如果順利的話,啓動後將看到類似以下輸出:
如果啓動過程中報錯:
pandas PydanticImportError:`BaseSettings`已移動到`pydantic-settings`包中
可以嘗試:
pip install ydata-profiling
啓動成功 後,用ApiPost驗證一下:
- longchain-api
先啓動
MODEL=/home/jimmy/code/models/chatglm2-6b-int4.bin uvicorn chatglm_cpp.langchain_api:app --host 127.0.0.1 --port 8000
然後測試longchain-client
python langchain_client.py
源代碼如下:
from langchain.llms import ChatGLM llm = ChatGLM(endpoint_url="http://127.0.0.1:8000", max_token=2048, top_p=0.7, temperature=0.95, with_history=False) print(llm.predict("你好"))
如果運行過程中報錯PydanticUserError: If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`. Note that `@root_validator` is deprecated and should be replaced with `@model_validator`. For further information visit https://errors.pydantic.dev/2.0.2/u/root-validator-pre-skip
嘗試:
pip install ydata-profiling
參考文章: