Machine Learning Mastery

Weight-Only Quantization

8.5内容质量

TL;DR · AI 摘要

权重仅量化技术通过减少模型权重的存储和计算需求,显著提升推理效率,尤其适用于Transformer模型。

核心要点

  • 权重仅量化可将FP16权重存储减少一半,例如INT8权重。
  • 使用低精度矩阵运算可加速AI GPU的计算,具体加速效果依赖硬件和模型结构。
  • 权重仅量化保持激活值为FP16或BF16,仅对权重进行整数存储。

结构提纲

按章节快速跳转。

  1. 本文介绍了权重仅量化技术,包括其原理、实现方法和评估方式。

  2. 非对称仿射量化通过缩放因子和零点映射实数到整数,实现权重的量化和反量化。

  3. ·使用PyTorch进行训练后量化

    PyTorch提供了训练后量化工具,用于生成可部署的量化模型。

  4. ·GPTQ和AWQ方法

    GPTQ和AWQ是两种流行的训练后量化方法,适用于不同场景。

  5. GGUF格式支持高效的模型存储和部署,适用于多种推理工具。

  6. 量化对内存、速度和模型质量的影响需通过实验评估。

思维导图

用一张图看清主题之间的关系。

查看大纲文本(无障碍 / 无 JS 友好)
  • 权重仅量化
    • 非对称仿射量化
      • 缩放因子
      • 零点映射
    • 量化方法
      • PyTorch训练后量化
      • GPTQ
      • AWQ
      • GGUF格式
    • 评估指标
      • 内存
      • 速度
      • 模型质量

金句 / Highlights

值得收藏与分享的关键句。

#Transformer#量化#AI推理#PyTorch
打开原文

仅权重量化 - MachineLearningMastery.com

仅权重量化

作者:

Adrian Tam

于

2026年11月7日

在

Transformer模型的推理

0

分享

文章

在自回归解码过程中,Transformer会为每个新生成的token读取其权重。在小批量大小的情况下,移动这些权重所需的时间可能比计算时间更长。量化通过使用更少的位数存储权重来减少这种成本。例如,一个INT8权重使用的原始存储空间仅为FP16或BF16权重的一半。

量化还可以加快计算速度。许多AI GPU可以比FP16操作更快地执行低精度矩阵运算。实际的加速效果取决于硬件、内核和模型形状。

仅权重量化将选定的权重存储为整数,同时保持激活值在FP16或BF16中。本文首先介绍不对称仿射映射,然后展示如何使用PyTorch和其他推理工具对模型进行量化和运行。

在本文中,你将学习:

  • 仅权重量化如何存储和重建模型权重
  • 事后训练方法和GGUF转换如何生成可部署的产物
  • 如何检查量化对内存、速度和质量的影响

让我们开始吧。

仅权重量化照片由Connor Wang拍摄。部分权利保留。

概述

本文分为五个部分;它们是:

  • 不对称仿射量化
  • 使用PyTorch进行事后训练量化
  • GPTQ和AWQ
  • 将模型量化为GGUF
  • 评估仅权重量化

注意:本文中的代码示例使用TorchAO,并需要CUDA启用的PyTorch安装。你可以通过以下命令安装依赖项:python -m pip install torchao transformers accelerate GPTQ和AWQ部分有各自的安装步骤。GGUF转换需要构建好的llama.cpp检查。

不对称仿射量化

整数量化将一组实数值映射到有限的整数编码集合上。不对称仿射量化器使用一个比例因子 $s$ 和一个零点 $z$:$$ q = \operatorname{clamp}\Big(\operatorname{round}\big(\frac{x}{s}\big) + z, q_{\min}, q_{\max}\Big) $$ 逆量化重建一个近似的浮点值:$$ \hat{x} = s(q-z) $$ 对于无符号的 $b$-位范围,$q_{\min}=0$ 和 $q_{\max}=2^b-1$。给定需要表示的最小值和最大值,一个常见的选择是:$$ \begin{aligned} s &= \frac{x_{\max}-x_{\min}}{q_{\max}-q_{\min}} \\ z &= \operatorname{clamp}\Big(\operatorname{round}\big(q_{\min}-\frac{x_{\min}}{s}\big),q_{\min},q_{\max}\Big) \end{aligned} $$ 比例因子决定了相邻可表示值之间的距离。零点是实数零的整数编码。将零包含在实数范围内可以确保它能被精确表示。

