Diffusers documentation

量化

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

量化

量化技术通过使用较低精度的数据类型(如 8 位整数 int8)来表示权重和激活值,从而降低内存和计算成本。这使得能够加载通常无法放入内存中的更大模型,并加快推理速度。

了解如何在量化指南中对模型进行量化。

PipelineQuantizationConfig

class diffusers.PipelineQuantizationConfig

< >

( quant_backend: str = Nonequant_kwargs: dict[str, str | float | int | dict] = Nonecomponents_to_quantize: list[str] | str | None = Nonequant_mapping: dict[str, DiffQuantConfigMixin | 'TransformersQuantConfigMixin'] = None )

参数

  • quant_backend (str) — 要使用的量化后端。使用此选项时,我们假设该后端在 diffusers 和 transformers 中均可用。
  • quant_kwargs (dict) — 用于初始化量化后端类的参数。
  • components_to_quantize (list) — 需要量化的流水线组件。
  • quant_mapping (dict) — 定义用于流水线组件的量化规范的映射。使用此参数时,用户无需提供 quant_backend、quant_kawargs 和 components_to_quantize。

在调用 from_pretrained() 时即时应用量化所使用的配置类。

BFLQuantizationConfig

class diffusers.BFLQuantizationConfig

< >

( compute_dtype: 'torch.dtype' | None = None )

参数

  • compute_dtype (torch.dtype,默认为 torch.bfloat16) — 激活值以及未量化层的 dtype。没有融合 FP8 或 NVFP4 内核的设备会在每次前向传播中将权重反量化为此 dtype。

用于加载使用 Black Forest Labs 的 fp8r 和 nvfp4 方案进行量化的检查点的配置。

两种方案均通过 ~FromSingleFileMixin.from_single_file 从检查点读取;不支持在加载过程中对模型进行量化。当线性层的权重附带 scale 张量时,该层会被量化:

  • fp8r:weight 为形状 [N, K] 的 float8_e4m3fn,weight_scale 为 fp32 逐行缩放因子 [N]。
  • nvfp4:weight 为 uint8,形状为 [N, K/2](每字节包含两个 E2M1 值),weight_scale 是 float8_e4m3fn 块级缩放因子 [N, K/16],而 weight_scale_2 和 input_scale 是 fp32 标量,分别存储全局权重缩放因子和校准后的激活缩放因子(即 ModelOpt NVFP4 布局)。

BitsAndBytesConfig

class diffusers.BitsAndBytesConfig

< >

( load_in_8bit = Falseload_in_4bit = Falsellm_int8_threshold = 6.0llm_int8_skip_modules = Nonellm_int8_enable_fp32_cpu_offload = Falsellm_int8_has_fp16_weight = Falsebnb_4bit_compute_dtype = Nonebnb_4bit_quant_type = 'fp4'bnb_4bit_use_double_quant = Falsebnb_4bit_quant_storage = None**kwargs )

参数

  • load_in_8bit (bool,可选,默认为 False) — 此标志用于启用基于 LLM.int8() 的 8 位量化。
  • load_in_4bit (bool,可选,默认为 False) — 此标志用于启用 4 位量化,通过用 bitsandbytes 中的 FP4/NF4 层替换 Linear 层来实现。
  • llm_int8_threshold (float,可选,默认值为 6.0) — 这对应于 LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale 论文中描述的离群值检测阈值:https://huggingface.co/papers/2208.07339 任何高于此阈值的隐藏状态值都将被视为离群值,对这些值的操作将以 fp16 执行。这些值通常呈正态分布,即大多数值位于 [-3.5, 3.5] 范围内,但对于大型模型,存在一些分布截然不同的系统性异常离群值。这些离群值通常位于区间 [-60, -6] 或 [6, 60] 内。Int8 量化对于量级约为 5 的值效果良好,但超出此范围会带来显著的性能损失。一个好的默认阈值是 6,但对于更不稳定的模型(小型模型、微调),可能需要更低的阈值。
  • llm_int8_skip_modules (list[str],可选) — 一个显式列表,指定我们不想转换为 8 位的模块。这对于像 Jukebox 这样在多个不同位置拥有多个头、且不一定位于最后位置的模型非常有用。例如,对于 CausalLM 模型,最后一个 lm_head 通常保持其原始的 dtype。
  • llm_int8_enable_fp32_cpu_offload (bool,可选,默认为 False) — 此标志用于高级使用场景,且用户需了解该功能。如果您希望将模型拆分为不同部分,并在 GPU 上以 int8 运行部分组件,同时在 CPU 上以 fp32 运行其他组件,则可以使用此标志。这对于卸载大型模型(例如 google/flan-t5-xxl)非常有用。请注意,int8 操作不会在 CPU 上执行。
  • llm_int8_has_fp16_weight (bool,可选,默认为 False) — 此标志使 LLM.int8() 以 16 位主权重运行。这对于微调非常有用,因为反向传播时无需将权重来回转换。
  • bnb_4bit_compute_dtype (torch.dtype 或 str,可选,默认为 torch.float32) — 此参数用于设置计算类型,该类型可能与输入类型不同。例如,输入可以是 fp32,但为了提升速度,可以将计算类型设置为 bf16。
  • bnb_4bit_quant_type (str,可选,默认为 "fp4") — 用于设置 bnb.nn.Linear4Bit 层中的量化数据类型。可选值为 FP4 和 NF4 数据类型,分别通过 fp4 或 nf4 指定。
  • bnb_4bit_use_double_quant (bool,可选,默认为 False) — 此标志用于嵌套量化,即对第一次量化得到的量化常数再次进行量化。
  • bnb_4bit_quant_storage (torch.dtype 或 str,可选,默认为 torch.uint8) — 用于设置打包量化 4 位参数的存储类型。
  • kwargs (dict[str, Any],可选) — 用于初始化配置对象的额外参数。

