groupwise.py 3.8 KB

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