对张量进行量化和重建,以显示整数舍入带来的误差。

import torch

def quantize_asymmetric(x, bits=8): if not 1 <= bits <= 8: raise ValueError("this uint8 example supports 1 to 8 bits") if not x.is_floating_point(): raise TypeError("x must be floating point")

max and min of quantized (unsigned int) values

qmin = 0 qmax = 2**bits - 1

max and min of actual (float) values

xmin = torch.minimum(x.amin(), x.new_zeros(())) xmax = torch.maximum(x.amax(), x.new_zeros(()))

compute the scale and zero point, then quantize the actual values

scale = (xmax - xmin) / (qmax - qmin) scale = scale.clamp_min(torch.finfo(x.dtype).eps) zero_point = torch.round(qmin - xmin / scale).clamp(qmin, qmax) q = torch.round(x / scale + zero_point).clamp(qmin, qmax) return q.to(torch.uint8), scale, zero_point.to(torch.int32)

def dequantize(q, scale, zero_point): return scale * (q.float() - zero_point.float())

x = torch.tensor([-2.3, -0.2, 0.0, 0.7, 3.1]) q, scale, zero_point = quantize_asymmetric(x) x_hat = dequantize(q, scale, zero_point) print("scale:", scale.item()) print("zero point:", zero_point.item()) print("quantized:", q) print("maximum error:", (x - x_hat).abs().max().item())

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import

torch

def

quantize_asymmetric

(

x

,

bits

=

)

:

if

not

<=

raise

ValueError

"this uint8 example supports 1 to 8 bits"

.

is_floating_point

TypeError

"x must be floating point"

max and min of quantized (unsigned int) values

qmin

qmax

*

-

max and min of actual (float) values

xmin

minimum

amin

new_zeros

xmax

maximum

amax

compute the scale and zero point, then quantize the actual values

scale

/

clamp_min

finfo

dtype

eps

zero_point

round

clamp

q

+

return

to

uint8

int32

dequantize

scale *

float

tensor

[

2.3

0.2

0.0

0.7

3.1

]

x_hat

print

"scale:"

item

"zero point:"

"quantized:"

"maximum error:"

abs

max

该示例演示了数值映射,而不是高效的存储方式。一个 uint8 张量始终使用每个元素一个字节,即使 bits 小于八。部署格式必须打包小于字节的值以获得预期的存储减少。此示例使用一个 scale 和 zero point 对整个张量进行量化。每个通道和每个组的量化通常可以更好地保留 LLM 权重质量,因为每个通道或组都有自己的范围。

对于线性层 $\mathbf{y}=\mathbf{x}\mathbf{W}^\top$,权重仅量化存储一个整数矩阵 $\mathbf{Q}$ 以及 scale 和 zero point,而不是 $\mathbf{W}$: $$ \mathbf{y} \approx \mathbf{x}\big(s(\mathbf{Q}-z)\big)^\top $$ 输入保持为浮点数。一个高效的内核将直接使用量化后的权重,而不是像方程所示那样重建 $\mathbf{W}$ 的浮点副本。

本文使用了非对称仿射映射作为解释模型。生产内核和检查点格式可能使用固定 zero point 或其他编码方式。运行时必须支持检查点中存储的确切量化方案和打包布局。

使用 PyTorch 进行训练后量化

PyTorch 当前的量化开发集中在 TorchAO。它的 quantize_() 函数会就地替换匹配的 torch.nn.Linear 模块的权重。将其应用于已评估和训练的模型上是训练后量化:不会执行任何训练步骤。

以下示例请求非对称、按通道的 INT8 权重仅量化。激活保持为 BF16:

使用 TorchAO 应用每通道 INT8 权重仅量化。

python
import torch
import torch.nn as nn
from torchao.quantization import (
    IntxWeightOnlyConfig,
    MappingType,
    PerAxis,
    quantize_,
)

