base_quanter.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright (c) 2022 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 abc
  15. from collections.abc import Iterable
  16. from typing import Union
  17. import numpy as np
  18. import paddle
  19. from paddle.nn import Layer
  20. class BaseQuanter(Layer, metaclass=abc.ABCMeta):
  21. r"""
  22. Built-in quanters and customized quanters should extend this base quanter
  23. and implement abstract methods.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. @abc.abstractmethod
  28. def forward(self, input):
  29. pass
  30. @abc.abstractmethod
  31. def scales(self) -> Union[paddle.Tensor, np.ndarray]:
  32. r"""
  33. Get the scales used for quantization.
  34. It can be none which means the quanter didn't hold scales for quantization.
  35. """
  36. pass
  37. @abc.abstractmethod
  38. def zero_points(self) -> Union[paddle.Tensor, np.ndarray]:
  39. r"""
  40. Get the zero points used for quantization.
  41. It can be none which means the quanter didn't hold zero points for quantization.
  42. """
  43. pass
  44. @abc.abstractmethod
  45. def quant_axis(self) -> Union[int, Iterable]:
  46. r"""
  47. Get the axis of quantization. None means tensor-wise quantization.
  48. """
  49. pass
  50. @abc.abstractmethod
  51. def bit_length(self):
  52. r"""
  53. Get the bit length of quantization.
  54. """
  55. pass