这是一个封装类,涵盖了使用 bitsandbytes 加载的模型中所有可用的属性和功能。

这将替代 load_in_8bit 或 load_in_4bit,因此这两个选项是互斥的。

目前仅支持 LLM.int8()、FP4 和 NF4 量化。如果 bitsandbytes 中添加了更多方法,则此类将增加更多参数。

is_quantizable

< >

( )

如果模型可量化,则返回 True,否则返回 False。

post_init

< >

( )

用于检查参数是否正确的安全检查器——同时会将某些 NoneType 参数替换为其默认值。

quantization_method

< >

( )

此方法返回用于该模型的量化方法。如果模型不可量化,则返回 None。

to_diff_dict

< >

( ) → dict[str, Any]

返回值

dict[str, Any]

构成此配置实例的所有属性的字典,

移除 config 中对应于默认配置属性的所有属性,以提高可读性,并将其序列化为 Python 字典。

GGUFQuantizationConfig

class diffusers.GGUFQuantizationConfig

< >

( compute_dtype: 'torch.dtype' | None = None )

参数

  • compute_dtype — (torch.dtype,默认为 torch.float32): 用于设置计算类型,该类型可能与输入类型不同。例如,输入可以是 fp32,但为了提升速度,可以将计算类型设置为 bf16。

这是用于 GGUF 量化技术的配置类。

NunchakuLiteQuantizationConfig

class diffusers.NunchakuLiteQuantizationConfig

< >

( compute_dtype: 'torch.dtype' | str | None = Nonesvdq_w4a4: dict[str, Any] | None = Noneawq_w4a16: dict[str, Any] | None = None**kwargs )

参数

  • compute_dtype (torch.dtype,默认为 torch.bfloat16) — 量化模块中浮点缓冲区在运行时使用的 dtype。
  • svdq_w4a4 (dict, 可选) — 显式 SVDQ W4A4 目标配置,包含 precision、group_size、rank 和 targets。
  • awq_w4a16 (dict, 可选) — 显式的 AWQ W4A16 目标配置,包含 precision、group_size 和 targets。

用于加载 Nunchaku Lite 检查点的配置。

Diffusers 中的 Nunchaku Lite 支持加载预量化检查点。要创建兼容的检查点,请使用 diffuse-compressor 为模型架构选择或调整目标配置,对 transformer 进行量化并导出,然后将其打包为 Diffusers pipeline,并将紧凑的 quantization_config 存储在 config.json 中。

导出的 state dict 必须与目标 Diffusers 模型架构完全匹配。使用融合 QKV 投影进行量化的检查点无法加载到期望使用独立 Q、K 和 V 投影模块的模型配置中。

紧凑的 config.json 配置示例:

{
  "_class_name": "ErnieImageTransformer2DModel",
  "quantization_config": {
    "quant_method": "nunchaku_lite",
    "compute_dtype": "bfloat16",
    "svdq_w4a4": {
      "precision": "nvfp4",
      "group_size": 16,
      "rank": 32,
      "targets": ["layers.0.self_attention.to_q"]
    },
    "awq_w4a16": {
      "precision": "int4",
      "group_size": 64,
      "targets": ["final_linear"]
    }
  }
}

