stub.py 3.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. """ Define stub used in quantization."""
  15. from ..layer.layers import Layer
  16. class Stub(Layer):
  17. r"""
  18. The stub is used as placeholders that will be replaced by observers before PTQ or QAT.
  19. It is hard to assign a quantization configuration to a functional API called in
  20. the forward of a layer. Instead, we can create a stub and add it to the sublayers of the layer.
  21. And call the stub before the functional API in the forward. The observer held by the
  22. stub will observe or quantize the inputs of the functional API.
  23. Args:
  24. observer(QuanterFactory): The configured information of the observer to be inserted.
  25. It will use a global configuration to create the observers if the 'observer' is none.
  26. Examples:
  27. .. code-block:: python
  28. >>> import paddle
  29. >>> from paddle.nn.quant import Stub
  30. >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
  31. >>> from paddle.nn import Conv2D
  32. >>> from paddle.quantization import QAT, QuantConfig
  33. >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
  34. >>> class Model(paddle.nn.Layer):
  35. ... def __init__(self, num_classes=10):
  36. ... super().__init__()
  37. ... self.conv = Conv2D(3, 6, 3, stride=1, padding=1)
  38. ... self.quant = Stub(quanter)
  39. ...
  40. ... def forward(self, inputs):
  41. ... out = self.conv(inputs)
  42. ... out = self.quant(out)
  43. ... return paddle.nn.functional.relu(out)
  44. >>> model = Model()
  45. >>> q_config = QuantConfig(activation=quanter, weight=quanter)
  46. >>> qat = QAT(q_config)
  47. >>> quant_model = qat.quantize(model)
  48. >>> print(quant_model)
  49. Model(
  50. (conv): QuantedConv2D(
  51. (weight_quanter): FakeQuanterWithAbsMaxObserverLayer()
  52. (activation_quanter): FakeQuanterWithAbsMaxObserverLayer()
  53. )
  54. (quant): QuanterStub(
  55. (_observer): FakeQuanterWithAbsMaxObserverLayer()
  56. )
  57. )
  58. """
  59. def __init__(self, observer=None):
  60. super().__init__()
  61. self._observer = observer
  62. def forward(self, input):
  63. return input
  64. class QuanterStub(Layer):
  65. r"""
  66. It is an identity layer with an observer observing the input.
  67. Before QAT or PTQ, the stub in the model will be replaced with an instance of QuanterStub.
  68. The user should not use this class directly.
  69. Args:
  70. layer(paddle.nn.Layer): The stub layer with an observer configure factory. If the observer
  71. of the stub layer is none, it will use 'q_config' to create an observer instance.
  72. q_config(QuantConfig): The quantization configuration for the current stub layer.
  73. """
  74. def __init__(self, layer: Stub, q_config):
  75. super().__init__()
  76. self._observer = None
  77. if layer._observer is not None:
  78. self._observer = layer._observer._instance(layer)
  79. elif q_config.activation is not None:
  80. self._observer = q_config.activation._instance(layer)
  81. def forward(self, input):
  82. return self._observer(input) if self._observer is not None else input