Transformers documentation

Optimum Quanto

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Optimum Quanto

Quanto 是 Optimum 的 PyTorch 量化后端。它支持权重的线性量化(float8、int8、int4、int2),精度与全精度模型非常接近。Quanto 兼容任意模型模态和设备,因此无论使用何种硬件,使用起来都非常简单。

Quanto 还兼容 torch.compile,以实现更快的生成速度。

使用以下命令安装 Quanto。

pip install optimum-quanto accelerate transformers

通过创建 QuantoConfig 并指定 weights 参数来量化模型。只要模型包含 torch.nn.Linear 层,此方法适用于任何模态下的任何模型。

Transformers 集成仅支持权重量化。如果需要激活量化、校准或 QAT,请直接使用 Quanto 库。

from transformers import AutoModelForCausalLM, AutoTokenizer, QuantoConfig

quant_config = QuantoConfig(weights="int8")
model = transformers.AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B", 
    dtype="auto", 
    device_map="auto", 
    quantization_config=quant_config
)

torch.compile

使用 torch.compile 包装 Quanto 模型以加快生成速度。

import torch
from transformers import AutoModelForSpeechSeq2Seq, QuantoConfig

quant_config = QuantoConfig(weights="int8")
model = AutoModelForSpeechSeq2Seq.from_pretrained(
  "openai/whisper-large-v2",
  dtype="auto",
  device_map="auto",
  quantization_config=quant_config
)

model = torch.compile(model)

资源

阅读 Quanto:Optimum 的 PyTorch 量化后端 博客文章,以了解该库的设计和基准测试。

如需更多实践示例,请查看 Quanto notebook。

Update on GitHub