Diffusers 文档

量化

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

量化

量化技术通过使用较低精度的数据类型(如 8 位整数 (int8))表示权重和激活,从而降低内存和计算成本。这使得您可以加载通常无法放入内存的更大模型,并加快推理速度。 Diffusers 支持使用 bitsandbytes 进行 8 位和 4 位量化。

Transformers 中不支持的量化技术可以使用 DiffusersQuantizer 类添加。

请参阅量化指南,了解如何量化模型。

BitsAndBytesConfig

class diffusers.BitsAndBytesConfig

< >

( load_in_8bit = False load_in_4bit = False llm_int8_threshold = 6.0 llm_int8_skip_modules = None llm_int8_enable_fp32_cpu_offload = False llm_int8_has_fp16_weight = False bnb_4bit_compute_dtype = None bnb_4bit_quant_type = 'fp4' bnb_4bit_use_double_quant = False bnb_4bit_quant_storage = None **kwargs )

参数

  • load_in_8bit (bool, 可选, 默认为 False) — 此标志用于启用 LLM.int8() 的 8 位量化。
  • load_in_4bit (bool, 可选, 默认为 False) — 此标志用于启用 4 位量化,方法是将 Linear 层替换为 bitsandbytes 中的 FP4/NF4 层。
  • llm_int8_threshold (float, 可选, 默认为 6.0) — 这对应于 https://arxiv.org/abs/2208.07339 论文 LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale 中描述的异常值检测的异常值阈值:。任何高于此阈值的隐藏状态值都将被视为异常值,并且对这些值的操作将在 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) — 此标志使用 16 位主权重运行 LLM.int8()。这对于微调很有用,因为权重不必为后向传递来回转换。
  • bnb_4bit_compute_dtype (torch.dtype 或 str, 可选, 默认为 torch.float32) — 这设置了计算类型,该类型可能与输入类型不同。例如,输入可能是 fp32,但为了加速,可以将计算设置为 bf16。
  • bnb_4bit_quant_type (str, 可选, 默认为 "fp4") — 这在 bnb.nn.Linear4Bit 层中设置量化数据类型。选项为 FP4 和 NF4 数据类型,由 fp4nf4 指定。
  • bnb_4bit_use_double_quant (bool, 可选, 默认为 False) — 此标志用于嵌套量化,其中来自第一次量化的量化常数再次被量化。
  • bnb_4bit_quant_storage (torch.dtype 或 str, 可选, 默认为 torch.uint8) — 这设置了存储类型以打包量化的 4 位参数。
  • kwargs (Dict[str, Any], 可选) — 用于初始化配置对象的其他参数。

这是一个包装类,包含可以使用 bitsandbytes 加载的模型的所有可能属性和功能。

这取代了 load_in_8bitload_in_4bit,因此这两个选项是互斥的。

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

is_quantizable

< >

( )

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

post_init

< >

( )

安全检查器,用于检查参数是否正确 - 还会将一些 NoneType 参数替换为其默认值。

quantization_method

< >

( )

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

to_diff_dict

< >

( ) Dict[str, Any]

返回:

Dict[str, Any]

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

从配置中删除与默认配置属性对应的所有属性,以提高可读性,并序列化为 Python 字典。

GGUFQuantizationConfig

class diffusers.GGUFQuantizationConfig

< >

( compute_dtype: typing.Optional[ForwardRef('torch.dtype')] = None )

参数

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

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

TorchAoConfig

class diffusers.TorchAoConfig

< >

( quant_type: str modules_to_not_convert: typing.Optional[typing.List[str]] = None **kwargs )

参数

  • quant_type (str) — 我们想要使用的量化类型,目前支持:

    • 整数量化:

      • 完整函数名称:int4_weight_only, int8_dynamic_activation_int4_weight, int8_weight_only, int8_dynamic_activation_int8_weight
      • 缩写:int4wo, int4dq, int8wo, int8dq
    • 浮点 8 位量化:

      • 完整函数名称:float8_weight_only, float8_dynamic_activation_float8_weight, float8_static_activation_float8_weight
      • 缩写:float8wo, float8wo_e5m2, float8wo_e4m3, float8dq, float8dq_e4m3, float8_e4m3_tensor, float8_e4m3_row,
    • 浮点 X 位量化:

      • 完整函数名称:fpx_weight_only
      • 缩写:fpX_eAwB,其中 X 是位数(介于 17 之间),A 是指数位数,B 是尾数位数。对于给定的缩写符号,必须满足 X == A + B + 1 的约束。
    • 无符号整数量化:

      • 完整函数名称:uintx_weight_only
      • 缩写:uint1wo, uint2wo, uint3wo, uint4wo, uint5wo, uint6wo, uint7wo
  • kwargs (Dict[str, Any], optional) — The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments group_size and inner_k_tiles currently. More API examples and documentation of arguments can be found in https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques

