qconfig_mapping.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # mypy: allow-untyped-defs
  2. from __future__ import annotations
  3. from collections import OrderedDict
  4. from typing import Any, Callable, Union
  5. import torch
  6. from .fake_quantize import default_weight_fake_quant, FixedQParamsFakeQuantize
  7. from .observer import (
  8. _PartialWrapper,
  9. default_fixed_qparams_range_0to1_observer,
  10. default_fixed_qparams_range_neg1to1_observer,
  11. default_placeholder_observer,
  12. default_weight_observer,
  13. )
  14. from .qconfig import (
  15. default_quint8_weight_qconfig,
  16. default_reuse_input_qconfig,
  17. default_symmetric_qnnpack_qat_qconfig,
  18. default_symmetric_qnnpack_qconfig,
  19. get_default_qat_qconfig,
  20. get_default_qconfig,
  21. QConfig,
  22. QConfigAny,
  23. )
  24. __all__ = [
  25. "get_default_qconfig_mapping",
  26. "get_default_qat_qconfig_mapping",
  27. "QConfigMapping",
  28. ]
  29. # TODO: replace all usages with these constants
  30. _GLOBAL_DICT_KEY = ""
  31. _OBJECT_TYPE_DICT_KEY = "object_type"
  32. _MODULE_NAME_REGEX_DICT_KEY = "module_name_regex"
  33. _MODULE_NAME_DICT_KEY = "module_name"
  34. _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY = "module_name_object_type_order"
  35. # TODO: derive this map from the BackendConfig
  36. _FIXED_QPARAMS_OP_TO_OBSERVER: dict[Union[Callable, str], _PartialWrapper] = {
  37. torch.nn.Hardsigmoid: default_fixed_qparams_range_0to1_observer,
  38. torch.nn.functional.hardsigmoid: default_fixed_qparams_range_0to1_observer,
  39. "hardsigmoid": default_fixed_qparams_range_0to1_observer,
  40. "hardsigmoid_": default_fixed_qparams_range_0to1_observer,
  41. torch.nn.Sigmoid: default_fixed_qparams_range_0to1_observer,
  42. torch.sigmoid: default_fixed_qparams_range_0to1_observer,
  43. "sigmoid": default_fixed_qparams_range_0to1_observer,
  44. "sigmoid_": default_fixed_qparams_range_0to1_observer,
  45. torch.nn.Softmax: default_fixed_qparams_range_0to1_observer,
  46. torch.nn.Tanh: default_fixed_qparams_range_neg1to1_observer,
  47. torch.tanh: default_fixed_qparams_range_neg1to1_observer,
  48. "tanh": default_fixed_qparams_range_neg1to1_observer,
  49. "tanh_": default_fixed_qparams_range_neg1to1_observer,
  50. }
  51. def _get_default_qconfig_mapping(
  52. is_qat: bool, backend: str, version: int
  53. ) -> QConfigMapping:
  54. """
  55. Return the default QConfigMapping for the given quantization type and backend.
  56. """
  57. if is_qat:
  58. qconfig = get_default_qat_qconfig(backend, version)
  59. else:
  60. qconfig = get_default_qconfig(backend, version)
  61. default_weight = default_weight_fake_quant if is_qat else default_weight_observer
  62. # default_per_channel_weight_observer is not currently compatible with fbgemm backend
  63. # so we have to modify the weight observer to default_weight_observer or another
  64. # per tensor supported observer.
  65. # see https://github.com/pytorch/pytorch/issues/47535
  66. if backend in ("fbgemm", "x86"):
  67. qconfig_transpose = QConfig(
  68. activation=qconfig.activation, weight=default_weight
  69. )
  70. else:
  71. qconfig_transpose = qconfig
  72. # currently layernorm only supports float weights
  73. # we have to add this because otherwise there will be a extra quantize-dequantize pair
  74. qconfig_layernorm = QConfig(
  75. activation=qconfig.activation, weight=default_placeholder_observer
  76. )
  77. qconfig_mapping = (
  78. QConfigMapping()
  79. .set_global(qconfig)
  80. .set_object_type("reshape", default_reuse_input_qconfig)
  81. .set_object_type(torch.nn.ConvTranspose1d, qconfig_transpose)
  82. .set_object_type(torch.nn.ConvTranspose2d, qconfig_transpose)
  83. .set_object_type(torch.nn.ConvTranspose3d, qconfig_transpose)
  84. .set_object_type(torch.nn.functional.conv_transpose1d, qconfig_transpose)
  85. .set_object_type(torch.nn.functional.conv_transpose2d, qconfig_transpose)
  86. .set_object_type(torch.nn.functional.conv_transpose3d, qconfig_transpose)
  87. .set_object_type(torch.nn.functional.layer_norm, qconfig_layernorm)
  88. .set_object_type(torch.nn.LayerNorm, qconfig_layernorm)
  89. .set_object_type(torch.nn.PReLU, default_quint8_weight_qconfig)
  90. )
  91. # Use special observers for ops with fixed qparams
  92. fixed_qparams_observer_to_qconfig: dict[Any, QConfigAny] = {}
  93. for fixed_qparams_op, observer in _FIXED_QPARAMS_OP_TO_OBSERVER.items():
  94. if observer in fixed_qparams_observer_to_qconfig:
  95. fixed_qparams_qconfig = fixed_qparams_observer_to_qconfig[observer]
  96. else:
  97. if is_qat:
  98. activation = FixedQParamsFakeQuantize.with_args(observer=observer)
  99. else:
  100. activation = observer
  101. fixed_qparams_qconfig = QConfig(
  102. activation=activation, weight=default_weight
  103. )
  104. fixed_qparams_observer_to_qconfig[observer] = fixed_qparams_qconfig
  105. qconfig_mapping.set_object_type(fixed_qparams_op, fixed_qparams_qconfig)
  106. # TODO Currently it's required that separate ops in a fused op/module have the same qconfig.
  107. # Need to be able to support fusion of ops with different qconfigs
  108. return qconfig_mapping
  109. def get_default_qconfig_mapping(backend="x86", version=0) -> QConfigMapping:
  110. """
  111. Return the default QConfigMapping for post training quantization.
  112. Args:
  113. * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be
  114. one of ["x86" (default), "fbgemm", "qnnpack", "onednn"]
  115. * ``version`` (int) : the version for the default qconfig mapping
  116. """
  117. # TODO: add assert for backend choices
  118. return _get_default_qconfig_mapping(False, backend, version)
  119. def get_default_qat_qconfig_mapping(backend="x86", version=1) -> QConfigMapping:
  120. """
  121. Return the default QConfigMapping for quantization aware training.
  122. Args:
  123. * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be
  124. one of ["x86" (default), "fbgemm", "qnnpack", "onednn"]
  125. * ``version`` (int) : the version for the default qconfig mapping
  126. """
  127. return _get_default_qconfig_mapping(True, backend, version)
  128. def _get_symmetric_qnnpack_qconfig_mapping() -> QConfigMapping:
  129. """
  130. Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qconfig`
  131. as the default QConfig.
  132. """
  133. default_qconfig = default_symmetric_qnnpack_qconfig
  134. return _get_default_qconfig_mapping_with_default_qconfig(
  135. False, "qnnpack", default_qconfig
  136. )
  137. def _get_symmetric_qnnpack_qat_qconfig_mapping() -> QConfigMapping:
  138. """
  139. Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qat_qconfig`
  140. as the default QConfig.
  141. """
  142. default_qconfig = default_symmetric_qnnpack_qat_qconfig
  143. return _get_default_qconfig_mapping_with_default_qconfig(
  144. True, "qnnpack", default_qconfig
  145. )
  146. def _get_default_qconfig_mapping_with_default_qconfig(
  147. is_qat: bool,
  148. backend: str,
  149. default_qconfig: QConfig,
  150. ) -> QConfigMapping:
  151. """
  152. Return a QConfigMapping that uses the provided qconfig as the default QConfig.
  153. """
  154. if is_qat:
  155. qconfig_mapping = get_default_qat_qconfig_mapping(backend)
  156. else:
  157. qconfig_mapping = get_default_qconfig_mapping(backend)
  158. qconfig_mapping.set_global(default_qconfig)
  159. for pattern in qconfig_mapping.object_type_qconfigs.keys():
  160. if pattern not in _FIXED_QPARAMS_OP_TO_OBSERVER:
  161. qconfig_mapping.set_object_type(pattern, default_qconfig)
  162. return qconfig_mapping
  163. _QCONFIG_STYLE_ORDER: list[str] = [
  164. "global_qconfig",
  165. "object_type_qconfigs",
  166. "module_name_regex_qconfigs",
  167. "module_name_qconfigs",
  168. "module_name_object_type_order_qconfigs",
  169. ]
  170. class QConfigMapping:
  171. """
  172. Mapping from model ops to :class:`torch.ao.quantization.QConfig` s.
  173. The user can specify QConfigs using the following methods (in increasing match priority):
  174. ``set_global`` : sets the global (default) QConfig
  175. ``set_object_type`` : sets the QConfig for a given module type, function, or method name
  176. ``set_module_name_regex`` : sets the QConfig for modules matching the given regex string
  177. ``set_module_name`` : sets the QConfig for modules matching the given module name
  178. ``set_module_name_object_type_order`` : sets the QConfig for modules matching a combination
  179. of the given module name, object type, and the index at which the module appears
  180. Example usage::
  181. qconfig_mapping = QConfigMapping()
  182. .set_global(global_qconfig)
  183. .set_object_type(torch.nn.Linear, qconfig1)
  184. .set_object_type(torch.nn.ReLU, qconfig1)
  185. .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
  186. .set_module_name_regex("foo.*", qconfig2)
  187. .set_module_name("module1", qconfig1)
  188. .set_module_name("module2", qconfig2)
  189. .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, qconfig3)
  190. """
  191. def __init__(self) -> None:
  192. # In increasing match priority:
  193. self.global_qconfig: QConfigAny = None
  194. self.object_type_qconfigs: OrderedDict[Union[Callable, str], QConfigAny] = (
  195. OrderedDict()
  196. )
  197. self.module_name_regex_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
  198. self.module_name_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
  199. self.module_name_object_type_order_qconfigs: OrderedDict[
  200. tuple[str, Callable, int], QConfigAny
  201. ] = OrderedDict()
  202. def set_global(self, global_qconfig: QConfigAny) -> QConfigMapping:
  203. """
  204. Set the global (default) QConfig.
  205. """
  206. self.global_qconfig = global_qconfig
  207. return self
  208. def set_object_type(
  209. self, object_type: Union[Callable, str], qconfig: QConfigAny
  210. ) -> QConfigMapping:
  211. """
  212. Set the QConfig for a given module type, function, or method name.
  213. If the QConfig for an existing object type was already set, the new QConfig will override the old one.
  214. """
  215. self.object_type_qconfigs[object_type] = qconfig
  216. return self
  217. def set_module_name_regex(
  218. self, module_name_regex: str, qconfig: QConfigAny
  219. ) -> QConfigMapping:
  220. """
  221. Set the QConfig for modules matching the given regex string.
  222. Regexes will be matched in the order in which they are registered through this method.
  223. Thus, the caller should register more specific patterns first, e.g.::
  224. qconfig_mapping = QConfigMapping()
  225. .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
  226. .set_module_name_regex("foo.*bar.*", qconfig2)
  227. .set_module_name_regex("foo.*", qconfig3)
  228. In this example, "foo.bar.conv0" would match qconfig1, "foo.bar.linear" would match qconfig2,
  229. and "foo.baz.relu" would match qconfig3.
  230. If the QConfig for an existing module name regex was already set, the new QConfig will override the
  231. old one while preserving the order in which the regexes were originally registered.
  232. """
  233. self.module_name_regex_qconfigs[module_name_regex] = qconfig
  234. return self
  235. def set_module_name(self, module_name: str, qconfig: QConfigAny) -> QConfigMapping:
  236. """
  237. Set the QConfig for modules matching the given module name.
  238. If the QConfig for an existing module name was already set, the new QConfig will override the old one.
  239. """
  240. self.module_name_qconfigs[module_name] = qconfig
  241. return self
  242. def set_module_name_object_type_order(
  243. self, module_name: str, object_type: Callable, index: int, qconfig: QConfigAny
  244. ) -> QConfigMapping:
  245. """
  246. Set the QConfig for modules matching a combination of the given module name, object type,
  247. and the index at which the module appears.
  248. If the QConfig for an existing (module name, object type, index) was already set, the new QConfig
  249. will override the old one.
  250. """
  251. self.module_name_object_type_order_qconfigs[
  252. (module_name, object_type, index)
  253. ] = qconfig
  254. return self
  255. def __repr__(self) -> str:
  256. output = self.__class__.__name__ + " ("
  257. for style_name in _QCONFIG_STYLE_ORDER:
  258. output += f"\n {style_name}"
  259. qconfigs = getattr(self, style_name)
  260. if isinstance(qconfigs, OrderedDict) and len(qconfigs) > 0:
  261. for key, qconfig in qconfigs.items():
  262. output += f"\n {key}: {qconfig}"
  263. else:
  264. output += f"\n {qconfigs}"
  265. return output + "\n)"
  266. # TODO: remove this
  267. def to_dict(self) -> dict[str, Any]:
  268. """
  269. Convert this ``QConfigMapping`` to a dictionary with the following keys:
  270. "" (for global QConfig)
  271. "object_type"
  272. "module_name_regex"
  273. "module_name"
  274. "module_name_object_type_order"
  275. The values of this dictionary are lists of tuples.
  276. """
  277. return {
  278. _GLOBAL_DICT_KEY: self.global_qconfig,
  279. _OBJECT_TYPE_DICT_KEY: list(self.object_type_qconfigs.items()),
  280. _MODULE_NAME_REGEX_DICT_KEY: list(self.module_name_regex_qconfigs.items()),
  281. _MODULE_NAME_DICT_KEY: list(self.module_name_qconfigs.items()),
  282. _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY: [
  283. (*k, v) for k, v in self.module_name_object_type_order_qconfigs.items()
  284. ],
  285. }
  286. # TODO: remove this
  287. @classmethod
  288. def from_dict(cls, qconfig_dict: dict[str, Any]) -> QConfigMapping:
  289. """
  290. Create a ``QConfigMapping`` from a dictionary with the following keys (all optional):
  291. "" (for global QConfig)
  292. "object_type"
  293. "module_name_regex"
  294. "module_name"
  295. "module_name_object_type_order"
  296. The values of this dictionary are expected to be lists of tuples.
  297. """
  298. conf = cls()
  299. if _GLOBAL_DICT_KEY in qconfig_dict:
  300. conf.set_global(qconfig_dict[_GLOBAL_DICT_KEY])
  301. for object_type, qconfig in qconfig_dict.get(_OBJECT_TYPE_DICT_KEY, []):
  302. conf.set_object_type(object_type, qconfig)
  303. for module_name_regex, qconfig in qconfig_dict.get(
  304. _MODULE_NAME_REGEX_DICT_KEY, []
  305. ):
  306. conf.set_module_name_regex(module_name_regex, qconfig)
  307. for module_name, qconfig in qconfig_dict.get(_MODULE_NAME_DICT_KEY, []):
  308. conf.set_module_name(module_name, qconfig)
  309. for module_name, object_type, index, qconfig in qconfig_dict.get(
  310. _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY, []
  311. ):
  312. conf.set_module_name_object_type_order(
  313. module_name, object_type, index, qconfig
  314. )
  315. return conf