if not torch.cuda.is_available():
    raise RuntimeError("This example requires a CUDA GPU")

model = nn.Sequential(
    nn.Linear(2048, 2048, bias=False),
    nn.ReLU(),
    nn.Linear(2048, 2048, bias=False),
).eval().to(device="cuda", dtype=torch.bfloat16)

config = IntxWeightOnlyConfig(
    weight_dtype=torch.int8,
    granularity=PerAxis(0),
    mapping_type=MappingType.ASYMMETRIC,
)

quantize_(model, config)

x = torch.randn(1, 2048, device="cuda", dtype=torch.bfloat16)
with torch.inference_mode():
    output = model(x)
print(output.shape)

PerAxis(0) 为每个线性权重矩阵的行分配单独的量化参数。IntxWeightOnlyConfig 还支持每组粒度。其可用的打包格式和优化内核取决于 TorchAO 的版本和目标设备。

TorchAO 还提供了面向硬件的预设,如 Int8WeightOnlyConfig 和 Int4WeightOnlyConfig。这些预设可能使用与显式不对称示例不同的映射。您应使用目标硬件文档中说明的配置,然后对完整模型进行基准测试。数学上有效的配置不一定是最快的配置。

transformers 库可以在加载模型时应用 TorchAO 配置。例如:

使用 TorchAO 量化配置加载因果模型。

python
import torch
from torchao.quantization import Int4WeightOnlyConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig

model_id = "Qwen/Qwen2.5-0.5B-Instruct"
quantization_config = TorchAoConfig(
    quant_type=Int4WeightOnlyConfig(
        group_size=128,
        int4_packing_format="tile_packed_to_4d",
        int4_choose_qparams_algorithm="hqq",
    )
)

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    dtype=torch.bfloat16,
    device_map="auto",
    quantization_config=quantization_config,
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
inputs = tokenizer("Explain post-training quantization.", return_tensors="pt")
inputs = inputs.to(model.device)

with torch.inference_mode():
    generated = model.generate(**inputs, max_new_tokens=32)
print(tokenizer.decode(generated[0], skip_special_tokens=True))

这是无需校准的仅权重 PTQ。显式的 HQQ 参数选择和分块打包避免了在测试的 RTX 4090 上 TorchAO 0.17 中可选的 MSLK 内核依赖。其他 TorchAO 版本和设备可能支持不同的布局。静态激活量化是另一种工作流程:它准备一个导出的模型,运行代表性输入以收集激活范围,然后转换模型。

GPTQ 和 AWQ

四舍五入量化将每个权重视为局部处理。GPTQ 和 AWQ 使用校准激活来减少量化误差对模型输出的影响。

独立地对每个权重进行四舍五入会忽略其输入通道对输出的贡献频率和强度。校准示例可以让量化器估计这种影响并减少输出误差,尽管结果取决于这些示例的代表性程度。

GPTQ 使用近似的二阶信息逐层量化权重。随着权重被量化,它会调整剩余的权重以补偿之前的误差。transformers 库现在使用 GPT-QModel 作为其 GPTQ 后端。安装所需的软件包以使用 GPTQ 进行量化:

安装 GPTQ 转换依赖项。

python -m pip install setuptools --upgrade wheel accelerate optimum transformers python -m pip install gptqmodel --no-build-isolation

python

m

pip

install

setuptools

--

upgrade

wheel

accelerate

optimum

gptqmodel

no

build

isolation

然后你可以量化并保存一个小型模型。GPTQConfig 设置 dataset="c4" 为校准提供输入样本。设置 sym=False 请求非对称形式。以下是一个将小型模型量化为 INT4 的示例:

校准并保存一个 INT4 GPTQ 检查点。

