utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from typing import Dict, Any, List, Callable, Union, Tuple, Type
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from .backend_config import (
  6. BackendConfig,
  7. BackendPatternConfig,
  8. DTypeConfig,
  9. )
  10. from ..utils import Pattern
  11. from ..fuser_method_mappings import (
  12. _reverse2,
  13. _reverse3,
  14. )
  15. __all__ = [
  16. "get_pattern_to_dtype_configs",
  17. "get_qat_module_classes",
  18. "get_fused_module_classes",
  19. "get_pattern_to_input_type_to_index",
  20. "get_root_module_to_quantized_reference_module",
  21. "get_fuser_method_mapping",
  22. "get_module_to_qat_module",
  23. "get_fusion_pattern_to_root_node_getter",
  24. "get_fusion_pattern_to_extra_inputs_getter",
  25. "remove_boolean_dispatch_from_name",
  26. "pattern_to_human_readable",
  27. "entry_to_pretty_str",
  28. ]
  29. def get_pattern_to_dtype_configs(backend_config: BackendConfig) -> Dict[Pattern, List[DTypeConfig]]:
  30. pattern_to_dtype_configs: Dict[Pattern, List[DTypeConfig]] = {}
  31. for pattern, config in backend_config._pattern_complex_format_to_config.items():
  32. pattern_to_dtype_configs[pattern] = config.dtype_configs
  33. return pattern_to_dtype_configs
  34. def get_qat_module_classes(backend_config: BackendConfig) -> Tuple[type, ...]:
  35. qat_module_classes = []
  36. for config in backend_config.configs:
  37. if config.qat_module is not None:
  38. qat_module_classes.append(config.qat_module)
  39. return tuple(set(qat_module_classes))
  40. def get_fused_module_classes(backend_config: BackendConfig) -> Tuple[type, ...]:
  41. fused_module_classes = []
  42. for config in backend_config.configs:
  43. if config.fused_module is not None:
  44. fused_module_classes.append(config.fused_module)
  45. return tuple(set(fused_module_classes))
  46. def get_pattern_to_input_type_to_index(backend_config: BackendConfig) -> Dict[Pattern, Dict[str, int]]:
  47. pattern_to_input_type_to_index: Dict[Pattern, Dict[str, int]] = {}
  48. for pattern, config in backend_config._pattern_complex_format_to_config.items():
  49. pattern_to_input_type_to_index[pattern] = config._input_type_to_index
  50. return pattern_to_input_type_to_index
  51. def get_root_module_to_quantized_reference_module(
  52. backend_config: BackendConfig) -> Dict[Type[torch.nn.Module], Type[torch.nn.Module]]:
  53. mapping: Dict[Type[torch.nn.Module], Type[torch.nn.Module]] = {}
  54. for config in backend_config.configs:
  55. if config.root_module is not None and config.reference_quantized_module is not None:
  56. mapping[config.root_module] = config.reference_quantized_module
  57. return mapping
  58. def get_fuser_method_mapping(backend_config: BackendConfig) -> Dict[Pattern, Union[nn.Sequential, Callable]]:
  59. fuser_method_mapping : Dict[Pattern, Union[nn.Sequential, Callable]] = {}
  60. for pattern, config in backend_config._pattern_complex_format_to_config.items():
  61. if config.fuser_method is not None:
  62. # Note: both the fuser method and the pattern are specified in forward order in the
  63. # BackendConfig, but the internal pattern matching code uses the reversed nested tuple
  64. # format, so we need to convert both to the internal format
  65. fuser_method = _get_fuser_method_in_reversed_nested_tuple_format(config)
  66. fuser_method_mapping[pattern] = fuser_method
  67. return fuser_method_mapping
  68. def get_module_to_qat_module(backend_config: BackendConfig) -> Dict[Pattern, Type[torch.nn.Module]]:
  69. module_to_qat_module: Dict[Pattern, Type[torch.nn.Module]] = {}
  70. for pattern, config in backend_config._pattern_complex_format_to_config.items():
  71. if config.qat_module is not None:
  72. module_to_qat_module[pattern] = config.qat_module
  73. return module_to_qat_module
  74. def get_fusion_pattern_to_root_node_getter(backend_config: BackendConfig) -> Dict[Pattern, Callable]:
  75. """ Get a map from fusion pattern to a function that returns the root node
  76. from the fusion pattern, e.g. the most common one is:
  77. def get_root_node(node_pattern):
  78. while not isinstance(node_pattern[-1], Node):
  79. node_pattern = node_pattern[-1]
  80. return node_pattern[-1]
  81. This can work for all patterns whose root node is the "last node" in the pattern,
  82. e.g. (torch.add, MatchAllNode, (torch.ReLU, torch.Conv2d))
  83. """
  84. root_node_getter_mapping: Dict[Pattern, Callable] = {}
  85. for pattern, config in backend_config._pattern_complex_format_to_config.items():
  86. if config._root_node_getter is not None:
  87. root_node_getter_mapping[pattern] = config._root_node_getter
  88. return root_node_getter_mapping
  89. def get_fusion_pattern_to_extra_inputs_getter(backend_config: BackendConfig) -> Dict[Pattern, Callable]:
  90. """ Get a map from fusion pattern to a function that returns extra input nodes
  91. from the fusion pattern, in the order required by the root node. This is optional,
  92. if not specified, we will not copy over any extra inputs for the root node.
  93. Example:
  94. # Let's say we have the pattern (torch.add, MatchAllNode, (torch.nn.BatchNorm2d, torch.nn.Conv2d))
  95. # and root node is torch.nn.Conv2d, and the node in MatchAllNode would be an extra
  96. # argument to the fused module, we can unpack the pattern and return the node at
  97. # MatchAllNode here
  98. # we can implement extra_inputs_getter as follows:
  99. def extra_inputs_getter(pattern) -> List[Any]:
  100. add, extra_input, conv_pattern = pattern
  101. return [extra_input]
  102. """
  103. extra_inputs_getter_mapping: Dict[Pattern, Callable] = {}
  104. for pattern, config in backend_config._pattern_complex_format_to_config.items():
  105. if config._extra_inputs_getter is not None:
  106. extra_inputs_getter_mapping[pattern] = config._extra_inputs_getter
  107. return extra_inputs_getter_mapping
  108. def remove_boolean_dispatch_from_name(p) -> Any:
  109. """
  110. Some ops have a default string representation such as
  111. '<function boolean_dispatch.<locals>.fn at 0x7ff1106bf280>',
  112. this function replaces them with the hardcoded function names.
  113. """
  114. if p is F.fractional_max_pool2d:
  115. return "torch.nn.functional.fractional_max_pool2d"
  116. elif p is F.fractional_max_pool3d:
  117. return "torch.nn.functional.fractional_max_pool3d"
  118. elif p is F.max_pool1d:
  119. return "torch.nn.functional.max_pool1d"
  120. elif p is F.max_pool2d:
  121. return "torch.nn.functional.max_pool2d"
  122. elif p is F.max_pool3d:
  123. return "torch.nn.functional.max_pool3d"
  124. elif p is F.adaptive_max_pool1d:
  125. return "torch.nn.functional.adaptive_max_pool1d"
  126. elif p is F.adaptive_max_pool2d:
  127. return "torch.nn.functional.adaptive_max_pool2d"
  128. elif p is F.adaptive_max_pool3d:
  129. return "torch.nn.functional.adaptive_max_pool3d"
  130. assert "boolean_dispatch" not in str(p), \
  131. f"{p} does not have a human readable representation in " + \
  132. "quantization documentation"
  133. return p
  134. def pattern_to_human_readable(p) -> Any:
  135. if isinstance(p, tuple):
  136. # nested patterns, recurse
  137. return tuple(pattern_to_human_readable(inner_p) for inner_p in p)
  138. elif isinstance(p, str):
  139. # method names are already human readable
  140. return p
  141. else:
  142. p = remove_boolean_dispatch_from_name(p)
  143. return p
  144. # TODO(future PR): move backend_config_dict to use dataclass and move this logic to
  145. # the corresponding __str__ function
  146. def entry_to_pretty_str(entry) -> str:
  147. """
  148. Given a backend_config_dict entry, returns a string with the human readable
  149. representation of it.
  150. """
  151. s = "{\n"
  152. # always output the pattern first
  153. if "pattern" in entry:
  154. pattern_str = pattern_to_human_readable(entry["pattern"])
  155. s += f" 'pattern': {pattern_str},\n"
  156. # custom output for dtype_configs to make it look nice
  157. if "dtype_configs" in entry:
  158. s += " 'dtype_configs': [\n"
  159. for dtype_config in entry["dtype_configs"]:
  160. s += " {\n"
  161. for k, v in dtype_config.items():
  162. s += f" '{k}': {v},\n"
  163. s += " },\n"
  164. s += " ],\n"
  165. # custom output for num_tensor_args_to_observation_type to make it look nice
  166. if "num_tensor_args_to_observation_type" in entry:
  167. s += " 'num_tensor_args_to_observation_type': {\n"
  168. for k, v in entry["num_tensor_args_to_observation_type"].items():
  169. s += f" {k}: {v},\n"
  170. s += " },\n"
  171. # output all the other fields
  172. custom_handled_fields = [
  173. "pattern",
  174. "dtype_configs",
  175. "num_tensor_args_to_observation_type",
  176. ]
  177. for field_name in entry:
  178. if field_name in custom_handled_fields:
  179. continue
  180. s += f" '{field_name}': {entry[field_name]},\n"
  181. s += "}"
  182. return s
  183. def _get_pattern_in_reversed_nested_tuple_format(config: BackendPatternConfig) -> Pattern:
  184. """
  185. Return the pattern specified in the given config in the reversed nested tuple format
  186. used internally in the quantization pattern matching code.
  187. If the pattern is not a tuple, or the pattern is already specified in the reversed
  188. nested tuple format, return the pattern as is. Otherwise:
  189. For 2-tuples (a, b), return (b, a).
  190. For 3-tuples (a, b, c), return (c, (b, a)).
  191. For example:
  192. * Given nn.Linear, return nn.Linear
  193. * Given (nn.Linear, nn.ReLU), return (nn.ReLU, nn.Linear)
  194. * Given (nn.Conv2d, nn.BatchNorm2d, nn.ReLU), return
  195. (nn.ReLU, (nn.BatchNorm2d, nn.Conv2d))
  196. For context, the reason why this is needed is the user-facing BackendConfig
  197. API accepts the flat 2-or-3-tuple format in forward order. While this simple
  198. format handles the vast majority of use cases, it does not handle the more
  199. complex ones, and so the internal pattern matching code for quantization uses
  200. the following, more general reversed nested tuple format instead:
  201. operator = module_type | functional | torch op | native op | MatchAllNode
  202. Pattern = (operator, Pattern, Pattern, ...) | operator
  203. In the future, we expect to replace the above complex format with the one used
  204. by the subgraph rewriter in torch.fx, so we don't have to maintain our own
  205. complex pattern matching code. Then we won't need this helper function anymore.
  206. """
  207. if config._pattern_complex_format is not None:
  208. return config._pattern_complex_format
  209. if config.pattern is None:
  210. raise ValueError("Either 'pattern' or 'pattern_complex_format' must be specified")
  211. if not isinstance(config.pattern, tuple):
  212. return config.pattern
  213. # Pattern is specified in the simple tuple format, need to convert
  214. if len(config.pattern) == 2:
  215. (a, b) = config.pattern
  216. return (b, a)
  217. elif len(config.pattern) == 3:
  218. (a, b, c) = config.pattern
  219. return (c, (b, a))
  220. else:
  221. raise ValueError("Expected a tuple with 2 or 3 elements, got: ", config.pattern)
  222. def _get_fuser_method_in_reversed_nested_tuple_format(config: BackendPatternConfig) -> Callable:
  223. """
  224. Return the fuser method specified in the given config in the reversed nested
  225. tuple format used internally in the quantization pattern matching code.
  226. If pattern is specified in the reversed nested tuple format, we assume the
  227. fuser method is also specified in this format and simply return it as is.
  228. Otherwise, we convert the fuser method as follows:
  229. * Given f(is_qat, conv, relu), return f'(is_qat, relu, conv)
  230. * Given f(is_qat, conv, bn, relu), return f'(is_qat, relu, bn_conv),
  231. where bn_conv is a 2-tuple (bn, conv)
  232. The first argument of a fuser method is always `is_qat` and is not affected
  233. in the conversion. We currently only support functions with 3 or 4 arguments.
  234. """
  235. assert config.fuser_method is not None
  236. if config._pattern_complex_format is not None:
  237. return config.fuser_method
  238. if not isinstance(config.pattern, tuple):
  239. raise ValueError("Expected pattern to be a tuple, got: ", config.pattern)
  240. # Pattern is specified in the simple tuple format, need to convert
  241. if len(config.pattern) == 2:
  242. return _reverse2(config.fuser_method)
  243. elif len(config.pattern) == 3:
  244. return _reverse3(config.fuser_method)
  245. else:
  246. raise ValueError("Expected a tuple with 2 or 3 elements, got: ", config.pattern)