|
| 1 | +# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# ============================================================================== |
| 15 | +import os |
| 16 | +import unittest |
| 17 | +import torch |
| 18 | +from mct_quantizers import get_ort_session_options |
| 19 | +import onnxruntime as ort |
| 20 | + |
| 21 | +from mct_quantizers import PytorchActivationQuantizationHolder |
| 22 | +from mct_quantizers.pytorch.quantizers import ActivationPOTInferableQuantizer, ActivationSymmetricInferableQuantizer, \ |
| 23 | + ActivationUniformInferableQuantizer, ActivationLutPOTInferableQuantizer |
| 24 | + |
| 25 | +LAYER2NAME = {torch.nn.ReLU: 'relu', |
| 26 | + torch.nn.LeakyReLU: 'leaky_relu', |
| 27 | + torch.add: 'add', |
| 28 | + torch.nn.SiLU: 'swish', |
| 29 | + torch.mul: 'mul'} |
| 30 | + |
| 31 | +QUANTIZER2NAME = {ActivationPOTInferableQuantizer: 'pot', |
| 32 | + ActivationSymmetricInferableQuantizer: 'sym', |
| 33 | + ActivationUniformInferableQuantizer: 'unf', |
| 34 | + ActivationLutPOTInferableQuantizer: 'pot_lut'} |
| 35 | + |
| 36 | +QUANTIZER2ARGS = {**dict.fromkeys([ActivationPOTInferableQuantizer, ActivationSymmetricInferableQuantizer], |
| 37 | + {'num_bits': 4, |
| 38 | + 'threshold': [0.5], |
| 39 | + 'signed': True |
| 40 | + }), |
| 41 | + ActivationUniformInferableQuantizer: |
| 42 | + {'num_bits': 4, |
| 43 | + 'min_range': [-2.0], |
| 44 | + 'max_range': [3.0] |
| 45 | + }, |
| 46 | + ActivationLutPOTInferableQuantizer: |
| 47 | + {'num_bits': 4, |
| 48 | + 'threshold': [0.5], |
| 49 | + 'signed': True, |
| 50 | + 'lut_values': [22.0, -53.0, 62.0, 0.0, -66.0, -21.0, 44.0, -40.0], |
| 51 | + 'lut_values_bitwidth': 8, |
| 52 | + 'eps': 1e-8 |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | +def _build_model_with_quantization_holder(act_layer, quant_activation_holder, input_shape, model_name): |
| 57 | + class Model(torch.nn.Module): |
| 58 | + def __init__(self): |
| 59 | + super(Model, self).__init__() |
| 60 | + self.conv = torch.nn.Conv2d(in_channels=3, out_channels=3, kernel_size=4) |
| 61 | + self.act_layer = act_layer |
| 62 | + self.quant_activation_holder = quant_activation_holder |
| 63 | + |
| 64 | + def forward(self, inp): |
| 65 | + z = self.conv(inp) |
| 66 | + y = self.act_layer(z) |
| 67 | + x = self.quant_activation_holder(y) |
| 68 | + return x, y |
| 69 | + |
| 70 | + return Model() |
| 71 | + |
| 72 | + |
| 73 | +def _build_model_with_operator_quantization_holder(act_layer, quant_activation_holder, input_shape, model_name): |
| 74 | + class Model(torch.nn.Module): |
| 75 | + def __init__(self): |
| 76 | + super(Model, self).__init__() |
| 77 | + self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=3, kernel_size=4) |
| 78 | + self.conv2 = torch.nn.Conv2d(in_channels=3, out_channels=3, kernel_size=4) |
| 79 | + self.act_layer = act_layer |
| 80 | + self.quant_activation_holder = quant_activation_holder |
| 81 | + |
| 82 | + def forward(self, inp): |
| 83 | + z1 = self.conv1(inp) |
| 84 | + z2 = self.conv2(inp) |
| 85 | + y = self.act_layer(z1,z2) |
| 86 | + x = self.quant_activation_holder(y) |
| 87 | + return x, y |
| 88 | + |
| 89 | + return Model() |
| 90 | + |
| 91 | +class BaseActivationQuantizerBuildAndSaveTest(unittest.TestCase): |
| 92 | + device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") |
| 93 | + VERSION = None |
| 94 | + |
| 95 | + def build_and_save_model(self, quantizer, quantizer_params, layer, model_name, input_shape, is_op=False): |
| 96 | + assert BaseActivationQuantizerBuildAndSaveTest.VERSION is not None |
| 97 | + act_quantizer = quantizer(**quantizer_params) |
| 98 | + act_quantizer.enable_custom_impl() |
| 99 | + |
| 100 | + quant_act_holder = PytorchActivationQuantizationHolder(activation_holder_quantizer=act_quantizer) |
| 101 | + |
| 102 | + |
| 103 | + if is_op: |
| 104 | + model = _build_model_with_operator_quantization_holder(act_layer=layer, |
| 105 | + quant_activation_holder=quant_act_holder, |
| 106 | + input_shape=input_shape, |
| 107 | + model_name=model_name) |
| 108 | + else: |
| 109 | + model = _build_model_with_quantization_holder(act_layer=layer, |
| 110 | + quant_activation_holder=quant_act_holder, |
| 111 | + input_shape=input_shape, |
| 112 | + model_name=model_name) |
| 113 | + |
| 114 | + |
| 115 | + quant_holder_layer = [_l for _, _l in model.named_modules() if isinstance(_l, PytorchActivationQuantizationHolder)] |
| 116 | + self.assertEqual(len(quant_holder_layer), 1) |
| 117 | + |
| 118 | + rand_inp = torch.rand(1, *input_shape).to(BaseActivationQuantizerBuildAndSaveTest.device) |
| 119 | + model = model.to(BaseActivationQuantizerBuildAndSaveTest.device) |
| 120 | + |
| 121 | + # Verifying activation quantization after holder |
| 122 | + output = model(rand_inp) |
| 123 | + self.assertTrue(torch.any(output[0] != output[1]), "Expecting activation layer output to be different " |
| 124 | + "from the activation holder layer output, which should be " |
| 125 | + "quantized.") |
| 126 | + |
| 127 | + file_path = f'{model_name}.onnx' |
| 128 | + torch.onnx.export(model, |
| 129 | + rand_inp, |
| 130 | + file_path, |
| 131 | + opset_version=16, |
| 132 | + verbose=False, |
| 133 | + input_names=['input'], |
| 134 | + output_names=['output'], |
| 135 | + dynamic_axes={'input': {0: 'batch_size'}, |
| 136 | + 'output': {0: 'batch_size'}}) |
| 137 | + |
| 138 | + def activation_test(self, quantizer, layer, is_op=False, layer_type=None): |
| 139 | + self.build_and_save_model(quantizer=quantizer, |
| 140 | + quantizer_params=QUANTIZER2ARGS[quantizer], |
| 141 | + layer=layer(), |
| 142 | + model_name=f"{BaseActivationQuantizerBuildAndSaveTest.VERSION}_" |
| 143 | + f"{LAYER2NAME[layer_type if layer_type is not None else layer]}_" |
| 144 | + f"{QUANTIZER2NAME[quantizer]}", |
| 145 | + input_shape=(3, 8, 8), |
| 146 | + is_op=is_op) |
| 147 | + |
| 148 | + |
| 149 | +class BaseActivationQuantizerLoadAndCompareTest(unittest.TestCase): |
| 150 | + SAVED_VERSION = None |
| 151 | + |
| 152 | + def load_and_compare_model(self, quantizer_type, layer_type): |
| 153 | + assert BaseActivationQuantizerLoadAndCompareTest.SAVED_VERSION is not None |
| 154 | + |
| 155 | + model_path = (f"{BaseActivationQuantizerLoadAndCompareTest.SAVED_VERSION}_" |
| 156 | + f"{LAYER2NAME[layer_type]}_" |
| 157 | + f"{QUANTIZER2NAME[quantizer_type]}.onnx") |
| 158 | + |
| 159 | + ort.InferenceSession(model_path, |
| 160 | + get_ort_session_options(), |
| 161 | + providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) |
| 162 | + |
| 163 | + self._check_quantizer_init_from_onnx_model(model_path) |
| 164 | + os.remove(model_path) |
| 165 | + |
| 166 | + def _check_quantizer_init_from_onnx_model(self, filepath): |
| 167 | + raise NotImplemented |
| 168 | + |
| 169 | + def activation_test(self, quantizer_type, layer): |
| 170 | + self.load_and_compare_model(quantizer_type=quantizer_type, |
| 171 | + layer_type=layer) |
| 172 | + |
0 commit comments