from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig model_id = "facebook/opt-125m" tokenizer = AutoTokenizer.from_pretrained(model_id) quantization_config = GPTQConfig( bits=4, # 2, 3, 4, or 8 group_size=128, dataset="c4", tokenizer=tokenizer, sym=False, ) model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", quantization_config=quantization_config, ) model.save_pretrained("opt-125m-gptq") tokenizer.save_pretrained("opt-125m-gptq") print("Saved the GPTQ checkpoint to opt-125m-gptq")

GPTQConfig

"facebook/opt-125m"

2, 3, 4, or 8

dataset

"c4"

sym

save_pretrained

"opt-125m-gptq"

"Saved the GPTQ checkpoint to opt-125m-gptq"

要在新的进程中加载保存的 GPTQ 检查点并运行一次推理:

重新加载保存的 GPTQ 检查点并生成文本。

import torch from transformers import AutoModelForCausalLM, AutoTokenizer checkpoint = "opt-125m-gptq" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForCausalLM.from_pretrained( checkpoint, device_map="auto", ) model.eval() inputs = tokenizer("Weight quantization makes inference", return_tensors="pt") inputs = inputs.to(model.device) with torch.inference_mode(): output = model.generate( **inputs, max_new_tokens=32, pad_token_id=tokenizer.eos_token_id, ) print(tokenizer.decode(output[0], skip_special_tokens=True))

checkpoint

"Weight quantization makes inference"

pad_token_id

eos_token_id

非对称 GPTQ 检查点比默认映射兼容的内核更少。例如,Marlin 后端不支持非对称 GPTQ。你应该一起选择量化方案和推理后端。

激活感知权重量化(AWQ)是另一种量化方法。它识别在代表性激活下重要的权重,并在低比特量化之前搜索保护这些权重的缩放因子。--model_path 参数指向 Hugging Face 格式的原始未量化模型。从参考 llm-awq 实现的代码库中克隆,并安装其依赖项后,首先运行搜索,然后创建真实的 INT4 检查点:

在运行其命令之前,请在单独的环境中安装参考实现:

安装 AutoAWQ 和 Hugging Face Hub 客户端。

git clone https://github.com/mit-han-lab/llm-awq.git cd llm-awq python -m pip install -e . python -m pip install huggingface_hub

git

clone

https

//github.com/mit-han-lab/llm-awq.git

cd

llm

awq

e

huggingface_hub

该参考项目为该环境文档中记录了 Python 3.10。请使用其安装说明来安装匹配的 CUDA 扩展。使用以下命令下载模型:

hf download TinyLlama/TinyLlama-1.1B-Chat-v1.0 --local-dir models/tinyllama

hf

download

TinyLlama

1.1B

Chat

v1

local

dir

models

然后运行以下命令:

搜索 AWQ 缩放因子并量化 TinyLlama 检查点。

搜索 AWQ 缩放参数。

python -m awq.entry \ --model_path models/tinyllama \ --w_bit 4 \ --q_group_size 128 \ --run_awq \ --dump_awq awq_cache/tinyllama-w4-g128.pt

创建量化检查点。

python -m awq.entry \ --model_path models/tinyllama \ --w_bit 4 \ --q_group_size 128 \ --load_awq awq_cache/tinyllama-w4-g128.pt \ --q_backend real \ --dump_quant quant_cache/tinyllama-w4-g128-awq-v2.pt

搜索 AWQ 缩放参数。

entry

\

model_path

w

_

bit

q_group

size

run

dump_awq

awq_cache

w4

g128

pt

创建量化检查点。

load_awq

q_backend

real

dump_quant

quant_cache

v2

--run_awq 命令内部获取校准输入。它使用 mit-han-lab/pile-val-backup 的验证数据集中的 128 个样本,形成 512 个 token 的序列。该参考 CLI 不提供选择其他文本数据集的参数。省略 --no_zero_point 保留实现的零点量化。

由 --dump_quant 生成的原始 .pt 文件不是一个完整的 Hugging Face 检查点。它包含量化权重,但不包含模型配置或分词器。以下脚本将它们打包到本地目录中:

将 AWQ 权重文件与其模型配置和分词器打包在一起。

from pathlib import Path import shutil from transformers import AutoConfig, AutoTokenizer, AwqConfig

source_model = "models/tinyllama" quantized_weights = "quant_cache/tinyllama-w4-g128-awq-v2.pt" output_dir = Path("models/tinyllama-awq") output_dir.mkdir(parents=True, exist_ok=True)

awq_config = AwqConfig( bits=4, group_size=128, zero_point=True, backend="llm-awq", version="gemv", )

config = AutoConfig.from_pretrained(source_model) config.quantization_config = awq_config config.save_pretrained(output_dir)

tokenizer = AutoTokenizer.from_pretrained(source_model) tokenizer.save_pretrained(output_dir)

shutil.copyfile( quantized_weights, output_dir / "pytorch_model.bin", )

pathlib

Path

shutil

AutoConfig

AwqConfig

source_model

"models/tinyllama"

quantized_weights

"quant_cache/tinyllama-w4-g128-awq-v2.pt"

output_dir

"models/tinyllama-awq"

mkdir

parents

exist_ok

awq_config

backend

"llm-awq"

version

"gemv"

copyfile

"pytorch_model.bin"

然后,transformers 库可以从检查点的 quantization_config 中识别出 AWQ 格式,加载量化后的权重并运行推理:

加载打包的 AWQ 检查点并生成文本。

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "models/tinyllama-awq"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, device_map="auto",
)
model.eval()

