quanter.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 copy
  15. import json
  16. import logging
  17. import os
  18. import paddle
  19. from ...base.framework import IrGraph, core
  20. from ..log_helper import get_logger
  21. from .quantization_pass import (
  22. AddQuantDequantForResidual,
  23. AddQuantDequantPass,
  24. ConvertToInt8Pass,
  25. OutScaleForInferencePass,
  26. OutScaleForTrainingPass,
  27. QuantizationFreezePass,
  28. QuantizationTransformPass,
  29. )
  30. _logger = get_logger(__name__, level=logging.INFO)
  31. from . import quant_config
  32. from .post_training_quantization import PostTrainingQuantizationProgram
  33. from .quantization_pass import (
  34. AddQuantDequantForInferencePass,
  35. AddQuantDequantPassV2,
  36. QuantizationTransformPassV2,
  37. QuantWeightPass,
  38. )
  39. WEIGHT_QUANTIZATION_TYPES = [
  40. 'abs_max',
  41. 'channel_wise_abs_max',
  42. 'range_abs_max',
  43. 'moving_average_abs_max',
  44. ]
  45. WEIGHT_QUANTIZATION_TYPES_TENSORRT = ['channel_wise_abs_max']
  46. ACTIVATION_QUANTIZATION_TYPES = [
  47. 'abs_max',
  48. 'range_abs_max',
  49. 'moving_average_abs_max',
  50. ]
  51. ACTIVATION_QUANTIZATION_TYPES_TENSORRT = [
  52. 'range_abs_max',
  53. 'moving_average_abs_max',
  54. ]
  55. VALID_DTYPES = ['int8']
  56. TRANSFORM_PASS_OP_TYPES = list(
  57. quant_config.SUPPORT_WEIGHT_QUANTIZATION_OP_DICT.keys()
  58. )
  59. QUANT_DEQUANT_PASS_OP_TYPES = list(
  60. quant_config.SUPPORT_ACT_QUANTIZATION_OP_DICT.keys()
  61. )
  62. TENSORRT_OP_TYPES = [
  63. 'mul',
  64. 'conv2d',
  65. 'pool2d',
  66. 'depthwise_conv2d',
  67. 'elementwise_add',
  68. 'leaky_relu',
  69. ]
  70. VARS_MAPPING_TABLE = './mapping_table_for_saving_inference_model'
  71. _quant_config_default = {
  72. # weight quantize type, default is 'channel_wise_abs_max'
  73. 'weight_quantize_type': 'channel_wise_abs_max',
  74. # activation quantize type, default is 'moving_average_abs_max'
  75. 'activation_quantize_type': 'moving_average_abs_max',
  76. # weight quantize bit num, default is 8
  77. 'weight_bits': 8,
  78. # activation quantize bit num, default is 8
  79. 'activation_bits': 8,
  80. # ops of name_scope in not_quant_pattern list, will not be quantized
  81. 'not_quant_pattern': ['skip_quant'],
  82. # ops of type in quantize_op_types, will be quantized
  83. 'quantize_op_types': ['conv2d', 'depthwise_conv2d', 'mul'],
  84. # data type after quantization, such as 'uint8', 'int8', etc. default is 'int8'
  85. 'dtype': 'int8',
  86. # window size for 'range_abs_max' quantization. default is 10000
  87. 'window_size': 10000,
  88. # The decay coefficient of moving average, default is 0.9
  89. 'moving_rate': 0.9,
  90. # if True, 'quantize_op_types' will be TENSORRT_OP_TYPES
  91. 'for_tensorrt': False,
  92. # if True, 'quantize_op_types' will be TRANSFORM_PASS_OP_TYPES + QUANT_DEQUANT_PASS_OP_TYPES
  93. 'is_full_quantize': False,
  94. # if True, use onnx format to quant.
  95. 'onnx_format': True,
  96. # quant post to get initial scale for quant_aware
  97. 'quant_post_first': False,
  98. # whether scale can be train
  99. 'scale_trainable': True,
  100. }
  101. def load_dict():
  102. with open(VARS_MAPPING_TABLE, 'r') as file:
  103. data = file.read()
  104. data = json.loads(data)
  105. return data
  106. def save_dict(table):
  107. with open(VARS_MAPPING_TABLE, 'w') as file:
  108. file.write(json.dumps(table))
  109. def _parse_configs(user_config):
  110. """
  111. check if user's configs are valid.
  112. Args:
  113. user_config(dict): user's config.
  114. Return:
  115. configs(dict): final configs will be used.
  116. """
  117. configs = copy.deepcopy(_quant_config_default)
  118. configs.update(user_config)
  119. assert isinstance(configs['for_tensorrt'], bool) and isinstance(
  120. configs['is_full_quantize'], bool
  121. ), "'for_tensorrt' and 'is_full_quantize' must both be bool'"
  122. # check if configs is valid
  123. if configs['for_tensorrt']:
  124. weight_types = WEIGHT_QUANTIZATION_TYPES_TENSORRT
  125. activation_types = ACTIVATION_QUANTIZATION_TYPES_TENSORRT
  126. platform = 'TensorRT'
  127. else:
  128. weight_types = WEIGHT_QUANTIZATION_TYPES
  129. activation_types = WEIGHT_QUANTIZATION_TYPES
  130. platform = 'PaddleLite'
  131. assert (
  132. configs['weight_quantize_type'] in weight_types
  133. ), "Unknown weight_quantize_type: {}. {} only supports {} ".format(
  134. configs['weight_quantize_type'], platform, weight_types
  135. )
  136. assert (
  137. configs['activation_quantize_type'] in activation_types
  138. ), "Unknown activation_quantize_type: {}. {} only supports {}".format(
  139. configs['activation_quantize_type'], platform, activation_types
  140. )
  141. assert isinstance(
  142. configs['weight_bits'], int
  143. ), "weight_bits must be int value."
  144. assert (
  145. configs['weight_bits'] >= 1 and configs['weight_bits'] <= 16
  146. ), "weight_bits should be between 1 and 16."
  147. assert isinstance(
  148. configs['activation_bits'], int
  149. ), "activation_bits must be int value."
  150. assert (
  151. configs['activation_bits'] >= 1 and configs['activation_bits'] <= 16
  152. ), "activation_bits should be between 1 and 16."
  153. assert isinstance(
  154. configs['not_quant_pattern'], (list, str)
  155. ), "not_quant_pattern must be list or str"
  156. assert isinstance(
  157. configs['quantize_op_types'], list
  158. ), "quantize_op_types must be a list"
  159. if configs['for_tensorrt']:
  160. configs['quantize_op_types'] = TENSORRT_OP_TYPES
  161. elif configs['is_full_quantize']:
  162. configs['quantize_op_types'] = (
  163. TRANSFORM_PASS_OP_TYPES + QUANT_DEQUANT_PASS_OP_TYPES
  164. )
  165. else:
  166. for op_type in configs['quantize_op_types']:
  167. assert (op_type in QUANT_DEQUANT_PASS_OP_TYPES) or (
  168. op_type in TRANSFORM_PASS_OP_TYPES
  169. ), f"{op_type} is not support, \
  170. now support op types are {TRANSFORM_PASS_OP_TYPES + QUANT_DEQUANT_PASS_OP_TYPES}"
  171. assert isinstance(configs['dtype'], str), "dtype must be a str."
  172. assert configs['dtype'] in VALID_DTYPES, "dtype can only be " + " ".join(
  173. VALID_DTYPES
  174. )
  175. assert isinstance(
  176. configs['window_size'], int
  177. ), "window_size must be int value, window size for 'range_abs_max' quantization, default is 10000."
  178. assert isinstance(
  179. configs['moving_rate'], float
  180. ), "moving_rate must be float value, The decay coefficient of moving average, default is 0.9."
  181. return configs
  182. def quant_aware(
  183. program,
  184. place,
  185. config=None,
  186. scope=None,
  187. for_test=False,
  188. weight_quantize_func=None,
  189. act_quantize_func=None,
  190. weight_preprocess_func=None,
  191. act_preprocess_func=None,
  192. optimizer_func=None,
  193. executor=None,
  194. return_program=False,
  195. calib_config={},
  196. draw_graph=False,
  197. return_scale_dict=False,
  198. scale_dict=None,
  199. model_type=None,
  200. pattern_ops=None,
  201. ):
  202. """Add quantization and dequantization operators to "program"
  203. for quantization training or testing.
  204. Args:
  205. program(paddle.static.Program): training or testing ``program``.
  206. place(paddle.CPUPlace or paddle.CUDAPlace): This parameter represents
  207. the executor run on which device.
  208. config(dict, optional): configs for quantization. if None, will use default config.
  209. Default: None.
  210. scope(paddle.static.Scope): Scope records the mapping between variable names and variables,
  211. similar to brackets in programming languages. Usually users can use
  212. `paddle.static.global_scope <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_.
  213. When ``None`` will use `paddle.static.global_scope() <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_ .
  214. Default: ``None``.
  215. for_test(bool): If the 'program' parameter is a test program, this parameter should be set to ``True``.
  216. Otherwise, set to ``False``.Default: False
  217. weight_quantize_func(function): Function that defines how to quantize weight. Using this
  218. can quickly test if user's quantization method works or not. In this function, user should
  219. both define quantization function and dequantization function, that is, the function's input
  220. is non-quantized weight and function returns dequantized weight. If None, will use
  221. quantization op defined by 'weight_quantize_type'.
  222. Default is None.
  223. act_quantize_func(function): Function that defines how to quantize activation. Using this
  224. can quickly test if user's quantization method works or not. In this function, user should
  225. both define quantization and dequantization process, that is, the function's input
  226. is non-quantized activation and function returns dequantized activation. If None, will use
  227. quantization op defined by 'activation_quantize_type'.
  228. Default is None.
  229. weight_preprocess_func(function): Function that defines how to preprocess weight before quantization. Using this
  230. can quickly test if user's preprocess method works or not. The function's input
  231. is non-quantized weight and function returns processed weight to be quantized. If None, the weight will
  232. be quantized directly.
  233. Default is None.
  234. act_preprocess_func(function): Function that defines how to preprocess activation before quantization. Using this
  235. can quickly test if user's preprocess method works or not. The function's input
  236. is non-quantized activation and function returns processed activation to be quantized. If None, the activation will
  237. be quantized directly.
  238. Default is None.
  239. optimizer_func(function): Function return a optimizer. When 'is_test' is False and user want to use self-defined
  240. quantization function and preprocess function, this function must be set. Default is None.
  241. exe(paddle.static.Executor): If user want to use self-defined quantization function and preprocess function, exe must be set for
  242. initialization. Default is None.
  243. return_program(bool): If user want return value is a Program rather than Compiled Program, This argument should be set True.
  244. Default is False.
  245. draw_graph(bool): whether to draw graph when quantization is initialized. In order to prevent cycle,
  246. the ERNIE model needs to be set to True. Default is False.
  247. return_scale_dict(bool): If user want to return scale dict, model_type and pattern_ops, this argument should be set True.
  248. Default is False.
  249. scale_dict(dict): Use scale dict to initialize scales in program. Default is None.
  250. model_type(str): Model type can be 'transformer' or 'non-transformer'. If model type is transformer, patterns will be analyzed.
  251. Default is None.
  252. pattern_ops(dict): Pattern_ops contain pattern name and corresponding ops. Default is None.
  253. Returns:
  254. paddle.static.CompiledProgram | paddle.static.Program: Program with quantization and dequantization ``operators``
  255. """
  256. scope = paddle.static.global_scope() if not scope else scope
  257. if config is None:
  258. config = _quant_config_default
  259. else:
  260. assert isinstance(config, dict), "config must be dict"
  261. config = _parse_configs(config)
  262. _logger.info(f"quant_aware config {config}")
  263. skip_tensor_list = []
  264. same_scale_tensor_list = []
  265. is_test = True if for_test else not config['scale_trainable']
  266. if config['quant_post_first'] and for_test:
  267. if 'quantizable_op_type' not in calib_config:
  268. calib_config['quantizable_op_type'] = config['quantize_op_types']
  269. exe = paddle.static.Executor() if executor is None else executor
  270. post_training_quantization = PostTrainingQuantizationProgram(
  271. exe,
  272. program,
  273. freeze_model=False,
  274. skip_tensor_list=skip_tensor_list,
  275. same_scale_tensor_list=same_scale_tensor_list,
  276. batch_nums=10,
  277. scale_dict=scale_dict,
  278. return_graph=True,
  279. **calib_config,
  280. )
  281. main_graph = post_training_quantization.quantize()
  282. scale_dict = post_training_quantization._scale_dict
  283. sub_graphs = list(main_graph.all_sub_graphs())
  284. else:
  285. main_graph = IrGraph(core.Graph(program.desc), for_test=for_test)
  286. sub_graphs = list(main_graph.all_sub_graphs())
  287. transform_pass_ops = []
  288. quant_dequant_ops = []
  289. if 'quant_config' in config and config['quant_config']:
  290. transform_pass_ops = config[
  291. 'quant_config'
  292. ].weight_quant_operation_types
  293. quant_dequant_ops = config[
  294. 'quant_config'
  295. ].activation_quant_operation_types
  296. else:
  297. for op_type in config['quantize_op_types']:
  298. if op_type in TRANSFORM_PASS_OP_TYPES:
  299. transform_pass_ops.append(op_type)
  300. elif op_type in QUANT_DEQUANT_PASS_OP_TYPES:
  301. quant_dequant_ops.append(op_type)
  302. if len(transform_pass_ops) > 0:
  303. transform_func = (
  304. QuantizationTransformPassV2
  305. if config['onnx_format']
  306. else QuantizationTransformPass
  307. )
  308. transform_pass = transform_func(
  309. scope=scope,
  310. place=place,
  311. weight_bits=config['weight_bits'],
  312. activation_bits=config['activation_bits'],
  313. activation_quantize_type=config['activation_quantize_type'],
  314. weight_quantize_type=config['weight_quantize_type'],
  315. window_size=config['window_size'],
  316. moving_rate=config['moving_rate'],
  317. quantizable_op_type=transform_pass_ops,
  318. skip_pattern=config['not_quant_pattern'],
  319. weight_quantize_func=weight_quantize_func,
  320. act_quantize_func=act_quantize_func,
  321. weight_preprocess_func=weight_preprocess_func,
  322. act_preprocess_func=act_preprocess_func,
  323. optimizer_func=optimizer_func,
  324. executor=executor,
  325. is_test=is_test,
  326. )
  327. for sub_graph in sub_graphs:
  328. transform_pass.apply(sub_graph)
  329. residual_pass = AddQuantDequantForResidual(
  330. scope=scope,
  331. place=place,
  332. quant_bits=config['activation_bits'],
  333. is_test=is_test,
  334. )
  335. for subgraph in sub_graphs:
  336. residual_pass.apply(sub_graph)
  337. if len(quant_dequant_ops) > 0:
  338. qdq_func = (
  339. AddQuantDequantPassV2
  340. if config['onnx_format']
  341. else AddQuantDequantPass
  342. )
  343. quant_dequant_pass = qdq_func(
  344. scope=scope,
  345. place=place,
  346. moving_rate=config['moving_rate'],
  347. quant_bits=config['activation_bits'],
  348. skip_pattern=config['not_quant_pattern'],
  349. quantizable_op_type=quant_dequant_ops,
  350. is_test=is_test,
  351. )
  352. for sub_graph in sub_graphs:
  353. quant_dequant_pass.apply(sub_graph)
  354. out_scale_training_pass = OutScaleForTrainingPass(
  355. scope=scope,
  356. place=place,
  357. moving_rate=config['moving_rate'],
  358. is_test=is_test,
  359. scale_dict=scale_dict,
  360. )
  361. for sub_graph in sub_graphs:
  362. out_scale_training_pass.apply(sub_graph)
  363. if (
  364. (weight_preprocess_func is not None or act_preprocess_func is not None)
  365. and not for_test
  366. and not config['onnx_format']
  367. ):
  368. _logger.info(
  369. "When a preprocess_func is used in quant_aware, Need to save a mapping table to match variable names in the convert phase."
  370. )
  371. _logger.info(f"The mapping table is saved as '{VARS_MAPPING_TABLE}'.")
  372. for sub_graph in sub_graphs:
  373. save_dict(sub_graph.out_node_mapping_table)
  374. # TDOD: remove it.
  375. if draw_graph:
  376. main_graph.draw('./', 'graph.pdf')
  377. if for_test or return_program:
  378. quant_program = main_graph.to_program()
  379. else:
  380. quant_program = paddle.static.CompiledProgram(main_graph.graph)
  381. if return_scale_dict:
  382. return quant_program, scale_dict, model_type, pattern_ops
  383. else:
  384. return quant_program
  385. def convert(program, place, config=None, scope=None, save_int8=False):
  386. """
  387. convert quantized and well-trained ``program`` to final quantized
  388. ``program``that can be used to save ``inference model``.
  389. Args:
  390. program(paddle.static.Program): quantized and well-trained ``test program``.
  391. place(paddle.CPUPlace or paddle.CUDAPlace): This parameter represents
  392. the executor run on which device.
  393. config(dict, optional): configs for convert. if set None, will use
  394. default config. It must be same with config that used in
  395. 'quant_aware'. Default is None.
  396. scope(paddle.static.Scope, optional): Scope records the mapping between
  397. variable names and variables, similar to brackets in
  398. programming languages. Usually users can use
  399. `paddle.static.global_scope <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_.
  400. When ``None`` will use
  401. `paddle.static.global_scope() <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_
  402. . Default: ``None``.
  403. save_int8: Whether to return ``program`` which model parameters'
  404. dtype is ``int8``. This parameter can only be used to
  405. get model size. Default: ``False``.
  406. Returns:
  407. Tuple : freezed program which can be used for inference.
  408. when ``save_int8`` is False, return ``freezed_program(paddle.static.Program)``.
  409. when ``save_int8`` is True, return ``freezed_program(paddle.static.Program)``
  410. and ``freezed_program_int8(paddle.static.Program)``
  411. """
  412. scope = paddle.static.global_scope() if not scope else scope
  413. if config is None:
  414. config = _quant_config_default
  415. else:
  416. assert isinstance(config, dict), "config must be dict"
  417. config = _parse_configs(config)
  418. _logger.info(f"convert config {config}")
  419. test_graph = IrGraph(core.Graph(program.desc), for_test=True)
  420. if config['onnx_format']:
  421. quant_weight_pass = QuantWeightPass(scope, place)
  422. for sub_graph in test_graph.all_sub_graphs():
  423. quant_weight_pass.apply(sub_graph)
  424. out_scale_infer_pass = AddQuantDequantForInferencePass(
  425. scope=scope, place=place, quant_bits=config['activation_bits']
  426. )
  427. for sub_graph in test_graph.all_sub_graphs():
  428. out_scale_infer_pass.apply(sub_graph)
  429. else:
  430. out_scale_infer_pass = OutScaleForInferencePass(scope=scope)
  431. for sub_graph in test_graph.all_sub_graphs():
  432. out_scale_infer_pass.apply(sub_graph)
  433. # Freeze the graph after training by adjusting the quantize
  434. # operators' order for the inference.
  435. freeze_pass = QuantizationFreezePass(
  436. scope=scope,
  437. place=place,
  438. weight_bits=config['weight_bits'],
  439. activation_bits=config['activation_bits'],
  440. weight_quantize_type=config['weight_quantize_type'],
  441. )
  442. if os.path.exists(VARS_MAPPING_TABLE):
  443. test_graph.out_node_mapping_table = load_dict()
  444. for sub_graph in test_graph.all_sub_graphs():
  445. freeze_pass.apply(sub_graph)
  446. freezed_program = test_graph.to_program()
  447. # Move sub blocks persistable var to global block
  448. global_block = freezed_program.global_block()
  449. for _op in global_block.ops:
  450. if _op.type == "while":
  451. _block_id = _op.attr("sub_block").id
  452. _block = freezed_program.block(_block_id)
  453. persistables = []
  454. for _name, _var in _block.vars.items():
  455. if _var.persistable:
  456. global_block._clone_variable(_var)
  457. persistables.append(_name)
  458. for _name in persistables:
  459. _block._remove_var(_name)
  460. persistables.extend(_op.input('X'))
  461. _op.desc.set_input("X", persistables)
  462. assert not (
  463. save_int8 and config['onnx_format']
  464. ), "When onnx_format=True, already saved int8 weight,so you can't set save_int8=True."
  465. if save_int8:
  466. convert_int8_pass = ConvertToInt8Pass(scope=scope, place=place)
  467. for sub_graph in test_graph.all_sub_graphs():
  468. convert_int8_pass.apply(sub_graph)
  469. freezed_program_int8 = test_graph.to_program()
  470. return freezed_program, freezed_program_int8
  471. else:
  472. return freezed_program