• Tutorials >
  • (prototype) PyTorch BackendConfig Tutorial
Shortcuts

(原型) PyTorch BackendConfig 教程

创建于:2023年1月3日 | 最后更新:2023年1月18日 | 最后验证:未验证

作者: Andrew Or

BackendConfig API 使开发者能够将他们的后端与 PyTorch 量化集成。目前仅支持 FX 图模式量化,但未来可能会扩展到其他量化模式。在本教程中,我们将演示如何使用此 API 为特定后端自定义量化支持。有关 BackendConfig 背后的动机和实现细节的更多信息,请参阅此 README

假设我们是一个后端开发者,我们希望将我们的后端与PyTorch的量化API集成。我们的后端仅包含两个操作:量化线性和量化卷积-relu。在本节中,我们将通过使用自定义的BackendConfig,通过prepare_fxconvert_fx来量化一个示例模型,来了解如何实现这一点。

import torch
from torch.ao.quantization import (
    default_weight_observer,
    get_default_qconfig_mapping,
    MinMaxObserver,
    QConfig,
    QConfigMapping,
)
from torch.ao.quantization.backend_config import (
    BackendConfig,
    BackendPatternConfig,
    DTypeConfig,
    DTypeWithConstraints,
    ObservationType,
)
from torch.ao.quantization.quantize_fx import prepare_fx, convert_fx

1. 为每个量化操作符推导参考模式

对于量化线性,假设我们的后端期望参考模式 [dequant - fp32_linear - quant] 并将其降低为单个量化 线性操作。实现这一点的方法是首先在浮点线性操作之前和之后插入量化-反量化操作, 这样我们就可以生成以下参考模型:

quant1 - [dequant1 - fp32_linear - quant2] - dequant2

同样地,对于量化的conv-relu,我们希望生成以下参考模型,其中方括号中的参考模式将被降低为单个量化的conv-relu操作:

quant1 - [dequant1 - fp32_conv_relu - quant2] - dequant2

2. 设置带有后端约束的DTypeConfigs

在上述参考模式中,DTypeConfig中指定的输入dtype将作为dtype参数传递给quant1,而输出dtype将作为dtype参数传递给quant2。如果输出dtype是fp32,就像动态量化的情况一样,那么输出的量化-反量化对将不会被插入。这个例子还展示了如何对特定dtype的量化范围和比例范围进行限制。

quint8_with_constraints = DTypeWithConstraints(
    dtype=torch.quint8,
    quant_min_lower_bound=0,
    quant_max_upper_bound=255,
    scale_min_lower_bound=2 ** -12,
)

# Specify the dtypes passed to the quantized ops in the reference model spec
weighted_int8_dtype_config = DTypeConfig(
    input_dtype=quint8_with_constraints,
    output_dtype=quint8_with_constraints,
    weight_dtype=torch.qint8,
    bias_dtype=torch.float)

3. 设置融合用于conv-relu

请注意,原始用户模型包含独立的卷积和ReLU操作, 因此我们需要首先将卷积和ReLU操作融合成一个单一的卷积-ReLU 操作(fp32_conv_relu),然后像量化线性操作一样量化这个操作。我们可以通过定义一个接受 3个参数的函数来设置融合,其中第一个参数是这是否用于QAT,而 其余参数指的是融合模式的各个项目。

def fuse_conv2d_relu(is_qat, conv, relu):
    """Return a fused ConvReLU2d from individual conv and relu modules."""
    return torch.ao.nn.intrinsic.ConvReLU2d(conv, relu)

4. 定义BackendConfig

现在我们有了所有必要的部分,因此我们继续定义我们的BackendConfig。在这里,我们为线性操作的输入和输出使用了不同的观察者(将重命名),因此传递给两个量化操作(quant1和quant2)的量化参数将不同。这对于像线性和卷积这样的加权操作来说是很常见的。

对于conv-relu操作,观察类型是相同的。然而,我们需要两个BackendPatternConfigs来支持这个操作,一个用于融合,一个用于量化。对于conv-relu和linear,我们使用上面定义的DTypeConfig。

linear_config = BackendPatternConfig() \
    .set_pattern(torch.nn.Linear) \
    .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
    .add_dtype_config(weighted_int8_dtype_config) \
    .set_root_module(torch.nn.Linear) \
    .set_qat_module(torch.nn.qat.Linear) \
    .set_reference_quantized_module(torch.ao.nn.quantized.reference.Linear)

# For fusing Conv2d + ReLU into ConvReLU2d
# No need to set observation type and dtype config here, since we are not
# inserting quant-dequant ops in this step yet
conv_relu_config = BackendPatternConfig() \
    .set_pattern((torch.nn.Conv2d, torch.nn.ReLU)) \
    .set_fused_module(torch.ao.nn.intrinsic.ConvReLU2d) \
    .set_fuser_method(fuse_conv2d_relu)

# For quantizing ConvReLU2d
fused_conv_relu_config = BackendPatternConfig() \
    .set_pattern(torch.ao.nn.intrinsic.ConvReLU2d) \
    .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
    .add_dtype_config(weighted_int8_dtype_config) \
    .set_root_module(torch.nn.Conv2d) \
    .set_qat_module(torch.ao.nn.intrinsic.qat.ConvReLU2d) \
    .set_reference_quantized_module(torch.ao.nn.quantized.reference.Conv2d)

backend_config = BackendConfig("my_backend") \
    .set_backend_pattern_config(linear_config) \
    .set_backend_pattern_config(conv_relu_config) \
    .set_backend_pattern_config(fused_conv_relu_config)

5. 设置满足后端约束的QConfigMapping