QuantoConfig

class diffusers.QuantoConfig

< >

( weights_dtype: str = 'int8'modules_to_not_convert: list[str] | None = None**kwargs )

参数

  • weights_dtype (str, 可选, 默认为 "int8") — 量化后权重的目标数据类型。支持的值为(“float8”、“int8”、“int4”、“int2”)

这是一个封装类,涵盖了使用 quanto 加载的模型中所有可操作的属性和功能。

QuantoConfig 已弃用,并将在 1.0.0 版本中移除。请考虑切换到其他受支持的量化后端,例如 BitsAndBytesConfig 或 TorchAoConfig。

modules_to_not_convert (list, 可选,默认为 None): 不进行量化的模块列表。对于明确要求某些模块保留原始精度的模型(例如 Whisper 编码器、Llava 编码器、Mixtral 门控层),此参数非常有用。

post_init

< >

( )

检查参数是否正确

SDNQConfig

类 diffusers.SDNQConfig

< >

( *args**kwargs )

参数

  • weights_dtype (str,可选,默认为 "int8") — 量化后权重的目标数据类型,例如 "int8"、"uint4"、"float8_e4m3fn"。所有支持的取值请参见 sdnq.common.accepted_weight_dtypes。
  • group_size (int,可选,默认为 0) — 张量中有多少个元素共享同一个量化组。0 会根据 weights_dtype 自动选择, -1 则禁用分组,改用按行量化。
  • use_svd (bool,可选,默认为 False) — 是否在 SDNQ 量化的基础上应用 SVDQuant 算法。
  • use_quantized_matmul (bool,可选,默认为 False) — 是否在前向传播中使用量化后的 INT8 / FP8 / FP16 矩阵乘法,而不是 BF16 / FP16。
  • modules_to_not_convert (list,可选,默认为 None) — 量化过程中需要跳过的模块列表。
  • kwargs (dict[str, Any],可选) — 转发给 sdnq.SDNQConfig 的额外关键字参数(例如 quantized_matmul_dtype、svd_rank、 use_hadamard、quant_conv、quant_embedding、modules_dtype_dict)。

SDNQ(SD.Next Quantization)的配置类。

sdnq 库自带了兼容 diffusers 的配置文件和量化器;此类是一个轻量级的工厂,将工作委托给它们,以便 quant_method="sdnq" 检查点能够原生地在 diffusers 中加载。所有参数都会转发给 sdnq.SDNQConfig。需要 sdnq 库:pip install sdnq。

参考:https://github.com/Disty0/sdnq

TorchAoConfig

class diffusers.TorchAoConfig

< >

( quant_type: 'AOBaseConfig'modules_to_not_convert: list[str] | None = None**kwargs )

参数

  • quant_type (AOBaseConfig) — AOBaseConfig 的子类实例,用于指定量化类型。有关可用的配置类(例如 Int4WeightOnlyConfig、Int8WeightOnlyConfig、Float8WeightOnlyConfig、Float8DynamicActivationFloat8WeightConfig 等),请参阅 torchao 文档。
  • modules_to_not_convert (list[str],可选,默认为 None) — 不进行量化的模块列表。对于明确要求某些模块保留原始精度的模型,此参数在量化时非常有用。

这是用于 torchao 量化/稀疏化技术的配置类。

示例:

from diffusers import FluxTransformer2DModel, TorchAoConfig
from torchao.quantization import Int8WeightOnlyConfig

quantization_config = TorchAoConfig(Int8WeightOnlyConfig())
transformer = FluxTransformer2DModel.from_pretrained(
    "black-forest-labs/Flux.1-Dev",
    subfolder="transformer",
    quantization_config=quantization_config,
    torch_dtype=torch.bfloat16,
)

from_dict

< >

( config_dictreturn_unused_kwargs = False**kwargs )

从字典创建配置。

get_apply_tensor_subclass

< >

( )

根据配置创建相应的量化方法。

to_dict

< >

( )

将配置转换为字典。

DiffusersQuantizer

class diffusers.DiffusersQuantizer

< >

( quantization_config: QuantizationConfigMixin**kwargs )

HuggingFace 量化器的抽象类。目前支持对 HF diffusers 模型进行推理和/或量化。该类仅用于 diffusers.models.modeling_utils.ModelMixin.from_pretrained,目前尚无法轻松地在该方法的作用域之外使用。

