博主原文链接:https://www.yourmetaverse.cn/llm/213/
大模型部署实战(三)——ChatGLM-6B
ChatGLM-6B 是一个开源的、支持中英双语的对话语言模型,基于 General Language Model (GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。 ChatGLM-6B 使用了和 ChatGPT 相似的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。本文基于ChatGLM官方代码演示如何部署ChatGLM模型。
在线体验地址:
- 博主自己部署的地址:http://www.yourmetaverse.cn:39002/
1.部署准备
1.1 硬件环境
量化等级 | 最低 GPU 显存(推理) | 最低 GPU 显存(高效参数微调) |
---|---|---|
FP16(无量化) | 13 GB | 14 GB |
INT8 | 8 GB | 9 GB |
INT4 | 6 GB | 7 GB |
1.2 python环境
protobuf
transformers==4.27.1
cpm_kernels
torch>=1.10
gradio
mdtex2html
sentencepiece
accelerate
1.3 模型下载
可以从以下网址下载ChatGLM的模型参数:
https://huggingface.co/THUDM/chatglm-6b/tree/main
int8量化后的模型参数可以从下面网址下载:
https://huggingface.co/THUDM/chatglm-6b-int8/tree/main
int4量化后的模型参数可以从下面网址下载:
https://huggingface.co/THUDM/chatglm-6b-int4/tree/main
2. 模型部署
首先说明一下项目的文件系统目录
-chatglm-6b
-chatglm-6b-int8
-chatglm-6b-int4
-launch.py
import os
from transformers import AutoModel, AutoTokenizer
import gradio as gr
import mdtex2html
# 设置GPU ID
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
# 这里需要将模型路径修改为你自己下载ChatGLM模型的路径,我这里默认下载到./chatglm-6b路径下面
tokenizer = AutoTokenizer.from_pretrained("./chatglm-6b", trust_remote_code=True)
# 这里需要将模型路径修改为你自己下载ChatGLM模型的路径,我这里默认下载到./chatglm-6b路径下面
model = AutoModel.from_pretrained("./chatglm-6b", trust_remote_code=True).half().cuda()
model = model.eval()
"""Override Chatbot.postprocess"""
def postprocess(self, y):
if y is None:
return []
for i, (message, response) in enumerate(y):
y[i] = (
None if message is None else mdtex2html.convert((message)),
None if response is None else mdtex2html.convert(response),
)
return y
gr.Chatbot.postprocess = postprocess
def parse_text(text):
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
lines = text.split("\n")
lines = [line for line in lines if line != ""]
count = 0
for i, line in enumerate(lines):
if "```" in line:
count += 1
items = line.split('`')
if count % 2 == 1:
lines[i] = f'<pre><code class="language-{items[-1]}">'
else:
lines[i] = f'<br></code></pre>'
else:
if i > 0:
if count % 2 == 1:
line = line.replace("`", "\`")
line = line.replace("<", "<")
line = line.replace(">", ">")
line = line.replace(" ", " ")
line = line.replace("*", "*")
line = line.replace("_", "_")
line = line.replace("-", "-")
line = line.replace(".", ".")
line = line.replace("!", "!")
line = line.replace("(", "(")
line = line.replace(")", ")")
line = line.replace("$", "$")
lines[i] = "<br>"+line
text = "".join(lines)
return text
def predict(input, chatbot, max_length, top_p, temperature, history):
chatbot.append((parse_text(input), ""))
for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p,
temperature=temperature):
chatbot[-1] = (parse_text(input), parse_text(response))
yield chatbot, history
def reset_user_input():
return gr.update(value='')
def reset_state():
return [], []
with gr.Blocks() as demo:
gr.HTML("""<h1 align="center">ChatGLM</h1>""")
chatbot = gr.Chatbot()
with gr.Row():
with gr.Column(scale=4):
with gr.Column(scale=12):
user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10).style(
container=False)
with gr.Column(min_width=32, scale=1):
submitBtn = gr.Button("Submit", variant="primary")
with gr.Column(scale=1):
emptyBtn = gr.Button("Clear History")
max_length = gr.Slider(0, 4096, value=2048, step=1.0, label="Maximum length", interactive=True)
top_p = gr.Slider(0, 1, value=0.7, step=0.01, label="Top P", interactive=True)
temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True)
history = gr.State([])
submitBtn.click(predict, [user_input, chatbot, max_length, top_p, temperature, history], [chatbot, history],
show_progress=True)
submitBtn.click(reset_user_input, [], [user_input])
emptyBtn.click(reset_state, outputs=[chatbot, history], show_progress=True)
demo.queue().launch(share=False,server_name="127.0.0.1", server_port=7886, inbrowser=False)
该代码中需要修改的地方已经在代码块上标出。