4. vLLM模型量化加载与推理
任务目标
本案例演示如何使用 vLLM 加载一个已量化的模型(AWQ/ 格式)并执行推理,同时验证量化模型与原始 FP16 模型在输出上的等价性。通过本案例,你将掌握 vLLM 中 Quantization 参数的配置方法,以及量化模型加载时的关键注意事项。
环境与依赖
- vLLM ≥ 0.4.0(推荐 0.6.x)
- HuggingFace Hub 可访问(或本地已缓存模型)
- GPU 显存 ≥ 8GB(以 7B 模型为例)
核心实现
以下代码完成:加载 AWQ 量化模型 → 执行单次推理 → 与 FP16 基线模型输出对比。使用 TheBloke/Llama-2-7B-Chat-AWQ 作为量化模型,meta-llama/Llama-2-7b-chat-hf 作为基线(需 HuggingFace 登录或使用公开镜像)。
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
# ========== 1. 加载量化模型 ==========
quant_llm = LLM(
model="TheBloke/Llama-2-7B-Chat-AWQ",
quantization="awq", # 关键:指定量化格式
dtype="float16", # 量化模型推理时仍以 fp16 计算
max_model_len=2048,
gpu_memory_utilization=0.7, # 按需调整
)
# ========== 2. 加载基线 FP16 模型(用于对比) ==========
base_llm = LLM(
model="meta-llama/Llama-2-7b-chat-hf",
dtype="float16",
max_model_len=2048,
gpu_memory_utilization=0.7,
)
# ========== 3. 准备输入 ==========
tokenizer = AutoTokenizer.from_pretrained("TheBloke/Llama-2-7B-Chat-AWQ")
prompt = "What is the capital of France?"
messages = [{"role": "user", "content": prompt}]
formatted_prompt = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
sampling_params = SamplingParams(
temperature=0.0, # 贪心解码,保证可复现
max_tokens=64,
)
# ========== 4. 执行推理 ==========
quant_output = quant_llm.generate([formatted_prompt], sampling_params)
base_output = base_llm.generate([formatted_prompt], sampling_params)
# ========== 5. 提取与对比 ==========
quant_text = quant_output[0].outputs[0].text.strip()
base_text = base_output[0].outputs[0].text.strip()
print("=== Quantized (AWQ) Output ===")
print(quant_text)
print("\n=== Baseline (FP16) Output ===")
print(base_text)
# 简单一致性检查(首句是否相同)
quant_first = quant_text.split(".")[0]
base_first = base_text.split(".")[0]
if quant_first == base_first:
print("\n[PASS] 量化模型与基线模型首句输出一致")
else:
print("\n[WARN] 输出存在差异(量化精度损失导致,可接受)")
运行方式
# 安装依赖(如未安装)
pip install vllm transformers
# 运行脚本
python quant_inference.py
验证方法与判定标准
- 加载验证:控制台无报错,且出现类似
Loading model weights took X seconds的日志,说明量化模型权重成功加载。 - 推理验证:脚本正常输出两段文本,且量化模型输出为通顺的英文回答(如 "Paris is the capital of France.")。
- 等价性判定:若输出
[PASS],说明量化模型与基线模型在贪心解码下输出一致;若输出[WARN],则需人工判断差异是否在可接受范围内(通常为措辞变化,核心语义不变)。
常见问题
- 显存不足:降低
gpu_memory_utilization至 0.5,或改用更小的量化模型(如TheBloke/Llama-2-7B-)。 - 模型下载失败:提前执行
huggingface-cli download TheBloke/Llama-2-7B-Chat-AWQ手动缓存。 - 模型:将
quantization="awq"改为quantization="",其余代码不变。