quantization_mappings.py 14 KB

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