post_quantization.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. # copyright (c) 2020 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. from paddle.fluid.contrib.slim.quantization.quantization_pass import QuantizationTransformPass
  15. from paddle.fluid.contrib.slim.quantization.quantization_pass import AddQuantDequantPass
  16. from paddle.fluid.contrib.slim.quantization.quantization_pass import _out_scale_op_list
  17. from paddle.fluid.contrib.slim.quantization import PostTrainingQuantization
  18. import paddlex.utils.logging as logging
  19. import paddle.fluid as fluid
  20. import os
  21. import re
  22. import numpy as np
  23. import time
  24. def _load_variable_data(scope, var_name):
  25. '''
  26. Load variable value from scope
  27. '''
  28. var_node = scope.find_var(var_name)
  29. assert var_node is not None, \
  30. "Cannot find " + var_name + " in scope."
  31. return np.array(var_node.get_tensor())
  32. class PaddleXPostTrainingQuantization(PostTrainingQuantization):
  33. def __init__(self,
  34. executor,
  35. dataset,
  36. program,
  37. inputs,
  38. outputs,
  39. batch_size=10,
  40. batch_nums=None,
  41. scope=None,
  42. algo="KL",
  43. quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
  44. is_full_quantize=False,
  45. is_use_cache_file=False,
  46. cache_dir="./temp_post_training"):
  47. '''
  48. The class utilizes post training quantization methon to quantize the
  49. fp32 model. It uses calibrate data to calculate the scale factor of
  50. quantized variables, and inserts fake quant/dequant op to obtain the
  51. quantized model.
  52. Args:
  53. executor(fluid.Executor): The executor to load, run and save the
  54. quantized model.
  55. dataset(Python Iterator): The data Reader.
  56. program(fluid.Program): The paddle program, save the parameters for model.
  57. inputs(dict): The input of prigram.
  58. outputs(dict): The output of program.
  59. batch_size(int, optional): The batch size of DataLoader. Default is 10.
  60. batch_nums(int, optional): If batch_nums is not None, the number of
  61. calibrate data is batch_size*batch_nums. If batch_nums is None, use
  62. all data provided by sample_generator as calibrate data.
  63. scope(fluid.Scope, optional): The scope of the program, use it to load
  64. and save variables. If scope=None, get scope by global_scope().
  65. algo(str, optional): If algo=KL, use KL-divergenc method to
  66. get the more precise scale factor. If algo='direct', use
  67. abs_max methon to get the scale factor. Default is KL.
  68. quantizable_op_type(list[str], optional): List the type of ops
  69. that will be quantized. Default is ["conv2d", "depthwise_conv2d",
  70. "mul"].
  71. is_full_quantized(bool, optional): If set is_full_quantized as True,
  72. apply quantization to all supported quantizable op type. If set
  73. is_full_quantized as False, only apply quantization to the op type
  74. according to the input quantizable_op_type.
  75. is_use_cache_file(bool, optional): If set is_use_cache_file as False,
  76. all temp data will be saved in memory. If set is_use_cache_file as True,
  77. it will save temp data to disk. When the fp32 model is complex or
  78. the number of calibrate data is large, we should set is_use_cache_file
  79. as True. Defalut is False.
  80. cache_dir(str, optional): When is_use_cache_file is True, set cache_dir as
  81. the directory for saving temp data. Default is ./temp_post_training.
  82. Returns:
  83. None
  84. '''
  85. self._support_activation_quantize_type = [
  86. 'range_abs_max', 'moving_average_abs_max', 'abs_max'
  87. ]
  88. self._support_weight_quantize_type = [
  89. 'abs_max', 'channel_wise_abs_max'
  90. ]
  91. self._support_algo_type = ['KL', 'abs_max', 'min_max']
  92. self._support_quantize_op_type = \
  93. list(set(QuantizationTransformPass._supported_quantizable_op_type +
  94. AddQuantDequantPass._supported_quantizable_op_type))
  95. # Check inputs
  96. assert executor is not None, "The executor cannot be None."
  97. assert batch_size > 0, "The batch_size should be greater than 0."
  98. assert algo in self._support_algo_type, \
  99. "The algo should be KL, abs_max or min_max."
  100. self._executor = executor
  101. self._dataset = dataset
  102. self._batch_size = batch_size
  103. self._batch_nums = batch_nums
  104. self._scope = fluid.global_scope() if scope == None else scope
  105. self._algo = algo
  106. self._is_use_cache_file = is_use_cache_file
  107. self._cache_dir = cache_dir
  108. self._activation_bits = 8
  109. self._weight_bits = 8
  110. self._activation_quantize_type = 'range_abs_max'
  111. self._weight_quantize_type = 'channel_wise_abs_max'
  112. if self._is_use_cache_file and not os.path.exists(self._cache_dir):
  113. os.mkdir(self._cache_dir)
  114. if is_full_quantize:
  115. self._quantizable_op_type = self._support_quantize_op_type
  116. else:
  117. self._quantizable_op_type = quantizable_op_type
  118. for op_type in self._quantizable_op_type:
  119. assert op_type in self._support_quantize_op_type + \
  120. AddQuantDequantPass._activation_type, \
  121. op_type + " is not supported for quantization."
  122. self._place = self._executor.place
  123. self._program = program
  124. self._feed_list = list(inputs.values())
  125. self._fetch_list = list(outputs.values())
  126. self._data_loader = None
  127. self._out_scale_op_list = _out_scale_op_list
  128. self._bit_length = 8
  129. self._quantized_weight_var_name = set()
  130. self._quantized_act_var_name = set()
  131. self._sampling_data = {}
  132. self._quantized_var_kl_threshold = {}
  133. self._quantized_var_min = {}
  134. self._quantized_var_max = {}
  135. self._quantized_var_abs_max = {}
  136. def quantize(self):
  137. '''
  138. Quantize the fp32 model. Use calibrate data to calculate the scale factor of
  139. quantized variables, and inserts fake quant/dequant op to obtain the
  140. quantized model.
  141. Args:
  142. None
  143. Returns:
  144. the program of quantized model.
  145. '''
  146. self._load_model_data()
  147. self._collect_target_varnames()
  148. self._set_activation_persistable()
  149. batch_ct = 0
  150. for data in self._data_loader():
  151. batch_ct += 1
  152. if self._batch_nums and batch_ct >= self._batch_nums:
  153. break
  154. batch_id = 0
  155. logging.info("Start to run batch!")
  156. for data in self._data_loader():
  157. start = time.time()
  158. with fluid.scope_guard(self._scope):
  159. self._executor.run(program=self._program,
  160. feed=data,
  161. fetch_list=self._fetch_list,
  162. return_numpy=False)
  163. if self._algo == "KL":
  164. self._sample_data(batch_id)
  165. else:
  166. self._sample_threshold()
  167. end = time.time()
  168. logging.debug(
  169. '[Run batch data] Batch={}/{}, time_each_batch={} s.'.format(
  170. str(batch_id + 1), str(batch_ct), str(end - start)))
  171. batch_id += 1
  172. if self._batch_nums and batch_id >= self._batch_nums:
  173. break
  174. logging.info("All run batch: ".format(batch_id))
  175. self._reset_activation_persistable()
  176. logging.info("Calculate scale factor ...")
  177. if self._algo == "KL":
  178. self._calculate_kl_threshold()
  179. logging.info("Update the program ...")
  180. if self._algo in ["KL", "abs_max"]:
  181. self._update_program()
  182. else:
  183. self._save_input_threhold()
  184. logging.info("Save ...")
  185. self._save_output_threshold()
  186. logging.info("Finish quant!")
  187. return self._program
  188. def save_quantized_model(self, save_model_path):
  189. '''
  190. Save the quantized model to the disk.
  191. Args:
  192. save_model_path(str): The path to save the quantized model
  193. Returns:
  194. None
  195. '''
  196. with fluid.scope_guard(self._scope):
  197. feed_vars_names = [var.name for var in self._feed_list]
  198. fluid.io.save_inference_model(
  199. dirname=save_model_path,
  200. feeded_var_names=feed_vars_names,
  201. target_vars=self._fetch_list,
  202. executor=self._executor,
  203. params_filename='__params__',
  204. main_program=self._program)
  205. def _load_model_data(self):
  206. '''
  207. Set data loader.
  208. '''
  209. feed_vars = [fluid.framework._get_var(var.name, self._program) \
  210. for var in self._feed_list]
  211. self._data_loader = fluid.io.DataLoader.from_generator(
  212. feed_list=feed_vars, capacity=3 * self._batch_size, iterable=True)
  213. self._data_loader.set_sample_list_generator(
  214. self._dataset.generator(
  215. self._batch_size, drop_last=True),
  216. places=self._place)
  217. def _calculate_kl_threshold(self):
  218. '''
  219. Calculate the KL threshold of quantized variables.
  220. '''
  221. assert self._algo == "KL", "The algo should be KL to calculate kl threshold."
  222. ct = 1
  223. # Abs_max threshold for weights
  224. for var_name in self._quantized_weight_var_name:
  225. start = time.time()
  226. weight_data = self._sampling_data[var_name]
  227. weight_threshold = None
  228. if self._weight_quantize_type == "abs_max":
  229. weight_threshold = np.max(np.abs(weight_data))
  230. elif self._weight_quantize_type == "channel_wise_abs_max":
  231. weight_threshold = []
  232. for i in range(weight_data.shape[0]):
  233. abs_max_value = np.max(np.abs(weight_data[i]))
  234. weight_threshold.append(abs_max_value)
  235. self._quantized_var_kl_threshold[var_name] = weight_threshold
  236. end = time.time()
  237. logging.debug(
  238. '[Calculate weight] Weight_id={}/{}, time_each_weight={} s.'.
  239. format(
  240. str(ct),
  241. str(len(self._quantized_weight_var_name)),
  242. str(end - start)))
  243. ct += 1
  244. ct = 1
  245. # KL threshold for activations
  246. if self._is_use_cache_file:
  247. for var_name in self._quantized_act_var_name:
  248. start = time.time()
  249. sampling_data = []
  250. file_name = os.path.join(self._cache_dir, var_name)
  251. cache_dir, var_name_ = os.path.split(file_name)
  252. filenames = [f for f in os.listdir(cache_dir) \
  253. if re.match(var_name_ + '_[0-9]+.npy', f)]
  254. for filename in filenames:
  255. file_path = os.path.join(cache_dir, filename)
  256. sampling_data.append(np.load(file_path))
  257. os.remove(file_path)
  258. sampling_data = np.concatenate(sampling_data)
  259. self._quantized_var_kl_threshold[var_name] = \
  260. self._get_kl_scaling_factor(np.abs(sampling_data))
  261. end = time.time()
  262. logging.debug(
  263. '[Calculate activation] Activation_id={}/{}, time_each_activation={} s.'.
  264. format(
  265. str(ct),
  266. str(len(self._quantized_act_var_name)),
  267. str(end - start)))
  268. ct += 1
  269. else:
  270. for var_name in self._quantized_act_var_name:
  271. start = time.time()
  272. self._sampling_data[var_name] = np.concatenate(
  273. self._sampling_data[var_name])
  274. self._quantized_var_kl_threshold[var_name] = \
  275. self._get_kl_scaling_factor(np.abs(self._sampling_data[var_name]))
  276. end = time.time()
  277. logging.debug(
  278. '[Calculate activation] Activation_id={}/{}, time_each_activation={} s.'.
  279. format(
  280. str(ct),
  281. str(len(self._quantized_act_var_name)),
  282. str(end - start)))
  283. ct += 1
  284. def _sample_data(self, iter):
  285. '''
  286. Sample the tensor data of quantized variables,
  287. applied in every iteration.
  288. '''
  289. assert self._algo == "KL", "The algo should be KL to sample data."
  290. for var_name in self._quantized_weight_var_name:
  291. if var_name not in self._sampling_data:
  292. var_tensor = _load_variable_data(self._scope, var_name)
  293. self._sampling_data[var_name] = var_tensor
  294. if self._is_use_cache_file:
  295. for var_name in self._quantized_act_var_name:
  296. var_tensor = _load_variable_data(self._scope, var_name)
  297. var_tensor = var_tensor.ravel()
  298. save_path = os.path.join(self._cache_dir,
  299. var_name + "_" + str(iter) + ".npy")
  300. save_dir, file_name = os.path.split(save_path)
  301. if not os.path.exists(save_dir):
  302. os.makedirs(save_dir)
  303. np.save(save_path, var_tensor)
  304. else:
  305. for var_name in self._quantized_act_var_name:
  306. if var_name not in self._sampling_data:
  307. self._sampling_data[var_name] = []
  308. var_tensor = _load_variable_data(self._scope, var_name)
  309. var_tensor = var_tensor.ravel()
  310. self._sampling_data[var_name].append(var_tensor)
  311. class PaddleXPostTrainingQuantizationV2(PostTrainingQuantization):
  312. def __init__(self,
  313. executor,
  314. dataset,
  315. program,
  316. inputs,
  317. outputs,
  318. batch_size=10,
  319. batch_nums=None,
  320. scope=None,
  321. algo="KL",
  322. quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
  323. is_full_quantize=False,
  324. activation_bits=8,
  325. weight_bits=8,
  326. activation_quantize_type='range_abs_max',
  327. weight_quantize_type='channel_wise_abs_max',
  328. optimize_model=False,
  329. is_use_cache_file=False,
  330. cache_dir="./temp_post_training"):
  331. '''
  332. Constructor.
  333. Args:
  334. executor(fluid.Executor): The executor to load, run and save the
  335. quantized model.
  336. dataset(Python Iterator): The data Reader.
  337. program(fluid.Program): The paddle program, save the parameters for model.
  338. inputs(dict): The input of prigram.
  339. outputs(dict): The output of program.
  340. scope(fluid.Scope, optional): The scope of the program, use it to load
  341. and save variables. If scope=None, get scope by global_scope().
  342. batch_size(int, optional): The batch size of DataLoader. Default is 10.
  343. batch_nums(int, optional): If batch_nums is not None, the number of
  344. calibrate data is batch_size*batch_nums. If batch_nums is None, use
  345. all data provided by sample_generator as calibrate data.
  346. algo(str, optional): If algo='KL', use KL-divergenc method to
  347. get the KL threshold for quantized activations and get the abs_max
  348. value for quantized weights. If algo='abs_max', get the abs max
  349. value for activations and weights. If algo= 'min_max', get the min
  350. and max value for quantized activations and weights. Default is KL.
  351. quantizable_op_type(list[str], optional): List the type of ops
  352. that will be quantized. Default is ["conv2d", "depthwise_conv2d",
  353. "mul"].
  354. is_full_quantized(bool, optional): If set is_full_quantized as True,
  355. apply quantization to all supported quantizable op type. If set
  356. is_full_quantized as False, only apply quantization to the op type
  357. according to the input quantizable_op_type.
  358. activation_bits(int): quantization bit number for activation.
  359. weight_bits(int, optional): quantization bit number for weights.
  360. activation_quantize_type(str): quantization type for activation,
  361. now support 'range_abs_max', 'moving_average_abs_max' and 'abs_max'.
  362. This param only specifies the fake ops in saving quantized model.
  363. If it is 'range_abs_max' or 'moving_average_abs_max', we save the scale
  364. obtained by post training quantization in fake ops. Note that, if it
  365. is 'abs_max', the scale will not be saved in fake ops.
  366. weight_quantize_type(str): quantization type for weights,
  367. support 'abs_max' and 'channel_wise_abs_max'. This param only specifies
  368. the fake ops in saving quantized model, and we save the scale obtained
  369. by post training quantization in fake ops. Compared to 'abs_max',
  370. the model accuracy is usually higher when it is 'channel_wise_abs_max'.
  371. optimize_model(bool, optional): If set optimize_model as True, it applies
  372. some passes to the model before quantization, and it supports
  373. `conv2d/depthwise_conv2d + bn` pass so far. Some targets require the
  374. weights are quantized by tensor-wise method, which means the weights
  375. scale for all channel are the same. However, if fuse
  376. `conv2d/depthwise_conv2d + bn`, the weights scale for all channel will
  377. be different. In address this problem, fuse the pattern before
  378. quantization. Default False.
  379. is_use_cache_file(bool, optional): This param is deprecated.
  380. cache_dir(str, optional): This param is deprecated.
  381. Returns:
  382. None
  383. '''
  384. self._support_activation_quantize_type = [
  385. 'range_abs_max', 'moving_average_abs_max', 'abs_max'
  386. ]
  387. self._support_weight_quantize_type = [
  388. 'abs_max', 'channel_wise_abs_max'
  389. ]
  390. self._support_algo_type = ['KL', 'abs_max', 'min_max']
  391. self._dynamic_quantize_op_type = ['lstm']
  392. self._support_quantize_op_type = \
  393. list(set(QuantizationTransformPass._supported_quantizable_op_type +
  394. AddQuantDequantPass._supported_quantizable_op_type +
  395. self._dynamic_quantize_op_type))
  396. # Check inputs
  397. assert executor is not None, "The executor cannot be None."
  398. assert batch_size > 0, "The batch_size should be greater than 0."
  399. assert algo in self._support_algo_type, \
  400. "The algo should be KL, abs_max or min_max."
  401. assert activation_quantize_type in self._support_activation_quantize_type, \
  402. "The activation_quantize_type ({}) should in ({}).".format(
  403. activation_quantize_type, self._support_activation_quantize_type)
  404. assert weight_quantize_type in self._support_weight_quantize_type, \
  405. "The weight_quantize_type ({}) shoud in ({}).".format(
  406. weight_quantize_type, self._support_weight_quantize_type)
  407. # Save input params
  408. self._executor = executor
  409. self._dataset = dataset
  410. self._scope = fluid.global_scope() if scope == None else scope
  411. self._batch_size = batch_size
  412. self._batch_nums = batch_nums
  413. self._algo = algo
  414. self._activation_bits = activation_bits
  415. self._weight_bits = weight_bits
  416. self._activation_quantize_type = activation_quantize_type
  417. self._weight_quantize_type = weight_quantize_type
  418. self._is_full_quantize = is_full_quantize
  419. if is_full_quantize:
  420. self._quantizable_op_type = self._support_quantize_op_type
  421. else:
  422. self._quantizable_op_type = quantizable_op_type
  423. for op_type in self._quantizable_op_type:
  424. assert op_type in self._support_quantize_op_type, \
  425. op_type + " is not supported for quantization."
  426. self._optimize_model = optimize_model
  427. # Define variables
  428. self._place = self._executor.place
  429. self._program = program
  430. self._feed_list = [var.name for var in inputs.values()]
  431. self._fetch_list = list(outputs.values())
  432. self._data_loader = None
  433. self._out_scale_op_list = _out_scale_op_list
  434. self._quantized_weight_var_name = set()
  435. self._quantized_act_var_name = set()
  436. self._weight_op_pairs = {}
  437. # The vars for alog = KL
  438. self._sampling_act_abs_min_max = {}
  439. self._sampling_act_histogram = {}
  440. self._sampling_data = {}
  441. self._quantized_var_kl_threshold = {}
  442. self._histogram_bins = 2048
  443. # The vars for algo = min_max
  444. self._quantized_var_min = {}
  445. self._quantized_var_max = {}
  446. # The vars for algo = abs_max
  447. self._quantized_var_abs_max = {}
  448. def _load_model_data(self):
  449. '''
  450. Set data loader.
  451. '''
  452. logging.info("Set data loader ...")
  453. if self._program.num_blocks > 1:
  454. _logger.error("The post training quantization requires that the "
  455. "program only has one block.")
  456. if self._optimize_model:
  457. self._optimize_fp32_model()
  458. feed_vars = [fluid.framework._get_var(var_name, self._program) \
  459. for var_name in self._feed_list]
  460. self._data_loader = fluid.io.DataLoader.from_generator(
  461. feed_list=feed_vars, capacity=3 * self._batch_size, iterable=True)
  462. self._data_loader.set_sample_list_generator(
  463. self._dataset.generator(
  464. self._batch_size, drop_last=True),
  465. places=self._place)
  466. def save_quantized_model(self, save_model_path):
  467. '''
  468. Save the quantized model to the disk.
  469. Args:
  470. save_model_path(str): The path to save the quantized model.
  471. Returns:
  472. None
  473. '''
  474. with fluid.scope_guard(self._scope):
  475. fluid.io.save_inference_model(
  476. dirname=save_model_path,
  477. model_filename='__model__',
  478. params_filename='__params__',
  479. feeded_var_names=self._feed_list,
  480. target_vars=self._fetch_list,
  481. executor=self._executor,
  482. main_program=self._program)
  483. logging.info("The quantized model is saved in " + save_model_path)