executorch.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # TODO: rename executorch to qnnpack_executorch since executorch is a general runtime
  2. # not a specific backend
  3. import operator
  4. from typing import List
  5. import torch
  6. import torch.nn.functional as F
  7. import torch.nn as nn
  8. import torch.ao.nn.qat as nnqat
  9. import torch.ao.nn.quantized.reference as nnqr
  10. from .backend_config import (
  11. BackendConfig,
  12. BackendPatternConfig,
  13. DTypeConfig,
  14. ObservationType,
  15. )
  16. from .qnnpack import (
  17. qnnpack_weighted_op_qint8_symmetric_dtype_config,
  18. qnnpack_default_op_qint8_symmetric_dtype_config
  19. )
  20. from ._common_operator_config_utils import _Conv2dMetadata
  21. from ..fuser_method_mappings import _sequential_wrapper2
  22. __all__ = [
  23. "get_executorch_backend_config",
  24. ]
  25. # ===================
  26. # | DTYPE CONFIGS |
  27. # ===================
  28. executorch_weighted_op_int8_dtype_config = DTypeConfig(
  29. input_dtype=torch.quint8,
  30. output_dtype=torch.quint8,
  31. weight_dtype=torch.qint8,
  32. bias_dtype=torch.float,
  33. )
  34. executorch_default_op_quint8_dtype_config = DTypeConfig(
  35. input_dtype=torch.quint8,
  36. output_dtype=torch.quint8,
  37. )
  38. executorch_default_dynamic_int8_dtype_config = DTypeConfig(
  39. input_dtype=torch.quint8,
  40. output_dtype=torch.float,
  41. weight_dtype=torch.qint8,
  42. bias_dtype=torch.float,
  43. is_dynamic=True,
  44. )
  45. executorch_default_dynamic_float16_dtype_config = DTypeConfig(
  46. input_dtype=torch.float16,
  47. output_dtype=torch.float,
  48. weight_dtype=torch.float16,
  49. bias_dtype=torch.float,
  50. is_dynamic=True,
  51. )
  52. executorch_weight_only_quint8_dtype_config = DTypeConfig(
  53. input_dtype=torch.float,
  54. output_dtype=torch.float,
  55. weight_dtype=torch.quint8,
  56. )
  57. # =============================
  58. # | BACKEND PATTERN CONFIGS |
  59. # =============================
  60. def _get_linear_configs() -> List[BackendPatternConfig]:
  61. """
  62. Return all configs related to linear modules and ops.
  63. """
  64. observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
  65. dtype_configs = [
  66. qnnpack_weighted_op_qint8_symmetric_dtype_config,
  67. executorch_weighted_op_int8_dtype_config,
  68. executorch_default_dynamic_int8_dtype_config,
  69. executorch_default_dynamic_float16_dtype_config,
  70. ]
  71. linear_configs: List[BackendPatternConfig] = []
  72. # linear module
  73. linear_configs.append(
  74. BackendPatternConfig(torch.nn.Linear)
  75. .set_observation_type(observation_type) # noqa: E131
  76. .set_dtype_configs(dtype_configs)
  77. .set_root_module(torch.nn.Linear)
  78. .set_reference_quantized_module(nnqr.Linear)
  79. .set_qat_module(nnqat.Linear))
  80. # functional linear
  81. linear_configs.append(
  82. BackendPatternConfig(torch.nn.functional.linear)
  83. .set_observation_type(observation_type) # noqa: E131
  84. .set_dtype_configs(dtype_configs)
  85. ._set_input_type_to_index({"weight": 1, "bias": 2}))
  86. return linear_configs
  87. def _get_conv_configs() -> List[BackendPatternConfig]:
  88. """
  89. Return all configs related to conv modules and ops.
  90. """
  91. observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
  92. dtype_configs = [
  93. qnnpack_weighted_op_qint8_symmetric_dtype_config,
  94. executorch_weighted_op_int8_dtype_config
  95. ]
  96. conv_configs = []
  97. for convs in [_Conv2dMetadata]:
  98. # conv module
  99. conv_configs.append(
  100. BackendPatternConfig(convs.root)
  101. .set_observation_type(observation_type) # noqa: E131
  102. .set_dtype_configs(dtype_configs)
  103. .set_root_module(convs.root)
  104. .set_reference_quantized_module(convs.reference)
  105. .set_qat_module(convs.qat))
  106. # functional conv
  107. conv_configs.append(
  108. BackendPatternConfig(convs.func)
  109. .set_observation_type(observation_type) # noqa: E131
  110. .set_dtype_configs(dtype_configs)
  111. ._set_input_type_to_index({"weight": 1, "bias": 2}))
  112. # conv module + relu module
  113. conv_configs.append(
  114. BackendPatternConfig((convs.root, nn.ReLU))
  115. .set_dtype_configs(dtype_configs) # noqa: E131
  116. .set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
  117. .set_fused_module(convs.fused_conv_relu))
  118. # conv module + functional relu
  119. conv_configs.append(
  120. BackendPatternConfig((convs.root, F.relu))
  121. .set_dtype_configs(dtype_configs) # noqa: E131
  122. .set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
  123. .set_fused_module(convs.fused_conv_relu))
  124. # fused conv relu module
  125. conv_configs.append(
  126. BackendPatternConfig(convs.fused_conv_relu)
  127. .set_observation_type(observation_type) # noqa: E131
  128. .set_dtype_configs(dtype_configs)
  129. .set_root_module(convs.root)
  130. .set_reference_quantized_module(convs.reference)
  131. .set_qat_module(convs.relu_qat))
  132. # functional conv + relu module
  133. conv_configs.append(
  134. BackendPatternConfig((convs.func, nn.ReLU))
  135. .set_observation_type(observation_type) # noqa: E131
  136. .set_dtype_configs(dtype_configs))
  137. # functional conv + functional relu
  138. conv_configs.append(
  139. BackendPatternConfig((convs.func, F.relu))
  140. .set_observation_type(observation_type) # noqa: E131
  141. .set_dtype_configs(dtype_configs))
  142. return conv_configs
  143. def _get_binary_ops_configs() -> List[BackendPatternConfig]:
  144. """
  145. Return all configs related to binary ops.
  146. """
  147. dtype_configs = [
  148. qnnpack_default_op_qint8_symmetric_dtype_config,
  149. executorch_weighted_op_int8_dtype_config
  150. ]
  151. num_tensor_args_to_observation_type_mapping = {
  152. # TODO: this is not used right now since we have extra check in prepare
  153. # will need to change this to NO_OBSERVER later after we implemented
  154. # Tensor dtype inference properly
  155. 0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
  156. 1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,
  157. 2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
  158. }
  159. binary_op_configs: List[BackendPatternConfig] = []
  160. for op in [operator.add, torch.add]:
  161. binary_op_configs.append(
  162. BackendPatternConfig(op)
  163. .set_dtype_configs(dtype_configs) # noqa: E131
  164. ._set_num_tensor_args_to_observation_type(num_tensor_args_to_observation_type_mapping))
  165. return binary_op_configs
  166. def _get_share_qparams_ops_configs() -> List[BackendPatternConfig]:
  167. """
  168. Return the operator configs for the operators that works for both float and quantized
  169. input if input is quantized, the output Tensor shares the same quantization parameter
  170. with input.
  171. Example operator: avgpool2d, reshape, transpose, maxpool2d
  172. Example observed operator:
  173. observer_0 - avgpool2d - observer_0 (same observer instance as input)
  174. """
  175. observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
  176. dtype_configs = [
  177. qnnpack_default_op_qint8_symmetric_dtype_config,
  178. executorch_default_op_quint8_dtype_config
  179. ]
  180. share_qparams_ops = [
  181. F.adaptive_avg_pool2d,
  182. F.relu,
  183. F.relu6,
  184. torch.nn.AdaptiveAvgPool2d,
  185. torch.squeeze,
  186. "permute",
  187. "reshape",
  188. "relu",
  189. "relu_",
  190. "squeeze",
  191. "squeeze_",
  192. ]
  193. share_qparams_op_configs: List[BackendPatternConfig] = []
  194. for op in share_qparams_ops:
  195. share_qparams_op_configs.append(
  196. BackendPatternConfig(op)
  197. .set_observation_type(observation_type) # noqa: E131
  198. .set_dtype_configs(dtype_configs))
  199. return share_qparams_op_configs
  200. def _get_bn_configs() -> List[BackendPatternConfig]:
  201. """
  202. Return all configs related to batchnorm.
  203. """
  204. observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
  205. dtype_configs = [
  206. qnnpack_default_op_qint8_symmetric_dtype_config,
  207. executorch_default_op_quint8_dtype_config
  208. ]
  209. bn_configs = []
  210. bn_configs.append(
  211. BackendPatternConfig(nn.BatchNorm2d)
  212. .set_observation_type(observation_type) # noqa: E131
  213. .set_dtype_configs(dtype_configs))
  214. return bn_configs
  215. def _get_cat_configs() -> List[BackendPatternConfig]:
  216. dtype_configs = [
  217. qnnpack_default_op_qint8_symmetric_dtype_config,
  218. executorch_default_op_quint8_dtype_config
  219. ]
  220. cat_configs = []
  221. cat_configs.append(
  222. BackendPatternConfig(torch.cat)
  223. .set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
  224. .set_dtype_configs(dtype_configs))
  225. return cat_configs
  226. def _get_embedding_op_configs() -> List[BackendPatternConfig]:
  227. dtype_configs = [
  228. executorch_weight_only_quint8_dtype_config,
  229. ]
  230. embedding_op_configs = []
  231. for embedding_op, qat_embedding_op, ref_embedding_op in [
  232. (nn.Embedding, nnqat.Embedding, nnqr.Embedding),
  233. (nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag),
  234. ]:
  235. embedding_op_configs.append(
  236. BackendPatternConfig(embedding_op)
  237. .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
  238. .set_dtype_configs(dtype_configs)
  239. .set_qat_module(qat_embedding_op)
  240. .set_root_module(embedding_op)
  241. .set_reference_quantized_module(ref_embedding_op))
  242. # config for qat op
  243. embedding_op_configs.append(
  244. BackendPatternConfig(qat_embedding_op)
  245. .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
  246. .set_dtype_configs(dtype_configs)
  247. .set_root_module(embedding_op)
  248. .set_reference_quantized_module(ref_embedding_op))
  249. # config for functional embedding
  250. embedding_op_configs.append(
  251. BackendPatternConfig(torch.nn.functional.embedding)
  252. .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
  253. .set_dtype_configs(dtype_configs)
  254. ._set_input_type_to_index({"weight": 1}))
  255. return embedding_op_configs
  256. # =====================
  257. # | BACKEND CONFIGS |
  258. # =====================
  259. def get_executorch_backend_config() -> BackendConfig:
  260. """
  261. Return the `BackendConfig` for backends PyTorch lowers to through the Executorch stack.
  262. """
  263. return BackendConfig("executorch") \
  264. .set_backend_pattern_configs(_get_linear_configs()) \
  265. .set_backend_pattern_configs(_get_conv_configs()) \
  266. .set_backend_pattern_configs(_get_binary_ops_configs()) \
  267. .set_backend_pattern_configs(_get_share_qparams_ops_configs()) \
  268. .set_backend_pattern_configs(_get_bn_configs()) \
  269. .set_backend_pattern_configs(_get_cat_configs()) \
  270. .set_backend_pattern_configs(_get_embedding_op_configs())