Buckets:
量化
量化技术通过使用较低精度的数据类型(例如 8 位整数 int8)来表示权重和激活值,从而降低内存和计算成本。这使得能够加载通常无法放入内存中的更大模型,并加快推理速度。
了解如何在量化指南中对模型进行量化。
PipelineQuantizationConfig[[diffusers.PipelineQuantizationConfig]]
diffusers.PipelineQuantizationConfig[[diffusers.PipelineQuantizationConfig]]
diffusers.PipelineQuantizationConfig(quant_backend: str = None, quant_kwargs: dict[str, str | float | int | dict] = None, components_to_quantize: list[str] | str | None = None, quant_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[[diffusers.BFLQuantizationConfig]]
diffusers.BFLQuantizationConfig[[diffusers.BFLQuantizationConfig]]
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 从检查点读取;不支持在加载过程中对模型进行量化。当线性层的权重附带缩放张量时,该层会被量化:
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[[diffusers.BitsAndBytesConfig]]
diffusers.BitsAndBytesConfig[[diffusers.BitsAndBytesConfig]]
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):此标志用于通过用 bitsandbytes 中的 FP4/NF4 层替换 Linear 层来启用 4 位量化。
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):此标志会以 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 数据类型,分别由 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[[diffusers.BitsAndBytesConfig.is_quantizable]]
is_quantizable()
如果模型可量化,则返回 True,否则返回 False。
post_init[[diffusers.BitsAndBytesConfig.post_init]]
post_init()
用于检查参数是否正确的安全检查器——同时会将某些 NoneType 参数替换为其默认值。
quantization_method[[diffusers.BitsAndBytesConfig.quantization_method]]
quantization_method()
此方法返回用于该模型的量化方法。如果模型不可量化,则返回 None。
to_diff_dict[[diffusers.BitsAndBytesConfig.to_diff_dict]]
to_diff_dict()
返回: dict[str, Any]
构成此配置实例的所有属性的字典,
移除 config 中对应于默认配置属性的所有属性,以提高可读性,并将其序列化为 Python 字典。
GGUFQuantizationConfig[[diffusers.GGUFQuantizationConfig]]
diffusers.GGUFQuantizationConfig[[diffusers.GGUFQuantizationConfig]]
diffusers.GGUFQuantizationConfig(compute_dtype: 'torch.dtype' | None = None)
参数:
compute_dtype : (torch.dtype,默认为 torch.float32):用于设置计算类型,该类型可能与输入类型不同。例如,输入可以是 fp32,但为了提升速度,可以将计算类型设置为 bf16。
这是用于 GGUF 量化技术的配置类。
NunchakuLiteQuantizationConfig[[diffusers.NunchakuLiteQuantizationConfig]]
diffusers.NunchakuLiteQuantizationConfig[[diffusers.NunchakuLiteQuantizationConfig]]
diffusers.NunchakuLiteQuantizationConfig(compute_dtype: 'torch.dtype' | str | None = None, svdq_w4a4: dict[str, Any] | None = None, awq_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[[diffusers.QuantoConfig]]
diffusers.QuantoConfig[[diffusers.QuantoConfig]]
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[[diffusers.QuantoConfig.post_init]]
post_init()
检查参数是否正确
SDNQConfig[[diffusers.SDNQConfig]]
diffusers.SDNQConfig[[diffusers.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[[diffusers.TorchAoConfig]]
diffusers.TorchAoConfig[[diffusers.TorchAoConfig]]
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[[diffusers.TorchAoConfig.from_dict]]
from_dict(config_dict, return_unused_kwargs = False, **kwargs)
从字典创建配置。
get_apply_tensor_subclass[[diffusers.TorchAoConfig.get_apply_tensor_subclass]]
get_apply_tensor_subclass()
根据配置创建相应的量化方法。
to_dict[[diffusers.TorchAoConfig.to_dict]]
to_dict()
将配置转换为字典。
DiffusersQuantizer[[diffusers.DiffusersQuantizer]]
diffusers.DiffusersQuantizer[[diffusers.DiffusersQuantizer]]
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[[diffusers.DiffusersQuantizer.adjust_max_memory]]
adjust_max_memory(max_memory: dict[str, int | str])
如果量化需要额外的内存,请调整 infer_auto_device_map() 的 max_memory 参数
adjust_target_dtype[[diffusers.DiffusersQuantizer.adjust_target_dtype]]
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[[diffusers.DiffusersQuantizer.check_if_quantized_param]]
check_if_quantized_param(model: ModelMixin, param_value: torch.Tensor, param_name: str, state_dict: dict[str, typing.Any], **kwargs)
检查已加载的 state_dict 组件是否属于量化参数的一部分,并进行一些验证;仅针对需要为量化创建新参数的量化方法定义。
check_quantized_param_shape[[diffusers.DiffusersQuantizer.check_quantized_param_shape]]
check_quantized_param_shape(*args, **kwargs)
检查量化参数是否具有预期的形状。
create_quantized_param[[diffusers.DiffusersQuantizer.create_quantized_param]]
create_quantized_param(*args, **kwargs)
从 state_dict 中获取所需组件并创建量化参数。
dequantize[[diffusers.DiffusersQuantizer.dequantize]]
dequantize(model)
可能会反量化模型以恢复原始模型,但会损失一定的精度/性能。请注意,并非所有量化方案都支持此操作。
get_cuda_warm_up_factor[[diffusers.DiffusersQuantizer.get_cuda_warm_up_factor]]
get_cuda_warm_up_factor()
在 caching_allocator_warmup 中使用的系数,用于计算预热 cuda 所需预分配的字节数。系数为 2 表示分配空模型中的所有字节(因为以 fp16 进行分配),系数为 4 表示分配空模型中权重所占内存的一半,依此类推……
get_special_dtypes_update[[diffusers.DiffusersQuantizer.get_special_dtypes_update]]
get_special_dtypes_update(model, torch_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[[diffusers.DiffusersQuantizer.postprocess_model]]
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[[diffusers.DiffusersQuantizer.preprocess_model]]
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[[diffusers.DiffusersQuantizer.update_device_map]]
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[[diffusers.DiffusersQuantizer.update_missing_keys]]
update_missing_keys(model, missing_keys: list[str], prefix: str)
参数:
missing_keys (list[str], 可选) : 与模型状态字典相比,检查点中缺失的键列表
如果您想调整 missing_keys,请重写此方法。
update_torch_dtype[[diffusers.DiffusersQuantizer.update_torch_dtype]]
update_torch_dtype(torch_dtype: torch.dtype)
参数:
torch_dtype (torch.dtype):通过 from_pretrained 传入的输入数据类型
某些量化方法要求显式将模型的 dtype 设置为目标 dtype。如果您希望确保保留该行为,则需要重写此方法
validate_environment[[diffusers.DiffusersQuantizer.validate_environment]]
validate_environment(*args, **kwargs)
此方法用于检查通过 from_pretrained 传入的参数是否存在潜在冲突。您需要为所有与 diffusers 集成的未来量化器定义此方法。如果不需要显式检查,则直接返回空值即可。
Xet Storage Details
- Size:
- 23.9 kB
- Xet hash:
- dac9ab878dea5878fe40ac8d0fbd94646a70288307935fe3a130442dc9f14df6
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.