inputs = tokenizer("Explain weight quantization.", return_tensors="pt")
inputs = inputs.to(model.device)

with torch.inference_mode():
    output = model.generate(
        **inputs, max_new_tokens=64, pad_token_id=tokenizer.eos_token_id,
    )
    print(tokenizer.decode(output[0], skip_special_tokens=True))

"Explain weight quantization."

64

模型架构、分组大小、零点约定、打包布局以及安装的 AWQ 后端必须兼容。

量化大型模型可能需要大量时间和内存。在开始之前,请检查是否已经存在兼容的量化检查点。如果你自己进行量化,请保存分词器和完整的量化配置以及打包后的权重。

将模型量化为 GGUF 格式

GGUF 是 llama.cpp 生态系统中使用的一种容器格式。它在一个或多个文件中存储模型元数据、分词器信息、张量及其类型。GGUF 支持许多量化类型;它本身并不是一种量化算法。

llama.cpp 的工作流程分为两个阶段。首先,将原始的 Hugging Face 模型转换为高精度的 GGUF 文件(如 bfloat16),然后对这个文件进行量化。以下示例使用的是原始的、未量化的 TinyLlama/TinyLlama-1.1B-Chat-v1.0 检查点。从已构建的 llama.cpp 检出:

在单独的环境中安装转换脚本的 Python 依赖项并先构建二进制文件。转换需求可能会选择与本文前面 CUDA 示例中使用的不同 PyTorch 构建。这个 CUDA 构建需要 CMake、C++ 编译器和 CUDA 工具包;对于 CPU 构建,请省略 -DGGML_CUDA=ON。

克隆并构建支持 GGUF 转换的 llama.cpp。

bash
git clone https://github.com/ggml-org/llama.cpp.git
cd llama.cpp
python -m pip install -r requirements/requirements-convert_hf_to_gguf.txt
python -m pip install huggingface_hub
cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release
hf download TinyLlama/TinyLlama-1.1B-Chat-v1.0 --local-dir models/tinyllama

https://github.com/ggml-org/llama.cpp.git

llama

cpp

r

requirements

convert_hf_to_gguf

txt

cmake

B

DGGML_CUDA

Release

将 TinyLlama 转换为 GGUF 并量化为 Q4_K_M。

bash
python3 convert_hf_to_gguf.py models/tinyllama \
    --outfile tinyllama-bf16.gguf \
    --outtype bf16
./build/bin/llama-quantize tinyllama-bf16.gguf tinyllama-Q4_K_M.gguf Q4_K_M

python3

py

outfile

bf16

gguf

outtype

bin

quantize

Q4_K_M

Q4_K_M 是一种混合 GGUF 量化类型,它对不同的张量使用不同的编码。其文件大小包括缩放因子、元数据和以其他精度存储的张量,因此它并不是每个模型参数正好四比特。它的名称并不意味着每个值都遵循前面展示的仿射公式。