Attributes quantization_config (diffusers.quantizers.quantization_config.QuantizationConfigMixin): 定义您想要量化的模型的量化参数的量化配置。 modules_to_not_convert (list[str], 可选): 量化模型时不进行转换的模块名称列表。 required_packages (list[str], 可选): 使用量化器之前需要安装的 pip 包列表。 requires_calibration (bool): 量化方法是否要求在使用前对模型进行校准。

adjust_max_memory

< >

( max_memory: dict[str, int | str] )

如果量化需要额外的内存,请调整 infer_auto_device_map() 的 max_memory 参数

adjust_target_dtype

< >

( torch_dtype: torch.dtype )

参数

  • torch_dtype (torch.dtype,可选) — 用于计算 device_map 的 torch_dtype。

如果需要调整在 from_pretrained 中用于计算 device_map 的 target_dtype 变量(当 device_map 为 str 时),请重写此方法。例如,对于 bitsandbytes,我们会强制将 target_dtype 设置为 torch.int8;而对于 4-bit,则传入自定义枚举 accelerate.CustomDtype.int4。

check_if_quantized_param

< >

( model: ModelMixinparam_value: torch.Tensorparam_name: strstate_dict: dict[str, typing.Any]**kwargs )

检查已加载的 state_dict 组件是否属于量化参数的一部分,并进行一些验证;仅针对需要为量化创建新参数的量化方法定义。

check_quantized_param_shape

< >

( *args**kwargs )

检查量化参数是否具有预期的形状。

create_quantized_param

< >

( *args**kwargs )

从 state_dict 中获取所需组件并创建量化参数。

dequantize

< >

( model )

可能会反量化模型以恢复原始模型,但会损失一定的精度/性能。请注意,并非所有量化方案都支持此操作。

get_cuda_warm_up_factor

< >

( )

在 caching_allocator_warmup 中使用的系数,用于计算预热 cuda 所需预分配的字节数。 系数为 2 表示我们分配空模型中的所有字节(因为我们以 fp16 进行分配),系数为 4 表示 我们分配空模型中驻留权重所占内存的一半,依此类推……

get_special_dtypes_update

< >

( modeltorch_dtype: torch.dtype )

参数

  • model (~diffusers.models.modeling_utils.ModelMixin) — 要量化的模型
  • torch_dtype (torch.dtype) — 在 from_pretrained 方法中传入的 dtype。

返回未量化模块的 dtypes - 当传入 str 作为 device_map 时,用于计算 device_map。该方法会使用在 _process_model_before_weight_loading 中修改的 modules_to_not_convert。diffusers 模型目前还没有任何 modules_to_not_convert 属性,但未来可能会很快发生变化。

postprocess_model

< >

( model: ModelMixin**kwargs )

参数

  • model (~diffusers.models.modeling_utils.ModelMixin) — 要量化的模型
  • kwargs (dict,可选) — 传递给 _process_model_after_weight_loading 的关键字参数。

在加载权重后对模型进行后处理。请确保重写抽象方法 _process_model_after_weight_loading。

preprocess_model

< >

( model: ModelMixin**kwargs )

参数

  • model (~diffusers.models.modeling_utils.ModelMixin) — 要量化的模型
  • kwargs (dict, 可选) — 传递给 _process_model_before_weight_loading 的关键字参数。

在加载权重之前设置模型属性和/或转换模型。此时,模型应在 meta 设备上完成初始化,因此您可以自由操作模型的骨架,以便就地替换模块。请务必重写抽象方法 _process_model_before_weight_loading。

update_device_map

< >

( device_map: dict[str, typing.Any] | None )

参数

  • device_map (dict | str,可选) — 通过 from_pretrained 方法传递的 device_map。

如果需要覆盖现有的设备映射,请重写此方法。例如,对于 bitsandbytes,由于 accelerate 是硬性要求,如果未传入 device_map,则 device_map 会被设置为 `“auto”“

update_missing_keys

< >

( modelmissing_keys: list[str]prefix: str )

参数

  • missing_keys (list[str],可选) — 与模型状态字典相比,检查点中缺失的键列表

如果您想调整 missing_keys,请重写此方法。

update_torch_dtype

< >

( torch_dtype: torch.dtype )

参数

  • torch_dtype (torch.dtype) — 通过 from_pretrained 传入的输入数据类型

某些量化方法要求显式将模型的 dtype 设置为目标 dtype。如果您希望确保保留该行为,则需要重写此方法

validate_environment

< >

( *args**kwargs )

此方法用于检查通过 from_pretrained 传入的参数是否存在潜在冲突。您需要为所有与 diffusers 集成的未来量化器定义此方法。如果不需要显式检查,则直接返回空值即可。

Update on GitHub