未验证 提交 0c5781e5 编写于 作者: S Sonder 提交者: GitHub

[xdoctest] reformat example code with google style No.116-119 (#56118)

上级 786c6e99
...@@ -70,12 +70,15 @@ class QuantConfig: ...@@ -70,12 +70,15 @@ class QuantConfig:
Examples: Examples:
.. code-block:: python .. code-block:: python
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9) >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
q_config = QuantConfig(activation=quanter, weight=quanter) >>> q_config = QuantConfig(activation=quanter, weight=quanter)
print(q_config) >>> print(q_config)
Global config:
activation: FakeQuanterWithAbsMaxObserver(name=None,moving_rate=0.9,bit_length=8,dtype=float32)
weight: FakeQuanterWithAbsMaxObserver(name=None,moving_rate=0.9,bit_length=8,dtype=float32)
""" """
...@@ -100,31 +103,36 @@ class QuantConfig: ...@@ -100,31 +103,36 @@ class QuantConfig:
weight: QuanterFactory = None, weight: QuanterFactory = None,
): ):
r""" r"""
Set the quantization config by layer. It has the highest priority among Set the quantization config by layer. It has the highest priority among
all the setting methods. all the setting methods.
Args: Args:
layer(Union[Layer, list]): One or a list of layers. layer(Union[Layer, list]): One or a list of layers.
activation(QuanterFactory): Quanter used for activations. activation(QuanterFactory): Quanter used for activations.
weight(QuanterFactory): Quanter used for weights. weight(QuanterFactory): Quanter used for weights.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
from paddle.nn import Linear >>> from paddle.nn import Linear
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
class Model(paddle.nn.Layer): >>> class Model(paddle.nn.Layer):
def __init__(self): ... def __init__(self):
super().__init__() ... super().__init__()
self.fc = Linear(576, 120) ... self.fc = Linear(576, 120)
model = Model() >>> model = Model()
quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9) >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
q_config = QuantConfig(activation=None, weight=None) >>> q_config = QuantConfig(activation=None, weight=None)
q_config.add_layer_config([model.fc], activation=quanter, weight=quanter) >>> q_config.add_layer_config([model.fc], activation=quanter, weight=quanter)
print(q_config) >>> # doctest: +SKIP
>>> print(q_config)
Global config:
None
Layer prefix config:
{'linear_0': <paddle.quantization.config.SingleLayerConfig object at 0x7fe41a680ee0>}
""" """
if isinstance(layer, list): if isinstance(layer, list):
...@@ -144,31 +152,36 @@ class QuantConfig: ...@@ -144,31 +152,36 @@ class QuantConfig:
weight: QuanterFactory = None, weight: QuanterFactory = None,
): ):
r""" r"""
Set the quantization config by full name of layer. Its priority is Set the quantization config by full name of layer. Its priority is
lower than `add_layer_config`. lower than `add_layer_config`.
Args: Args:
layer_name(Union[str, list]): One or a list of layers' full name. layer_name(Union[str, list]): One or a list of layers' full name.
activation(QuanterFactory): Quanter used for activations. activation(QuanterFactory): Quanter used for activations.
weight(QuanterFactory): Quanter used for weights. weight(QuanterFactory): Quanter used for weights.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
from paddle.nn import Linear >>> from paddle.nn import Linear
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
class Model(paddle.nn.Layer): >>> class Model(paddle.nn.Layer):
def __init__(self): ... def __init__(self):
super().__init__() ... super().__init__()
self.fc = Linear(576, 120) ... self.fc = Linear(576, 120)
model = Model() >>> model = Model()
quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9) >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
q_config = QuantConfig(activation=None, weight=None) >>> q_config = QuantConfig(activation=None, weight=None)
q_config.add_name_config([model.fc.full_name()], activation=quanter, weight=quanter) >>> q_config.add_name_config([model.fc.full_name()], activation=quanter, weight=quanter)
print(q_config) >>> # doctest: +SKIP
>>> print(q_config)
Global config:
None
Layer prefix config:
{'linear_0': <paddle.quantization.config.SingleLayerConfig object at 0x7fe41a680fd0>}
""" """
if isinstance(layer_name, str): if isinstance(layer_name, str):
...@@ -198,22 +211,27 @@ class QuantConfig: ...@@ -198,22 +211,27 @@ class QuantConfig:
weight(QuanterFactory): Quanter used for weights. weight(QuanterFactory): Quanter used for weights.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
from paddle.nn import Linear >>> from paddle.nn import Linear
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
class Model(paddle.nn.Layer): >>> class Model(paddle.nn.Layer):
def __init__(self): ... def __init__(self):
super().__init__() ... super().__init__()
self.fc = Linear(576, 120) ... self.fc = Linear(576, 120)
model = Model() >>> model = Model()
quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9) >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
q_config = QuantConfig(activation=None, weight=None) >>> q_config = QuantConfig(activation=None, weight=None)
q_config.add_type_config([Linear], activation=quanter, weight=quanter) >>> q_config.add_type_config([Linear], activation=quanter, weight=quanter)
print(q_config) >>> # doctest: +SKIP
>>> print(q_config)
Global config:
None
Layer type config:
{<class 'paddle.nn.layer.common.Linear'>: <paddle.quantization.config.SingleLayerConfig object at 0x7fe41a680a60>}
""" """
if isinstance(layer_type, type) and issubclass( if isinstance(layer_type, type) and issubclass(
...@@ -240,18 +258,18 @@ class QuantConfig: ...@@ -240,18 +258,18 @@ class QuantConfig:
target(type): The type of layers that will be converted to. target(type): The type of layers that will be converted to.
Examples: Examples:
.. code-block:: python .. code-block:: python
from paddle.nn import Conv2D >>> from paddle.nn import Conv2D
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9) >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
q_config = QuantConfig(activation=None, weight=None) >>> q_config = QuantConfig(activation=None, weight=None)
class CustomizedQuantedConv2D: >>> class CustomizedQuantedConv2D:
def forward(self, x): ... def forward(self, x):
pass ... pass
# add some code for quantization simulation ... # add some code for quantization simulation
q_config.add_qat_layer_mapping(Conv2D, CustomizedQuantedConv2D) >>> q_config.add_qat_layer_mapping(Conv2D, CustomizedQuantedConv2D)
""" """
assert isinstance(source, type) and issubclass( assert isinstance(source, type) and issubclass(
source, paddle.nn.Layer source, paddle.nn.Layer
...@@ -272,13 +290,13 @@ class QuantConfig: ...@@ -272,13 +290,13 @@ class QuantConfig:
layer_type(type): The type of layer to be declared as leaf. layer_type(type): The type of layer to be declared as leaf.
Examples: Examples:
.. code-block:: python .. code-block:: python
from paddle.nn import Sequential >>> from paddle.nn import Sequential
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
q_config = QuantConfig(activation=None, weight=None) >>> q_config = QuantConfig(activation=None, weight=None)
q_config.add_customized_leaf(Sequential) >>> q_config.add_customized_leaf(Sequential)
""" """
self._customized_leaves.append(layer_type) self._customized_leaves.append(layer_type)
...@@ -379,22 +397,22 @@ class QuantConfig: ...@@ -379,22 +397,22 @@ class QuantConfig:
model(Layer): The model to be specified by the config. model(Layer): The model to be specified by the config.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
from paddle.nn import Linear, Sequential >>> from paddle.nn import Linear, Sequential
from paddle.quantization import QuantConfig >>> from paddle.quantization import QuantConfig
from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver >>> from paddle.quantization.quanters import FakeQuanterWithAbsMaxObserver
class Model(paddle.nn.Layer): >>> class Model(paddle.nn.Layer):
def __init__(self): ... def __init__(self):
super().__init__() ... super().__init__()
self.fc = Sequential(Linear(576, 120),Linear(576, 120)) ... self.fc = Sequential(Linear(576, 120),Linear(576, 120))
model = Model() >>> model = Model()
quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9) >>> quanter = FakeQuanterWithAbsMaxObserver(moving_rate=0.9)
q_config = QuantConfig(activation=None, weight=None) >>> q_config = QuantConfig(activation=None, weight=None)
q_config.add_layer_config([model.fc], activation=quanter, weight=quanter) >>> q_config.add_layer_config([model.fc], activation=quanter, weight=quanter)
q_config._specify(model) >>> q_config._specify(model)
""" """
self._model = model self._model = model
self._specify_helper(self._model) self._specify_helper(self._model)
......
...@@ -83,21 +83,22 @@ def quanter(class_name): ...@@ -83,21 +83,22 @@ def quanter(class_name):
Examples: Examples:
.. code-block:: python .. code-block:: python
# Given codes in ./customized_quanter.py >>> # doctest: +SKIP
from paddle.quantization import quanter >>> # Given codes in ./customized_quanter.py
from paddle.quantization import BaseQuanter >>> from paddle.quantization import quanter
@quanter("CustomizedQuanter") >>> from paddle.quantization import BaseQuanter
class CustomizedQuanterLayer(BaseQuanter): >>> @quanter("CustomizedQuanter")
def __init__(self, arg1, kwarg1=None): >>> class CustomizedQuanterLayer(BaseQuanter):
pass ... def __init__(self, arg1, kwarg1=None):
... pass
# Used in ./test.py
# from .customized_quanter import CustomizedQuanter >>> # Used in ./test.py
from paddle.quantization import QuantConfig >>> # from .customized_quanter import CustomizedQuanter
arg1_value = "test" >>> from paddle.quantization import QuantConfig
kwarg1_value = 20 >>> arg1_value = "test"
quanter = CustomizedQuanter(arg1_value, kwarg1=kwarg1_value) >>> kwarg1_value = 20
q_config = QuantConfig(activation=quanter, weight=quanter) >>> quanter = CustomizedQuanter(arg1_value, kwarg1=kwarg1_value)
>>> q_config = QuantConfig(activation=quanter, weight=quanter)
""" """
......
...@@ -135,79 +135,81 @@ class ImperativeQuantAware: ...@@ -135,79 +135,81 @@ class ImperativeQuantAware:
during training. If this attribute is not sets or the attribute is during training. If this attribute is not sets or the attribute is
false, the Layer would be qunatized in training. false, the Layer would be qunatized in training.
Examples 1: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
from paddle.static.quantization \ >>> from paddle.static.quantization import (
import ImperativeQuantAware ... ImperativeQuantAware,
from paddle.vision.models \ ... )
import resnet >>> from paddle.vision.models import (
... resnet,
model = resnet.resnet50(pretrained=True) ... )
imperative_qat = ImperativeQuantAware( >>> model = resnet.resnet50(pretrained=True)
weight_quantize_type='abs_max',
activation_quantize_type='moving_average_abs_max') >>> imperative_qat = ImperativeQuantAware(
... weight_quantize_type='abs_max',
# Add the fake quant logical. ... activation_quantize_type='moving_average_abs_max')
# The original model will be rewrite.
# The outscale of outputs in supportted layers would be calculated. >>> # Add the fake quant logical.
imperative_qat.quantize(model) >>> # The original model will be rewrite.
>>> # The outscale of outputs in supportted layers would be calculated.
# Fine-tune the quantized model >>> imperative_qat.quantize(model)
# ...
>>> # Fine-tune the quantized model
# Save quant model for the inference. >>> # ...
imperative_qat.save_quantized_model(
layer=model, >>> # Save quant model for the inference.
model_path="./resnet50_qat", >>> imperative_qat.save_quantized_model(
input_spec=[ ... layer=model,
paddle.static.InputSpec( ... model_path="./resnet50_qat",
shape=[None, 3, 224, 224], dtype='float32')]) ... input_spec=[
... paddle.static.InputSpec(
Examples 2: ... shape=[None, 3, 224, 224], dtype='float32')])
.. code-block:: python
.. code-block:: python
import paddle
from paddle.static.quantization \ >>> import paddle
import ImperativeQuantAware >>> from paddle.static.quantization import (
... ImperativeQuantAware,
class ImperativeModel(paddle.nn.Layer): ... )
def __init__(self):
super().__init__() >>> class ImperativeModel(paddle.nn.Layer):
# self.linear_0 would skip the quantization. ... def __init__(self):
self.linear_0 = paddle.nn.Linear(784, 400) ... super().__init__()
self.linear_0.skip_quant = True ... # self.linear_0 would skip the quantization.
... self.linear_0 = paddle.nn.Linear(784, 400)
# self.linear_1 would not skip the quantization. ... self.linear_0.skip_quant = True
self.linear_1 = paddle.nn.Linear(400, 10)
self.linear_1.skip_quant = False ... # self.linear_1 would not skip the quantization.
... self.linear_1 = paddle.nn.Linear(400, 10)
def forward(self, inputs): ... self.linear_1.skip_quant = False
x = self.linear_0(inputs)
x = self.linear_1(inputs) ... def forward(self, inputs):
return x ... x = self.linear_0(inputs)
... x = self.linear_1(inputs)
model = ImperativeModel() ... return x
imperative_qat = ImperativeQuantAware(
weight_quantize_type='abs_max', >>> model = ImperativeModel()
activation_quantize_type='moving_average_abs_max') >>> imperative_qat = ImperativeQuantAware(
... weight_quantize_type='abs_max',
# Add the fake quant logical. ... activation_quantize_type='moving_average_abs_max')
# The original model will be rewrite.
# >>> # Add the fake quant logical.
# There is only one Layer(self.linear1) would be added the >>> # The original model will be rewrite.
# fake quant logical. >>> #
imperative_qat.quantize(model) >>> # There is only one Layer(self.linear1) would be added the
>>> # fake quant logical.
# Fine-tune the quantized model >>> imperative_qat.quantize(model)
# ...
>>> # Fine-tune the quantized model
# Save quant model for the inference. >>> # ...
imperative_qat.save_quantized_model(
layer=model, >>> # Save quant model for the inference.
model_path="./imperative_model_qat") >>> imperative_qat.save_quantized_model(
... layer=model,
... model_path="./imperative_model_qat")
""" """
super().__init__() super().__init__()
self.fuse_conv_bn = fuse_conv_bn self.fuse_conv_bn = fuse_conv_bn
...@@ -245,39 +247,40 @@ class ImperativeQuantAware: ...@@ -245,39 +247,40 @@ class ImperativeQuantAware:
None None
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
from paddle.static.quantization \ >>> from paddle.static.quantization import (
import ImperativeQuantAware ... ImperativeQuantAware,
... )
class ImperativeModel(paddle.nn.Layer):
def __init__(self): >>> class ImperativeModel(paddle.nn.Layer):
super().__init__() ... def __init__(self):
# self.linear_0 would skip the quantization. ... super().__init__()
self.linear_0 = paddle.nn.Linear(784, 400) ... # self.linear_0 would skip the quantization.
self.linear_0.skip_quant = True ... self.linear_0 = paddle.nn.Linear(784, 400)
... self.linear_0.skip_quant = True
# self.linear_1 would not skip the quantization.
self.linear_1 = paddle.nn.Linear(400, 10) ... # self.linear_1 would not skip the quantization.
self.linear_1.skip_quant = False ... self.linear_1 = paddle.nn.Linear(400, 10)
... self.linear_1.skip_quant = False
def forward(self, inputs):
x = self.linear_0(inputs) ... def forward(self, inputs):
x = self.linear_1(inputs) ... x = self.linear_0(inputs)
return x ... x = self.linear_1(inputs)
... return x
model = ImperativeModel()
imperative_qat = ImperativeQuantAware( >>> model = ImperativeModel()
weight_quantize_type='abs_max', >>> imperative_qat = ImperativeQuantAware(
activation_quantize_type='moving_average_abs_max') ... weight_quantize_type='abs_max',
... activation_quantize_type='moving_average_abs_max')
# Add the fake quant logical.
# The original model will be rewrite. >>> # Add the fake quant logical.
# >>> # The original model will be rewrite.
# There is only one Layer(self.linear1) would be added the >>> #
# fake quant logical. >>> # There is only one Layer(self.linear1) would be added the
imperative_qat.quantize(model) >>> # fake quant logical.
>>> imperative_qat.quantize(model)
""" """
assert isinstance( assert isinstance(
model, paddle.nn.Layer model, paddle.nn.Layer
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册