Transformers 文件

細粒度 FP8

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

細粒度 FP8

細粒度 FP8 量化將權重和啟用量化為 fp8。

  • 權重對每個 2D 塊(`weight_block_size=(128, 128)`)量化為 8 位。
  • 啟用對每個令牌的每個組進行 8 位量化。組值與輸入通道中的權重匹配(預設為 128)。

FP8 量化支援 DeepSeek-V3 和 DeepSeek-R1。

您需要一個計算能力 >=9 (H100) 的 GPU,並安裝與您的 GPU 的 CUDA 版本相容的 PyTorch 版本。

安裝 Accelerate 並升級到最新版本的 PyTorch。

pip install --upgrade accelerate torch

建立一個 FineGrainedFP8Config 類,並將其傳遞給 from_pretrained() 進行量化。預設情況下,無論權重以何種實際資料型別儲存,權重都以全精度(`torch.float32`)載入。設定 `torch_dtype="auto"` 以在模型 `config.json` 檔案中定義的資料型別中載入權重,從而自動載入最節省記憶體的資料型別。

from transformers import FineGrainedFP8Config, AutoModelForCausalLM, AutoTokenizer

model_name = "meta-llama/Meta-Llama-3-8B"
quantization_config = FineGrainedFP8Config()
quantized_model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto", quantization_config=quantization_config)

tokenizer = AutoTokenizer.from_pretrained(model_name)
input_text = "What are we having for dinner?"
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")

output = quantized_model.generate(**input_ids, max_new_tokens=10)
print(tokenizer.decode(output[0], skip_special_tokens=True))

使用 save_pretrained() 儲存量化模型,並使用 from_pretrained() 重新載入它。

quant_path = "/path/to/save/quantized/model"
model.save_pretrained(quant_path)
model = AutoModelForCausalLM.from_pretrained(quant_path, device_map="auto")
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.