Ubuntu系统下ChatGLM2-6b环境搭建与GPU驱动配置指南

📅 2026/7/17 2:58:54 👁️ 阅读次数 📝 编程学习
Ubuntu系统下ChatGLM2-6b环境搭建与GPU驱动配置指南

1. 环境准备:Ubuntu系统与GPU驱动配置

在开始搭建ChatGLM2-6b环境之前,我们需要确保基础环境配置正确。我推荐使用Ubuntu 20.04 LTS或22.04 LTS版本,这两个版本在深度学习社区中被广泛验证过稳定性。以下是详细的配置步骤:

1.1 系统基础环境检查

首先确认你的系统架构和内核版本:

uname -m # 确认是x86_64架构 lsb_release -a # 查看Ubuntu具体版本

对于GPU服务器,建议禁用自动更新以避免驱动冲突:

sudo apt-mark hold linux-image-generic linux-headers-generic sudo systemctl stop unattended-upgrades sudo systemctl disable unattended-upgrades

1.2 NVIDIA驱动安装实战

驱动安装是第一个容易踩坑的地方。根据我的经验,不要使用Ubuntu自带的"附加驱动"工具,而是直接从NVIDIA官网下载对应驱动:

  1. 先卸载已有驱动(如果是新系统可跳过):
sudo apt purge nvidia* sudo apt autoremove
  1. 安装编译依赖:
sudo apt update sudo apt install build-essential dkms libglvnd-dev
  1. 下载官方驱动(以515版本为例):
wget https://us.download.nvidia.com/XFree86/Linux-x86_64/515.76/NVIDIA-Linux-x86_64-515.76.run sudo chmod +x NVIDIA-Linux-x86_64-515.76.run sudo ./NVIDIA-Linux-x86_64-515.76.run --no-opengl-files -Z --dkms

重要提示:一定要加--no-opengl-files参数,否则可能导致图形界面崩溃。安装完成后需要重启系统。

验证驱动是否安装成功:

nvidia-smi # 应该能看到GPU信息和驱动版本

1.3 CUDA Toolkit选择与安装

ChatGLM2-6b需要CUDA 11.7或更高版本。我推荐使用runfile方式安装而非apt,因为可以更灵活地选择组件:

wget https://developer.download.nvidia.com/compute/cuda/11.7.1/local_installers/cuda_11.7.1_515.65.01_linux.run sudo sh cuda_11.7.1_515.65.01_linux.run

安装时注意:

  • 取消勾选Driver(已单独安装)
  • 确保勾选CUDA Toolkit和cuDNN
  • 添加环境变量到~/.bashrc:
export PATH=/usr/local/cuda-11.7/bin${PATH:+:${PATH}} export LD_LIBRARY_PATH=/usr/local/cuda-11.7/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

1.4 cuDNN与TensorRT安装

这些加速库对性能影响很大,建议从NVIDIA官网下载对应版本:

sudo apt install libcudnn8 libcudnn8-dev sudo apt install libnvinfer8 libnvinfer-plugin8 libnvinfer-dev libnvinfer-plugin-dev

验证安装:

nvcc -V # 查看CUDA编译器版本 cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2 # 查看cuDNN版本

2. Python环境与依赖库配置

2.1 Conda环境创建

我强烈建议使用conda隔离环境,避免包冲突:

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh source ~/.bashrc conda create -n chatglm python=3.8 conda activate chatglm

2.2 PyTorch GPU版本安装

PyTorch版本必须与CUDA匹配。对于CUDA 11.7:

pip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu117

验证PyTorch是否能识别GPU:

import torch print(torch.cuda.is_available()) # 应该返回True print(torch.cuda.get_device_name(0)) # 显示GPU型号

2.3 其他关键依赖

ChatGLM2-6b需要一些特定版本的库:

pip install transformers==4.33.3 icetk cpm_kernels sentencepiece gradio mdtex2html

特别注意:如果遇到protobuf版本冲突,可以尝试:

pip install protobuf==3.20.0

3. ChatGLM2-6b模型部署

3.1 模型下载与准备

从Hugging Face下载模型(需要先同意协议):

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

如果网络不稳定,可以使用镜像源:

git clone https://hf-mirror.com/THUDM/chatglm2-6b

3.2 模型加载测试

创建一个测试脚本test_load.py

from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("./chatglm2-6b", trust_remote_code=True) model = AutoModel.from_pretrained("./chatglm2-6b", trust_remote_code=True).cuda() response, history = model.chat(tokenizer, "你好", history=[]) print(response)

运行时应能看到模型成功加载并返回响应。如果出现OOM错误,可能需要启用量化:

model = AutoModel.from_pretrained("./chatglm2-6b", trust_remote_code=True).quantize(4).cuda()

3.3 常见加载问题解决

问题1:CUDA out of memory

  • 解决方案:减小batch size或使用量化
  • 修改加载代码:
model = AutoModel.from_pretrained("./chatglm2-6b", trust_remote_code=True).half().cuda()

问题2:Transformers版本不兼容

  • 解决方案:固定特定版本
pip install transformers==4.33.3

问题3:Protobuf冲突

  • 解决方案:
pip uninstall protobuf pip install protobuf==3.20.0

4. P-Tuning微调实战

4.1 准备训练数据

创建train.jsonl文件,格式示例:

{"prompt": "解释神经网络", "response": "神经网络是...", "history": []} {"prompt": "Python的装饰器", "response": "装饰器是...", "history": []}

建议数据量至少1000条,领域要集中。

4.2 配置P-Tuning参数

修改ptuning/train.sh关键参数:

PRE_SEQ_LEN=128 LR=2e-4 NUM_GPUS=1 torchrun --standalone --nnodes=1 --nproc-per-node=$NUM_GPUS main.py \ --do_train \ --train_file train.jsonl \ --validation_file dev.jsonl \ --pre_seq_len $PRE_SEQ_LEN \ --max_source_length 256 \ --max_target_length 256 \ --per_device_train_batch_size 8 \ --per_device_eval_batch_size 8 \ --gradient_accumulation_steps 4 \ --lr $LR \ --num_train_epochs 10 \ --save_steps 1000 \ --output_dir output \ --overwrite_output_dir

4.3 启动训练

bash train.sh

监控GPU使用情况:

watch -n 1 nvidia-smi

4.4 常见训练问题

问题1:Loss不下降

  • 检查学习率是否合适
  • 确认数据质量,可能需要清洗数据
  • 尝试调整pre_seq_len(通常64-256之间)

问题2:GPU内存不足

  • 减小per_device_train_batch_size
  • 增加gradient_accumulation_steps
  • 使用--fp16参数启用混合精度

问题3:NaN损失

  • 尝试减小学习率
  • 添加梯度裁剪:
--max_grad_norm 1.0

5. 模型部署与性能优化

5.1 量化部署

为了减少显存占用,可以使用4-bit或8-bit量化:

model = AutoModel.from_pretrained("./chatglm2-6b", trust_remote_code=True).quantize(8).cuda()

量化后显存占用可以从13GB降到6GB左右。

5.2 使用vLLM加速

安装vLLM:

pip install vllm

启动API服务:

python -m vllm.entrypoints.api_server --model chatglm2-6b --tokenizer chatglm2-6b --tensor-parallel-size 1

5.3 性能监控与调优

使用JTop监控:

pip install jetson-stats jtop

关注以下指标:

  • GPU Util:应该保持在70%以上
  • Memory Usage:避免接近100%
  • Temperature:保持在80°C以下

我在实际部署中发现,调整max_batch_sizemax_seq_len对吞吐量影响很大,需要根据具体硬件找到平衡点。