quantization_mappings.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import copy
  2. from typing import Any, Callable, Optional, Union
  3. import torch
  4. import torch.ao.nn as ao_nn
  5. import torch.ao.nn.intrinsic as nni
  6. import torch.ao.nn.intrinsic.qat as nniqat
  7. import torch.ao.nn.intrinsic.quantized as nniq
  8. import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
  9. import torch.ao.nn.qat as nnqat
  10. import torch.ao.nn.qat.dynamic as nnqatd
  11. import torch.ao.nn.quantized as nnq
  12. import torch.ao.nn.quantized.dynamic as nnqd
  13. import torch.ao.nn.quantized.reference as nnqr
  14. # Because `torch.ao.nn` uses lazy imports, we need to make
  15. # sure we import the contents explicitly here.
  16. import torch.ao.nn.sparse
  17. import torch.nn.functional as F
  18. from torch import nn
  19. from torch.ao.quantization.fake_quantize import (
  20. default_fixed_qparams_range_0to1_fake_quant,
  21. default_fixed_qparams_range_neg1to1_fake_quant,
  22. )
  23. from torch.ao.quantization.stubs import DeQuantStub, QuantStub
  24. from torch.ao.quantization.utils import get_combined_dict
  25. from torch.nn.utils.parametrize import type_before_parametrizations
  26. __all__ = [
  27. "DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS",
  28. "DEFAULT_STATIC_QUANT_MODULE_MAPPINGS",
  29. "DEFAULT_QAT_MODULE_MAPPINGS",
  30. "DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS",
  31. "DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS",
  32. "DEFAULT_MODULE_TO_ACT_POST_PROCESS",
  33. "DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS",
  34. "DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS",
  35. "no_observer_set",
  36. "get_default_static_quant_module_mappings",
  37. "get_default_static_quant_reference_module_mappings",
  38. "get_embedding_static_quant_module_mappings",
  39. "get_default_static_sparse_quant_module_mappings",
  40. "get_static_quant_module_class",
  41. "get_dynamic_quant_module_class",
  42. "get_default_qat_module_mappings",
  43. "get_embedding_qat_module_mappings",
  44. "get_default_dynamic_quant_module_mappings",
  45. "get_default_dynamic_sparse_quant_module_mappings",
  46. "get_default_qconfig_propagation_list",
  47. "get_default_compare_output_module_list",
  48. "get_default_float_to_quantized_operator_mappings",
  49. "get_quantized_operator",
  50. ]
  51. # Default map for swapping float module to reference quantized modules
  52. DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS: dict[Callable, Any] = {
  53. QuantStub: nnq.Quantize,
  54. DeQuantStub: nnq.DeQuantize,
  55. nn.Linear: nnqr.Linear,
  56. nn.Conv1d: nnqr.Conv1d,
  57. nn.Conv2d: nnqr.Conv2d,
  58. nn.Conv3d: nnqr.Conv3d,
  59. nn.ConvTranspose1d: nnqr.ConvTranspose1d,
  60. nn.ConvTranspose2d: nnqr.ConvTranspose2d,
  61. nn.ConvTranspose3d: nnqr.ConvTranspose3d,
  62. nn.Embedding: nnqr.Embedding,
  63. nn.EmbeddingBag: nnqr.EmbeddingBag,
  64. nn.GRUCell: nnqr.GRUCell,
  65. nn.LSTMCell: nnqr.LSTMCell,
  66. nn.RNNCell: nnqr.RNNCell,
  67. nn.LSTM: nnqr.LSTM,
  68. }
  69. # Default map for swapping float module to quantized ones
  70. DEFAULT_STATIC_QUANT_MODULE_MAPPINGS: dict[Callable, Any] = {
  71. QuantStub: nnq.Quantize,
  72. DeQuantStub: nnq.DeQuantize,
  73. nn.BatchNorm2d: nnq.BatchNorm2d,
  74. nn.BatchNorm3d: nnq.BatchNorm3d,
  75. nn.Dropout: nnq.Dropout,
  76. nn.Conv1d: nnq.Conv1d,
  77. nn.Conv2d: nnq.Conv2d,
  78. nn.Conv3d: nnq.Conv3d,
  79. nn.ConvTranspose1d: nnq.ConvTranspose1d,
  80. nn.ConvTranspose2d: nnq.ConvTranspose2d,
  81. nn.ConvTranspose3d: nnq.ConvTranspose3d,
  82. nn.ELU: nnq.ELU,
  83. nn.Embedding: nnq.Embedding,
  84. nn.EmbeddingBag: nnq.EmbeddingBag,
  85. nn.GroupNorm: nnq.GroupNorm,
  86. nn.Hardswish: nnq.Hardswish,
  87. nn.InstanceNorm1d: nnq.InstanceNorm1d,
  88. nn.InstanceNorm2d: nnq.InstanceNorm2d,
  89. nn.InstanceNorm3d: nnq.InstanceNorm3d,
  90. nn.LayerNorm: nnq.LayerNorm,
  91. nn.LeakyReLU: nnq.LeakyReLU,
  92. nn.modules.linear.NonDynamicallyQuantizableLinear: nnq.Linear,
  93. nn.Linear: nnq.Linear,
  94. nn.ReLU6: nnq.ReLU6,
  95. nn.PReLU: nnq.PReLU,
  96. # Wrapper Modules:
  97. nnq.FloatFunctional: nnq.QFunctional,
  98. # Intrinsic modules:
  99. nni.BNReLU2d: nniq.BNReLU2d,
  100. nni.BNReLU3d: nniq.BNReLU3d,
  101. nni.ConvReLU1d: nniq.ConvReLU1d,
  102. nni.ConvReLU2d: nniq.ConvReLU2d,
  103. nni.ConvReLU3d: nniq.ConvReLU3d,
  104. nni.ConvAdd2d: nniq.ConvAdd2d,
  105. nni.ConvAddReLU2d: nniq.ConvAddReLU2d,
  106. nni.LinearReLU: nniq.LinearReLU,
  107. nni.LinearLeakyReLU: nniq.LinearLeakyReLU,
  108. nni.LinearTanh: nniq.LinearTanh,
  109. nniqat.ConvBn1d: nnq.Conv1d,
  110. nniqat.ConvBn2d: nnq.Conv2d,
  111. nniqat.ConvBn3d: nnq.Conv3d,
  112. nniqat.ConvBnReLU1d: nniq.ConvReLU1d,
  113. nniqat.ConvBnReLU2d: nniq.ConvReLU2d,
  114. nniqat.ConvBnReLU3d: nniq.ConvReLU3d,
  115. nniqat.ConvReLU2d: nniq.ConvReLU2d,
  116. nniqat.ConvReLU3d: nniq.ConvReLU3d,
  117. nniqat.LinearReLU: nniq.LinearReLU,
  118. nniqat.LinearBn1d: nnq.Linear,
  119. # QAT modules:
  120. nnqat.Linear: nnq.Linear,
  121. nnqat.Conv2d: nnq.Conv2d,
  122. nnqat.Conv3d: nnq.Conv3d,
  123. }
  124. # Default map for swapping float module to qat modules
  125. DEFAULT_QAT_MODULE_MAPPINGS: dict[Callable, Any] = {
  126. nn.Conv2d: nnqat.Conv2d,
  127. nn.Conv3d: nnqat.Conv3d,
  128. nn.Linear: nnqat.Linear,
  129. nn.modules.linear.NonDynamicallyQuantizableLinear: nnqat.Linear,
  130. # Intrinsic modules:
  131. nni.ConvBn1d: nniqat.ConvBn1d,
  132. nni.ConvBn2d: nniqat.ConvBn2d,
  133. nni.ConvBn3d: nniqat.ConvBn3d,
  134. nni.ConvBnReLU1d: nniqat.ConvBnReLU1d,
  135. nni.ConvBnReLU2d: nniqat.ConvBnReLU2d,
  136. nni.ConvBnReLU3d: nniqat.ConvBnReLU3d,
  137. nni.ConvReLU2d: nniqat.ConvReLU2d,
  138. nni.ConvReLU3d: nniqat.ConvReLU3d,
  139. nni.LinearReLU: nniqat.LinearReLU,
  140. nni.LinearBn1d: nniqat.LinearBn1d,
  141. }
  142. # Default map for swapping dynamic modules
  143. DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS: dict[Callable, Any] = {
  144. nn.GRUCell: nnqd.GRUCell,
  145. nn.Linear: nnqd.Linear,
  146. nnqatd.Linear: nnqd.Linear,
  147. nn.modules.linear.NonDynamicallyQuantizableLinear: nnqd.Linear,
  148. nn.LSTM: nnqd.LSTM,
  149. nn.GRU: nnqd.GRU,
  150. nn.LSTMCell: nnqd.LSTMCell,
  151. nn.RNNCell: nnqd.RNNCell,
  152. nni.LinearReLU: nniqd.LinearReLU,
  153. nn.EmbeddingBag: nnq.EmbeddingBag,
  154. nn.Embedding: nnq.Embedding,
  155. # Don't want to enable these by default because the numerical
  156. # accuracy is poor compared to other dynamic ops
  157. # nn.Conv1d: nnqd.Conv1d,
  158. # nn.Conv2d: nnqd.Conv2d,
  159. # nn.Conv3d: nnqd.Conv3d,
  160. # nn.ConvTranspose1d: nnqd.ConvTranspose1d,
  161. # nn.ConvTranspose2d: nnqd.ConvTranspose2d,
  162. # nn.ConvTranspose3d: nnqd.ConvTranspose3d,
  163. }
  164. # Allowlist for propagating the qconfig
  165. _INCLUDE_QCONFIG_PROPAGATE_LIST: set[Callable] = {
  166. nn.Sequential,
  167. }
  168. # Default mapping from floating point function or torch ops to quantized ops
  169. # TODO: merge with default static mapping
  170. DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS: dict[Union[Callable, str], Callable] = {
  171. F.elu: torch.ops.quantized.elu,
  172. F.hardswish: torch.ops.quantized.hardswish,
  173. F.instance_norm: torch.ops.quantized.instance_norm,
  174. F.layer_norm: torch.ops.quantized.layer_norm,
  175. F.leaky_relu: torch.ops.quantized.leaky_relu,
  176. F.dropout: torch.ops.quantized.dropout,
  177. }
  178. # mapping from module to output activation post process class
  179. DEFAULT_MODULE_TO_ACT_POST_PROCESS: dict[Callable, Callable] = {
  180. nn.Hardsigmoid: default_fixed_qparams_range_0to1_fake_quant,
  181. nn.Sigmoid: default_fixed_qparams_range_0to1_fake_quant,
  182. nn.Softmax: default_fixed_qparams_range_0to1_fake_quant,
  183. nn.Tanh: default_fixed_qparams_range_neg1to1_fake_quant,
  184. }
  185. # Default map for swapping float module to static sparse quantized ones
  186. DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS: dict[Callable, Any] = {
  187. nn.Linear: ao_nn.sparse.quantized.Linear
  188. }
  189. # Default map for swapping float module to dynamic sparse quantized ones
  190. DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS: dict[Callable, Any] = {
  191. nn.Linear: ao_nn.sparse.quantized.dynamic.Linear
  192. }
  193. def no_observer_set() -> set[Any]:
  194. r"""These modules cannot have observers inserted by default."""
  195. no_observers = {nn.quantizable.LSTM, nn.quantizable.MultiheadAttention}
  196. return no_observers
  197. def get_default_static_quant_module_mappings() -> dict[Callable, Any]:
  198. """Get module mapping for post training static quantization"""
  199. return copy.deepcopy(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS)
  200. def get_default_static_quant_reference_module_mappings() -> dict[Callable, Any]:
  201. """Get reference module mapping for post training static quantization"""
  202. return copy.deepcopy(DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS)
  203. def get_embedding_static_quant_module_mappings() -> dict[Callable, Any]:
  204. """Get module mapping, including mapping for embedding QAT"""
  205. mapping = copy.deepcopy(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS)
  206. mapping[nnqat.EmbeddingBag] = nnq.EmbeddingBag
  207. mapping[nnqat.Embedding] = nnq.Embedding
  208. return mapping
  209. def get_default_static_sparse_quant_module_mappings() -> dict[Callable, Any]:
  210. """Get module mapping for post training static sparse quantization"""
  211. return copy.deepcopy(DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS)
  212. def get_static_quant_module_class(
  213. float_module_class: Callable,
  214. additional_static_quant_mapping: Optional[dict[Callable, Any]] = None,
  215. is_reference: bool = False,
  216. ) -> Any:
  217. r"""n Get the statically quantized module class corresponding to
  218. the floating point module class
  219. """
  220. if additional_static_quant_mapping is None:
  221. additional_static_quant_mapping = {}
  222. all_mappings = get_combined_dict(
  223. DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS
  224. if is_reference
  225. else DEFAULT_STATIC_QUANT_MODULE_MAPPINGS,
  226. additional_static_quant_mapping,
  227. )
  228. static_quant_module_class = all_mappings.get(float_module_class, None)
  229. assert static_quant_module_class is not None, (
  230. f"Floating point module class {str(float_module_class)}"
  231. + " does not have a corresponding quantized module class"
  232. )
  233. return copy.deepcopy(static_quant_module_class)
  234. def get_dynamic_quant_module_class(
  235. float_module_class: Callable,
  236. additional_dynamic_quant_mapping: Optional[dict[Callable, Any]] = None,
  237. ) -> Any:
  238. r"""n Get the dynamically quantized module class corresponding to
  239. the floating point module class
  240. """
  241. if additional_dynamic_quant_mapping is None:
  242. additional_dynamic_quant_mapping = {}
  243. all_mappings = get_combined_dict(
  244. DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS, additional_dynamic_quant_mapping
  245. )
  246. dynamic_quant_module_class = all_mappings.get(float_module_class, None)
  247. assert dynamic_quant_module_class is not None, (
  248. f"Floating point module class {str(float_module_class)}"
  249. + " does not have a corresponding quantized module class"
  250. )
  251. return copy.deepcopy(dynamic_quant_module_class)
  252. def get_default_qat_module_mappings() -> dict[Callable, Any]:
  253. """Get default module mapping for quantization aware training"""
  254. return copy.deepcopy(DEFAULT_QAT_MODULE_MAPPINGS)
  255. def get_embedding_qat_module_mappings() -> dict[Callable, Any]:
  256. """Get module mapping for quantization aware training
  257. This is includes default values in addition to
  258. enabling qat for embeddings.
  259. """
  260. mapping = copy.deepcopy(DEFAULT_QAT_MODULE_MAPPINGS)
  261. mapping[nn.EmbeddingBag] = nnqat.EmbeddingBag
  262. mapping[nn.Embedding] = nnqat.Embedding
  263. return mapping
  264. def get_default_dynamic_quant_module_mappings() -> dict[Callable, Any]:
  265. """Get module mapping for post training dynamic quantization"""
  266. return DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS
  267. def get_default_dynamic_sparse_quant_module_mappings() -> dict[Callable, Any]:
  268. """Get module mapping for post training dynamic sparse quantization"""
  269. return DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS
  270. def get_default_qconfig_propagation_list() -> set[Callable]:
  271. """Get the default list of module types that we'll attach qconfig
  272. attribute to in prepare
  273. """
  274. QCONFIG_PROPAGATE_MODULE_CLASS_LIST = (
  275. set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys())
  276. | set(DEFAULT_QAT_MODULE_MAPPINGS.keys())
  277. | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys())
  278. | _INCLUDE_QCONFIG_PROPAGATE_LIST
  279. )
  280. return copy.deepcopy(QCONFIG_PROPAGATE_MODULE_CLASS_LIST)
  281. def get_default_compare_output_module_list() -> set[Callable]:
  282. """Get list of module class types that we will record output
  283. in numeric suite
  284. """
  285. NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_MODULE_LIST = (
  286. set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.values())
  287. | set(DEFAULT_QAT_MODULE_MAPPINGS.values())
  288. | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.values())
  289. | set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys())
  290. | set(DEFAULT_QAT_MODULE_MAPPINGS.keys())
  291. | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys())
  292. | _INCLUDE_QCONFIG_PROPAGATE_LIST
  293. )
  294. return copy.deepcopy(NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_MODULE_LIST)
  295. def get_default_float_to_quantized_operator_mappings() -> dict[
  296. Union[Callable, str], Callable
  297. ]:
  298. return copy.deepcopy(DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS)
  299. # TODO: merge with get_static_quant_module_class
  300. def get_quantized_operator(float_op: Union[Callable, str]) -> Callable:
  301. """Get the quantized operator corresponding to the float operator"""
  302. quantized_op = DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS.get(float_op, None)
  303. assert quantized_op is not None, (
  304. f"Operator {str(float_op)} does not have corresponding quantized op"
  305. )
  306. return quantized_op
  307. def _get_special_act_post_process(module: torch.nn.Module) -> Optional[Callable]:
  308. r"""Get the special activation post process for `module`, this has
  309. higher priority than the activation post process in `qconfig`
  310. e.g.
  311. input: torch.nn.Sigmoid
  312. output: default_affine_fixed_qparam_fake_quant
  313. """
  314. return DEFAULT_MODULE_TO_ACT_POST_PROCESS.get(
  315. type_before_parametrizations(module), None
  316. )
  317. def _has_special_act_post_process(module: torch.nn.Module) -> bool:
  318. return module.training and type(module) in DEFAULT_MODULE_TO_ACT_POST_PROCESS