quantize_jit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import torch
  2. from torch.ao.quantization.qconfig import QConfig
  3. from torch.ao.quantization.quant_type import QuantType
  4. from torch.jit._recursive import wrap_cpp_module
  5. __all__ = [
  6. "script_qconfig",
  7. "script_qconfig_dict",
  8. "fuse_conv_bn_jit",
  9. "prepare_jit",
  10. "prepare_dynamic_jit",
  11. "convert_jit",
  12. "convert_dynamic_jit",
  13. "quantize_jit",
  14. "quantize_dynamic_jit",
  15. ]
  16. def _check_is_script_module(model):
  17. if not isinstance(model, torch.jit.ScriptModule):
  18. raise ValueError('input must be a script module, got: ' + str(type(model)))
  19. def _check_forward_method(model):
  20. if not model._c._has_method('forward'):
  21. raise ValueError('input script module does not have forward method')
  22. def script_qconfig(qconfig):
  23. r"""Instantiate the activation and weight observer modules and script
  24. them, these observer module instances will be deepcopied during
  25. prepare_jit step.
  26. """
  27. return QConfig(
  28. activation=torch.jit.script(qconfig.activation())._c,
  29. weight=torch.jit.script(qconfig.weight())._c)
  30. def script_qconfig_dict(qconfig_dict):
  31. r"""Helper function used by `prepare_jit`.
  32. Apply `script_qconfig` for all entries in `qconfig_dict` that is
  33. not None.
  34. """
  35. return {k: script_qconfig(v) if v else None for k, v in qconfig_dict.items()}
  36. def fuse_conv_bn_jit(model, inplace=False):
  37. r""" Fuse conv - bn module
  38. Works for eval model only.
  39. Args:
  40. model: TorchScript model from scripting or tracing
  41. """
  42. torch._C._log_api_usage_once("quantization_api.quantize_jit.fuse_conv_bn_jit")
  43. model_c = model._c
  44. model_c = torch._C._jit_pass_fold_convbn(model_c)
  45. if inplace:
  46. model._reconstruct(model_c)
  47. else:
  48. model = wrap_cpp_module(model_c)
  49. return model
  50. def _prepare_jit(model, qconfig_dict, inplace=False, quant_type=QuantType.STATIC):
  51. _check_is_script_module(model)
  52. _check_forward_method(model)
  53. if not all(isinstance(x, str) for x in qconfig_dict.keys()):
  54. raise ValueError('qconfig_dict should only contain names(str) as keys.')
  55. scripted_qconfig_dict = script_qconfig_dict(qconfig_dict)
  56. model = fuse_conv_bn_jit(model, inplace)
  57. model_c = torch._C._jit_pass_insert_observers(model._c,
  58. 'forward',
  59. scripted_qconfig_dict,
  60. inplace,
  61. quant_type)
  62. if inplace:
  63. model._reconstruct(model_c)
  64. else:
  65. model = wrap_cpp_module(model_c)
  66. return model
  67. def _prepare_ondevice_jit(model, qconfig_dict, method_name='forward', inplace=False, quant_type=QuantType.STATIC):
  68. _check_is_script_module(model)
  69. if not all(isinstance(x, str) for x in qconfig_dict.keys()):
  70. raise ValueError('qconfig_dict should only contain names(str) as keys.')
  71. scripted_qconfig_dict = script_qconfig_dict(qconfig_dict)
  72. method_graph = model._c._get_method(method_name).graph
  73. torch._C._jit_pass_inline(method_graph)
  74. model = fuse_conv_bn_jit(model, inplace)
  75. model_c = torch._C._jit_pass_insert_observer_method_for_ondevice_ptq(model._c,
  76. method_name,
  77. scripted_qconfig_dict,
  78. inplace,
  79. quant_type)
  80. if inplace:
  81. model._reconstruct(model_c)
  82. else:
  83. model = wrap_cpp_module(model_c)
  84. return model
  85. def prepare_jit(model, qconfig_dict, inplace=False):
  86. torch._C._log_api_usage_once("quantization_api.quantize_jit.prepare_jit")
  87. return _prepare_jit(model, qconfig_dict, inplace, quant_type=QuantType.STATIC)
  88. def prepare_dynamic_jit(model, qconfig_dict, inplace=False):
  89. torch._C._log_api_usage_once("quantization_api.quantize_jit.prepare_dynamic_jit")
  90. return _prepare_jit(model, qconfig_dict, inplace, quant_type=QuantType.DYNAMIC)
  91. def _prepare_ondevice_dynamic_jit(model, qconfig_dict, method_name='forward', inplace=False):
  92. return _prepare_ondevice_jit(model, qconfig_dict, method_name, inplace, quant_type=QuantType.DYNAMIC)
  93. def _convert_jit(model, inplace=False, debug=False, quant_type=QuantType.STATIC,
  94. preserved_attrs=None):
  95. _check_is_script_module(model)
  96. model.eval()
  97. model_c = model._c
  98. model_c = torch._C._jit_pass_insert_quant_dequant(model_c, 'forward', inplace, debug, quant_type)
  99. if not debug:
  100. is_xpu = all(p.device.type == 'xpu' for p in model.parameters())
  101. if not is_xpu:
  102. # Moving model parameters to CPU since quantized operators
  103. # are only supported on CPU and XPU right now
  104. model.cpu()
  105. if preserved_attrs is None:
  106. preserved_attrs = []
  107. model_c = torch._C._jit_pass_quant_finalize(model_c, quant_type, preserved_attrs)
  108. if inplace:
  109. model._reconstruct(model_c)
  110. else:
  111. model = wrap_cpp_module(model_c)
  112. torch._C._jit_pass_constant_propagation(model.graph)
  113. torch._C._jit_pass_dce(model.graph)
  114. return model
  115. def _convert_ondevice_jit(model, method_name, inplace=False, debug=False, quant_type=QuantType.STATIC):
  116. _check_is_script_module(model)
  117. assert quant_type == QuantType.DYNAMIC, "This API, while should work for static quant, is only tested for dynamic quant."
  118. assert not method_name.startswith("observe_"), "Pass in valid method to be quantized, e.g. forward"
  119. observe_method_name = "observe_" + method_name
  120. quantize_method_name = "quantize_" + method_name
  121. model_c = model._c
  122. model_c = torch._C._jit_pass_insert_quant_dequant_for_ondevice_ptq(
  123. model._c, observe_method_name, inplace, debug, QuantType.DYNAMIC)
  124. model_c = torch._C._jit_pass_quant_finalize_for_ondevice_ptq(model_c, QuantType.DYNAMIC, quantize_method_name)
  125. if inplace:
  126. model._reconstruct(model_c)
  127. else:
  128. model = wrap_cpp_module(model_c)
  129. return model
  130. def convert_jit(model, inplace=False, debug=False, preserved_attrs=None):
  131. torch._C._log_api_usage_once("quantization_api.quantize_jit.convert_jit")
  132. return _convert_jit(model, inplace, debug, quant_type=QuantType.STATIC, preserved_attrs=preserved_attrs)
  133. def convert_dynamic_jit(model, inplace=False, debug=False, preserved_attrs=None):
  134. torch._C._log_api_usage_once("quantization_api.quantize_jit.convert_dynamic_jit")
  135. return _convert_jit(model, inplace, debug, quant_type=QuantType.DYNAMIC, preserved_attrs=preserved_attrs)
  136. def _convert_ondevice_dynamic_jit(model, method_name, inplace=False, debug=False):
  137. return _convert_ondevice_jit(model, method_name, inplace, debug, quant_type=QuantType.DYNAMIC)
  138. def _quantize_ondevice_dynamic_jit_impl(model, qconfig_dict, method_name, inplace=False):
  139. model = _prepare_ondevice_dynamic_jit(model, qconfig_dict, method_name, inplace)
  140. model = _convert_ondevice_dynamic_jit(model, method_name, inplace)
  141. return model
  142. def _quantize_jit(model, qconfig_dict, run_fn=None, run_args=None, inplace=False, debug=False, quant_type=QuantType.STATIC):
  143. # Always do inplace convert because the Tensor is already
  144. # copied in prepare_jit when inplace is False
  145. if quant_type == QuantType.DYNAMIC:
  146. model = prepare_dynamic_jit(model, qconfig_dict, inplace)
  147. model = convert_dynamic_jit(model, True, debug)
  148. else:
  149. assert run_fn, "Must provide calibration function for post training static quantization"
  150. assert run_args, "Must provide calibration dataset for post training static quantization"
  151. model = prepare_jit(model, qconfig_dict, inplace)
  152. run_fn(model, *run_args)
  153. model = convert_jit(model, True, debug)
  154. torch._C._jit_pass_constant_propagation(model.graph)
  155. torch._C._jit_pass_dce(model.graph)
  156. return model
  157. def quantize_jit(model, qconfig_dict, run_fn, run_args, inplace=False, debug=False):
  158. r"""Quantize the input float TorchScript model with
  159. post training static quantization.
  160. First it will prepare the model for calibration, then it calls
  161. `run_fn` which will run the calibration step, after that we will
  162. convert the model to a quantized model.
  163. Args:
  164. `model`: input float TorchScript model
  165. `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
  166. qconfig for that module as value, empty key means the qconfig will be applied
  167. to whole model unless it's overwritten by more specific configurations, the
  168. qconfig for each module is either found in the dictionary or fallback to
  169. the qconfig of parent module.
  170. Right now qconfig_dict is the only way to configure how the model is quantized,
  171. and it is done in the granularity of module, that is, we only support one type
  172. of qconfig for each torch.nn.Module, and the qconfig for sub module will
  173. override the qconfig for parent module, empty string means global configuration.
  174. `run_fn`: a calibration function for calibrating the prepared model
  175. `run_args`: positional arguments for `run_fn`
  176. `inplace`: carry out model transformations in-place, the original module is
  177. mutated
  178. `debug`: flag for producing a debug friendly model (preserve weight attribute)
  179. Return:
  180. Quantized TorchSciprt model.
  181. Example:
  182. ```python
  183. import torch
  184. from torch.ao.quantization import get_default_qconfig
  185. from torch.ao.quantization import quantize_jit
  186. ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input)
  187. qconfig = get_default_qconfig('fbgemm')
  188. def calibrate(model, data_loader):
  189. model.eval()
  190. with torch.no_grad():
  191. for image, target in data_loader:
  192. model(image)
  193. quantized_model = quantize_jit(
  194. ts_model,
  195. {'': qconfig},
  196. calibrate,
  197. [data_loader_test])
  198. ```
  199. """
  200. torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_jit")
  201. return _quantize_jit(model, qconfig_dict, run_fn, run_args, inplace, debug, quant_type=QuantType.STATIC)
  202. def quantize_dynamic_jit(model, qconfig_dict, inplace=False, debug=False):
  203. r"""Quantize the input float TorchScript model with
  204. post training dynamic quantization.
  205. Currently only qint8 quantization of torch.nn.Linear is supported.
  206. Args:
  207. `model`: input float TorchScript model
  208. `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
  209. qconfig for that module as value, please see detailed
  210. descriptions in :func:`~torch.ao.quantization.quantize_jit`
  211. `inplace`: carry out model transformations in-place, the original module is
  212. mutated
  213. `debug`: flag for producing a debug friendly model (preserve weight attribute)
  214. Return:
  215. Quantized TorchSciprt model.
  216. Example:
  217. ```python
  218. import torch
  219. from torch.ao.quantization import per_channel_dynamic_qconfig
  220. from torch.ao.quantization import quantize_dynmiac_jit
  221. ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input)
  222. qconfig = get_default_qconfig('fbgemm')
  223. def calibrate(model, data_loader):
  224. model.eval()
  225. with torch.no_grad():
  226. for image, target in data_loader:
  227. model(image)
  228. quantized_model = quantize_dynamic_jit(
  229. ts_model,
  230. {'': qconfig},
  231. calibrate,
  232. [data_loader_test])
  233. ```
  234. """
  235. torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_dynamic_jit")
  236. return _quantize_jit(model, qconfig_dict, inplace=inplace, debug=debug, quant_type=QuantType.DYNAMIC)
  237. def _quantize_ondevice_dynamic_jit(model, qconfig_dict, method_name='forward', inplace=False):
  238. r"""Prepares the input float TorchScript model with
  239. *on-device* post training dynamic quantization.
  240. Currently only qint8 quantization of torch.nn.Linear is supported.
  241. Args:
  242. `model`: input float TorchScript model
  243. `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
  244. qconfig for that module as value, please see detailed
  245. `method_name`: Name of the method within the model, to be prepared for quantization
  246. descriptions in :func:`~torch.ao.quantization.quantize_jit`
  247. `inplace`: carry out model transformations in-place, the original module is
  248. mutated
  249. Return:
  250. TorchScript model that is ready for on device quantization.
  251. This means that the returned
  252. model has:
  253. - Method is inlined.
  254. - Model has observer modules inserted in the model.
  255. - Model has packed params inserted in the model. However they are empty as in they dont
  256. contain valid quantized weights.
  257. - observe_<method_name> is added that observe the values to be quantized.
  258. - reset_observers_<method_name> to reset observers.
  259. - quantize_<method_name> is added to the model.
  260. - This method extract scale, zero points.
  261. - Quantizes observed weights.
  262. - Creates packed params from it and update the attribute of the model with the new values
  263. for the packed params.
  264. - Reset the original fp32 weights with empty tensor using SetAttr.
  265. - quantized_<method_name> is added to the model.
  266. - This method uses quantized weights and quantized linear ops instead of fp32 op.
  267. - This method should be used for inference post PTQ.
  268. - Note that all method's signatures should be the same as method_name.
  269. Later on device:
  270. - Run reset_observers_<method_name>
  271. - Run observe_<method_name>
  272. - Run quantize_<method_name>
  273. - Now model can be saved and loaded later.
  274. - Run model with quantized_<method_name>
  275. Example:
  276. ```python
  277. import torch
  278. from torch.ao.quantization import per_channel_dynamic_qconfig
  279. from torch.ao.quantization.quantize_jit import _quantize_ondevice_dynamic_jit
  280. ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input)
  281. qconfig = get_default_qconfig('fbgemm')
  282. quant_ready_model = _quantize_ondevice_dynamic_jit(
  283. ts_model,
  284. {'': qconfig},
  285. 'forward',
  286. True)
  287. ```
  288. """
  289. return _quantize_ondevice_dynamic_jit_impl(model, qconfig_dict, method_name, inplace=inplace)