配置
本文档列出了Model Optimizer支持的量化格式以及示例量化配置。
量化格式
下表列出了Model Optimizer支持的量化格式及相应的量化配置。有关具体的量化配置定义,请参见量化配置。
请参阅选择正确的量化格式以了解更多关于这些格式及其使用场景的信息。
注意
下面推荐的配置适用于LLM模型。对于CNN模型,仅支持INT8量化。请使用量化配置INT8_DEFAULT_CFG用于CNN模型。
量化格式 |
模型优化器配置 |
|---|---|
INT8 |
|
FP8 |
|
INT4 仅权重 AWQ (W4A16) |
|
INT4-FP8 AWQ (W4A8) |
|
量化配置
量化配置是一个字典,指定了键"quant_cfg"和"algorithm"的值。键"quant_cfg"指定了量化配置。键"algorithm"指定了calibrate的algorithm参数。请参阅QuantizeConfig了解量化配置的定义。
‘量化配置’是一个将通配符或过滤函数映射到其‘量化器属性’的字典。通配符或过滤函数与量化器模块名称匹配。量化器模块的名称以weight_quantizer和input_quantizer结尾,它们分别执行权重量化和输入量化(或激活量化)。量化器模块通常是TensorQuantizer的实例。量化器属性由QuantizerAttributeConfig定义。有关量化器属性及其值的详细信息,请参见QuantizerAttributeConfig。
如果没有其他通配符或过滤函数匹配量化器模块名称,则应用量化配置字典中的“default”键。
量化器属性按照它们指定的顺序应用。对于缺失的属性,使用由QuantizerAttributeConfig定义的默认属性。
量化器属性也可以是一个字典列表。在这种情况下,匹配的量化器模块被替换为
SequentialQuantizer
模块,该模块用于按多种格式顺序量化张量。列表中的每个量化器属性字典指定了顺序量化器每个量化步骤的量化格式。例如,SequentialQuantizer用于‘INT4权重,FP8激活’量化,其中权重首先以INT4量化,然后以FP8量化。
此外,字典条目也可以是映射到特定类量化配置的pytorch模块类名。这些pytorch模块应该有一个量化等效版本。
要获取模块类的字符串表示,请执行以下操作:
from modelopt.torch.quantization.nn import QuantModuleRegistry
# Get the class name for nn.Conv2d
class_name = QuantModuleRegistry.get_key(nn.Conv2d)
这是一个量化配置的示例:
MY_QUANT_CFG = {
"quant_cfg": {
# Quantizer wildcard strings mapping to quantizer attributes
"*weight_quantizer": {"num_bits": 8, "axis": 0},
"*input_quantizer": {"num_bits": 8, "axis": None},
# Module class names mapping to quantizer configurations
"nn.LeakyReLU": {"*input_quantizer": {"enable": False}},
}
}
示例量化配置
以下是来自模型优化器的推荐量化配置,适用于FP8、INT8、INT4等量化格式:
INT8_DEFAULT_CFG = {
"quant_cfg": {
"*weight_quantizer": {"num_bits": 8, "axis": 0},
"*input_quantizer": {"num_bits": 8, "axis": None},
"*lm_head*": {"enable": False},
"*block_sparse_moe.gate*": {"enable": False}, # Skip the MOE router
"*router*": {"enable": False}, # Skip the MOE router
"default": {"enable": False},
},
"algorithm": "max",
}
INT8_SMOOTHQUANT_CFG = {
"quant_cfg": {
"*weight_quantizer": {"num_bits": 8, "axis": 0},
"*input_quantizer": {"num_bits": 8, "axis": -1},
"*lm_head*": {"enable": False},
"*block_sparse_moe.gate*": {"enable": False}, # Skip the MOE router
"*router*": {"enable": False}, # Skip the MOE router
"nn.Conv2d": {
"*weight_quantizer": {"num_bits": 8, "axis": 0},
"*input_quantizer": {"num_bits": 8, "axis": None},
},
"default": {"enable": False},
},
"algorithm": "smoothquant",
}
FP8_DEFAULT_CFG = {
"quant_cfg": {
"*weight_quantizer": {"num_bits": (4, 3), "axis": None},
"*input_quantizer": {"num_bits": (4, 3), "axis": None},
"*block_sparse_moe.gate*": {"enable": False}, # Skip the MOE router
"*router*": {"enable": False}, # Skip the MOE router
"default": {"enable": False},
},
"algorithm": "max",
}
INT4_BLOCKWISE_WEIGHT_ONLY_CFG = {
"quant_cfg": {
"*weight_quantizer": {"num_bits": 4, "block_sizes": {-1: 128}, "enable": True},
"*input_quantizer": {"enable": False},
"*lm_head*": {"enable": False},
"*block_sparse_moe.gate*": {"enable": False}, # Skip the MOE router
"*router*": {"enable": False}, # Skip the MOE router
"default": {"enable": False},
},
"algorithm": "max",
}
INT4_AWQ_CFG = {
"quant_cfg": {
"*weight_quantizer": {"num_bits": 4, "block_sizes": {-1: 128}, "enable": True},
"*input_quantizer": {"enable": False},
"*lm_head*": {"enable": False},
"*block_sparse_moe.gate*": {"enable": False}, # Skip the MOE router
"*router*": {"enable": False}, # Skip the MOE router
"default": {"enable": False},
},
"algorithm": {"method": "awq_lite", "alpha_step": 0.1},
# "algorithm": {"method": "awq_full", "alpha_step": 0.1, "max_co_batch_size": 1024},
# "algorithm": {"method": "awq_clip", "max_co_batch_size": 2048},
}
W4A8_AWQ_BETA_CFG = {
"quant_cfg": {
"*weight_quantizer": [
{"num_bits": 4, "block_sizes": {-1: 128}, "enable": True},
{"num_bits": (4, 3), "axis": None, "enable": True},
],
"*input_quantizer": {"num_bits": (4, 3), "axis": None, "enable": True},
"*lm_head*": {"enable": False},
"*block_sparse_moe.gate*": {"enable": False}, # Skip the MOE router
"*router*": {"enable": False}, # Skip the MOE router
"default": {"enable": False},
},
"algorithm": "awq_lite",
}
这些配置可以作为modelopt.torch.quantization的属性访问,并且可以作为输入提供给mtq.quantize()。例如:
import modelopt.torch.quantization as mtq
model = mtq.quantize(model, mtq.INT8_DEFAULT_CFG, forward_loop)
你也可以按照这些示例创建自己的配置。
例如,如果你想使用int4 AWQ算法量化模型,但需要跳过名为lm_head的层的量化,你可以创建一个自定义配置并按如下方式量化你的模型:
# Create custom config
CUSTOM_INT4_AWQ_CFG = copy.deepcopy(mtq.INT4_AWQ_CFG)
CUSTOM_INT4_AWQ_CFG["quant_cfg"]["*lm_head*"] = {"enable": False}
# quantize model
model = mtq.quantize(model, CUSTOM_INT4_AWQ_CFG, forward_loop)
- ModeloptConfig AWQClipCalibConfig
-
awq_clip(AWQ clip) 算法的配置。AWQ clip 搜索裁剪后的 amax 用于每组分数量化,这种搜索相比 AWQ lite 需要更多的计算。为了避免任何内存不足(OOM)问题,线性层权重沿着
out_features维度进行批处理,批处理大小为max_co_batch_size。AWQ clip 校准也比 AWQ lite 耗时更长。显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max", "max_co_batch_size": 1024, "max_tokens_per_batch": 64, "min_clip_ratio": 0.5, "shrink_step": 0.05, "debug": false }
- field debug: bool | None
显示详情
如果为True,模块的搜索元数据将保留为名为
awq_clip的模块属性。
- field max_co_batch_size: int | None
显示详情
如果发生CUDA内存不足错误,请减少此数字。
- field max_tokens_per_batch: int | None
显示详情
用于剪辑搜索的总令牌数将是
max_tokens_per_batch * number of batches。 原始的AWQ使用总共512个令牌来搜索剪辑值。
- field min_clip_ratio: float | None
显示详情
它应该在 (0, 1.0) 范围内。Clip 将在范围
[original block amax * min_clip_ratio, original block amax]内搜索最佳裁剪值。- Constraints:
gt = 0.0
lt = 1.0
- field shrink_step: float | None
显示详情
它应该在范围 (0, 1.0] 内。剪裁比例将从
min_clip_ratio到 1 进行搜索,步长由指定值决定。- Constraints:
gt = 0.0
le = 1.0
- ModeloptConfig AWQFullCalibConfig
基础类:
AWQLiteCalibConfig,AWQClipCalibConfigawq或awq_full算法的配置(AWQ 完整版)。AWQ full 执行
awq_lite后接着执行awq_clip。显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max", "max_co_batch_size": 1024, "max_tokens_per_batch": 64, "min_clip_ratio": 0.5, "shrink_step": 0.05, "debug": false, "alpha_step": 0.1 }
- field debug: bool | None
显示详情
如果为True,模块的搜索元数据将作为模块属性保留,属性名为
awq_lite和awq_clip。
- ModeloptConfig AWQLiteCalibConfig
-
awq_lite(AWQ lite) 算法的配置。AWQ lite 应用了通道级的缩放因子,以最小化量化后的输出差异。 详情请参阅 AWQ 论文。
显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max", "alpha_step": 0.1, "debug": false }
- field alpha_step: float | None
显示详情
alpha 将从 0 到 1 以指定的步长进行搜索。
- Constraints:
gt = 0.0
le = 1.0
- field debug: bool | None
显示详情
如果为True,模块的搜索元数据将保留为名为awq_lite的模块属性。
- ModeloptConfig MaxCalibConfig
-
最大校准算法的配置。
最大校准估计激活或权重的最大值,并使用这些最大值来设置量化比例因子。 有关概念,请参见整数量化。
显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max" }
- ModeloptConfig QuantizeAlgorithmConfig
-
校准算法配置基础。
显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max" }
- field method: str
显示详情
用于校准的算法。支持的算法包括
"max", "smoothquant", "awq_lite", "awq_full", 和 "awq_clip".
- ModeloptConfig QuantizeConfig
-
quantize模式的默认配置。显示默认配置为JSON
- 默认配置 (JSON):
{ "quant_cfg": { "default": { "num_bits": 8, "axis": null } }, "algorithm": "max" }
- field algorithm: None | str | MaxCalibConfig | SmoothQuantCalibConfig | AWQLiteCalibConfig | AWQClipCalibConfig | AWQFullCalibConfig | RealQuantizeConfig
- field quant_cfg: Dict[str | Callable, QuantizerAttributeConfig | List[QuantizerAttributeConfig] | Dict[str | Callable, QuantizerAttributeConfig | List[QuantizerAttributeConfig]]]
- ModeloptConfig QuantizerAttributeConfig
-
量化器属性类型。
Show default config as JSON
- Default config (JSON):
{ "enable": true, "num_bits": 8, "axis": null, "fake_quant": true, "unsigned": false, "narrow_range": false, "learn_amax": false, "type": "static", "block_sizes": null, "trt_high_precision_dtype": "Float", "calibrator": "max" }
- field axis: int | Tuple[int, ...] | None
显示详情
指定的轴/轴将有自己的amax用于计算缩放因子。如果为None(默认值),则使用每个张量的比例。必须在[-rank(input_tensor), rank(input_tensor))范围内。例如,对于KCRS权重张量,
quant_axis=(0)将产生每个通道的缩放。
- field block_sizes: Dict[int | str, int | Tuple[int, int] | str | Dict[int, int]] | None
Show details
The keys are the axes for block quantization and the values are block sizes for quantization along the respective axes. Keys must be in the range
[-tensor.dim(), tensor.dim()). Values, which are the block sizes for quantization must be positive integers.In addition, there can be special string keys
"type","scale_bits"and"scale_block_sizes".Key
"type"should map to"dynamic"or"static"where"dynamic"indicates dynamic block quantization and “static” indicates static calibrated block quantization. By default, the type is"static".Key
"scale_bits"specify the quantization bits for the per-block quantization scale factor (i.e a double quantization scheme).Key
"scale_block_sizes"specify the block size for double quantization. By default per-block quantization scale is not quantized.For example,
block_sizes = {-1: 32}will quantize the last axis of the input tensor in blocks of size 32 with static calibration andblock_sizes = {-1: 32, "type": "dynamic"}will perform dynamic block quantization. If None, block quantization is not performed.axismust be None whenblock_sizesis not None.
- field calibrator: str | Callable | Tuple
显示详情
校准器可以是来自
["max", "histogram"]的字符串,或者是创建继承自_Calibrator的校准器的构造函数。 有关如何指定构造函数的更多信息,请参见standardize_constructor_args。
- field enable: bool
显示详情
如果为True,启用量化器。如果为False,绕过量化器并返回输入张量。
- field fake_quant: bool
显示详情
如果为True,启用伪量化。
- field learn_amax: bool
显示详情
如果为True,启用学习amax。
- field narrow_range: bool
显示详情
如果为True,启用窄范围量化。仅用于整数量化。
- field num_bits: int | Tuple[int, int]
显示详情
num_bits 可以是:
- 用于整数量化的正整数参数。num_bits 指定
用于整数量化的位数。
- 用于浮点量化的常量整数元组 (E,M),模拟
Nvidia 的 FPx 量化。E 是指数位数,M 是尾数位数。支持的 FPx 量化格式:FP8 (E4M3)。
- field trt_high_precision_dtype: str
显示详情
该值是一个来自
["Float", "Half", "BFloat16"]的字符串。 QDQs 将被分配适当的数据类型,此变量仅在用户导出量化 ONNX 模型时使用。- Constraints:
pattern = ^Float$|^Half$|^BFloat16$
- field type: str
显示详情
该值是一个来自
["static", "dynamic"]的字符串。 如果为"dynamic",将启用动态量化,在校准期间不会收集任何统计信息。- Constraints:
pattern = ^static$|^dynamic$
- field unsigned: bool
显示详情
如果为True,启用无符号量化。仅用于整数量化。
- ModeloptConfig RealQuantizeConfig
-
真实量化配置的配置。
additional_algorithm将在将权重量化为低精度之前用于校准。显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max", "additional_algorithm": "" }
- field additional_algorithm: AWQLiteCalibConfig | AWQClipCalibConfig | AWQFullCalibConfig | None
显示详情
用于校准的算法。支持的算法包括
"awq_lite", "awq_full", 和 "awq_clip"。
- ModeloptConfig SmoothQuantCalibConfig
-
smoothquant算法的配置 (SmoothQuant)。SmoothQuant应用了一个平滑因子,该因子平衡了权重和激活中的异常值比例。 有关更多详细信息,请参阅SmoothQuant论文。
显示默认配置为JSON
- 默认配置 (JSON):
{ "method": "max", "alpha": 1.0 }
- field alpha: float | None
显示详情
此超参数控制迁移强度。迁移强度在[0, 1]范围内,值越大,将更多的量化难度迁移到权重上。
- Constraints:
ge = 0.0
le = 1.0