模型量化
量化是把模型参数从高精度(FP16/BF16)压缩到低精度(INT8/INT4)的技术。显存减半,速度翻倍,精度几乎不降。
为什么需要量化?
Section titled “为什么需要量化?”Llama-7B 的参数:
- FP16:7B × 2 字节 = 14 GB 显存
- INT4:7B × 0.5 字节 = 3.5 GB 显存
一张 RTX 3060 (12GB) 就能跑 7B 模型。
flowchart LR A[FP16 权重<br/>2 字节/参数] -->|量化| B[INT4 权重<br/>0.5 字节/参数] B -->|推理时反量化| C[FP16 计算]量化公式:
使用 bitsandbytes 量化
Section titled “使用 bitsandbytes 量化”from transformers import AutoModelForCausalLM, BitsAndBytesConfigimport torch
# 4-bit 量化配置bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", # 4-bit NormalFloat bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, # 双重量化,进一步压缩)
model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-3.2-3B", quantization_config=bnb_config, device_map="auto",)print(f"显存: {model.get_memory_footprint() / 1e9:.1f} GB")量化方法对比
Section titled “量化方法对比”| 方法 | 精度 | 速度 | 特点 |
|---|---|---|---|
| GPTQ | INT4/INT8 | 快 | 需要校准数据,一次性量化 |
| AWQ | INT4 | 快 | 保护重要权重通道 |
| bitsandbytes | INT4/INT8 | 中 | 动态量化,即插即用 |
| GGUF | INT4-INT8 | 中 | llama.cpp 格式,CPU 友好 |
量化对精度的影响
Section titled “量化对精度的影响”# 模拟量化误差import torch
x = torch.randn(1000) * 3 # 原始数据
# 模拟 INT4 量化(16 个值)scale = (x.max() - x.min()) / 15x_quant = torch.round(x / scale) * scale
error = (x - x_quant).abs().mean()print(f"平均量化误差: {error:.4f}")print(f"相对误差: {error / x.abs().mean() * 100:.1f}%")- 本地跑大模型:bitsandbytes 4-bit(最简单)
- 部署到生产:GPTQ 或 AWQ(更快)
- 边缘设备/CPU:GGUF(llama.cpp)