|
| 1 | +# Copyright (c) 2023 PaddlePaddle Authors. 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 numpy as np |
| 16 | + |
| 17 | +import paddle |
| 18 | + |
| 19 | +from ..base_observer import BaseObserver |
| 20 | +from ..factory import ObserverFactory |
| 21 | + |
| 22 | + |
| 23 | +class GroupWiseWeightObserver(ObserverFactory): |
| 24 | + r""" |
| 25 | + It collects channel-wise maximum absolute values of target weights. |
| 26 | + Args: |
| 27 | + bit_length(int, optional): Number of bits to represent an quantized integer in binary. |
| 28 | + dtype(str, optional): The data type of input tensor. |
| 29 | + name (str, optional): This parameter is used by developers to print debugging information. \ |
| 30 | + For details, please refer to :ref:`api_guide_Name`. Default is None. |
| 31 | + Examples: |
| 32 | + .. code-block:: python |
| 33 | + from paddle.quantization import QuantConfig |
| 34 | + from paddle.quantization.quanters import AbsMaxChannelWiseWeightObserver |
| 35 | + quanter = AbsMaxChannelWiseWeightObserver() |
| 36 | + q_config = QuantConfig(activation=None, weight=quanter) |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__(self, quant_bits=8, group_size=128): |
| 40 | + super().__init__(quant_bits=quant_bits) |
| 41 | + |
| 42 | + def _get_class(self): |
| 43 | + return GroupWiseWeightObserverLayer |
| 44 | + |
| 45 | + |
| 46 | +class GroupWiseWeightObserverLayer(BaseObserver): |
| 47 | + def __init__(self, layer, quant_bits=8, group_size=128): |
| 48 | + super().__init__() |
| 49 | + self.quant_bits = quant_bits |
| 50 | + self.group_size = group_size |
| 51 | + self._layer = layer |
| 52 | + self._max = None |
| 53 | + self._scale = None |
| 54 | + self._zero_point = None |
| 55 | + |
| 56 | + def forward(self, inputs): |
| 57 | + self._max = self._cal_abs_max(inputs) |
| 58 | + return inputs |
| 59 | + |
| 60 | + def _cal_abs_max(self, inputs): |
| 61 | + """Use group_size to group the input, then use the |
| 62 | + absmax method to calculate the scale |
| 63 | + """ |
| 64 | + input_shape = inputs.shape |
| 65 | + assert ( |
| 66 | + self.group_size == 64 or self.group_size == 128 |
| 67 | + ), "group_size only support 64 or 128" |
| 68 | + assert ( |
| 69 | + inputs.shape[0] % self.group_size == 0 |
| 70 | + ), "group_size must be a factor of input channels" |
| 71 | + assert len(inputs.shape) == 2, "Currently only support 2D tensor" |
| 72 | + input_processed = inputs.transpose([1, 0]).reshape( |
| 73 | + [input_shape[1], input_shape[0] // self.group_size, self.group_size] |
| 74 | + ) |
| 75 | + |
| 76 | + abs_max_values = paddle.max(paddle.abs(input_processed), axis=2).cast( |
| 77 | + "float32" |
| 78 | + ) |
| 79 | + abs_max_values = paddle.where( |
| 80 | + abs_max_values == np.float32(0), np.float32(1e-8), abs_max_values |
| 81 | + ) |
| 82 | + abs_max_values = abs_max_values.transpose([1, 0]) |
| 83 | + return abs_max_values |
| 84 | + |
| 85 | + def min_value(self) -> float: |
| 86 | + return 0.0 |
| 87 | + |
| 88 | + def max_value(self) -> float: |
| 89 | + return self._max |
| 90 | + |
| 91 | + def bit_length(self): |
| 92 | + return self._quant_bits |
| 93 | + |
| 94 | + def quant_axis(self): |
| 95 | + return -1 |
| 96 | + |
| 97 | + def cal_thresholds(self): |
| 98 | + """Compute thresholds for MAX function.""" |
| 99 | + if self._scale is None: |
| 100 | + self._scale = self._max |
| 101 | + self._zero_point = paddle.zeros_like(self._scale) |
| 102 | + |
| 103 | + def scales(self): |
| 104 | + """Return output scales.""" |
| 105 | + if self._scale is None: |
| 106 | + self.cal_thresholds() |
| 107 | + return self._scale |
| 108 | + |
| 109 | + def zero_points(self): |
| 110 | + """Return output zero points.""" |
| 111 | + if self._zero_point is None: |
| 112 | + self.cal_thresholds() |
| 113 | + return self._zero_point |
0 commit comments