Transformers documentation

反量化模型

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

and get access to the augmented documentation experience

to get started

反量化模型

反量化将量化后的权重转换回更高精度的数据类型,例如 bf16。您可以对模型进行反量化,以便对其进行完全微调、在方法内核不支持的硬件上运行,或将其转换为其他格式。反量化后的模型占用的内存与未量化模型相同,并且无法恢复因舍入而损失的精度。

Transformers 会根据方法的不同,以两种方式执行反量化。

方法如何反量化
bitsandbytes、HIGGS加载后调用 dequantize()。
compressed-tensors、细粒度 FP8、GGUF、Metal、MXFP4在加载时,向该方法的配置传入 dequantize=True。

其他方法会从 dequantize() 中引发 NotImplementedError。

加载后反量化

在加载的模型上调用 dequantize()。默认使用模型加载时的 dtype。传入 dtype 以选择其他类型。

import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B",
    quantization_config=BitsAndBytesConfig(load_in_4bit=True),
    device_map="auto",
)
model = model.dequantize(dtype=torch.bfloat16)

dequantize() 还会移除 quantization_config,因此 save_pretrained() 会保存一个常规的完整精度检查点。

加载时反量化

将 dequantize=True 传递给支持该参数的方法的 config。权重在加载时会被反量化,因此不会使用量化内核。下面的示例以 bf16 格式加载 gpt-oss 的 MXFP4 权重。

from transformers import AutoModelForCausalLM, Mxfp4Config

model = AutoModelForCausalLM.from_pretrained(
    "openai/gpt-oss-20b",
    quantization_config=Mxfp4Config(dequantize=True),
    device_map="auto",
)

某些方法在其内核无法运行时会自动反量化。例如,GGUF 在没有内核支持该文件的量化类型时,会回退到反量化。

Update on GitHub