|
| 1 | +# Copyright 2025 NXP |
| 2 | +# |
| 3 | +# This source code is licensed under the BSD-style license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +import unittest |
| 7 | + |
| 8 | +import kgb |
| 9 | +import numpy as np |
| 10 | +import torch |
| 11 | + |
| 12 | +from executorch.backends.nxp.backend.edge_program_converter import ( |
| 13 | + EdgeProgramToIRConverter, |
| 14 | +) |
| 15 | +from executorch.backends.nxp.quantizer.neutron_quantizer import ( |
| 16 | + act_qspec, |
| 17 | + NeutronAtenQuantizer, |
| 18 | + wgt_qspec, |
| 19 | +) |
| 20 | +from executorch.backends.nxp.quantizer.patterns import ( |
| 21 | + NodeArgsIdx, |
| 22 | + PartitionAnchors, |
| 23 | + QuantizationPattern, |
| 24 | +) |
| 25 | +from executorch.backends.nxp.quantizer.utils import get_bias_qparams |
| 26 | +from executorch.backends.nxp.tests.executorch_pipeline import to_quantized_edge_program |
| 27 | +from executorch.backends.nxp.tests.executors import ( |
| 28 | + convert_run_compare, |
| 29 | + ToChannelFirstPreprocess, |
| 30 | + ToChannelLastPreprocess, |
| 31 | +) |
| 32 | +from executorch.backends.nxp.tests.models import Conv2dModule |
| 33 | +from executorch.backends.nxp.tests.test_quantizer import _get_target_name |
| 34 | + |
| 35 | +from torch import fx |
| 36 | +from torch._ops import OpOverload |
| 37 | +from torch.export import ExportedProgram |
| 38 | +from torchao.quantization.pt2e import MinMaxObserver, PerChannelMinMaxObserver |
| 39 | +from torchao.quantization.pt2e.quantizer import ( |
| 40 | + DerivedQuantizationSpec, |
| 41 | + QuantizationConfig, |
| 42 | + QuantizationSpec, |
| 43 | +) |
| 44 | + |
| 45 | + |
| 46 | +class Conv2dPatternPerChannel(QuantizationPattern): |
| 47 | + |
| 48 | + def __init__(self, is_per_channel: bool): |
| 49 | + super().__init__() |
| 50 | + self.is_per_channel = is_per_channel |
| 51 | + |
| 52 | + def partition_types(self) -> list[OpOverload]: |
| 53 | + return [torch.ops.aten.conv2d.default] |
| 54 | + |
| 55 | + def get_anchors( |
| 56 | + self, gm: fx.GraphModule, fused_partition: list[fx.GraphModule] |
| 57 | + ) -> PartitionAnchors: |
| 58 | + conv2d_node = fused_partition[0].nodes[-1] |
| 59 | + |
| 60 | + bias_qscheme = ( |
| 61 | + torch.per_channel_symmetric |
| 62 | + if self.is_per_channel |
| 63 | + else torch.per_tensor_symmetric |
| 64 | + ) |
| 65 | + bias_quantization_qspec = DerivedQuantizationSpec( |
| 66 | + derived_from=[ |
| 67 | + (conv2d_node.args[0], conv2d_node), |
| 68 | + (conv2d_node.args[1], conv2d_node), |
| 69 | + ], |
| 70 | + derive_qparams_fn=get_bias_qparams, |
| 71 | + dtype=torch.int32, |
| 72 | + quant_min=-(2**31) + 1, |
| 73 | + quant_max=2**31 - 1, |
| 74 | + qscheme=bias_qscheme, |
| 75 | + ch_axis=0, |
| 76 | + ) |
| 77 | + |
| 78 | + weight_qscheme = ( |
| 79 | + torch.per_channel_symmetric |
| 80 | + if self.is_per_channel |
| 81 | + else torch.per_tensor_symmetric |
| 82 | + ) |
| 83 | + weight_observer_or_fake_quant_ctr = ( |
| 84 | + PerChannelMinMaxObserver if self.is_per_channel else MinMaxObserver |
| 85 | + ) |
| 86 | + weight_quantization_spec = QuantizationSpec( |
| 87 | + dtype=torch.int8, |
| 88 | + observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr, |
| 89 | + quant_min=-127, |
| 90 | + quant_max=127, |
| 91 | + qscheme=weight_qscheme, |
| 92 | + ch_axis=0, |
| 93 | + ) |
| 94 | + |
| 95 | + return PartitionAnchors( |
| 96 | + inputs=[(conv2d_node, NodeArgsIdx(0))], |
| 97 | + weights=[(conv2d_node, NodeArgsIdx(1), weight_quantization_spec)], |
| 98 | + biases=[(conv2d_node, NodeArgsIdx(2), bias_quantization_qspec)], |
| 99 | + output=[(conv2d_node,)], |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | +class TestPerChannelConversion(unittest.TestCase): |
| 104 | + __test__ = False # Prevent interfering with PyTest tests |
| 105 | + |
| 106 | + def test_per_channel_convolution(self): |
| 107 | + with kgb.spy_on( |
| 108 | + EdgeProgramToIRConverter.convert_program, call_original=True |
| 109 | + ) as converter_spy: |
| 110 | + model = Conv2dModule( |
| 111 | + in_channels=8, out_channels=32, kernel_size=5, padding=3 |
| 112 | + ) |
| 113 | + input_shape = (1, 8, 32, 32) |
| 114 | + |
| 115 | + static_qconfig = QuantizationConfig(act_qspec, act_qspec, wgt_qspec, None) |
| 116 | + _ = to_quantized_edge_program( |
| 117 | + model, |
| 118 | + input_shape, |
| 119 | + get_quantizer_fn=lambda: NeutronAtenQuantizer( |
| 120 | + Conv2dPatternPerChannel(is_per_channel=True), static_qconfig |
| 121 | + ), |
| 122 | + ) |
| 123 | + |
| 124 | + tflite_flatbuffers_model, io_formats = converter_spy.calls[-1].return_value |
| 125 | + exported_program: ExportedProgram = converter_spy.calls[-1].args[0] |
| 126 | + |
| 127 | + input_data = (np.random.random(input_shape).astype(np.float32) * 50).astype( |
| 128 | + np.int8 |
| 129 | + ) |
| 130 | + |
| 131 | + convert_run_compare( |
| 132 | + exported_program, |
| 133 | + tflite_input_preprocess=ToChannelLastPreprocess(), |
| 134 | + tfl_model=tflite_flatbuffers_model, |
| 135 | + tflite_output_preprocess=ToChannelFirstPreprocess(), |
| 136 | + input_data=input_data, |
| 137 | + atol=1.0, |
| 138 | + ) |
| 139 | + |
| 140 | + nodes = list(exported_program.graph.nodes) |
| 141 | + |
| 142 | + assert _get_target_name(nodes[8]).endswith( |
| 143 | + "quantized_decomposed.dequantize_per_channel.default" |
| 144 | + ) |
| 145 | + assert _get_target_name(nodes[9]).endswith( |
| 146 | + "quantized_decomposed.dequantize_per_channel.default" |
| 147 | + ) |
| 148 | + assert nodes[10].name == "aten_convolution_default" |
| 149 | + |
| 150 | + @classmethod |
| 151 | + def setUpClass(cls): |
| 152 | + torch.manual_seed(25) |
| 153 | + np.random.seed(25) |
0 commit comments