Transformers documentation

Optimum Quanto

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

Quantoモデルをtorch.compileでラップして、生成を高速化します。

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: a PyTorch quantization backend for Optimum というブログ記事をお読みください。

より実践的な例については、Quantoのノートブックをご覧ください。

Update on GitHub