This is a config class for torchao quantization/sparsity techniques.

Example

from diffusers import FluxTransformer2DModel, TorchAoConfig

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

DiffusersQuantizer

class diffusers.DiffusersQuantizer

< >

( quantization_config: QuantizationConfigMixin **kwargs )

Abstract class of the HuggingFace quantizer. Supports for now quantizing HF diffusers models for inference and/or quantization. This class is used only for diffusers.models.modeling_utils.ModelMixin.from_pretrained and cannot be easily used outside the scope of that method yet.

Attributes quantization_config (diffusers.quantizers.quantization_config.QuantizationConfigMixin): The quantization config that defines the quantization parameters of your model that you want to quantize. modules_to_not_convert (List[str], optional): The list of module names to not convert when quantizing the model. required_packages (List[str], optional): The list of required pip packages to install prior to using the quantizer requires_calibration (bool): Whether the quantization method requires to calibrate the model before using it.

adjust_max_memory

< >

( max_memory: typing.Dict[str, typing.Union[int, str]] )

adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization

adjust_target_dtype

< >

( torch_dtype: torch.dtype )

参数

  • torch_dtype (torch.dtype, optional) — The torch_dtype that is used to compute the device_map.

Override this method if you want to adjust the target_dtype variable used in from_pretrained to compute the device_map in case the device_map is a str. E.g. for bitsandbytes we force-set target_dtype to torch.int8 and for 4-bit we pass a custom enum accelerate.CustomDtype.int4.

check_if_quantized_param

< >

( model: ModelMixin param_value: torch.Tensor param_name: str state_dict: typing.Dict[str, typing.Any] **kwargs )

checks if a loaded state_dict component is part of quantized param + some validation; only defined for quantization methods that require to create a new parameters for quantization.

check_quantized_param_shape

< >

( *args **kwargs )

checks if the quantized param has expected shape.

create_quantized_param

< >

( *args **kwargs )

takes needed components from state_dict and creates quantized param.

dequantize

< >

( model )

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

get_special_dtypes_update

< >

( model torch_dtype: torch.dtype )

参数

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

返回未量化模块的dtypes - 用于计算 device_map,以防将 str 作为 device_map 传递。该方法将使用在 _process_model_before_weight_loading 中修改的 modules_to_not_convertdiffusers 模型目前没有任何 modules_to_not_convert 属性,但这在不久的将来可能会改变。

postprocess_model

< >

( model: ModelMixin **kwargs )

参数

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

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

preprocess_model

< >

( model: ModelMixin **kwargs )

参数

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

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

update_device_map

< >

( device_map: typing.Optional[typing.Dict[str, typing.Any]] )

参数

  • device_map (Union[dict, str], optional) — 通过 from_pretrained 方法传递的 device_map。

如果您想传递新的 device map 以覆盖现有的 device map,请重写此方法。例如,对于 bitsandbytes,由于 accelerate 是硬性要求,如果未传递 device_map,则 device_map 将设置为 `“auto”`。

update_missing_keys

< >

( model missing_keys: typing.List[str] prefix: str )

参数

  • missing_keys (List[str], optional) — 检查点中相对于模型状态字典的缺失键列表

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

update_torch_dtype

< >

( torch_dtype: torch.dtype )

参数

  • torch_dtype (torch.dtype) — 在 from_pretrained 中传入的输入 dtype

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

validate_environment

< >

( *args **kwargs )

此方法用于潜在地检查与在 from_pretrained 中传递的参数可能存在的冲突。您需要为所有未来与 diffusers 集成的量化器定义它。如果不需要显式检查,只需不返回任何内容即可。

< > Update on GitHub