量化基础、GPTQ/AWQ/SmoothQuant、GGUF、INT4推理、QLoRA、QAT、误差分析
量化是将高精度浮点数(FP32/FP16/BF16)映射到低精度整数(INT8/INT4/INT2)的过程,以减少模型存储和计算开销。一个7B模型从FP16量化到INT4,体积从14GB降至约3.5GB,推理速度提升2-4倍。
对称量化以0为中心,量化范围[-r, r]映射到[-127, 127](INT8)或[-7, 7](INT4)。公式:q = round(x / s),s = r / q_max,其中r = max(|x|)。
import numpy as np
import torch
# 对称量化: 以0为中心
def symmetric_quantize(tensor, n_bits=8):
"""对称量化到n_bits整数"""
q_max = 2 ** (n_bits - 1) - 1 # INT8: 127, INT4: 7
# 量化范围: r = max(|x|)
r = tensor.abs().max()
scale = r / q_max # 量化步长
# 量化: q = round(x / s)
quantized = torch.round(tensor / scale).clamp(-q_max, q_max).to(torch.int8)
return quantized, scale
# 反量化: x ≈ q * s
def dequantize(quantized, scale):
return quantized.float() * scale
# 示例
x = torch.randn(100) * 2 # 原始权重
q, s = symmetric_quantize(x, n_bits=8)
x_recovered = dequantize(q, s)
error = (x - x_recovered).abs().mean()
print(f"对称量化误差(MAE): {error:.6f}")
非对称量化不假设数据以0为中心,使用零点z和缩放因子s:q = round(x/s + z),s = (x_max - x_min) / (q_max - q_min),z = round(q_min - x_min/s)。
# 非对称量化: 适用于偏移分布 (如ReLU输出全为正)
def asymmetric_quantize(tensor, n_bits=8):
"""非对称量化: 引入零点z"""
q_min = 0
q_max = 2 ** n_bits - 1 # INT8: 255 (无符号)
x_min = tensor.min()
x_max = tensor.max()
# 缩放因子和零点
scale = (x_max - x_min) / (q_max - q_min)
zero_point = torch.round(q_min - x_min / scale).clamp(q_min, q_max)
# 量化: q = round(x/s + z)
quantized = torch.round(tensor / scale + zero_point).clamp(q_min, q_max).to(torch.int32)
return quantized, scale, zero_point
# 反量化: x ≈ (q - z) * s
def asymmetric_dequantize(quantized, scale, zero_point):
return (quantized.float() - zero_point) * scale
# 对比: 激活值全为正时非对称更优
activations = torch.rand(1000) * 3 # ReLU输出, 全正
q_sym, s_sym = symmetric_quantize(activations)
q_asym, s_asym, z = asymmetric_quantize(activations)
err_sym = (activations - dequantize(q_sym, s_sym)).abs().mean()
err_asym = (activations - asymmetric_dequantize(q_asym, s_asym, z)).abs().mean()
print(f"对称误差: {err_sym:.6f}, 非对称误差: {err_asym:.6f}")
# 逐Channel量化: 每个输出通道独立量化参数
def per_channel_quantize(weight, n_bits=8):
"""
weight: [out_features, in_features]
每个输出通道(out_features)有独立的scale和zero_point
"""
q_max = 2 ** (n_bits - 1) - 1
# 沿输入维度计算每通道的最大值
scales = weight.abs().amax(dim=1) / q_max # [out_features]
scales = scales.clamp(min=1e-8) # 避免除0
# 量化
quantized = torch.round(weight / scales.unsqueeze(1)).clamp(-q_max, q_max)
return quantized, scales
# 逐Group量化: 将通道分组, 每组独立量化 (更细粒度)
def per_group_quantize(weight, group_size=128, n_bits=4):
"""
将in_features分成若干group_size的组, 每组独立量化
group_size=128是AWQ的默认值
"""
q_max = 2 ** (n_bits - 1) - 1
out_features, in_features = weight.shape
# 确保in_features能被group_size整除
assert in_features % group_size == 0
num_groups = in_features // group_size
# 重排: [out_features, num_groups, group_size]
weight_grouped = weight.reshape(out_features, num_groups, group_size)
# 每组独立计算scale
scales = weight_grouped.abs().amax(dim=-1) / q_max # [out, num_groups]
scales = scales.clamp(min=1e-8)
# 量化
quantized = torch.round(weight_grouped / scales.unsqueeze(-1)).clamp(-q_max, q_max)
return quantized.reshape(out_features, in_features), scales
| 粒度 | 参数量 | 精度 | 开销 | 适用场景 |
|---|---|---|---|---|
| 逐Tensor | 1组scale/zp | 最低 | 最小 | 全局量化 |
| 逐Channel | C组(输出通道数) | 中等 | 小 | 权重量化 |
| 逐Group(128) | C×(K/128)组 | 高 | 中 | INT4权重量化 |
| 逐Group(32) | C×(K/32)组 | 最高 | 大 | 极低比特量化 |
GPTQ(Frantar et al., 2022)利用Hessian矩阵的近似信息逐列量化权重,补偿量化误差。核心思想:量化一列后,将量化误差分摊到未量化列上,最小化输出误差。
import torch
import math
# GPTQ算法完整实现
def gptq_quantize(
W, # 权重矩阵 [out_features, in_features]
X, # 校准数据输入 [n_samples, in_features]
n_bits=4,
group_size=128,
actorder="desc", # 按Hessian对角排序
):
"""
GPTQ量化算法:
1. 计算Hessian H = 2 * X^T * X
2. 按H对角线排序列 (可选)
3. 逐列量化, 用未量化列补偿误差
"""
out_features, in_features = W.shape
q_max = 2 ** (n_bits - 1) - 1
# Step 1: 计算Hessian H = 2 * X^T * X
H = 2 * (X.float().T @ X.float()) # [in_features, in_features]
H += 1e-5 * torch.eye(in_features, device=H.device) # 正则化
# Step 2: 按Hessian对角排序 (降低量化误差)
if actorder == "desc":
diag = torch.diag(H)
perm = torch.argsort(diag, descending=True)
W = W[:, perm]
H = H[perm][:, perm]
# Step 3: Cholesky分解 (数值稳定性)
dead = torch.diag(H) == 0
H[dead, dead] = 1.0
if actorder:
H = -torch.linalg.cholesky(-H, upper=True)
W_quantized = W.clone()
scales = torch.zeros(out_features, in_features // group_size)
# Step 4: 逐列量化
for i in range(in_features):
# 当前列
w_col = W_quantized[:, i]
# 计算当前列的scale (逐group)
group_idx = i // group_size
if i % group_size == 0:
group_w = W_quantized[:, group_idx*group_size:(group_idx+1)*group_size]
scales[:, group_idx] = group_w.abs().amax(dim=1) / q_max
scale = scales[:, group_idx].unsqueeze(1)
scale = scale.clamp(min=1e-8)
# 量化当前列
q_col = torch.round(w_col / scale.squeeze()).clamp(-q_max, q_max)
err = (w_col - q_col * scale.squeeze()) / H[i, i] # 量化误差
W_quantized[:, i] = q_col
# 将误差分摊到未量化列: W[:, j] -= err * H[j, i]
if i < in_features - 1:
W_quantized[:, i+1:] -= err.unsqueeze(1) * H[i, i+1:].unsqueeze(0)
# 恢复原始列顺序
if actorder:
inv_perm = torch.argsort(perm)
W_quantized = W_quantized[:, inv_perm]
return W_quantized, scales
# 使用AutoGPTQ量化模型
from auto_gptq import BaseQuantizeConfig, AutoGPTQForCausalLM
from transformers import AutoTokenizer
# 量化配置
quantize_config = BaseQuantizeConfig(
bits=4, # 量化比特数
group_size=128, # 逐group量化
desc_act=True, # 激活排序 (降低误差)
sym=True, # 对称量化
)
# 准备校准数据
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3-8B")
calibration_texts = [
"人工智能是计算机科学的一个分支...",
"机器学习是研究如何让计算机...",
"深度学习使用多层神经网络...",
# ... 通常需要128-512条校准样本
]
# 量化模型
model = AutoGPTQForCausalLM.from_pretrained(
"meta-llama/Llama-3-8B",
quantize_config,
)
model.quantize(calibration_texts, batch_size=4)
# 保存量化模型
model.save_quantized("./llama3-8b-gptq-4bit")
tokenizer.save_pretrained("./llama3-8b-gptq-4bit")
# 加载量化模型推理
model = AutoGPTQForCausalLM.from_quantized("./llama3-8b-gptq-4bit", device="cuda:0")
output = model.generate("什么是深度学习?", max_new_tokens=100)
AWQ(Lin et al., 2023)观察到并非所有权重同等重要——对应大激活值的权重对量化更敏感。AWQ通过搜索最优缩放因子保护"显著"权重,无需反向传播,速度比GPTQ快2倍。
AWQ将权重分为显著和非显著两部分。对显著权重乘以s放大(量化后精度更高),对对应激活除以s补偿,保持等价性:Q(W·s) · (X/s) ≈ W·X。
import torch
import torch.nn.functional as F
# AWQ: 激活感知权重量化
def awq_search_scale(W, X, n_bits=4, grid_size=20, max_shrink=0.5):
"""
搜索最优缩放因子s
W: [out_features, in_features] 权重
X: [n_samples, in_features] 激活
"""
q_max = 2 ** (n_bits - 1) - 1
out_features, in_features = W.shape
# Step 1: 找出显著权重 (对应大激活的权重)
# 激活幅度: 沿batch维度取平均
x_mean = X.abs().mean(dim=0) # [in_features]
# Step 2: 网格搜索最优s
best_scales = torch.ones(in_features)
best_loss = float('inf')
for shrink in torch.linspace(1.0, 1.0 - max_shrink, grid_size):
# 缩放因子: s = (x_max / x_mean) ^ shrink
s = (x_mean.max() / x_mean.clamp(min=1e-5)) ** shrink
s = s / s.mean() # 归一化
# 量化: Q(W * diag(s))
W_scaled = W * s.unsqueeze(0)
W_quant = torch.round(W_scaled / (W_scaled.abs().amax(dim=1, keepdim=True) / q_max)).clamp(-q_max, q_max)
W_dequant = W_quant * (W_scaled.abs().amax(dim=1, keepdim=True) / q_max)
# 反缩放: W_dequant / diag(s)
W_recovered = W_dequant / s.unsqueeze(0)
# 计算量化误差: ||W·X - W_recovered·X||^2
loss = ((W @ X.T - W_recovered @ X.T) ** 2).mean()
if loss < best_loss:
best_loss = loss
best_scales = s
return best_scales
# AWQ量化完整流程
def awq_quantize(W, X, n_bits=4, group_size=128):
# 1. 搜索最优缩放
scales = awq_search_scale(W, X, n_bits)
# 2. 应用缩放: W' = W * diag(s), X' = X / diag(s)
W_scaled = W * scales.unsqueeze(0)
# 3. 逐group量化
q_max = 2 ** (n_bits - 1) - 1
out_features, in_features = W.shape
num_groups = in_features // group_size
W_grouped = W_scaled.reshape(out_features, num_groups, group_size)
group_scales = W_grouped.abs().amax(dim=-1) / q_max
W_quant = torch.round(W_grouped / group_scales.unsqueeze(-1)).clamp(-q_max, q_max)
return W_quant.reshape(out_features, in_features), group_scales, scales
# 使用AutoAWQ量化
from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer
model_path = "meta-llama/Llama-3-8B"
quant_path = "./llama3-8b-awq-4bit"
# AWQ配置
quant_config = {
"zero_point": True, # 使用非对称量化
"q_group_size": 128, # group大小
"w_bit": 4, # 权重比特数
"version": "GEMM", # GEMM版本更快
}
# 加载并量化
model = AutoAWQForCausalLM.from_pretrained(model_path, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_path)
# 校准数据
calib_data = ["人工智能正在改变世界。", "深度学习是机器学习的子领域。"] * 64
model.quantize(tokenizer, quant_config=quant_config, calib_data=calib_data)
model.save_quantized(quant_path)
tokenizer.save_pretrained(quant_path)
# AWQ vs GPTQ 对比:
# AWQ: 更快量化(无需反向传播), 精度略好, 推理速度快
# GPTQ: 精度更高(二阶补偿), 量化慢(需校准), 生态成熟
SmoothQuant(Xiao et al., 2022)解决INT8量化中激活值离群点的问题。通过将激活的难度迁移到权重上:X·W = (X/s)·(s·W),使激活和权重都易于量化。
# SmoothQuant: 平滑激活离群点
def smooth_quant(W, X, alpha=0.5):
"""
SmoothQuant: 将激活难度迁移到权重
X * W = (X/s) * (s*W)
s = (max|X|^alpha / max|W|^(1-alpha))^0.5
"""
# 计算激活和权重的最大幅度
x_max = X.abs().amax(dim=0) # [in_features]
w_max = W.abs().amax(dim=0) # [in_features]
# 计算平滑因子
# alpha=0.5: 平衡激活和权重的量化难度
s = torch.pow(x_max ** alpha / w_max.clamp(min=1e-5) ** (1 - alpha), 0.5)
s = s.clamp(min=1e-5)
# 平滑: 激活除以s, 权重乘以s
X_smoothed = X / s.unsqueeze(0)
W_smoothed = W * s.unsqueeze(0)
return W_smoothed, X_smoothed, s
# 完整SmoothQuant量化流程
def smoothquant_model(model, calibration_data, alpha=0.5):
"""对模型每一层应用SmoothQuant + INT8量化"""
for name, module in model.named_modules():
if "Linear" in type(module).__name__:
# 收集激活统计
with torch.no_grad():
acts = collect_activations(module, calibration_data)
# 平滑
W_smooth, X_smooth, s = smooth_quant(module.weight.data, acts, alpha)
# 应用平滑到权重
module.weight.data = W_smooth
# 如果有前一层的权重, 需要除以s (融合到前一层的输出)
# 这通过修改前一层的weight/bias实现
apply_scale_to_previous_layer(module, s)
# 然后进行标准INT8量化
return quantize_int8(model)
| alpha | 激活量化难度 | 权重量化难度 | 适用场景 |
|---|---|---|---|
| 0.0 | 全部在权重 | 最大 | 权重分布均匀 |
| 0.5 | 平衡 | 平衡 | 通用推荐 |
| 0.75 | 较大 | 较小 | 激活离群点多 |
| 1.0 | 最大 | 最小 | 仅量化激活 |
GGUF(GPT-Generated Unified Format)是llama.cpp使用的模型文件格式,替代了旧的GGML格式。支持多种量化类型,可在CPU上运行量化模型。
| 类型 | 比特/权重 | 7B模型大小 | 质量损失 | 速度 |
|---|---|---|---|---|
| Q8_0 | 8.5 | ~7.2GB | 极小 | 快 |
| Q6_K | 6.0 | ~5.5GB | 很小 | 较快 |
| Q5_K_M | 5.5 | ~4.8GB | 小 | 中 |
| Q4_K_M | 4.5 | ~4.1GB | 中 | 中 |
| Q4_0 | 4.0 | ~3.6GB | 较大 | 快 |
| Q3_K_M | 3.5 | ~3.3GB | 大 | 较快 |
| Q2_K | 2.5 | ~2.7GB | 很大 | 快 |
# 将HuggingFace模型转换为GGUF格式
# 1. 克隆llama.cpp
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
# 2. 转换模型 (需要Python环境)
python convert_hf_to_gguf.py /path/to/hf-model --outfile model.gguf
# 3. 量化 (Q4_K_M)
./llama-quantize model.gguf model-Q4_K_M.gguf Q4_K_M
# 4. 推理
# CPU推理
./llama-cli -m model-Q4_K_M.gguf -p "什么是深度学习?" -n 200
# GPU推理 (CUDA)
cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release
./build/bin/llama-cli -m model-Q4_K_M.gguf -p "什么是深度学习?" -ngl 99
# 5. 启动API服务
./llama-server -m model-Q4_K_M.gguf --port 8080 -ngl 99 -c 4096
# 6. 多GPU推理
./llama-cli -m model-Q4_K_M.gguf -p "prompt" -ngl 99 -ts 2,1 # GPU0:2/3, GPU1:1/3
# GGUF文件结构 (二进制格式)
# Header:
# magic: "GGUF" (4 bytes)
# version: 3 (4 bytes, uint32)
# tensor_count: N (8 bytes, uint64)
# metadata_kv_count: M (8 bytes, uint64)
#
# Metadata KV pairs:
# key: string (length + UTF-8 bytes)
# value_type: enum (uint32)
# value: depends on type
#
# Key metadata fields:
# "general.name" - 模型名称
# "general.architecture" - 架构 (llama, qwen2, etc.)
# "llama.context_length" - 最大上下文长度
# "llama.embedding_length" - 隐藏维度
# "llama.block_count" - transformer层数
# "llama.attention.head_count" - 注意力头数
# "tokenizer.ggml.model" - tokenizer类型
# "tokenizer.ggml.tokens" - 词表
#
# Tensor info + data:
# name: string
# n_dims: uint32
# dims: uint64[]
# type: enum (GGML tensor type)
# offset: uint64 (from start of tensor data)
# data: raw bytes (aligned to 32 bytes)
# 使用gguf库读取
from gguf import GGUFReader
reader = GGUFReader("model-Q4_K_M.gguf")
print("Architecture:", reader.get_field("general.architecture"))
print("Context length:", reader.get_field("llama.context_length"))
print("Tensor count:", reader.tensor_count)
| 精度 | 模型大小 | 显存(7B) | 推理速度 | 困惑度 | MMLU |
|---|---|---|---|---|---|
| FP16 | 14.0GB | 16GB | 1.0× | 5.47 | 66.2 |
| INT8 (W8A16) | 7.2GB | 8GB | 1.5× | 5.48 | 66.1 |
| INT4 GPTQ | 3.8GB | 5GB | 2.5× | 5.56 | 65.5 |
| INT4 AWQ | 3.8GB | 5GB | 2.8× | 5.55 | 65.7 |
| INT4 GGUF Q4_K_M | 4.1GB | 5GB | 2.3× | 5.58 | 65.2 |
| INT2 Q2_K | 2.7GB | 3.5GB | 3.0× | 6.20 | 58.0 |
import torch
import numpy as np
# 量化误差分析: 不同比特数的量化误差
def analyze_quantization_error(weight, bits_list=[2, 3, 4, 8, 16]):
results = []
for n_bits in bits_list:
# 对称量化
q_max = 2 ** (n_bits - 1) - 1
scale = weight.abs().max() / q_max
quantized = torch.round(weight / scale).clamp(-q_max, q_max)
dequant = quantized * scale
# 误差指标
mae = (weight - dequant).abs().mean().item()
mse = ((weight - dequant) ** 2).mean().item()
rmse = math.sqrt(mse)
snr = 10 * torch.log10((weight ** 2).mean() / mse).item()
# 理论误差上界: Δ/2 = scale/2
theoretical_max = scale.item() / 2
results.append({
"bits": n_bits,
"MAE": mae,
"RMSE": rmse,
"SNR_dB": snr,
"max_error": (weight - dequant).abs().max().item(),
"theoretical_max": theoretical_max,
})
return results
# 分析实际模型权重的量化误差
weight = torch.randn(4096, 4096) * 0.02 # 模拟7B模型的一层权重
results = analyze_quantization_error(weight)
for r in results:
print(f"{r['bits']:2d}bit: MAE={r['MAE']:.6f} RMSE={r['RMSE']:.6f} SNR={r['SNR_dB']:.1f}dB")
QLoRA将4bit NF4量化的基座模型与LoRA适配器结合,使70B模型可在单张48GB GPU上微调,同时保持接近全参微调的效果。
NF4是QLoRA提出的量化格式,假设权重服从正态分布,量化点按正态分布的分位数设置,比均匀量化在4bit下精度更高。
# NF4量化点: 正态分布的16个分位数
import numpy as np
from scipy.stats import norm
# NF4的16个量化点 (对称, 包含0)
nf4_quantiles = np.array([
-1.0, -0.6961928009986877, -0.5250730553150024, -0.3949794855532024,
-0.28491549771063814, -0.18477207112316144, -0.09105935190449439, 0.0,
0.07995667831349297, 0.1609460578816231, 0.24712764030894886,
0.3414691617775409, 0.4472135954999579, 0.5695073180694013,
0.7211057663577506, 1.0
])
# NF4量化: 找最近的量化点
def nf4_quantize(tensor, nf4_points=nf4_quantiles):
"""将tensor量化到NF4的16个点之一"""
# 归一化到[-1, 1]
max_val = tensor.abs().max()
normalized = tensor / max_val
# 找最近的量化点
quantized = torch.zeros_like(normalized)
for i in range(normalized.numel()):
idx = torch.argmin(torch.abs(nf4_points - normalized.flatten()[i]))
quantized.flatten()[i] = nf4_points[idx]
# 反归一化
return quantized * max_val, max_val
# QLoRA完整训练流程
from transformers import BitsAndBytesConfig, AutoModelForCausalLM, TrainingArguments, Trainer
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
# 1. 4bit量化配置
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True, # 双重量化: 量化scale也量化
)
# 2. 加载4bit模型
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3-70B",
quantization_config=bnb_config,
device_map="auto",
)
# 3. 准备kbit训练
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
# 4. LoRA配置
lora_config = LoraConfig(
r=64,
lora_alpha=128,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
lora_dropout=0.05,
task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora_config)
# 5. 训练
training_args = TrainingArguments(
output_dir="./qlora_output",
per_device_train_batch_size=2,
gradient_accumulation_steps=16,
learning_rate=2e-4, # QLoRA用更高学习率
num_train_epochs=3,
bf16=True,
gradient_checkpointing=True,
optim="paged_adamw_8bit", # 分页优化器减少显存
)
trainer = Trainer(model=model, args=training_args, train_dataset=dataset)
trainer.train()
KV Cache在长上下文推理中占用大量显存。量化KV Cache可将显存占用降低2-4倍,支持更长上下文。
# KV Cache量化: FP16 -> INT8
class QuantizedKVCache:
"""量化KV Cache, 减少长上下文显存占用"""
def __init__(self, num_layers, num_heads, head_dim, max_seq_len, n_bits=8):
self.n_bits = n_bits
self.q_max = 2 ** (n_bits - 1) - 1
# 量化的K和V cache
shape = (num_layers, num_heads, max_seq_len, head_dim)
self.k_cache = torch.zeros(shape, dtype=torch.int8)
self.v_cache = torch.zeros(shape, dtype=torch.int8)
# 每层的量化scale
self.k_scales = torch.ones(num_layers, num_heads, max_seq_len)
self.v_scales = torch.ones(num_layers, num_heads, max_seq_len)
self.seq_len = 0
def update(self, layer_idx, new_k, new_v):
"""添加新的K, V到cache (量化存储)"""
# 量化
k_scale = new_k.abs().max() / self.q_max
v_scale = new_v.abs().max() / self.q_max
k_quant = torch.round(new_k / k_scale).clamp(-self.q_max, self.q_max).to(torch.int8)
v_quant = torch.round(new_v / v_scale).clamp(-self.q_max, self.q_max).to(torch.int8)
# 存储
pos = self.seq_len
self.k_cache[layer_idx, :, pos:pos+new_k.shape[-2]] = k_quant
self.v_cache[layer_idx, :, pos:pos+new_v.shape[-2]] = v_quant
self.k_scales[layer_idx, :, pos:pos+new_k.shape[-2]] = k_scale
self.v_scales[layer_idx, :, pos:pos+new_v.shape[-2]] = v_scale
self.seq_len += new_k.shape[-2]
def get(self, layer_idx):
"""反量化读取K, V"""
k = self.k_cache[layer_idx, :, :self.seq_len].float() * self.k_scales[layer_idx, :, :self.seq_len].unsqueeze(-1)
v = self.v_cache[layer_idx, :, :self.seq_len].float() * self.v_scales[layer_idx, :, :self.seq_len].unsqueeze(-1)
return k, v
# 显存对比 (Llama-3-8B, 32K上下文):
# FP16 KV Cache: ~8GB
# INT8 KV Cache: ~4GB (节省50%)
# INT4 KV Cache: ~2GB (节省75%)
# vLLM KV Cache量化部署
# FP8 KV Cache (推荐, 硬件加速)
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-70B-Instruct \
--quantization fp8 \
--kv-cache-dtype fp8 \
--max-model-len 32768
# INT8 KV Cache (bitsandbytes)
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-8B-Instruct \
--kv-cache-dtype int8 \
--quantization-prefix-method enable
# AWQ + FP8 KV Cache组合
python -m vllm.entrypoints.openai.api_server \
--model TheBloke/Llama-3-70B-AWQ \
--quantization awq \
--kv-cache-dtype fp8 \
--max-model-len 65536
量化感知训练(Quantization-Aware Training, QAT)在训练过程中模拟量化效果,让模型适应量化带来的精度损失。相比训练后量化(PTQ),QAT精度更高但需要训练资源。
import torch
import torch.nn as nn
# 量化感知训练: 在前向传播中模拟量化
class QATLinear(nn.Module):
"""带量化模拟的Linear层"""
def __init__(self, in_features, out_features, n_bits=8):
super().__init__()
self.linear = nn.Linear(in_features, out_features)
self.n_bits = n_bits
self.q_max = 2 ** (n_bits - 1) - 1
# 可学习的量化参数
self.weight_scale = nn.Parameter(torch.tensor(1.0))
self.act_scale = nn.Parameter(torch.tensor(1.0))
def fake_quantize(self, x, scale):
"""伪量化: 量化后立即反量化 (STE: 直通估计器)"""
# 量化
x_quant = torch.round(x / scale).clamp(-self.q_max, self.q_max)
# 反量化 (梯度直通)
x_dequant = x_quant * scale
# STE: 前向用量化值, 反向用原值梯度
return x + (x_dequant - x).detach()
def forward(self, x):
# 量化权重和激活
w_quant = self.fake_quantize(self.linear.weight, self.weight_scale)
x_quant = self.fake_quantize(x, self.act_scale)
return torch.nn.functional.linear(x_quant, w_quant, self.linear.bias)
# QAT训练流程
def qat_training(model, train_data, num_epochs=3):
# 1. 用预训练权重初始化
# 2. 替换Linear为QATLinear
for name, module in model.named_modules():
if isinstance(module, nn.Linear):
qat_layer = QATLinear(module.in_features, module.out_features, n_bits=8)
qat_layer.linear.weight.data = module.weight.data
qat_layer.linear.bias.data = module.bias.data
# 替换模块...
# 3. 正常训练 (模型学习适应量化)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)
for epoch in range(num_epochs):
for batch in train_data:
loss = compute_loss(model, batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
# 4. 训练后提取真正的量化模型
return extract_quantized_model(model)
| 方法 | 类型 | 比特数 | 需要校准 | 量化速度 | 精度保持 | 推理加速 |
|---|---|---|---|---|---|---|
| RTN (Round-to-Nearest) | PTQ | 4/8 | 否 | 最快 | 最低 | 高 |
| GPTQ | PTQ | 4/8 | 是(128样本) | 慢 | 高 | 高 |
| AWQ | PTQ | 4/8 | 是(128样本) | 中 | 高 | 最高 |
| SmoothQuant | PTQ | 8 | 是 | 快 | 高 | 高 |
| QLoRA(NF4) | QAT+PEFT | 4 | 否 | N/A(训练) | 很高 | 中 |
| QAT | QAT | 4/8 | 否(训练) | 最慢 | 最高 | 高 |
| GGUF Q4_K_M | PTQ | ~4.5 | 否 | 快 | 中高 | 中(CPU) |
| 场景 | 推荐方法 | 理由 |
|---|---|---|
| GPU在线推理 | AWQ INT4 | 推理最快, 精度好 |
| CPU/边缘部署 | GGUF Q4_K_M | CPU优化, 格式通用 |
| 长上下文推理 | AWQ + KV FP8 | 权重+KV双重压缩 |
| 微调训练 | QLoRA NF4 | 单卡微调大模型 |
| 最高精度要求 | QAT INT8 | 训练适应量化 |
| 极致压缩 | GGUF Q2_K | 最小体积, 精度损失大 |
| 框架 | 量化方案 | INT4 | INT8 | FP8 | 部署难度 |
|---|---|---|---|---|---|
| vLLM | AWQ/GPTQ | ✓ | ✓ | ✓ | 低 |
| SGLang | AWQ/GPTQ | ✓ | ✓ | ✓ | 低 |
| llama.cpp | GGUF k-quants | ✓ | ✓ | ✗ | 低 |
| TensorRT-LLM | SmoothQuant/W8A8 | ✓ | ✓ | ✓ | 中 |
| AutoGPTQ | GPTQ | ✓ | ✓ | ✗ | 中 |
| AutoAWQ | AWQ | ✓ | ✓ | ✗ | 中 |
| bitsandbytes | NF4/FP4 | ✓ | ✓ | ✗ | 低 |
# 量化模型验证: 精度 + 速度 + 显存
def validate_quantized_model(model_path, quant_type, test_data):
"""全面验证量化模型"""
results = {}
# 1. 加载模型
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
model_path, device_map="auto",
torch_dtype=torch.float16,
load_in_4bit=(quant_type == "int4"),
load_in_8bit=(quant_type == "int8"),
)
# 2. 精度评估
results["accuracy"] = evaluate_ppl(model, test_data)
# 3. 推理速度
import time
start = time.time()
for _ in range(100):
model.generate(test_input, max_new_tokens=50)
results["tokens_per_sec"] = 5000 / (time.time() - start)
# 4. 显存使用
results["memory_gb"] = torch.cuda.max_memory_allocated() / 1024**3
return results
# 对比FP16 vs INT4
fp16 = validate_quantized_model("model-fp16", "fp16", test_data)
int4 = validate_quantized_model("model-int4", "int4", test_data)
print(f"PPL: FP16={fp16['accuracy']:.2f} vs INT4={int4['accuracy']:.2f}")
print(f"速度: FP16={fp16['tokens_per_sec']:.0f} vs INT4={int4['tokens_per_sec']:.0f}")
print(f"显存: FP16={fp16['memory_gb']:.1f}GB vs INT4={int4['memory_gb']:.1f}GB")
# 逐层量化误差分析
def per_layer_quant_error(model, quantized_model):
"""分析每一层的量化误差"""
errors = {}
for name, param in model.named_parameters():
if "weight" in name:
# 获取量化后对应参数
quant_param = dict(quantized_model.named_parameters())[name]
# 计算相对误差
rel_error = (param.float() - quant_param.float()).norm() / param.float().norm()
errors[name] = rel_error.item()
# 找出误差最大的层
sorted_errors = sorted(errors.items(), key=lambda x: x[1], reverse=True)
print("量化误差最大的5层:")
for name, err in sorted_errors[:5]:
print(f" {name}: {err:.6f}")
return errors
# 敏感层检测: 量化后PPL上升最大的层
def detect_sensitive_layers(model, test_data, threshold=0.5):
"""
逐层反量化(恢复FP16), 观察PPL变化
PPL下降最大的层 = 最敏感层 = 应保持高精度
"""
base_ppl = evaluate_ppl(model, test_data)
sensitive_layers = []
for name in model_layers:
# 临时恢复该层为FP16
restore_layer_to_fp16(model, name)
ppl = evaluate_ppl(model, test_data)
ppl_drop = base_ppl - ppl
if ppl_drop > threshold:
sensitive_layers.append((name, ppl_drop))
# 重新量化该层
requantize_layer(model, name)
return sorted(sensitive_layers, key=lambda x: x[1], reverse=True)
# 混合精度量化: 敏感层保持高精度
def mixed_precision_quantize(model, sensitive_layers):
"""
敏感层保持FP16, 其余层INT4量化
兼顾精度与压缩率
"""
for name, param in model.named_parameters():
if name in sensitive_layers:
# 保持FP16
continue
else:
# INT4量化
quantize_to_int4(param)
print(f"混合精度: {len(sensitive_layers)}层FP16 + 其余INT4")