如何为 PyTorch 2 导出量化编写 Quantizer
¶
作者: Leslie Fang, Weiwen Xia, Jiong Gong, Kimish Patel, Jerry Zhang
先决条件:¶
必需
可选
介绍¶
(原型) PyTorch 2 导出训练后量化 介绍了 PyTorch 2 导出量化的整体 API。与 FX 图模式量化在 API 上的主要区别在于,我们明确了量化是针对特定后端的。因此,要使用新的流程,后端需要实现一个 Quantizer
类,该类编码了:(1) 后端支持的量化算子或模式;(2) 用户可以如何表达他们希望浮点模型被量化的方式,例如,将整个模型量化为 int8 对称量化,或仅量化线性层等。
有关新 API 和 Quantizer
的动机,请参阅此处。
XNNPACK
的现有量化器对象在 XNNPackQuantizer 中
注解 API¶
Quantizer
使用注解 API 来传达不同算子/模式的量化意图。注解 API 主要由 QuantizationSpec 和 QuantizationAnnotation 组成。
QuantizationSpec
用于传达张量如何被量化的意图,例如,数据类型、位宽、最小值、最大值、对称与否等。此外,QuantizationSpec
还允许量化器指定如何观察张量值,例如,MinMaxObserver
、HistogramObserver
或一些自定义观察器。
QuantizationAnnotation
由 QuantizationSpec
对象组成,用于注解模式的输入张量和输出张量。注解输入张量等同于注解输入边,而注解输出张量等同于注解节点。QuantizationAnnotation
是一个 dataclass
,包含几个字段:
input_qspec_map
字段是Dict
类,用于将每个输入张量(作为输入边)映射到QuantizationSpec
。output_qspec
字段表示用于注解输出张量的QuantizationSpec
;_annotated
字段指示该节点是否已被量化器注解。
总而言之,注解 API 要求量化器注解图的边(输入张量)或节点(输出张量)。现在,我们将逐步介绍如何使用具有不同类型 QuantizationSpec
的注解 API。
1. 注解常见算子模式¶
为了使用量化模式/算子,例如 quantized add
,后端开发者会有量化(由 QuantizationSpec
表达)输入和模式输出的意图。以下是一个示例流程(以 add
算子为例),说明此意图如何在量化工作流中使用注解 API 传达。
步骤 1:在 FX 图中识别原始浮点模式。识别此模式有几种方法:量化器可以使用模式匹配器来匹配算子模式;量化器可以从头到尾遍历节点,并将节点的 target 类型与算子模式进行匹配。在此示例中,我们可以使用 get_source_partitions 来匹配此模式。原始浮点
add
模式仅包含一个add
节点。
add_partitions = get_source_partitions(gm.graph, [operator.add, torch.add])
add_partitions = list(itertools.chain(*add_partitions.values()))
for add_partition in add_partitions:
add_node = add_partition.output_nodes[0]
步骤 2:为模式的输入和输出定义
QuantizationSpec
。QuantizationSpec
定义了用户关于如何观察或假量化张量的意图的数据类型
、qscheme
和其他量化参数。
act_quantization_spec = QuantizationSpec(
dtype=torch.int8,
quant_min=-128,
quant_max=127,
qscheme=torch.per_tensor_affine,
is_dynamic=False,
observer_or_fake_quant_ctr=HistogramObserver.with_args(eps=2**-12),
)
input_act_qspec = act_quantization_spec
output_act_qspec = act_quantization_spec
步骤 3:使用
QuantizationAnnotation
注解模式的输入和输出。在此示例中,我们将为add
节点(两个输入和一个输出)创建带有上面步骤 2 中创建的QuantizationSpec
的QuantizationAnnotation
对象。
input_qspec_map = {}
input_act0 = add_node.args[0]
input_qspec_map[input_act0] = input_act_qspec
input_act1 = add_node.args[1]
input_qspec_map[input_act1] = input_act_qspec
add_node.meta["quantization_annotation"] = QuantizationAnnotation(
input_qspec_map=input_qspec_map,
output_qspec=output_act_qspec,
_annotated=True,
)
在这样注解了 add
节点后,在后续的量化流程中,HistogramObserver
将在准备阶段插入到其两个输入节点和一个输出节点。在转换阶段,HistogramObserver
将被 quantize
节点和 dequantize
节点替换。
3. 注解具有固定量化参数的算子¶
另一种典型的注解量化模型用例是针对量化参数预先已知的张量。例如,像 sigmoid
这样的算子,其输入和输出张量具有预定义且固定的 scale/zero_point。 FixedQParamsQuantizationSpec 就是为这种情况设计的。要使用 FixedQParamsQuantizationSpec
,用户需要显式传入 scale
和 zero_point
参数。
步骤 1:在 FX 图中识别原始浮点模式。我们可以使用在
QuantizationSpec
示例中介绍的相同方法来识别sigmoid
模式。步骤 2:使用固定的
scale
、zero_point
值创建FixedQParamsQuantizationSpec
对象。这些值将用于在转换阶段创建quantize
节点和dequantize
节点。步骤 3:注解输入和输出以使用此
FixedQParamsQuantizationSpec
对象。
act_qspec = FixedQParamsQuantizationSpec(
dtype=torch.uint8,
quant_min=0,
quant_max=255,
qscheme=torch.per_tensor_affine,
scale=1.0 / 256.0,
zero_point=0,
)
sigmoid_node.meta["quantization_annotation"] = QuantizationAnnotation(
input_qspec_map={input_act: act_qspec},
output_qspec=act_qspec,
_annotated=True,
)
4. 注解具有派生量化参数的张量¶
另一个用例是为量化参数从其他张量派生的张量定义约束。例如,如果我们想注解一个卷积节点,并将激活张量的 scale
和权重张量的 scale
相乘来定义其偏置输入张量的 scale
。我们可以使用 DerivedQuantizationSpec 来注解这个 conv 节点。
步骤 1:在 FX 图中识别原始浮点模式。我们可以使用在
QuantizationSpec
示例中介绍的相同方法来识别convolution
模式。步骤 2:定义
derive_qparams_fn
函数,它接受ObserverOrFakeQuantize
(ObserverBase 或 FakeQuantizeBase)的列表作为输入。从每个ObserverOrFakeQuantize
对象中,用户可以获取scale
、zero point
值。用户可以定义其启发式方法,根据从观察器或假量化实例计算出的量化参数来派生新的scale
、zero point
值。步骤 3:定义
DerivedQuantizationSpec
对象,它接受以下输入:EdgeOrNode
对象的列表。与每个EdgeOrNode
对象对应的观察器将传递给derive_qparams_fn
函数;derive_qparams_fn
函数;其他几个量化参数,如dtype
、qscheme
。步骤 4:使用
QuantizationAnnotation
注解此 conv 节点的输入和输出。
def derive_qparams_fn(obs_or_fqs: List[ObserverOrFakeQuantize]) -> Tuple[Tensor, Tensor]:
assert len(obs_or_fqs) == 2, \
"Expecting two obs/fqs, one for activation and one for weight, got: {}".format(len(obs_or_fq))
act_obs_or_fq = obs_or_fqs[0]
weight_obs_or_fq = obs_or_fqs[1]
act_scale, act_zp = act_obs_or_fq.calculate_qparams()
weight_scale, weight_zp = weight_obs_or_fq.calculate_qparams()
return torch.tensor([act_scale * weight_scale]).to(torch.float32), torch.tensor([0]).to(torch.int32)
bias_qspec = DerivedQuantizationSpec(
derived_from=[(input_act, node), (weight, node)],
derive_qparams_fn=derive_qparams_fn,
dtype=torch.int32,
quant_min=-2**31,
quant_max=2**31 - 1,
qscheme=torch.per_tensor_symmetric,
)
input_qspec_map = {input_act: act_quantization_spec, weight: weight_quantization_spec, bias: bias_qspec}
node.meta["quantization_annotation"] = QuantizationAnnotation(
input_qspec_map=input_qspec_map,
output_qspec=act_quantization_spec,
_annotated=True,
)
5. Resnet18 的玩具示例¶
在定义了以上使用 QuantizationAnnotation API
的注解方法后,我们现在可以将它们组合起来,构建一个 BackendQuantizer
,并运行一个使用 Torchvision Resnet18
的玩具示例。为了更好地理解最终示例,以下是示例中使用的类和实用函数:
QuantizationConfig 由激活、权重和偏置的
QuantizationSpec
分别组成。在注解模型时,可以使用 get_input_act_qspec、get_output_act_qspec、get_weight_qspec 和 get_bias_qspec 从特定模式的
QuantizationConfig
中获取QuantizationSpec
。
关于 PT2E 量化流程 IR 的说明¶
IR 指的是模型的中间表示,例如 torch
IR(torch.nn
模块,torch.nn.functional
ops)或 aten
IR(torch.ops.aten.linear
,…)。PT2E 量化流程使用预自动微分的 aten IR(torch.export API 的输出),以便我们支持训练。如前所述,我们需要匹配算子或算子模式才能在其上附加注解。那么问题是,我们如何匹配模式?
动机:直接匹配 aten
IR 的问题¶
最直接的方法可能是直接匹配 aten
IR。
示例
for n in gm.graph.nodes:
if n.op != "call_function" or n.target not in [
torch.ops.aten.relu.default,
torch.ops.aten.relu_.default,
]:
continue
relu_node = n
maybe_conv_node = n.args[0]
if (
not isinstance(maybe_conv_node, Node)
or maybe_conv_node.op != "call_function"
or maybe_conv_node.target
not in [
torch.ops.aten.conv1d.default,
torch.ops.aten.conv2d.default,
]
):
continue
# annotate conv and relu nodes
...
然而,使用此 IR 的一个问题是,如果 PyTorch 对模块或函数式操作的实现发生更改,表示形式可能会改变。但这可能是意料之外的,因为建模用户通常假设当命令式模型代码不变时,他们在程序捕获后也应该得到相同的模型表示。此问题的一个具体影响是,如果一个 Quantizer
基于识别 aten
IR 模式来进行注解,那么在 PyTorch 版本更新后,它可能无法识别该模式,并且相同的命令式浮点模型可能会保持未被量化。
建议:使用 SubgraphMatcherWithNameNodeMap
进行模式匹配¶
因此,我们建议人们通过捕获 torch
IR 模式(与捕获浮点模型使用的程序捕获相同)来通过 SubgraphMatcherWithNameNodeMap
(SubgraphMatcher
的改进版本,使其更容易查询要注解的节点)来识别模式,而不是直接使用 aten
IR 模式。
示例
def conv_relu_pattern(input, weight, bias):
conv = torch.nn.functional.conv2d(input, weight, bias)
output = torch.nn.functional.relu(conv)
# returns an additional dict that includes a map from name to node that we want to annotate
return relu, {"input": input, "weight": weight, "bias": bias, "output": output}
matcher = SubgraphMatcherWithNameNodeMap(conv_relu_pattern)
matches = matcher.match(model)
for match in matches:
# find input and output of the pattern
# annotate the nodes
name_node_map = match.name_node_map
input_node = name_node_map["input"]
weight_node = name_node_map["weight"]
bias_node = name_node_map["bias"]
output_node = name_node_map["relu"]
input_node.users[0].meta["quantization_annotation"] = ...
weight_node.users[0].meta["quantization_annotation"] = ...
bias_node.users[0].meta["quantization_annotation"] = ...
output_node.meta["quantization_annotation"] = ...
这样,即使在神经网络模块和函数式的实现发生变化时,Quantizer
仍然有效。aten
IR 对于浮点模型来说会发生变化,但由于我们重新捕获模式而不是硬编码模式的 aten
IR,我们将获得更新的 aten
IR,并且仍然能够匹配模式。
一个注意事项是,如果模式的输入有多个用户,除了检查 aten op 目标外,我们没有好方法来识别我们想要注解的哪个用户节点。
另一个注意事项是,我们需要确保有一个详尽的示例列表(例如,2D、3D、4D 输入,真实输入 vs. 符号输入,training=True vs. training=False 等)来确保覆盖从 torch
IR 模式捕获的各种可能的 aten
IR 结果。
注意:我们将来可能会提供一些(模式,示例输入列表)或一些预生成的匹配器对象,以便人们可以直接使用它们。
结论¶
通过本教程,我们介绍了 PyTorch 2 中的新量化路径。用户可以学习如何使用 QuantizationAnnotation API
定义 BackendQuantizer
并将其集成到 PyTorch 2 导出量化流程中。给出了 QuantizationSpec
、SharedQuantizationSpec
、FixedQParamsQuantizationSpec
和 DerivedQuantizationSpec
的示例,用于特定的注解用例。您可以将 XNNPACKQuantizer 作为示例来开始实现您自己的 Quantizer
。之后,请按照此教程实际量化您的模型。