You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

qat.py 35 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """
  16. Quantization aware training
  17. User can use quantization aware to train a model. MindSpore supports quantization aware training,
  18. which models quantization errors in both the forward and backward passes using fake-quantization
  19. operations. Note that the entire computation is carried out in floating point. At the end of quantization
  20. aware training, MindSpore provides conversion functions to convert the trained model into lower precision.
  21. """
  22. import re
  23. import mindspore.context as context
  24. import numpy as np
  25. from ... import nn, ops
  26. from ..._checkparam import Validator, Rel
  27. from ...nn.layer import quant
  28. from ...ops import functional as F
  29. from ..common import QuantDtype
  30. from .quantizer import Quantizer, OptimizeOption
  31. from .quant_utils import compute_kl_threshold
  32. __all__ = ["QuantizationAwareTraining", "create_quant_config"]
  33. def create_quant_config(quant_observer=(nn.FakeQuantWithMinMaxObserver, nn.FakeQuantWithMinMaxObserver),
  34. quant_delay=(0, 0),
  35. quant_dtype=(QuantDtype.INT8, QuantDtype.INT8),
  36. per_channel=(False, False),
  37. symmetric=(False, False),
  38. narrow_range=(False, False),
  39. mode="DEFAULT"):
  40. r"""
  41. Config the observer type of weights and data flow with quant parameters.
  42. Args:
  43. quant_observer (Union[Observer, list, tuple]): The types of observer for quantization. The first element
  44. applies to weights and the second applies to data flow. Currently, only
  45. :class:`FakeQuantWithMinMaxObserver` supported.
  46. Default: (nn.FakeQuantWithMinMaxObserver, nn.FakeQuantWithMinMaxObserver).
  47. quant_delay (Union[int, list, tuple]): Number of steps after which weights and activations are quantized
  48. during train and eval. The first element represents weights and the second element represents data flow.
  49. Default: (0, 0).
  50. quant_dtype (Union[QuantDtype, list, tuple]): Datatype used to quantize weights and activations. The first
  51. element represents weights and the second element represents data flow.
  52. Default: (QuantDtype.INT8, QuantDtype.INT8).
  53. per_channel (Union[bool, list, tuple]): Quantization granularity based on layer or on channel. If `True`
  54. then base on per channel, otherwise base on per layer. The first element represents weights
  55. and the second element represents data flow, and the second element must be `False` now.
  56. Default: (False, False).
  57. symmetric (Union[bool, list, tuple]): Whether the quantization algorithm is symmetric or not. If `True` then
  58. base on symmetric, otherwise base on asymmetric. The first element represents weights and the second
  59. element represents data flow. Default: (False, False).
  60. narrow_range (Union[bool, list, tuple]): Whether the quantization algorithm uses narrow range or not.
  61. The first element represents weights and the second element represents data flow.
  62. Default: (False, False).
  63. mode (str): Optional quantization mode, currently only `DEFAULT`(QAT) and `LEARNED_SCALE` are supported.
  64. Default: ("DEFAULT").
  65. Returns:
  66. QuantConfig, contains the observer type of weight and activation.
  67. Raises:
  68. ValueError: If the second element of `per_channel` is not `False`.
  69. """
  70. if per_channel[-1]:
  71. raise ValueError("Arg 'per_channel' second element must be 'False'.")
  72. weight_observer = quant_observer[0].partial_init(quant_delay=quant_delay[0], quant_dtype=quant_dtype[0],
  73. per_channel=per_channel[0], symmetric=symmetric[0],
  74. narrow_range=narrow_range[0], mode=mode)
  75. act_observer = quant_observer[-1].partial_init(quant_delay=quant_delay[-1], quant_dtype=quant_dtype[-1],
  76. per_channel=per_channel[-1], symmetric=symmetric[-1],
  77. narrow_range=narrow_range[-1], mode=mode)
  78. return quant.QuantConfig(weight=weight_observer, activation=act_observer)
  79. class _AddFakeQuantInput(nn.Cell):
  80. """
  81. Add FakeQuant OP at input of the network. Only support one input case.
  82. """
  83. def __init__(self, network, quant_delay=0):
  84. super(_AddFakeQuantInput, self).__init__(auto_prefix=False)
  85. self.fake_quant_input = quant.FakeQuantWithMinMaxObserver(min_init=-6, max_init=6,
  86. quant_delay=quant_delay, ema=True)
  87. self.fake_quant_input.update_parameters_name('fake_quant_input.')
  88. self.network = network
  89. def construct(self, data):
  90. data = self.fake_quant_input(data)
  91. output = self.network(data)
  92. return output
  93. class _AddFakeQuantAfterSubCell(nn.Cell):
  94. """
  95. Add FakeQuant OP after of the sub Cell.
  96. """
  97. def __init__(self, subcell, **kwargs):
  98. super(_AddFakeQuantAfterSubCell, self).__init__(auto_prefix=False)
  99. self.subcell = subcell
  100. self.mode = "DEFAULT"
  101. self.max_init = 6
  102. self.min_init = -6
  103. if OptimizeOption.LEARNED_SCALE in kwargs["optimize_option"]:
  104. self.mode = "LEARNED_SCALE"
  105. self.max_init = 16
  106. self.min_init = -16
  107. self.fake_quant_act = quant.FakeQuantWithMinMaxObserver(min_init=self.min_init,
  108. max_init=self.max_init,
  109. ema=True,
  110. quant_dtype=kwargs["quant_dtype"],
  111. quant_delay=kwargs["quant_delay"],
  112. per_channel=kwargs["per_channel"],
  113. symmetric=kwargs["symmetric"],
  114. narrow_range=kwargs["narrow_range"],
  115. mode=self.mode)
  116. def construct(self, *data):
  117. output = self.subcell(*data)
  118. output = self.fake_quant_act(output)
  119. return output
  120. class QuantizationAwareTraining(Quantizer):
  121. r"""
  122. Quantizer for quantization aware training.
  123. Args:
  124. bn_fold (bool): Whether to use bn fold ops for simulation inference operation. Default: True.
  125. freeze_bn (int): Number of steps after which BatchNorm OP parameters fixed to global mean and variance.
  126. Default: 1e7.
  127. quant_delay (Union[int, list, tuple]): Number of steps after which weights and activations are quantized
  128. during train and eval. The first element represents weights and the second element represents data flow.
  129. Default: (0, 0).
  130. quant_dtype (Union[QuantDtype, list, tuple]): Datatype used to quantize weights and activations. The first
  131. element represents weights and the second element represents data flow. It is necessary to consider the
  132. precision support of hardware devices in the practical quantization infer scenario.
  133. Default: (QuantDtype.INT8, QuantDtype.INT8).
  134. per_channel (Union[bool, list, tuple]): Quantization granularity based on layer or on channel. If `True`
  135. then base on per channel, otherwise base on per layer. The first element represents weights and the
  136. second element represents data flow, and the second element must be `False` now. Default: (False, False).
  137. symmetric (Union[bool, list, tuple]): Whether the quantization algorithm is symmetric or not. If `True` then
  138. base on symmetric, otherwise base on asymmetric. The first element represents weights and the second
  139. element represents data flow. Default: (False, False).
  140. narrow_range (Union[bool, list, tuple]): Whether the quantization algorithm uses narrow range or not.
  141. The first element represents weights and the second element represents data flow.
  142. Default: (False, False).
  143. optimize_option (Union[OptimizeOption, list, tuple]): Specifies the quant algorithm and options, currently
  144. only support `QAT` and `LEARNED_SCALE` (Note that, if both `QAT` and `LEARNED_SCALE` are configured,
  145. `LEARNED_SCALE` has a higher priority. `LEARNED_SCALE` currently only work under some constraints, which
  146. includes: freeze_bn=0, quant_delay=0, symmetric=True, narrow_range=True, More specifically, for operators
  147. such as Relu and Relu6, which only have positive values, we add a negative truncation to optimize this
  148. scenario, and narrow_range will automatically match to False). Default: OptimizeOption.QAT.
  149. one_conv_fold (bool): Whether to use one conv bn fold ops for simulation inference operation. Default: True.
  150. Raises:
  151. TypeError: If the element of `quant_delay` or `freeze_bn` is not int.
  152. TypeError: If `bn_fold`, `one_conv_fold` or the element of `per_channel`, `symmetric`, `narrow_range`
  153. is not bool.
  154. TypeError: If the element of `quant_dtype` is not `QuantDtype`.
  155. ValueError: If the length of `quant_delay`, `quant_dtype`, `per_channel`, `symmetric` or `narrow_range` is
  156. not less than 2.
  157. ValueError: If the `optimize_option` is `LEARNED_SCALE` and `freeze_bn` is not equal to 0.
  158. ValueError: If the `optimize_option` is `LEARNED_SCALE` and `symmetric` is not (True, True).
  159. ValueError: If the `optimize_option` is `LEARNED_SCALE` and `narrow_range` is not (True, True).
  160. ValueError: If the `optimize_option` is `LEARNED_SCALE` and `quant_delay` is not (0, 0).
  161. Examples:
  162. >>> from mindspore.compression.quant import QuantizationAwareTraining
  163. >>> class LeNet5(nn.Cell):
  164. ... def __init__(self, num_class=10, channel=1):
  165. ... super(LeNet5, self).__init__()
  166. ... self.type = "fusion"
  167. ... self.num_class = num_class
  168. ...
  169. ... # change `nn.Conv2d` to `nn.Conv2dBnAct`
  170. ... self.conv1 = nn.Conv2dBnAct(channel, 6, 5, pad_mode='valid', activation='relu')
  171. ... self.conv2 = nn.Conv2dBnAct(6, 16, 5, pad_mode='valid', activation='relu')
  172. ... # change `nn.Dense` to `nn.DenseBnAct`
  173. ... self.fc1 = nn.DenseBnAct(16 * 5 * 5, 120, activation='relu')
  174. ... self.fc2 = nn.DenseBnAct(120, 84, activation='relu')
  175. ... self.fc3 = nn.DenseBnAct(84, self.num_class)
  176. ...
  177. ... self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  178. ... self.flatten = nn.Flatten()
  179. ...
  180. ... def construct(self, x):
  181. ... x = self.conv1(x)
  182. ... x = self.max_pool2d(x)
  183. ... x = self.conv2(x)
  184. ... x = self.max_pool2d(x)
  185. ... x = self.flatten(x)
  186. ... x = self.fc1(x)
  187. ... x = self.fc2(x)
  188. ... x = self.fc3(x)
  189. ... return x
  190. ...
  191. >>> net = LeNet5()
  192. >>> quantizer = QuantizationAwareTraining(bn_fold=False, per_channel=[True, False], symmetric=[True, False])
  193. >>> net_qat = quantizer.quantize(net)
  194. """
  195. __quant_op_name__ = ["Add", "Sub", "Mul", "RealDiv", "ReduceMean"]
  196. def __init__(self,
  197. bn_fold=True,
  198. freeze_bn=10000000,
  199. quant_delay=(0, 0),
  200. quant_dtype=(QuantDtype.INT8, QuantDtype.INT8),
  201. per_channel=(False, False),
  202. symmetric=(False, False),
  203. narrow_range=(False, False),
  204. optimize_option=OptimizeOption.QAT,
  205. one_conv_fold=True):
  206. """Init for QuantizationAwareTraining quantizer"""
  207. super(QuantizationAwareTraining, self).__init__(optimize_option=optimize_option)
  208. def convert2list(name, value):
  209. if not isinstance(value, list) and not isinstance(value, tuple):
  210. value = [value]
  211. elif len(value) > 2:
  212. raise ValueError("input `{}` len should less then 2".format(name))
  213. return value
  214. quant_delay = convert2list("quant delay", quant_delay)
  215. quant_dtype = convert2list("quant dtype", quant_dtype)
  216. per_channel = convert2list("per channel", per_channel)
  217. symmetric = convert2list("symmetric", symmetric)
  218. narrow_range = convert2list("narrow range", narrow_range)
  219. self.weight_qdelay = Validator.check_non_negative_int(quant_delay[0], "quant delay")
  220. self.act_qdelay = Validator.check_int(quant_delay[-1], 0, Rel.GE, "quant delay")
  221. self.bn_fold = Validator.check_bool(bn_fold, "bn fold")
  222. self.freeze_bn = Validator.check_non_negative_int(freeze_bn, "freeze bn")
  223. self.weight_dtype = Validator.check_isinstance("weights dtype", quant_dtype[0], QuantDtype)
  224. self.act_dtype = Validator.check_isinstance("activations dtype", quant_dtype[-1], QuantDtype)
  225. self.weight_channel = Validator.check_bool(per_channel[0], "per channel")
  226. self.act_channel = Validator.check_bool(per_channel[-1], "per channel")
  227. self.weight_symmetric = Validator.check_bool(symmetric[0], "symmetric")
  228. self.act_symmetric = Validator.check_bool(symmetric[-1], "symmetric")
  229. self.weight_range = Validator.check_bool(narrow_range[0], "narrow range")
  230. self.act_range = Validator.check_bool(narrow_range[-1], "narrow range")
  231. self.one_conv_fold = Validator.check_bool(one_conv_fold, "one conv fold")
  232. self._convert_method_map = {nn.Conv2dBnAct: self._convert_conv,
  233. nn.DenseBnAct: self._convert_dense}
  234. self.mode = "DEFAULT"
  235. if OptimizeOption.LEARNED_SCALE in self.optimize_option:
  236. self.mode = "LEARNED_SCALE"
  237. if not self.weight_symmetric or not self.act_symmetric:
  238. raise ValueError("OptimizeOption.LEARNED_SCALE currently only support "
  239. "symmetric=(True, True) for quant")
  240. if not self.weight_range or not self.act_range:
  241. raise ValueError("OptimizeOption.LEARNED_SCALE currently only support narrow_range=(True, True) "
  242. "for quant")
  243. if self.freeze_bn != 0:
  244. raise ValueError("OptimizeOption.LEARNED_SCALE currently only support freeze_bn equal to 0, "
  245. "but get freeze_bn={}".format(self.freeze_bn))
  246. if self.weight_qdelay != 0 or self.act_qdelay != 0:
  247. raise ValueError("OptimizeOption.LEARNED_SCALE currently only support quant_delay=(0, 0)")
  248. self.quant_config = create_quant_config(quant_delay=quant_delay,
  249. quant_dtype=quant_dtype,
  250. per_channel=per_channel,
  251. symmetric=symmetric,
  252. narrow_range=narrow_range,
  253. mode=self.mode)
  254. self.eps = 1e-5
  255. @staticmethod
  256. def _convert_op_name(name):
  257. pattern = re.compile(r'([A-Z]{1})')
  258. name_new = re.sub(pattern, r'_\1', name).lower()
  259. if name_new[0] == '_':
  260. name_new = name_new[1:]
  261. return name_new
  262. def quantize(self, network):
  263. """
  264. Quant API to convert input network to a quantization aware training network.
  265. Note:
  266. Please refer to the Examples of class: `mindspore.compression.quant.QuantizationAwareTraining`.
  267. Args:
  268. network (Cell): network to be quantized.
  269. Returns:
  270. Cell, a quantization aware training network.
  271. Raises:
  272. KeyError: If the `device_target` set in context is not in `support_device`.
  273. """
  274. support_device = ["Ascend", "GPU"]
  275. if context.get_context('device_target') not in support_device:
  276. raise KeyError("Unsupported {} device target.".format(context.get_context('device_target')))
  277. if OptimizeOption.QAT in self.optimize_option or OptimizeOption.LEARNED_SCALE in self.optimize_option:
  278. network.update_cell_prefix()
  279. network = self._convert_subcells2quant(network)
  280. network.update_cell_type("quant")
  281. return network
  282. def _convert_subcells2quant(self, network):
  283. """
  284. convert sub cell like `Conv2dBnAct` and `DenseBnAct` to quant cell
  285. """
  286. cells = network.name_cells()
  287. change = False
  288. for name in cells:
  289. subcell = cells[name]
  290. if subcell == network:
  291. continue
  292. elif isinstance(subcell, (nn.Conv2dBnAct, nn.DenseBnAct)):
  293. prefix = subcell.param_prefix
  294. new_subcell = self._convert_method_map[type(subcell)](subcell)
  295. new_subcell.update_parameters_name(prefix + '.')
  296. network.insert_child_to_cell(name, new_subcell)
  297. change = True
  298. else:
  299. self._convert_subcells2quant(subcell)
  300. if isinstance(network, nn.SequentialCell) and change:
  301. network.cell_list = list(network.cells())
  302. # add FakeQuant OP after OP in white list, but not including those wrapped in the below quantization cell.
  303. if isinstance(network, (nn.FakeQuantWithMinMaxObserver,
  304. nn.Conv2dBnFoldQuantOneConv,
  305. nn.Conv2dBnFoldQuant,
  306. nn.Conv2dBnWithoutFoldQuant,
  307. nn.Conv2dQuant,
  308. nn.DenseQuant,
  309. nn.ActQuant,
  310. nn.TensorAddQuant,
  311. nn.MulQuant)):
  312. return network
  313. add_list = []
  314. for name in network.__dict__:
  315. if name[0] == '_':
  316. continue
  317. attr = network.__dict__[name]
  318. if isinstance(attr, ops.Primitive) and attr.name in self.__quant_op_name__:
  319. add_list.append((name, attr))
  320. for name, prim_op in add_list:
  321. prefix = name
  322. add_quant = _AddFakeQuantAfterSubCell(prim_op,
  323. quant_dtype=self.act_dtype,
  324. quant_delay=self.act_qdelay,
  325. per_channel=self.act_channel,
  326. symmetric=self.act_symmetric,
  327. narrow_range=self.act_range,
  328. optimize_option=self.optimize_option)
  329. if network.param_prefix:
  330. prefix = '.'.join([network.param_prefix, prefix])
  331. add_quant.update_parameters_name(prefix + '.')
  332. del network.__dict__[name]
  333. network.insert_child_to_cell(name, add_quant)
  334. return network
  335. def _convert_conv(self, subcell):
  336. """
  337. convert Conv2d cell to quant cell
  338. """
  339. min_init = -6
  340. max_init = 6
  341. if OptimizeOption.LEARNED_SCALE in self.optimize_option:
  342. subcell_weight_para = subcell.conv.weight.data.asnumpy()
  343. if subcell.has_bn:
  344. scale_factor = (subcell.batchnorm.gamma.data.asnumpy() /
  345. np.sqrt(subcell.batchnorm.moving_variance.data.asnumpy() + self.eps))
  346. subcell_weight_para = subcell_weight_para * scale_factor.reshape(-1, 1, 1, 1)
  347. min_init, max_init = self._kl_init(subcell_weight_para, self.weight_dtype)
  348. self.quant_config = self.quant_config._replace(
  349. weight=self.quant_config.weight.partial_init(min_init=min_init, max_init=max_init))
  350. conv_inner = subcell.conv
  351. if subcell.has_bn:
  352. bn_inner = subcell.batchnorm
  353. if self.bn_fold:
  354. if self.one_conv_fold:
  355. conv_inner = quant.Conv2dBnFoldQuantOneConv(conv_inner.in_channels,
  356. conv_inner.out_channels,
  357. kernel_size=conv_inner.kernel_size,
  358. stride=conv_inner.stride,
  359. pad_mode=conv_inner.pad_mode,
  360. padding=conv_inner.padding,
  361. dilation=conv_inner.dilation,
  362. group=conv_inner.group,
  363. eps=bn_inner.eps,
  364. momentum=1 - bn_inner.momentum,
  365. has_bias=conv_inner.has_bias,
  366. bias_init=conv_inner.bias_init,
  367. quant_config=self.quant_config,
  368. quant_dtype=self.weight_dtype,
  369. fake=True)
  370. else:
  371. conv_inner = quant.Conv2dBnFoldQuant(conv_inner.in_channels,
  372. conv_inner.out_channels,
  373. kernel_size=conv_inner.kernel_size,
  374. stride=conv_inner.stride,
  375. pad_mode=conv_inner.pad_mode,
  376. padding=conv_inner.padding,
  377. dilation=conv_inner.dilation,
  378. group=conv_inner.group,
  379. eps=bn_inner.eps,
  380. momentum=1 - bn_inner.momentum,
  381. has_bias=conv_inner.has_bias,
  382. bias_init=conv_inner.bias_init,
  383. freeze_bn=self.freeze_bn,
  384. quant_config=self.quant_config,
  385. quant_dtype=self.weight_dtype,
  386. fake=True)
  387. # change original network Batch Normalization OP parameters to quant network
  388. conv_inner.gamma = subcell.batchnorm.gamma
  389. conv_inner.beta = subcell.batchnorm.beta
  390. conv_inner.moving_mean = subcell.batchnorm.moving_mean
  391. conv_inner.moving_variance = subcell.batchnorm.moving_variance
  392. else:
  393. conv_inner = quant.Conv2dBnWithoutFoldQuant(conv_inner.in_channels,
  394. conv_inner.out_channels,
  395. kernel_size=conv_inner.kernel_size,
  396. stride=conv_inner.stride,
  397. pad_mode=conv_inner.pad_mode,
  398. padding=conv_inner.padding,
  399. dilation=conv_inner.dilation,
  400. group=conv_inner.group,
  401. eps=bn_inner.eps,
  402. momentum=1 - bn_inner.momentum,
  403. has_bias=conv_inner.has_bias,
  404. bias_init=conv_inner.bias_init,
  405. quant_config=self.quant_config,
  406. quant_dtype=self.weight_dtype)
  407. # change original network Batch Normalization OP parameters to quant network
  408. conv_inner.batchnorm.gamma = subcell.batchnorm.gamma
  409. conv_inner.batchnorm.beta = subcell.batchnorm.beta
  410. conv_inner.batchnorm.moving_mean = subcell.batchnorm.moving_mean
  411. conv_inner.batchnorm.moving_variance = subcell.batchnorm.moving_variance
  412. del subcell.batchnorm
  413. subcell.batchnorm = None
  414. subcell.has_bn = False
  415. else:
  416. conv_inner = quant.Conv2dQuant(conv_inner.in_channels, conv_inner.out_channels,
  417. kernel_size=conv_inner.kernel_size, stride=conv_inner.stride,
  418. pad_mode=conv_inner.pad_mode, padding=conv_inner.padding,
  419. dilation=conv_inner.dilation, group=conv_inner.group,
  420. has_bias=conv_inner.has_bias, quant_config=self.quant_config,
  421. quant_dtype=self.weight_dtype)
  422. # change original network Conv2D OP parameters to quant network
  423. conv_inner.weight = subcell.conv.weight
  424. if subcell.conv.has_bias:
  425. conv_inner.bias = subcell.conv.bias
  426. subcell.conv = conv_inner
  427. if subcell.has_act and subcell.activation is not None:
  428. subcell.activation = self._convert_activation(subcell.activation)
  429. elif subcell.after_fake:
  430. subcell.has_act = True
  431. subcell.activation = _AddFakeQuantAfterSubCell(F.identity, quant_dtype=self.act_dtype,
  432. quant_delay=self.act_qdelay, per_channel=self.act_channel,
  433. symmetric=self.act_symmetric, narrow_range=self.act_range,
  434. optimize_option=self.optimize_option)
  435. return subcell
  436. def _convert_dense(self, subcell):
  437. """
  438. convert dense cell to quant cell
  439. """
  440. min_init = -6
  441. max_init = 6
  442. if OptimizeOption.LEARNED_SCALE in self.optimize_option:
  443. subcell_weight_para = subcell.dense.weight.data.asnumpy()
  444. if subcell.has_bn:
  445. scale_factor = (subcell.batchnorm.gamma.data.asnumpy() /
  446. np.sqrt(subcell.batchnorm.moving_variance.data.asnumpy() + self.eps))
  447. subcell_weight_para = subcell_weight_para * scale_factor.reshape(-1, 1, 1, 1)
  448. min_init, max_init = self._kl_init(subcell_weight_para, self.weight_dtype)
  449. self.quant_config = self.quant_config._replace(
  450. weight=self.quant_config.weight.partial_init(min_init=min_init, max_init=max_init))
  451. dense_inner = subcell.dense
  452. dense_inner = quant.DenseQuant(dense_inner.in_channels,
  453. dense_inner.out_channels,
  454. has_bias=dense_inner.has_bias,
  455. quant_config=self.quant_config,
  456. quant_dtype=self.weight_dtype)
  457. # change original network Dense OP parameters to quant network
  458. dense_inner.weight = subcell.dense.weight
  459. if subcell.dense.has_bias:
  460. dense_inner.bias = subcell.dense.bias
  461. subcell.dense = dense_inner
  462. if subcell.has_act and subcell.activation is not None:
  463. subcell.activation = self._convert_activation(subcell.activation)
  464. elif subcell.after_fake:
  465. subcell.has_act = True
  466. subcell.activation = _AddFakeQuantAfterSubCell(F.identity,
  467. quant_dtype=self.act_dtype,
  468. quant_delay=self.act_qdelay,
  469. per_channel=self.act_channel,
  470. symmetric=self.act_symmetric,
  471. narrow_range=self.act_range,
  472. optimize_option=self.optimize_option)
  473. return subcell
  474. def _convert_activation(self, activation):
  475. """
  476. convert activation cell to quant cell
  477. """
  478. act_class = activation.__class__
  479. act_list = [nn.ReLU, nn.ReLU6, nn.Sigmoid]
  480. act_list_with_fake_before = [nn.LeakyReLU, nn.HSigmoid, nn.HSwish]
  481. if act_class in act_list:
  482. return quant.ActQuant(activation=activation,
  483. quant_config=self.quant_config,
  484. quant_dtype=self.act_dtype)
  485. if act_class in act_list_with_fake_before:
  486. return quant.ActQuant(activation=activation,
  487. ema=True,
  488. fake_before=True,
  489. quant_config=self.quant_config,
  490. quant_dtype=self.act_dtype)
  491. raise ValueError("Unsupported activation in auto quant: ", act_class)
  492. def _kl_init(self, subcell_weight_para, weight_dtype):
  493. """
  494. Calculate the value of max_init and min_init with compute_kl_threshold.
  495. """
  496. if self.weight_channel:
  497. max_init = [compute_kl_threshold(weight_para_each, weight_dtype)
  498. for weight_para_each in subcell_weight_para]
  499. min_init = [-x for x in max_init]
  500. else:
  501. max_init = [compute_kl_threshold(subcell_weight_para, weight_dtype)]
  502. min_init = [-x for x in max_init]
  503. return min_init, max_init
  504. def _set_mixed_bits(self, network, strategy):
  505. r"""
  506. Set network's quantization strategy, this function is currently only valid for `LEARNED_SCALE`
  507. optimize_option.
  508. Args:
  509. network (Cell): Input network.
  510. strategy (list): The quantization strategy for layers that need to be quantified (eg. [[8], [8],
  511. ..., [6], [4], [8]]), currently only the quant_dtype for weights of the dense layer and the
  512. convolution layer is supported.
  513. Returns:
  514. Cell, a network with mixed bit strategy configured.
  515. Raises:
  516. ValueError: If `OptimizeOption.LEARNED_SCALE` is not in `self.optimize_option`.
  517. """
  518. if OptimizeOption.LEARNED_SCALE not in self.optimize_option:
  519. raise ValueError("The `_set_mixed_bits` function is currently only valid for `LEARNED_SCALE` "
  520. "optimize_option.")
  521. quantizable_idx = []
  522. pass_cell = None
  523. for i, cell_and_name in enumerate(network.cells_and_names()):
  524. cell = cell_and_name[1]
  525. if isinstance(cell, (nn.Conv2dBnAct, nn.DenseBnAct)) and cell is not pass_cell:
  526. quantizable_idx.append(i)
  527. if len(quantizable_idx) != len(strategy):
  528. raise ValueError("The dimension of quantifiable layers is not consistent with that of strategy.")
  529. quantizable_layer_bit_dict = {idx: bit for idx, bit in zip(quantizable_idx, strategy)}
  530. type_map = {
  531. QuantDtype.INT2.num_bits: QuantDtype.INT2,
  532. QuantDtype.INT3.num_bits: QuantDtype.INT3,
  533. QuantDtype.INT4.num_bits: QuantDtype.INT4,
  534. QuantDtype.INT5.num_bits: QuantDtype.INT5,
  535. QuantDtype.INT6.num_bits: QuantDtype.INT6,
  536. QuantDtype.INT7.num_bits: QuantDtype.INT7,
  537. QuantDtype.INT8.num_bits: QuantDtype.INT8
  538. }
  539. for i, cell_and_name in enumerate(network.cells_and_names()):
  540. cell = cell_and_name[1]
  541. if i not in quantizable_idx:
  542. continue
  543. else:
  544. if isinstance(cell, (nn.Conv2dBnAct, nn.DenseBnAct)):
  545. cell.weight_dtype = type_map[quantizable_layer_bit_dict[i][0]]
  546. if isinstance(cell, nn.Conv2dBnAct):
  547. subcell_weight_para = cell.conv.weight.data.asnumpy()
  548. if hasattr(cell.conv, 'gamma'):
  549. scale_factor = (cell.conv.gamma.data.asnumpy() /
  550. np.sqrt(cell.conv.moving_variance.data.asnumpy() + self.eps))
  551. subcell_weight_para = subcell_weight_para * scale_factor.reshape(-1, 1, 1, 1)
  552. min_init, max_init = self._kl_init(subcell_weight_para, cell.weight_dtype)
  553. cell.conv.fake_quant_weight.reset(quant_dtype=cell.weight_dtype,
  554. min_init=min_init,
  555. max_init=max_init)
  556. elif isinstance(cell, nn.DenseBnAct):
  557. subcell_weight_para = cell.dense.weight.data.asnumpy()
  558. if hasattr(cell.dense, 'gamma'):
  559. scale_factor = (cell.dense.gamma.data.asnumpy() /
  560. np.sqrt(cell.dense.moving_variance.data.asnumpy() + self.eps))
  561. subcell_weight_para = subcell_weight_para * scale_factor.reshape(-1, 1, 1, 1)
  562. min_init, max_init = self._kl_init(subcell_weight_para, cell.weight_dtype)
  563. cell.dense.fake_quant_weight.reset(quant_dtype=cell.weight_dtype,
  564. min_init=min_init,
  565. max_init=max_init)
  566. return network