主题
GPU 环境配置
在本地或服务器上运行 LLM 需要正确配置 GPU 环境。
硬件选择
消费级 GPU(个人使用)
| GPU | 显存 | 能跑的模型 | 价格区间 |
|---|---|---|---|
| RTX 3060 | 12GB | 7B(量化) | ¥2000 |
| RTX 4070 Ti | 12GB | 7B | ¥5000 |
| RTX 4090 | 24GB | 7B(满精度)、13B | ¥13000 |
| RTX 3090(二手) | 24GB | 7B、13B | ¥5000 |
专业级 GPU(生产环境)
| GPU | 显存 | 特点 | 价格 |
|---|---|---|---|
| A100 40GB | 40GB | 最快 | ¥50000+ |
| A100 80GB | 80GB | 能跑 70B | ¥80000+ |
| L40S | 48GB | 推理优化 | ¥30000+ |
| H100 | 80GB | 最新最强 | ¥200000+ |
软件环境配置
1. 安装 NVIDIA 驱动
bash
# 查看显卡
nvidia-smi
# 如果没有输出,需要安装驱动
# Ubuntu
sudo apt update
sudo apt install nvidia-driver-535
# 安装后重启
sudo reboot2. 安装 CUDA Toolkit
bash
# 查看 CUDA 版本
nvcc --version
# 如果没有,安装 CUDA 12.1
# 从 NVIDIA 官网下载安装包
# https://developer.nvidia.com/cuda-toolkit3. 安装 cuDNN
bash
# 从 NVIDIA 官网下载
# https://developer.nvidia.com/cudnn4. 验证 GPU 可用(PyTorch)
python
import torch
print(torch.cuda.is_available()) # True = GPU 可用
print(torch.cuda.get_device_name(0)) # GPU 型号Docker 方式(推荐)
用 NVIDIA 官方 Docker 镜像,避免环境配置问题:
bash
# 安装 NVIDIA Container Toolkit
# https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/
# 运行 PyTorch 容器
docker run --gpus all -it --rm \
-v $(pwd):/workspace \
pytorch/pytorch:2.1.0-cuda12.1-cudnn8-runtime \
python /workspace/test.py显存估算
模型加载所需显存 ≈ 参数量 × 每个参数的字节数
FP16(半精度):每个参数 2 字节
FP32(全精度):每个参数 4 字节
INT8(量化):每个参数 1 字节
INT4(量化):每个参数 0.5 字节
例:Llama 3.1 8B(80 亿参数)
- FP16:8B × 2B = 16GB
- INT4:8B × 0.5B = 4GB
加上 KV Cache 和中间激活值,实际需要的显存更多。多 GPU 配置
数据并行(Data Parallel)
一个模型复制多份,分别处理不同数据:
python
# PyTorch
model = nn.DataParallel(model)模型并行(Model Parallel)
模型太大,分到多个 GPU 上:
python
# 用 vLLM 或 DeepSpeed 自动处理
# 手动(PyTorch):
model.layer1.to("cuda:0")
model.layer2.to("cuda:1")云 GPU 租赁
如果没有本地 GPU,可以租云 GPU:
| 平台 | 特点 |
|---|---|
| AutoDL | 国内,便宜,RTX 4090 ¥3/小时 |
| RunPod | 国际,支持多种 GPU |
| Lambda Labs | 专业,A100 可用 |
| Google Colab | 免费(有限制),付费 $10/月 |