案例目标:选定量化方案并写明理由 → 执行量化转换 → 用 self_check.py 对量化模型做冒烟测试并记录性能 → 封装交付物。
| 方案A:INT4 + GGUF(llama.cpp) | 方案B:INT8 + ONNX(optimum) | |
|---|---|---|
| 体积 | 最小 7B 模型约 4GB | 约减半,仍较大 |
| 适用场景 | CPU/低显存(≤8GB)部署,推理快 | 需要跨框架/跨硬件标准化部署时 |
| 依赖 | pip install llama-cpp-python,llama.cpp 的 convert/quantize 工具 | pip install optimum onnxruntime |
所选方案:INT4 + GGUF(llama.cpp)
选择理由:云端显存受限(≤8GB),INT4 可将 7B 模型体积压缩约 4 倍(约 15GB→4GB),
大幅降低显存占用;GGUF 格式配合 llama.cpp 可在 CPU/低显存环境高效推理。
依赖安装:pip install llama-cpp-python
# 方案A(推荐):HF模型 → GGUF 中间文件 → INT4 量化文件(两条命令照抄改路径即可)
python llama.cpp/convert.py model_b/checkpoint-best \
--outfile model_b/quantization/base.gguf # 第1步:转成 GGUF
./llama.cpp/quantize model_b/quantization/base.gguf \
model_b/quantization/model_int4.gguf q4_0 # 第2步:量化为 q4_0(4bit)
# 方案B:ONNX + INT8(optimum 一段代码搞定)
from optimum.onnxruntime import ORTQuantizer
from optimum.onnxruntime.configuration import AutoQuantizationConfig
quantizer = ORTQuantizer.from_pretrained("model_b/checkpoint-best")
dqconfig = AutoQuantizationConfig.avx2_vnni(is_static=False) # 动态INT8,CPU指令集优化
quantizer.quantize(save_dir="model_b/quantization/onnx_int8", quantization_config=dqconfig)
量化后必须自测:模型答不答得出人话(有无乱码/复读/语义断裂),顺便记录推理速度写入报告。
# /home/user/workspace/model_b/quantization/self_check.py —— 量化模型自检
import time
from llama_cpp import Llama
llm = Llama(model_path="/home/user/workspace/model_b/quantization/model_int4.gguf",
n_ctx=2048) # 上下文长度给够
questions = ["你是谁?", "请简要介绍人工智能。", "什么是金融危机?"] # 固定的3个自检问题
report = []
for q in questions:
t0 = time.time()
out = llm.create_completion(prompt=f"### 指令:\n{q}\n### 回答:\n",
max_tokens=256, temperature=0.1)
dt = time.time() - t0
n_tok = out["usage"]["completion_tokens"]
ans = out["choices"][0]["text"].strip()
report.append(f"问题:{q}\n回答:{ans}\n耗时:{dt:.2f}s | 速度:{n_tok/dt:.1f} token/s\n")
print(report[-1])
with open("/home/user/workspace/model_b/quantization/self_check_report.txt", "w",
encoding="utf-8") as f:
f.write("\n".join(report) + "\n对比结论:INT4量化后体积从约15GB降至4GB,"
"平均推理速度 xx token/s(原始模型 xx token/s),输出语义连贯无乱码。")
# 注意用 cp 复制而不是 mv 移动——务必保留原文件
mkdir -p /home/user/workspace/model_b/submission
cp model_b/quantization/model_int4.gguf model_b/submission/
cp inference 脚本 # submission/ 里只放:模型文件 + 推理脚本
— AI训练师技术交流教程 · 仅供学习交流 —