quantize_jit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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.keys()):
  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.keys()):
  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. assert quant_type == QuantType.DYNAMIC, (
  133. "This API, while should work for static quant, is only tested for dynamic quant."
  134. )
  135. assert not method_name.startswith("observe_"), (
  136. "Pass in valid method to be quantized, e.g. forward"
  137. )
  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. assert run_fn, (
  196. "Must provide calibration function for post training static quantization"
  197. )
  198. assert run_args, (
  199. "Must provide calibration dataset for post training static quantization"
  200. )
  201. model = prepare_jit(model, qconfig_dict, inplace)
  202. run_fn(model, *run_args)
  203. model = convert_jit(model, True, debug)
  204. torch._C._jit_pass_constant_propagation(model.graph)
  205. torch._C._jit_pass_dce(model.graph)
  206. return model
  207. def quantize_jit(model, qconfig_dict, run_fn, run_args, inplace=False, debug=False):
  208. r"""Quantize the input float TorchScript model with
  209. post training static quantization.
  210. First it will prepare the model for calibration, then it calls
  211. `run_fn` which will run the calibration step, after that we will
  212. convert the model to a quantized model.
  213. Args:
  214. `model`: input float TorchScript model
  215. `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
  216. qconfig for that module as value, empty key means the qconfig will be applied
  217. to whole model unless it's overwritten by more specific configurations, the
  218. qconfig for each module is either found in the dictionary or fallback to
  219. the qconfig of parent module.
  220. Right now qconfig_dict is the only way to configure how the model is quantized,
  221. and it is done in the granularity of module, that is, we only support one type
  222. of qconfig for each torch.nn.Module, and the qconfig for sub module will
  223. override the qconfig for parent module, empty string means global configuration.
  224. `run_fn`: a calibration function for calibrating the prepared model
  225. `run_args`: positional arguments for `run_fn`
  226. `inplace`: carry out model transformations in-place, the original module is
  227. mutated
  228. `debug`: flag for producing a debug friendly model (preserve weight attribute)
  229. Return:
  230. Quantized TorchSciprt model.
  231. Example:
  232. ```python
  233. import torch
  234. from torch.ao.quantization import get_default_qconfig
  235. from torch.ao.quantization import quantize_jit
  236. ts_model = torch.jit.script(
  237. float_model.eval()
  238. ) # or torch.jit.trace(float_model, input)
  239. qconfig = get_default_qconfig("fbgemm")
  240. def calibrate(model, data_loader):
  241. model.eval()
  242. with torch.no_grad():
  243. for image, target in data_loader:
  244. model(image)
  245. quantized_model = quantize_jit(
  246. ts_model, {"": qconfig}, calibrate, [data_loader_test]
  247. )
  248. ```
  249. """
  250. torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_jit")
  251. return _quantize_jit(
  252. model,
  253. qconfig_dict,
  254. run_fn,
  255. run_args,
  256. inplace,
  257. debug,
  258. quant_type=QuantType.STATIC,
  259. )
  260. def quantize_dynamic_jit(model, qconfig_dict, inplace=False, debug=False):
  261. r"""Quantize the input float TorchScript model with
  262. post training dynamic quantization.
  263. Currently only qint8 quantization of torch.nn.Linear is supported.
  264. Args:
  265. `model`: input float TorchScript model
  266. `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
  267. qconfig for that module as value, please see detailed
  268. descriptions in :func:`~torch.ao.quantization.quantize_jit`
  269. `inplace`: carry out model transformations in-place, the original module is
  270. mutated
  271. `debug`: flag for producing a debug friendly model (preserve weight attribute)
  272. Return:
  273. Quantized TorchSciprt model.
  274. Example:
  275. ```python
  276. import torch
  277. from torch.ao.quantization import per_channel_dynamic_qconfig
  278. from torch.ao.quantization import quantize_dynamic_jit
  279. ts_model = torch.jit.script(
  280. float_model.eval()
  281. ) # or torch.jit.trace(float_model, input)
  282. qconfig = get_default_qconfig("fbgemm")
  283. def calibrate(model, data_loader):
  284. model.eval()
  285. with torch.no_grad():
  286. for image, target in data_loader:
  287. model(image)
  288. quantized_model = quantize_dynamic_jit(
  289. ts_model, {"": qconfig}, calibrate, [data_loader_test]
  290. )
  291. ```
  292. """
  293. torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_dynamic_jit")
  294. return _quantize_jit(
  295. model, qconfig_dict, inplace=inplace, debug=debug, quant_type=QuantType.DYNAMIC
  296. )
  297. def _quantize_ondevice_dynamic_jit(
  298. model, qconfig_dict, method_name="forward", inplace=False
  299. ):
  300. r"""Prepares the input float TorchScript model with
  301. *on-device* post training dynamic quantization.
  302. Currently only qint8 quantization of torch.nn.Linear is supported.
  303. Args:
  304. `model`: input float TorchScript model
  305. `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
  306. qconfig for that module as value, please see detailed
  307. `method_name`: Name of the method within the model, to be prepared for quantization
  308. descriptions in :func:`~torch.ao.quantization.quantize_jit`
  309. `inplace`: carry out model transformations in-place, the original module is
  310. mutated
  311. Return:
  312. TorchScript model that is ready for on device quantization.
  313. This means that the returned
  314. model has:
  315. - Method is inlined.
  316. - Model has observer modules inserted in the model.
  317. - Model has packed params inserted in the model. However they are empty as in they dont
  318. contain valid quantized weights.
  319. - observe_<method_name> is added that observe the values to be quantized.
  320. - reset_observers_<method_name> to reset observers.
  321. - quantize_<method_name> is added to the model.
  322. - This method extract scale, zero points.
  323. - Quantizes observed weights.
  324. - Creates packed params from it and update the attribute of the model with the new values
  325. for the packed params.
  326. - Reset the original fp32 weights with empty tensor using SetAttr.
  327. - quantized_<method_name> is added to the model.
  328. - This method uses quantized weights and quantized linear ops instead of fp32 op.
  329. - This method should be used for inference post PTQ.
  330. - Note that all method's signatures should be the same as method_name.
  331. Later on device:
  332. - Run reset_observers_<method_name>
  333. - Run observe_<method_name>
  334. - Run quantize_<method_name>
  335. - Now model can be saved and loaded later.
  336. - Run model with quantized_<method_name>
  337. Example:
  338. ```python
  339. import torch
  340. from torch.ao.quantization import per_channel_dynamic_qconfig
  341. from torch.ao.quantization.quantize_jit import _quantize_ondevice_dynamic_jit
  342. ts_model = torch.jit.script(
  343. float_model.eval()
  344. ) # or torch.jit.trace(float_model, input)
  345. qconfig = get_default_qconfig("fbgemm")
  346. quant_ready_model = _quantize_ondevice_dynamic_jit(
  347. ts_model, {"": qconfig}, "forward", True
  348. )
  349. ```
  350. """
  351. return _quantize_ondevice_dynamic_jit_impl(
  352. model, qconfig_dict, method_name, inplace=inplace
  353. )