引言

ChatGLM-6B是由清华大学开源的双语对话大模型,该模型有62亿参数,但在经过量化后模型体积大幅下降,因此不同于其他需要部署到服务器上的大模型,该模型可以部署到本地电脑,那么接下来我们来看看如何部署该模型。

首先是下载源码:双语对话大模型

随后下载对应的权重文件,这里我们使用的是Hugging Face提供的模型权重文件,但由于该网站需要,所以可以使用该网站的镜像网站:Hugging Face镜像网站,将ChatGLM-6B项目下载到本地:

ChatGLM-6B部署到本地电脑_json

环境部署

该项目使用python语言开发,这里建议python>=3.9,环境创建完成后激活进入:

conda create -n chatgpt python=3.10
activate chatgpt

随后便是安装相应依赖,直接使用requirements.txt中的依赖包即可

pip install -r requirements.txt -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

环境如下:

Package                   Version
------------------------- ------------
accelerate                0.34.2
aiofiles                  23.2.1
altair                    5.4.1
annotated-types           0.7.0
anyio                     4.4.0
attrs                     24.2.0
blinker                   1.8.2
cachetools                5.5.0
certifi                   2024.8.30
charset-normalizer        3.3.2
click                     8.1.7
colorama                  0.4.6
contourpy                 1.3.0
cpm-kernels               1.0.11
cycler                    0.12.1
exceptiongroup            1.2.2
fastapi                   0.114.2
ffmpy                     0.4.0
filelock                  3.16.0
fonttools                 4.53.1
fsspec                    2024.9.0
gitdb                     4.0.11
GitPython                 3.1.43
gradio                    3.50.0
gradio_client             0.6.1
h11                       0.14.0
httpcore                  1.0.5
httpx                     0.27.2
huggingface-hub           0.24.7
idna                      3.10
importlib_resources       6.4.5
Jinja2                    3.1.4
jsonschema                4.23.0
jsonschema-specifications 2023.12.1
kiwisolver                1.4.7
latex2mathml              3.77.0
Markdown                  3.7
markdown-it-py            3.0.0
MarkupSafe                2.1.5
matplotlib                3.9.2
mdtex2html                1.3.0
mdurl                     0.1.2
mpmath                    1.3.0
narwhals                  1.8.1
networkx                  3.3
numpy                     1.26.4
orjson                    3.10.7
packaging                 24.1
pandas                    2.2.2
pillow                    10.4.0
pip                       24.2
protobuf                  5.28.1
psutil                    6.0.0
pyarrow                   17.0.0
pydantic                  2.9.1
pydantic_core             2.23.3
pydeck                    0.9.1
pydub                     0.25.1
Pygments                  2.18.0
pyparsing                 3.1.4
python-dateutil           2.9.0.post0
python-multipart          0.0.9
pytz                      2024.2
PyYAML                    6.0.2
referencing               0.35.1
regex                     2024.9.11
requests                  2.32.3
rich                      13.8.1
rpds-py                   0.20.0
ruff                      0.6.5
safetensors               0.4.5
semantic-version          2.10.0
sentencepiece             0.2.0
setuptools                72.1.0
shellingham               1.5.4
six                       1.16.0
smmap                     5.0.1
sniffio                   1.3.1
starlette                 0.38.5
streamlit                 1.38.0
streamlit-chat            0.1.1
sympy                     1.13.2
tenacity                  8.5.0
tokenizers                0.13.3
toml                      0.10.2
tomlkit                   0.12.0
torch                     2.2.2+cu118
torchaudio                2.2.2+cu118
torchvision               0.17.2+cu118
tornado                   6.4.1
tqdm                      4.66.5
transformers              4.27.1
typer                     0.12.5
typing_extensions         4.12.2
tzdata                    2024.1
urllib3                   2.2.3
uvicorn                   0.30.6
watchdog                  4.0.2
websockets                11.0.3
wheel                     0.44.0

要运行上述模型,我们需要的一些文件如下:

pytorch_model.bin
config.json
vocab.txt
tokenizer.json
tokenizer_config.json

项目运行代码调用

可以通过如下代码调用 ChatGLM2-6B 模型来生成对话:

from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True)
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True, device='cuda')
 model = model.eval()
response, history = model.chat(tokenizer, "你好", history=[])
print(response)
你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。
response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
print(response)

在运行过程中 ,会从 transformers中自动下载上述需要的文件的权重文件,如下:

C:\Users\pengxiang\.cache\huggingface\hub\models--THUDM--chatglm-6b

ChatGLM-6B部署到本地电脑_json_02

本地加载模型

但如果不能下载模型参数可能会花费较长时间甚至失败。此时可以先将模型下载到本地,然后从本地加载,当然此时我们需要修改一下对应的地址

Hugging Face Hub 下载模型需要先安装Git LFS,然后运行

git clone https://huggingface.co/THUDM/chatglm2-6b

如果你从 Hugging Face Hub 上下载 checkpoint 的速度较慢,可以只下载模型实现

GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm2-6b

然后从这里手动下载模型参数文件,并将下载的文件替换到本地的 chatglm-6b 目录下。

ChatGLM-6B部署到本地电脑_人工智能_03

代码如下:

ChatGLM-6B部署到本地电脑_人工智能_04

随后运行项目即可,访问下面的路径即可

ChatGLM-6B部署到本地电脑_人工智能_05

代码理解

首先是分词器,这个是将人类语言转换为向量形式,使用 AutoTokenizer编码语句

# 输入句子 
seq = "I want eat apple." 
# 将句子编码为模型输入格式 
output_token = tokenizer(seq, return_tensors='pt') 
print(output_token)
# 输出如下
"""
	{
	'input_ids': [101, 1045, 2215, 4521, 6207, 1012, 102],
	'token_type_ids': [0, 0, 0, 0, 0, 0, 0],
	'attention_mask': [1, 1, 1, 1, 1, 1, 1]
	}
"""

通过tokenizer之后,我们将人类语言转化为了机器语言,接下来就可以输入模型了。

前向传播:

# 模型前向传播 
output_text = model(**output_token) 
print(output_text)
# 输出如下
"""
MaskedLMOutput(loss=None, 
logits=tensor([[
[ -7.2956, -7.2397, -7.2123, ..., -6.6302, -6.5285, -4.5029], 
[-12.3488, -11.8462, -12.1994, ..., -11.4275, -10.0496, -10.4256], [-12.4339, -12.0643, -12.2072, ..., -9.8157, -10.9645, -12.5600], ..., 
[ -7.5780, -7.5130, -7.3408, ..., -7.6641, -6.0655, -7.4937], 
[-11.6407, -11.3535, -11.7890, ..., -10.2565, -10.7414, -4.9831], [-11.4632, -11.5140, -11.4960, ..., -9.2537, -8.9689, -8.3067]]], 
grad_fn=<ViewBackward0>), hidden_states=None, attentions=None)

通过AutoModelForMaskedLM,我们将输入转化为了一系列的预测分数(logits),之后在对它们进行归一化就可以得到概率啦。这个概率会对应我们的分词表,随后根据概率查询对应的分词转换为人类语言即可。

效果展示

该模型部署后的显存占用情况如下:

ChatGLM-6B部署到本地电脑_json_06

ChatGLM-6B部署到本地电脑_语言模型_07

随便提一个问题,说起来确实一套一套的,好像谁不知道似的,说点干活嘛。

ChatGLM-6B部署到本地电脑_git_08