你可以使用 llama-cli 加载量化后的 GGUF 文件,并直接从其打包的权重生成文本:

使用 llama.cpp 运行量化后的 GGUF 模型。

bash
./build/bin/llama-cli \
    -m tinyllama-Q4_K_M.gguf \
    -p "Explain weight-only quantization in one paragraph." \
    -n 128 --single-turn

cli

p

用一段话解释仅权重量化。

这确认了 llama.cpp 可以从打包文件中生成内容。TinyLlama 可能会给出不准确的解释,因此请针对您的任务使用单独的质量检查。

一些 GGUF 模型可在 Hugging Face Hub 上找到,并且可以直接运行:

直接从 Hugging Face Hub 运行 GGUF 模型。

./build/bin/llama-cli -hf Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_M \ -p "What is a quantized model?" -n 64 --single-turn

Qwen

Qwen2

0.5B

Instruct

Q4_K

"What is a quantized model?"

如果您更喜欢使用 Python 代码,transformers 也接受支持架构的 GGUF 文件名:

安装支持 GGUF 加载的 Hugging Face 库。

python -m pip install --upgrade transformers gguf

对于下面的 Qwen3.5 示例,请使用较新的 transformers 版本。加载时可能会对张量进行反量化,并且需要比 GGUF 文件大小所建议的更多内存。

通过 Hugging Face 库加载 GGUF 检查点。

from transformers import AutoModelForCausalLM, AutoTokenizer model_id = "unsloth/Qwen3.5-4B-GGUF" filename = "Qwen3.5-4B-Q4_K_M.gguf" model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename) tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename) print(type(model).__name__, type(tokenizer).__name__)

"unsloth/Qwen3.5-4B-GGUF"

filename

"Qwen3.5-4B-Q4_K_M.gguf"

gguf_file

type

__name__

但您不应假设 transformers 保留了压缩推理。它仅在有限的模型架构、设备和量化类型组合中保持 GGUF 块打包;其他组合在加载时会被反量化。当需要广泛的 GGUF 兼容性和直接执行打包权重时,您可以使用 llama.cpp。您应该从最高质量的源进行量化。对已经量化过的模型进行重新量化会累积近似误差,而 llama-quantize 会警告这可能会严重降低质量。

评估仅权重量化

在代表性输入上评估量化模型。如果质量下降超出您的应用容忍度,请尝试使用不同的校准集、量化器或位宽。

一些量化器使用校准示例来减少原始模型和量化模型之间的输出误差。这种代理方法不能替代应用质量指标。有用的检查包括:

  • 在代表性文本上的困惑度
  • 准确率或任务特定的分数
  • 逐一对比贪婪生成
  • 在多个种子、提示长度和温度下对比采样生成

在使用前面的命令创建 opt-125m-gptq 后,在一个 CUDA GPU 上运行此脚本。它依次加载并测量 FP16 基线和 GPTQ 检查点,以便它们的峰值分配内存测量结果可以进行比较。时间包括 generate(),但不包括模型加载和分词:

比较不同模型检查点的内存使用和生成时间。

import gc import time import torch from transformers import AutoModelForCausalLM, AutoTokenizer if not torch.cuda.is_available(): raise RuntimeError("This comparison needs a CUDA GPU and a GPTQ CUDA kernel") tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m") inputs = tokenizer("Weight quantization makes inference", return_tensors="pt").to("cuda") def measure_checkpoint(path): torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats() model = AutoModelForCausalLM.from_pretrained( path, device_map="cuda:0", dtype=torch.float16, ).eval() def generate(current_model): with torch.inference_mode(): return current_model.generate( inputs, max_new_tokens=32, do_sample=False, pad_token_id=tokenizer.eos_token_id, ) generate(model) # warm up torch.cuda.synchronize() times = [] for _ in range(3): start = time.perf_counter() ids = generate(model) torch.cuda.synchronize() times.append(time.perf_counter() - start) result = { "median_seconds": sorted(times)[1], "peak_allocated_gib": torch.cuda.max_memory_allocated() / 230, "output": tokenizer.decode(ids[0], skip_special_tokens=True), } del model gc.collect() torch.cuda.empty_cache() return result for checkpoint in ("facebook/opt-125m", "opt-125m-gptq"): print(checkpoint, measure_checkpoint(checkpoint))

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

