评价此页

使用 Intel® Neural Compressor 进行 PyTorch 的易用量化#

创建日期:2022年1月11日 | 最后更新:2026年3月31日 | 最后验证:未验证

概述#

大多数深度学习应用程序在推理时使用 32 位浮点精度。但由于性能的大幅提升,低精度数据类型(如 fp8)正受到越来越多的关注。采用低精度的关键问题在于如何在满足预定义要求的同时减轻精度损失。

Intel® Neural Compressor 旨在通过为 PyTorch 扩展以精度为导向的自动调优策略来解决上述问题,帮助用户快速在 Intel 硬件上找到最佳的量化模型。

Intel® Neural Compressor 是一个开源项目,托管于 Github

特性#

  • 易用 API:Intel® Neural Compressor 复用了 PyTorch 的 prepareconvert API 供用户使用。

  • 以精度为导向的调优:Intel® Neural Compressor 支持以精度为导向的自动调优过程,并提供 autotune API 供用户使用。

  • 量化种类:Intel® Neural Compressor 支持多种量化方法,包括经典的 INT8 量化、仅权重(Weight-only)量化以及流行的 FP8 量化。Neural Compressor 还提供了模拟工作的最新研究成果,例如 MX 数据类型仿真量化。更多详情,请参考 支持矩阵 (Supported Matrix)

入门#

安装#

# install stable version from pip
pip install neural-compressor-pt

注意:Neural Compressor 提供自动加速器检测,包括 HPU、Intel GPU、CUDA 和 CPU。若要指定目标设备,建议使用 INC_TARGET_DEVICE,例如:export INC_TARGET_DEVICE=cpu

示例#

本节展示了使用 Intel® Neural Compressor 进行各类量化的示例。

FP8 量化#

FP8 量化受 Intel® Gaudi®2&3 AI 加速器 (HPU) 支持。有关准备环境的信息,请参考 Intel® Gaudi® 文档

运行示例,

# FP8 Quantization Example
from neural_compressor.torch.quantization import (
    FP8Config,
    prepare,
    convert,
)

import torch
import torchvision.models as models

# Load a pre-trained ResNet18 model
model = models.resnet18()

# Configure FP8 quantization
qconfig = FP8Config(fp8_config="E4M3")
model = prepare(model, qconfig)

# Perform calibration (replace with actual calibration data)
calibration_data = torch.randn(1, 3, 224, 224).to("hpu")
model(calibration_data)

# Convert the model to FP8
model = convert(model)

# Perform inference
input_data = torch.randn(1, 3, 224, 224).to("hpu")
output = model(input_data).to("cpu")
print(output)

仅权重(Weight-only)量化#

仅权重(Weight-only)量化同样受 Intel® Gaudi®2&3 AI 加速器支持。量化模型可以按照如下方式加载。

from neural_compressor.torch.quantization import load

# The model name comes from HuggingFace Model Hub.
model_name = "TheBloke/Llama-2-7B-GPTQ"
model = load(
    model_name_or_path=model_name,
    format="huggingface",
    device="hpu",
    torch_dtype=torch.bfloat16,
)

注意:Intel Neural Compressor 在首次加载时会将模型格式从 auto-gptq 转换为 hpu 格式,并保存 hpu_model.safetensors 到本地缓存目录以便下次加载。因此,首次加载可能需要一些时间。

使用 PT2E 后端的静态量化#

PT2E 路径使用 torch.dynamo 将 Eager 模型捕获为 FX 图模型,然后在图上插入观察器(observers)和 Q/DQ 对。最后,它使用 torch.compile 执行模式匹配,并将 Q/DQ 对替换为优化的量化算子。

使用 PT2E 后端执行 W8A8 静态量化分为四个步骤:exportprepareconvertcompile

import torch
from neural_compressor.torch.export import export
from neural_compressor.torch.quantization import StaticQuantConfig, prepare, convert

# Prepare the float model and example inputs for export model
model = UserFloatModel()
example_inputs = ...

# Export eager model into FX graph model
exported_model = export(model=model, example_inputs=example_inputs)
# Quantize the model
quant_config = StaticQuantConfig()
prepared_model = prepare(exported_model, quant_config=quant_config)
# Calibrate
run_fn(prepared_model)
q_model = convert(prepared_model)
# Compile the quantized model and replace the Q/DQ pattern with Q-operator
from torch._inductor import config

config.freezing = True
opt_model = torch.compile(q_model)

以精度为导向的调优#

为了利用以精度为导向的自动调优,必须指定调优空间。autotune 会遍历调优空间,将配置应用到给定的高精度模型上,记录并将其评估结果与基准进行比较。当满足退出策略时,调优过程停止。

from neural_compressor.torch.quantization import RTNConfig, TuningConfig, autotune


def eval_fn(model) -> float:
    return ...


tune_config = TuningConfig(
    config_set=RTNConfig(use_sym=[False, True], group_size=[32, 128]),
    tolerable_loss=0.2,
    max_trials=10,
)
q_model = autotune(model, tune_config=tune_config, eval_fn=eval_fn)

教程#

更多详细教程可在官方 Intel® Neural Compressor 文档中找到。