quantize_jit.py 14 KB

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