qconfig_mapping.py 14 KB

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