qconfig_mapping.py 13 KB

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