为了使用上面定义的操作,用户必须定义一个满足DTypeConfig中指定约束的QConfig。更多详情,请参阅DTypeConfig的文档。然后,我们将使用这个QConfig来配置我们希望量化的模式中使用的所有模块。

# Note: Here we use a quant_max of 127, but this could be up to 255 (see `quint8_with_constraints`)
activation_observer = MinMaxObserver.with_args(quant_min=0, quant_max=127, eps=2 ** -12)
qconfig = QConfig(activation=activation_observer, weight=default_weight_observer)

# Note: All individual items of a fused pattern, e.g. Conv2d and ReLU in
# (Conv2d, ReLU), must have the same QConfig
qconfig_mapping = QConfigMapping() \
    .set_object_type(torch.nn.Linear, qconfig) \
    .set_object_type(torch.nn.Conv2d, qconfig) \
    .set_object_type(torch.nn.BatchNorm2d, qconfig) \
    .set_object_type(torch.nn.ReLU, qconfig)

6. 通过准备和转换量化模型

最后,我们通过将定义的BackendConfig传递到prepare和convert中来量化模型。这将生成一个量化线性模块和一个融合的量化conv-relu模块。

class MyModel(torch.nn.Module):
    def __init__(self, use_bn: bool):
        super().__init__()
        self.linear = torch.nn.Linear(10, 3)
        self.conv = torch.nn.Conv2d(3, 3, 3)
        self.bn = torch.nn.BatchNorm2d(3)
        self.relu = torch.nn.ReLU()
        self.sigmoid = torch.nn.Sigmoid()
        self.use_bn = use_bn

    def forward(self, x):
        x = self.linear(x)
        x = self.conv(x)
        if self.use_bn:
            x = self.bn(x)
        x = self.relu(x)
        x = self.sigmoid(x)
        return x

example_inputs = (torch.rand(1, 3, 10, 10, dtype=torch.float),)
model = MyModel(use_bn=False)
prepared = prepare_fx(model, qconfig_mapping, example_inputs, backend_config=backend_config)
prepared(*example_inputs)  # calibrate
converted = convert_fx(prepared, backend_config=backend_config)
>>> print(converted)

GraphModule(
  (linear): QuantizedLinear(in_features=10, out_features=3, scale=0.012136868201196194, zero_point=67, qscheme=torch.per_tensor_affine)
  (conv): QuantizedConvReLU2d(3, 3, kernel_size=(3, 3), stride=(1, 1), scale=0.0029353597201406956, zero_point=0)
  (sigmoid): Sigmoid()
)

def forward(self, x):
    linear_input_scale_0 = self.linear_input_scale_0
    linear_input_zero_point_0 = self.linear_input_zero_point_0
    quantize_per_tensor = torch.quantize_per_tensor(x, linear_input_scale_0, linear_input_zero_point_0, torch.quint8);  x = linear_input_scale_0 = linear_input_zero_point_0 = None
    linear = self.linear(quantize_per_tensor);  quantize_per_tensor = None
    conv = self.conv(linear);  linear = None
    dequantize_2 = conv.dequantize();  conv = None
    sigmoid = self.sigmoid(dequantize_2);  dequantize_2 = None
    return sigmoid

(7. 实验错误的BackendConfig设置)

作为实验,这里我们修改模型以使用conv-bn-relu 而不是conv-relu,但使用相同的BackendConfig,它不知道 如何量化conv-bn-relu。因此,只有线性部分被 量化,但conv-bn-relu既没有融合也没有量化。

>>> print(converted)

GraphModule(
  (linear): QuantizedLinear(in_features=10, out_features=3, scale=0.015307803638279438, zero_point=95, qscheme=torch.per_tensor_affine)
  (conv): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
  (bn): BatchNorm2d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (relu): ReLU()
  (sigmoid): Sigmoid()
)

def forward(self, x):
    linear_input_scale_0 = self.linear_input_scale_0
    linear_input_zero_point_0 = self.linear_input_zero_point_0
    quantize_per_tensor = torch.quantize_per_tensor(x, linear_input_scale_0, linear_input_zero_point_0, torch.quint8);  x = linear_input_scale_0 = linear_input_zero_point_0 = None
    linear = self.linear(quantize_per_tensor);  quantize_per_tensor = None
    dequantize_1 = linear.dequantize();  linear = None
    conv = self.conv(dequantize_1);  dequantize_1 = None
    bn = self.bn(conv);  conv = None
    relu = self.relu(bn);  bn = None
    sigmoid = self.sigmoid(relu);  relu = None
    return sigmoid

作为另一个实验,这里我们使用默认的QConfigMapping,它不满足后端指定的dtype约束。因此,由于QConfigs被简单地忽略了,所以没有任何量化操作。

>>> print(converted)

GraphModule(
  (linear): Linear(in_features=10, out_features=3, bias=True)
  (conv): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
  (bn): BatchNorm2d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (relu): ReLU()
  (sigmoid): Sigmoid()
)

def forward(self, x):
    linear = self.linear(x);  x = None
    conv = self.conv(linear);  linear = None
    bn = self.bn(conv);  conv = None
    relu = self.relu(bn);  bn = None
    sigmoid = self.sigmoid(relu);  relu = None
    return sigmoid

内置的BackendConfigs

PyTorch量化支持在torch.ao.quantization.backend_config命名空间下的几个内置原生BackendConfigs:

目前还有其他正在开发中的BackendConfigs(例如用于TensorRT和x86的),但这些目前大多仍处于实验阶段。如果用户希望将一个新的自定义后端与PyTorch的量化API集成,他们可以使用与上述示例中定义原生支持的BackendConfigs相同的API集来定义自己的BackendConfigs。

优云智算