INT8量化

8-bit Integer Quantization for LLMs

概述

INT8量化将模型权重从FP16/FP32压缩到8-bit整数,显存占用减少50%, 是在精度损失和压缩率之间取得良好平衡的量化方案。

核心价值:精度损失极小,推理速度提升,适合生产环境。

量化方法

对称量化

将权重映射到对称的INT8范围(-127到127):

# 量化

scale = max(|W|) / 127

W_int8 = round(W / scale)


# 反量化

W_fp16 = W_int8 * scale

非对称量化

允许零点偏移,适合非对称分布:

scale = (max(W) - min(W)) / 255

zero_point = round(-min(W) / scale)

W_int8 = round(W / scale) + zero_point

bitsandbytes INT8

Hugging Face bitsandbytes库提供便捷的INT8量化:

from transformers import AutoModelForCausalLM, AutoTokenizer

# 加载INT8量化模型
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-hf",
    load_in_8bit=True,      # 启用INT8量化
    device_map="auto"
)

# 推理
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
inputs = tokenizer("Hello, world!", return_tensors="pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens=50)
print(tokenizer.decode(outputs[0]))

LLM.int8()方法

bitsandbytes使用的混合精度量化:

  • 检测异常值(outliers)特征
  • 异常值保持FP16
  • 其他特征使用INT8
  • 保证数值稳定性

显存对比

模型FP16INT8节省
7B14GB7GB50%
13B26GB13GB50%
30B60GB30GB50%
70B140GB70GB50%

精度评估

量化方案MMLUPerplexity相对FP16
FP16 (基准)46.95.68-
INT8 (LLM.int8())46.85.69-0.2%

INT8量化精度损失极小,几乎可以忽略不计。

INT8 vs INT4

特性INT8INT4
显存节省50%75%
精度损失极小
推理速度更快
硬件支持广泛需要特定优化
推荐场景精度敏感任务显存受限场景

动态量化 vs 静态量化

动态量化

运行时量化激活值:

  • • 无需校准数据
  • • 权重量化后固定
  • • 激活值动态量化
  • • 实现简单

静态量化

预先计算量化参数:

  • • 需要校准数据
  • • 推理速度更快
  • • 精度可能更高
  • • 需要额外步骤

最佳实践

  • 精度敏感场景选择INT8而非INT4
  • 使用bitsandbytes快速启用INT8
  • 验证量化后模型在目标任务的表现
  • 显存充足时INT8是安全选择
  • 生产环境可先用INT8验证,再考虑INT4

参考资料

  • LLM.int8(): 8-bit Matrix Multiplication for Transformers (Dettmers et al., 2022)
  • bitsandbytes Documentation
  • Hugging Face Quantization Guide
----