gc

time

"This comparison needs a CUDA GPU and a GPTQ CUDA kernel"

measure_checkpoint

empty_cache

reset_peak_memory_stats

"cuda:0"

float16

current_model

do_sample

warm up

synchronize

times

for

range

start

perf_counter

ids

append

result

{

"median_seconds"

sorted

"peak_allocated_gib"

max_memory_allocated

"output"

}

del

collect

这是一个小型的诊断基准测试。在进行部署决策时,请使用与实际工作负载相同的提示、输出限制、预热和并发性。您还应测量困惑度或任务准确性以及样本生成;一个匹配的贪心答案并不能证明质量的对等性。峰值 PyTorch 分配可能忽略了其他库所占用的内存,因此也要检查设备级别的内存。

量化模型可能需要专用的内核或兼容的推理引擎。为了获得最佳性能,您可能需要专用的硬件。您可以在目标平台上比较以下测量值,以决定量化是否值得付出努力:

  • 检查点大小和模型加载内存
  • 预填充和解码期间的峰值内存
  • 首个令牌生成时间
  • 在实际批量大小和并发性下的吞吐量

进一步阅读

以下是一些可能对您有用的相关资源:

  • PyTorch TorchAO 文档。量化推理。此指南列出了当前的仅权重和动态推理配置。
  • PyTorch TorchAO 文档。quantize_。此页面记录了在训练后进行量化(in-place)的 API。
  • Elias Frantar 等人(2022)。GPTQ:生成预训练变压器的精确训练后量化。这篇论文介绍了 GPTQ 算法。
  • Hugging Face Transformers 文档。GPTQ。此指南涵盖了使用 GPT-QModel 进行量化和检查点加载。
  • Ji Lin 等人(2023)。AWQ:用于大语言模型压缩和加速的激活感知权重量化。这篇论文介绍了 AWQ。
  • AWQ 参考实现。由 MIT Han Lab 提供。此仓库包括用于搜索 AWQ 参数和生成实际量化权重的命令。
  • AWQ 转换示例。在参考仓库中。这展示了如何将原始量化状态字典与 Transformers 配置和分词器打包在一起。
  • LLM Compressor。由 vLLM 项目开发。该工具包提供了 GPTQ、AWQ 等后训练压缩方案。
  • llama.cpp 量化。在 llama.cpp 仓库中。该指南记录了转换、量化类型、重要性矩阵和执行方法。
  • Hugging Face Transformers 文档。GGUF。该页面解释了支持的 GGUF 加载路径和回退反量化方法。
  • NVIDIA A100 Tensor Core GPU。在 NVIDIA 文档中。其规格比较了 FP16、INT8 等不同数值格式的峰值吞吐量。
  • AMD Instinct MI300X 平台。在 AMD 文档中。其规格提供了另一个比 FP16 吞吐量更高的 INT8 矩阵峰值吞吐量示例。

总结

在本文中,你学习了非对称仿射量化如何使用比例因子和零点将浮点权重映射到整数编码。每个张量、每个通道和每个组的参数在精度和内核复杂度之间进行权衡。仅权重的后训练量化在训练后推导这些参数,同时保持激活值的更高精度。

TorchAO 提供了原生的 PyTorch PTQ,而 GPTQ 和 AWQ 使用校准数据在低比特宽度下保留模型行为。GPT-QModel、LLM Compressor 和 AWQ 的参考实现提供了 TorchAO 之外的工作流程。GGUF 为像 llama.cpp 这样的运行时打包量化张量。

只有当检查点格式、数值方案、打包布局和推理内核协同工作时,量化才有用。在实际部署目标上评估质量、内存、延迟、吞吐量和兼容性。

关于此主题的更多内容

  • 机器学习中的量化:5 个原因……
  • OpenCV 中的 K-Means 聚类及其应用……
  • 如何实现学习向量量化(LVQ)……
  • 机器学习中的学习向量量化