qat.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 os
  15. import paddle
  16. from paddle.base.framework import IrGraph
  17. from paddle.framework import core
  18. from paddle.nn.quant import quant_layers
  19. from ...static.quantization.quantization_pass import (
  20. QuantWeightPass,
  21. ReplaceFakeQuantDequantPass,
  22. )
  23. from ...static.quantization.utils import (
  24. _get_input_name_index,
  25. _get_op_input_var_names,
  26. _get_output_name_index,
  27. move_persistable_var_to_global_block,
  28. )
  29. from . import fuse_utils, utils
  30. INFER_MODEL_SUFFIX = ".pdmodel"
  31. INFER_PARAMS_SUFFIX = ".pdiparams"
  32. def lazy_import_fleet(layer_name_map, fake_quant_input_layers):
  33. from paddle.distributed import fleet
  34. layer_name_map[
  35. 'ColumnParallelLinear'
  36. ] = fleet.meta_parallel.parallel_layers.mp_layers.ColumnParallelLinear
  37. layer_name_map[
  38. 'RowParallelLinear'
  39. ] = fleet.meta_parallel.parallel_layers.mp_layers.RowParallelLinear
  40. fake_quant_input_layers.append(fleet.meta_parallel.RowParallelLinear)
  41. fake_quant_input_layers.append(fleet.meta_parallel.ColumnParallelLinear)
  42. return layer_name_map, fake_quant_input_layers
  43. class ImperativeQuantAware:
  44. """
  45. Applying quantization aware training (QAT) to the dygraph model.
  46. """
  47. def __init__(
  48. self,
  49. quantizable_layer_type=[
  50. 'Conv2D',
  51. 'Linear',
  52. 'Conv2DTranspose',
  53. 'ColumnParallelLinear',
  54. 'RowParallelLinear',
  55. ],
  56. weight_quantize_type='abs_max',
  57. activation_quantize_type='moving_average_abs_max',
  58. weight_bits=8,
  59. activation_bits=8,
  60. moving_rate=0.9,
  61. fuse_conv_bn=False,
  62. weight_preprocess_layer=None,
  63. act_preprocess_layer=None,
  64. weight_quantize_layer=None,
  65. act_quantize_layer=None,
  66. onnx_format=False,
  67. ):
  68. """
  69. The constructor for ImperativeQuantAware.
  70. Args:
  71. quantizable_layer_type(list[str | layer]): List the type of
  72. layers that will be quantized. Default is ['Conv2D', 'Linear'].
  73. weight_quantize_type(str): quantization type for weights,
  74. which supports 'abs_max' and 'channel_wise_abs_max'.
  75. activation_quantize_type(str): quantization type for activations,
  76. which supports 'abs_max' and 'moving_average_abs_max' now.
  77. If using 'abs_max' mode, the quantization scale will be
  78. calculated dynamically each step in both training and testing
  79. period. If using 'moving_average_abs_max', the static
  80. quantization scale will be calculated during training and
  81. used in inference.
  82. weight_bits(int): quantization bit number for weights, whereas
  83. the bias is not quantized.
  84. activation_bits(int): quantization bit number for activations.
  85. moving_rate(float): the parameter for 'moving_average_abs_max'
  86. quantization.
  87. fuse_conv_bn(bool): Whether to fuse conv and bn, default is False.
  88. weight_preprocess_layer(paddle.nn.Layer, optional): A paddle
  89. Layer that defines how to preprocess weight before quantization.
  90. Using this can quickly test if user's preprocess method works
  91. or not. The input is non-quantized weight and function returns
  92. processed weight to be quantized.
  93. If None, the weight will be quantized directly.
  94. Default is None.
  95. act_preprocess_layer(paddle.nn.Layer, optional): A paddle Layer
  96. that defines how to preprocess activation before quantization.
  97. Using this can quickly test if user's preprocess method works
  98. or not. The input is non-quantized activation and function returns
  99. processed activation to be quantized.
  100. If None, the activation will be quantized directly.
  101. Default is None.
  102. weight_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that
  103. defines how to quantize weight.
  104. Using this can quickly test if user's quantization method works or not.
  105. In this layer, user should both define quantization method and
  106. dequantization method, that is, the function's input is non-quantized
  107. weight and returns dequantized weight.
  108. If None, will use quantization op defined by 'weight_quantize_type'.
  109. Default is None.
  110. act_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that defines
  111. how to quantize activation.
  112. Using this can quickly test if user's quantization method works or not.
  113. In this layer, user should both define quantization method and
  114. dequantization method, that is, the function's input is non-quantized
  115. activation and returns dequantized activation.
  116. If None, will use quantization op defined by 'activation_quantize_type'.
  117. Default is None.
  118. onnx_format (bool, optional): Whether to export the quantized model
  119. with format of ONNX. Default is False.
  120. Note:
  121. If user sets attribute 'skip_quant' to a Layer that support dynamic
  122. quantization and sets it to true, the layer would not be quantized
  123. during training. If this attribute is not sets or the attribute is
  124. false, the Layer would be quantized in training.
  125. Examples:
  126. .. code-block:: python
  127. >>> import paddle
  128. >>> from paddle.static.quantization import (
  129. ... ImperativeQuantAware,
  130. ... )
  131. >>> from paddle.vision.models import (
  132. ... resnet,
  133. ... )
  134. >>> model = resnet.resnet50(pretrained=True)
  135. >>> imperative_qat = ImperativeQuantAware(
  136. ... weight_quantize_type='abs_max',
  137. ... activation_quantize_type='moving_average_abs_max')
  138. >>> # Add the fake quant logical.
  139. >>> # The original model will be rewrite.
  140. >>> # The outscale of outputs in supported layers would be calculated.
  141. >>> imperative_qat.quantize(model)
  142. >>> # Fine-tune the quantized model
  143. >>> # ...
  144. >>> # Save quant model for the inference.
  145. >>> imperative_qat.save_quantized_model(
  146. ... layer=model,
  147. ... model_path="./resnet50_qat",
  148. ... input_spec=[
  149. ... paddle.static.InputSpec(
  150. ... shape=[None, 3, 224, 224], dtype='float32')])
  151. .. code-block:: python
  152. >>> import paddle
  153. >>> from paddle.static.quantization import (
  154. ... ImperativeQuantAware,
  155. ... )
  156. >>> class ImperativeModel(paddle.nn.Layer):
  157. ... def __init__(self):
  158. ... super().__init__()
  159. ... # self.linear_0 would skip the quantization.
  160. ... self.linear_0 = paddle.nn.Linear(784, 400)
  161. ... self.linear_0.skip_quant = True
  162. ... # self.linear_1 would not skip the quantization.
  163. ... self.linear_1 = paddle.nn.Linear(400, 10)
  164. ... self.linear_1.skip_quant = False
  165. ... def forward(self, inputs):
  166. ... x = self.linear_0(inputs)
  167. ... x = self.linear_1(inputs)
  168. ... return x
  169. >>> model = ImperativeModel()
  170. >>> imperative_qat = ImperativeQuantAware(
  171. ... weight_quantize_type='abs_max',
  172. ... activation_quantize_type='moving_average_abs_max')
  173. >>> # Add the fake quant logical.
  174. >>> # The original model will be rewrite.
  175. >>> #
  176. >>> # There is only one Layer(self.linear1) would be added the
  177. >>> # fake quant logical.
  178. >>> imperative_qat.quantize(model)
  179. >>> # Fine-tune the quantized model
  180. >>> # ...
  181. >>> # Save quant model for the inference.
  182. >>> imperative_qat.save_quantized_model(
  183. ... layer=model,
  184. ... model_path="./imperative_model_qat")
  185. """
  186. super().__init__()
  187. self.fuse_conv_bn = fuse_conv_bn
  188. kwargs = {
  189. "quantizable_layer_type": quantizable_layer_type,
  190. "weight_quantize_type": weight_quantize_type,
  191. "activation_quantize_type": activation_quantize_type,
  192. "weight_bits": weight_bits,
  193. "activation_bits": activation_bits,
  194. "moving_rate": moving_rate,
  195. "weight_preprocess_layer": weight_preprocess_layer,
  196. "act_preprocess_layer": act_preprocess_layer,
  197. "weight_quantize_layer": weight_quantize_layer,
  198. "act_quantize_layer": act_quantize_layer,
  199. }
  200. self._quantize_inputs = ImperativeQuantizeInputs(**kwargs)
  201. self._quantize_outputs = ImperativeQuantizeOutputs(
  202. moving_rate, activation_bits, onnx_format
  203. )
  204. def quantize(self, model):
  205. """
  206. According to weights' and activations' quantization types,
  207. the model will be added some fake quant ops, such as
  208. fake_quantize_dequantize_moving_average_abs_max,
  209. fake_quantize_dequantize_abs_max and so on. At the same time,
  210. the out_scale value of outputs would be calculated.
  211. Args:
  212. model(paddle.nn.Layer): the model to be quantized.
  213. Returns:
  214. None
  215. Examples:
  216. .. code-block:: python
  217. >>> import paddle
  218. >>> from paddle.static.quantization import (
  219. ... ImperativeQuantAware,
  220. ... )
  221. >>> class ImperativeModel(paddle.nn.Layer):
  222. ... def __init__(self):
  223. ... super().__init__()
  224. ... # self.linear_0 would skip the quantization.
  225. ... self.linear_0 = paddle.nn.Linear(784, 400)
  226. ... self.linear_0.skip_quant = True
  227. ... # self.linear_1 would not skip the quantization.
  228. ... self.linear_1 = paddle.nn.Linear(400, 10)
  229. ... self.linear_1.skip_quant = False
  230. ... def forward(self, inputs):
  231. ... x = self.linear_0(inputs)
  232. ... x = self.linear_1(inputs)
  233. ... return x
  234. >>> model = ImperativeModel()
  235. >>> imperative_qat = ImperativeQuantAware(
  236. ... weight_quantize_type='abs_max',
  237. ... activation_quantize_type='moving_average_abs_max')
  238. >>> # Add the fake quant logical.
  239. >>> # The original model will be rewrite.
  240. >>> #
  241. >>> # There is only one Layer(self.linear1) would be added the
  242. >>> # fake quant logical.
  243. >>> imperative_qat.quantize(model)
  244. """
  245. assert isinstance(
  246. model, paddle.nn.Layer
  247. ), "The model must be the instance of paddle.nn.Layer."
  248. if self.fuse_conv_bn:
  249. fuse_utils.fuse_conv_bn(model)
  250. self._quantize_inputs.apply(model)
  251. self._quantize_outputs.apply(model)
  252. return model
  253. def save_quantized_model(self, layer, path, input_spec=None, **config):
  254. self._quantize_outputs.save_quantized_model(
  255. layer, path, input_spec, **config
  256. )
  257. class ImperativeQuantizeInputs:
  258. """
  259. Based on the input params, add the quant_dequant computational
  260. logic both for activation inputs and weight inputs.
  261. """
  262. def __init__(
  263. self,
  264. quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'],
  265. weight_quantize_type='abs_max',
  266. activation_quantize_type='moving_average_abs_max',
  267. weight_bits=8,
  268. activation_bits=8,
  269. moving_rate=0.9,
  270. weight_preprocess_layer=None,
  271. act_preprocess_layer=None,
  272. weight_quantize_layer=None,
  273. act_quantize_layer=None,
  274. ):
  275. """
  276. The constructor for ImperativeQuantizeInputs.
  277. Please refer to the args of ImperativeQuantAware.
  278. """
  279. super().__init__()
  280. self.layer_name_map, self.fake_quant_input_layers = lazy_import_fleet(
  281. utils.layer_name_map, utils.fake_quant_input_layers
  282. )
  283. self._quantizable_layer_type = tuple(
  284. self.layer_name_map[layer]
  285. if layer in self.layer_name_map
  286. else layer
  287. for layer in quantizable_layer_type
  288. )
  289. for layer in self._quantizable_layer_type:
  290. assert (
  291. not isinstance(layer, str)
  292. and layer in self.fake_quant_input_layers
  293. ), ("%s is unsupported to be quantized." % layer)
  294. quantize_type = {
  295. 'abs_max',
  296. 'moving_average_abs_max',
  297. 'channel_wise_abs_max',
  298. 'lsq_weight',
  299. 'channel_wise_lsq_weight',
  300. }
  301. act_quantize_type = {'moving_average_abs_max', 'lsq_act'}
  302. assert (
  303. weight_quantize_type != 'moving_average_abs_max'
  304. and weight_quantize_type in quantize_type
  305. ), (
  306. "Unsupported weight_quantize_type: %s. It can only "
  307. "be abs_max or channel_wise_abs_max." % weight_quantize_type
  308. )
  309. # TODO (jc): activation_quantize_type supports range_abs_max
  310. assert activation_quantize_type in act_quantize_type, (
  311. "Unsupported activation_quantize_type: %s. It can "
  312. "only be moving_average_abs_max or lsq_act now."
  313. % activation_quantize_type
  314. )
  315. bits_check = (
  316. lambda bits: isinstance(bits, int) and bits >= 0 and bits <= 16
  317. )
  318. assert bits_check(weight_bits), "weight_bits should be 1, 2,... or 16."
  319. assert bits_check(
  320. activation_bits
  321. ), "activation_bits should be 1, 2,... or 16."
  322. layer_check = lambda method: method is None or issubclass(
  323. method, paddle.nn.Layer
  324. )
  325. assert layer_check(
  326. weight_preprocess_layer
  327. ), "weight_preprocess should be nn.Layer."
  328. assert layer_check(
  329. act_preprocess_layer
  330. ), "act_preprocess should be nn.Layer."
  331. assert layer_check(
  332. weight_quantize_layer
  333. ), "weight_quantize should be nn.Layer."
  334. assert layer_check(
  335. act_quantize_layer
  336. ), "act_quantize should be nn.Layer."
  337. self._kwargs = {
  338. "weight_quantize_type": weight_quantize_type,
  339. "activation_quantize_type": activation_quantize_type,
  340. "weight_bits": weight_bits,
  341. "activation_bits": activation_bits,
  342. "moving_rate": moving_rate,
  343. "weight_pre_layer": weight_preprocess_layer,
  344. "act_pre_layer": act_preprocess_layer,
  345. "weight_quant_layer": weight_quantize_layer,
  346. "act_quant_layer": act_quantize_layer,
  347. }
  348. def apply(self, model):
  349. """
  350. Quantize the weights and activations to calculate for specific
  351. layers.
  352. Args:
  353. model(paddle.nn.Layer): The target model which would
  354. calculate the input quantization scale.
  355. Returns:
  356. None
  357. """
  358. assert isinstance(
  359. model, paddle.nn.Layer
  360. ), "The model must be the instance of paddle.nn.Layer."
  361. for name, cur_layer in model.named_sublayers():
  362. if not isinstance(cur_layer, self._quantizable_layer_type) or (
  363. hasattr(cur_layer, "skip_quant")
  364. and cur_layer.skip_quant is True
  365. ):
  366. continue
  367. parent_layer, sub_name = utils.find_parent_layer_and_sub_name(
  368. model, name
  369. )
  370. cur_quant_layer = self._get_input_quantized_layer(cur_layer)
  371. setattr(parent_layer, sub_name, cur_quant_layer)
  372. def _get_input_quantized_layer(self, layer):
  373. quant_layer_name = None
  374. for key, value in self.layer_name_map.items():
  375. if isinstance(layer, value):
  376. quant_layer_name = 'Quantized' + key
  377. break
  378. assert quant_layer_name is not None, (
  379. "The layer %s is unsupported to be quantized." % layer.full_name()
  380. )
  381. return quant_layers.__dict__[quant_layer_name](layer, **self._kwargs)
  382. class ImperativeQuantizeOutputs:
  383. """
  384. Calculate the output scales for target layers.
  385. """
  386. def __init__(self, moving_rate=0.9, activation_bits=8, onnx_format=False):
  387. """
  388. The constructor for ImperativeQuantizeOutputs.
  389. Args:
  390. moving_rate(float): The decay coefficient of moving average.
  391. The default value is 0.9.
  392. activation_bits(int, optional): quantization bit number for activation. Default is 8.
  393. """
  394. super().__init__()
  395. self._moving_rate = moving_rate
  396. self._activation_bits = activation_bits
  397. self._onnx_format = onnx_format
  398. def apply(self, model):
  399. """
  400. Insert the `moving_average_abs_max_scale` layers to calculate the
  401. output scales for specific layers in the dygraph model.
  402. Args:
  403. model(paddle.nn.Layer): The target model which would be
  404. calculate the output quantization scale.
  405. Returns:
  406. None
  407. """
  408. assert isinstance(
  409. model, paddle.nn.Layer
  410. ), "The model must be the instance of paddle.nn.Layer."
  411. for cur_name, cur_layer in model.named_sublayers():
  412. if '_act_preprocess' in cur_name:
  413. continue
  414. if not self._is_target_layer(cur_layer):
  415. continue
  416. parent_layer, sub_name = utils.find_parent_layer_and_sub_name(
  417. model, cur_name
  418. )
  419. reduce_type = None
  420. if isinstance(cur_layer, tuple(utils.fake_quant_output_layers)):
  421. cur_quant_layer = quant_layers.FakeQuantMAOutputScaleLayer(
  422. cur_layer, self._moving_rate, reduce_type=reduce_type
  423. )
  424. else:
  425. cur_quant_layer = quant_layers.MAOutputScaleLayer(
  426. cur_layer, self._moving_rate, reduce_type=reduce_type
  427. )
  428. setattr(parent_layer, sub_name, cur_quant_layer)
  429. def save_quantized_model(self, model, path, input_spec=None, **config):
  430. """
  431. Save the quantized model for the inference.
  432. Args:
  433. model (Layer): The model to be saved.
  434. path (str): The path prefix to save model. The format is
  435. ``dirname/file_prefix`` or ``file_prefix``.
  436. input_spec (list[InputSpec|Tensor], optional): Describes the input
  437. of the saved model's forward method, which can be described by
  438. InputSpec or example Tensor. If None, all input variables of
  439. the original Layer's forward method would be the inputs of
  440. the saved model. Default None.
  441. **config (dict, optional): Other save configuration options for
  442. compatibility. We do not recommend using these configurations,
  443. they may be removed in the future. If not necessary, DO NOT use
  444. them. Default None.
  445. The following options are currently supported:
  446. (1) output_spec (list[Tensor]): Selects the output targets of
  447. the saved model. By default, all return variables of original
  448. Layer's forward method are kept as the output of the saved model.
  449. If the provided ``output_spec`` list is not all output variables,
  450. the saved model will be pruned according to the given
  451. ``output_spec`` list.
  452. Returns:
  453. None
  454. """
  455. assert isinstance(
  456. model, paddle.nn.Layer
  457. ), "The model must be the instance of paddle.nn.Layer."
  458. if input_spec:
  459. paddle.jit.to_static(model, input_spec=input_spec)
  460. paddle.jit.save(layer=model, path=path, input_spec=input_spec, **config)
  461. is_dynamic_mode = False
  462. if paddle.in_dynamic_mode():
  463. is_dynamic_mode = True
  464. paddle.enable_static()
  465. place = core.CPUPlace()
  466. scope = paddle.static.global_scope()
  467. exe = paddle.static.Executor(place)
  468. dirname = os.path.dirname(path)
  469. basename = os.path.basename(path)
  470. model_filename = basename + INFER_MODEL_SUFFIX
  471. params_filename = basename + INFER_PARAMS_SUFFIX
  472. [
  473. infer_program,
  474. feed_target_names,
  475. fetch_targets,
  476. ] = paddle.static.load_inference_model(
  477. dirname,
  478. executor=exe,
  479. model_filename=model_filename,
  480. params_filename=params_filename,
  481. )
  482. if not self._onnx_format:
  483. self._gather_scales(infer_program, scope, fetch_targets)
  484. # Remove `moving_average_abs_max_scale` node in sub graphs.
  485. graph = IrGraph(core.Graph(infer_program.desc), for_test=False)
  486. for sub_graph in graph.all_sub_graphs():
  487. for _op in sub_graph.all_op_nodes():
  488. if _op.name() == "moving_average_abs_max_scale":
  489. sub_graph.safe_remove_nodes(_op)
  490. sub_graph.resolve_hazard()
  491. infer_program = graph.to_program()
  492. self._set_skip_quant_attr(infer_program)
  493. clip_extra = False
  494. else:
  495. graph = IrGraph(core.Graph(infer_program.desc), for_test=False)
  496. transform_pass = ReplaceFakeQuantDequantPass(
  497. scope, place, quant_bits=self._activation_bits
  498. )
  499. for sub_graph in graph.all_sub_graphs():
  500. sub_graph._for_test = True
  501. transform_pass.apply(sub_graph)
  502. quant_weight_pass = QuantWeightPass(scope, place)
  503. for sub_graph in graph.all_sub_graphs():
  504. sub_graph._for_test = True
  505. quant_weight_pass.apply(sub_graph)
  506. infer_program = graph.to_program()
  507. clip_extra = True
  508. move_persistable_var_to_global_block(infer_program)
  509. model_name = None
  510. if model_filename is None:
  511. model_name = "model"
  512. elif model_filename.endswith(".pdmodel"):
  513. model_name = model_filename.rsplit(".", 1)[0]
  514. else:
  515. model_name = model_filename
  516. path_prefix = os.path.join(dirname, model_name)
  517. feed_vars = [
  518. infer_program.global_block().var(name) for name in feed_target_names
  519. ]
  520. paddle.static.save_inference_model(
  521. path_prefix,
  522. feed_vars,
  523. fetch_targets,
  524. executor=exe,
  525. program=infer_program.clone(),
  526. clip_extra=clip_extra,
  527. )
  528. if is_dynamic_mode:
  529. paddle.disable_static()
  530. def _is_target_layer(self, layer):
  531. """
  532. Whether the layer needs to calculate output scales.
  533. """
  534. # exclude fake_quant ops in quant_layers file
  535. if not isinstance(layer, paddle.nn.Layer):
  536. return False
  537. if self._onnx_format:
  538. return (
  539. True
  540. if isinstance(layer, tuple(utils.fake_quant_wrap_layers))
  541. else False
  542. )
  543. flag = False
  544. if utils.is_leaf_layer(layer) and not isinstance(
  545. layer, tuple(utils.fake_quant_leaf_layers)
  546. ):
  547. flag = True
  548. if isinstance(layer, tuple(utils.fake_quant_wrap_layers)):
  549. flag = True
  550. if isinstance(layer, paddle.nn.quant.FloatFunctionalLayer):
  551. flag = True
  552. return flag
  553. def _gather_scales(self, program, scope, fetch_targets):
  554. """
  555. Get all scales from fake ops, save them into the corresponding ops
  556. and delete all moving_average_abs_max_scale ops.
  557. """
  558. def _gather_input_scale():
  559. target_ops = []
  560. skip_ops = utils.fake_quantize_dequantize_op_types + [
  561. "moving_average_abs_max_scale"
  562. ]
  563. for block in program.blocks:
  564. for op in block.ops:
  565. if op.type not in skip_ops:
  566. target_ops.append(op)
  567. for op in target_ops:
  568. for in_var_name in _get_op_input_var_names(op):
  569. previous_op = utils.find_previous_op(op.block, in_var_name)
  570. if previous_op is not None and (
  571. "quantize_dequantize" in previous_op.type
  572. or previous_op.type == "moving_average_abs_max_scale"
  573. ):
  574. scale_name = previous_op.output('OutScale')[0]
  575. in_scale = utils.load_variable_data(scope, scale_name)
  576. in_scale = utils.fp_numpy_to_naive(in_scale)
  577. argname, index = _get_input_name_index(op, in_var_name)
  578. op._set_attr(
  579. argname + str(index) + "_threshold", in_scale
  580. )
  581. op._set_attr("with_quant_attr", True)
  582. def _gather_output_scale():
  583. target_ops = []
  584. for block in program.blocks:
  585. for op in block.ops:
  586. if op.type == "moving_average_abs_max_scale":
  587. target_ops.append(op)
  588. for op in target_ops:
  589. in_var_name = op.input('X')[0]
  590. out_var_name = op.output('Out')[0]
  591. block = op.block
  592. previous_op = utils.find_previous_op(block, in_var_name)
  593. next_ops = utils.find_next_ops(block, out_var_name)
  594. out_scale_name = op.output('OutScale')[0]
  595. out_scale = utils.load_variable_data(scope, out_scale_name)
  596. out_scale = utils.fp_numpy_to_naive(out_scale)
  597. if previous_op.type != "feed":
  598. res = _get_output_name_index(previous_op, in_var_name)
  599. if res is not None:
  600. argname, index = res
  601. previous_op._set_attr(
  602. argname + str(index) + "_threshold", out_scale
  603. )
  604. previous_op._set_attr("out_threshold", out_scale)
  605. previous_op._set_attr("with_quant_attr", True)
  606. for next_op in next_ops:
  607. next_op._rename_input(out_var_name, in_var_name)
  608. # If next_op is `fetch` and out_var_name in fetch_targets,
  609. # fetch_targets must update to in_var_name when rename input.
  610. for i in range(len(fetch_targets)):
  611. if fetch_targets[i].name == out_var_name:
  612. fetch_targets[i] = block.var(in_var_name)
  613. _gather_input_scale()
  614. _gather_output_scale()
  615. def _set_skip_quant_attr(self, program):
  616. """
  617. Label the skip quantized ops.
  618. """
  619. for block in program.blocks:
  620. for op in block.ops:
  621. if self._is_skip_quant_op(block, op):
  622. op._set_attr("skip_quant", True)
  623. op._set_attr("with_quant_attr", True)
  624. def _is_skip_quant_op(self, block, in_op):
  625. """
  626. The input op should be skipped quantization.
  627. 1. the type of input op should be conv2d, depthwise_conv2d or matmul
  628. 2. the previous ops of the input op are not fake_quantize_dequantize ops
  629. """
  630. target_op_types = [
  631. "conv2d",
  632. "depthwise_conv2d",
  633. "matmul",
  634. "conv2d_transpose",
  635. ]
  636. if in_op.type not in target_op_types:
  637. return False
  638. previous_ops = [
  639. utils.find_previous_op(block, arg_name)
  640. for arg_name in in_op.input_arg_names
  641. ]
  642. return any(
  643. op is not None
  644. and op.type not in utils.fake_quantize_dequantize_op_types
  645. for op in previous_ops
  646. )