ChatGLM-6B 使用、微调与训练指南
本文介绍了 ChatGLM-6B 大模型的基本架构、环境配置、推理方法及微调流程。内容涵盖 GLM 架构原理、基于 HuggingFace 的模型加载与对话代码、P-Tuning V2 参数高效微调方案以及 INT8 量化部署技巧。文章旨在帮助开发者在消费级显卡上快速上手大模型的本地化应用与定制开发。

本文介绍了 ChatGLM-6B 大模型的基本架构、环境配置、推理方法及微调流程。内容涵盖 GLM 架构原理、基于 HuggingFace 的模型加载与对话代码、P-Tuning V2 参数高效微调方案以及 INT8 量化部署技巧。文章旨在帮助开发者在消费级显卡上快速上手大模型的本地化应用与定制开发。

ChatGLM-6B 是由清华大学知识工程实验室(KEG)和智谱 AI 公司于 2023 年共同训练的开源语言模型。该模型基于 GLM(General Language Model)架构,拥有 62 亿参数。相较于需要万卡集群训练的 ChatGPT,ChatGLM-6B 经过优化,可以在消费级显卡上运行(建议显存 16GB-24GB,最低 13GB),极大地降低了大模型的使用门槛。
GLM 架构旨在统一三种主流的预训练模型模式:
ChatGLM-6B 通过掩码自回归预测(Masked Autoregressive Prediction)的方式,结合了上述优势,实现了高效的预训练与微调。
在使用 ChatGLM-6B 之前,需要配置好 Python 环境和相关依赖库。推荐使用 CUDA 11.x 或更高版本的 GPU 加速环境。
pip install transformers>=4.28.0
pip install sentencepiece
pip install cpm_kernels
pip install gradio
pip install mdtex2html
加载预训练模型并进行简单的问答交互。
from transformers import AutoTokenizer, AutoModel
import torch
# 加载分词器和模型
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
# 创建对话历史
history = []
response, history = model.chat(tokenizer, "你好", history=history)
print(response)
# 多轮对话
response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
print(response)
为了提升用户体验,支持流式输出(Streaming Output)。
for response, history in model.stream_chat(tokenizer, "请介绍一下你自己", history=[]):
print(response)
直接使用全量参数微调大模型成本过高,通常采用参数高效微调(PEFT)技术。ChatGLM-6B 官方推荐使用 P-Tuning V2。
P-Tuning V2 将需要微调的参数减少到原来的 0.1%-3%,主要更新 PrefixEncoder 部分,大幅降低显存占用并加快训练速度。
instruction, input, output 字段。ptuning/configs/finetune_config.json,设置数据路径、学习率等参数。bash train.sh
PrefixEncoder 的权重文件。微调后的模型推理时,需同时加载原始基座模型和微调后的 PrefixEncoder 权重。
from peft import PeftModel
from transformers import AutoModel, AutoTokenizer
base_model = AutoModel.from_pretrained('THUDM/chatglm-6b', trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained('THUDM/chatglm-6b', trust_remote_code=True)
peft_model = PeftModel.from_pretrained(base_model, 'path/to/your/adapter')
response, history = peft_model.chat(tokenizer, "测试问题", history=[])
为了进一步降低资源消耗,可以使用 INT8 量化技术。
from transformers import AutoModel, AutoTokenizer
model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
model = model.quantize(8)
model = model.half().cuda()
device_map="auto" 自动分配设备,或开启 INT8 量化。temperature 和 top_p 参数,增加多样性或确定性。ChatGLM-6B 是一个优秀的开源中文大模型,适用于个人开发者及中小企业进行私有化部署。通过 P-Tuning V2 和量化技术,可以在有限的硬件资源下实现高效的微调与推理。随着生态的发展,更多工具链正在完善,建议关注官方 GitHub 仓库获取最新进展。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online