prepare.py 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. import copy
  2. import torch
  3. import warnings
  4. from torch.fx import (
  5. GraphModule,
  6. )
  7. from torch.fx.graph import (
  8. Graph,
  9. Node,
  10. )
  11. from torch.fx.node import Argument
  12. from ..quantize import (
  13. propagate_qconfig_,
  14. )
  15. from ..observer import (
  16. ObserverBase,
  17. _is_activation_post_process
  18. )
  19. from ..qconfig import (
  20. _is_reuse_input_qconfig,
  21. QConfigAny,
  22. )
  23. from ..qconfig_mapping import (
  24. QConfigMapping,
  25. )
  26. from .qconfig_mapping_utils import (
  27. _generate_node_name_to_qconfig,
  28. _update_qconfig_for_fusion,
  29. _get_flattened_qconfig_dict,
  30. _update_qconfig_for_qat,
  31. )
  32. from .quantize_handler import (
  33. _default_root_node_getter,
  34. _get_pattern_to_quantize_handlers,
  35. QuantizeHandler,
  36. )
  37. from torch.ao.quantization.utils import (
  38. Pattern,
  39. NodePattern,
  40. )
  41. from ._equalize import (
  42. is_equalization_observer,
  43. node_supports_equalization,
  44. )
  45. from .pattern_utils import (
  46. _sorted_patterns_dict,
  47. )
  48. from .match_utils import (
  49. _MatchResultWithQConfig,
  50. _find_matches,
  51. )
  52. from .utils import (
  53. _insert_dequant_stubs_for_custom_module_lstm_output,
  54. _is_custom_module_lstm,
  55. _maybe_get_custom_module_lstm_from_node_arg,
  56. _qconfig_satisfies_dtype_config_constraints,
  57. get_custom_module_class_keys,
  58. all_node_args_have_no_tensors,
  59. assert_and_get_unique_device,
  60. get_non_observable_arg_indexes_and_types,
  61. get_new_attr_name_with_prefix,
  62. node_arg_is_weight,
  63. node_arg_is_bias,
  64. NON_QUANTIZABLE_WEIGHT_OPS,
  65. ObservedGraphModuleAttrs,
  66. )
  67. from torch.ao.quantization import (
  68. PlaceholderObserver
  69. )
  70. from torch.ao.quantization.quantize import (
  71. convert
  72. )
  73. from ..utils import (
  74. _parent_name,
  75. get_qconfig_dtypes,
  76. get_swapped_custom_module_class,
  77. activation_is_statically_quantized,
  78. )
  79. from ..backend_config.utils import (
  80. get_pattern_to_dtype_configs,
  81. get_module_to_qat_module,
  82. get_fusion_pattern_to_root_node_getter,
  83. )
  84. from ..backend_config import (
  85. BackendConfig,
  86. DTypeConfig,
  87. get_native_backend_config,
  88. )
  89. from .custom_config import (
  90. PrepareCustomConfig,
  91. StandaloneModuleConfigEntry,
  92. )
  93. from torch._subclasses import FakeTensor
  94. from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union, Callable
  95. __all__ = [
  96. "insert_observers_for_model",
  97. "prepare",
  98. "propagate_dtypes_for_known_nodes",
  99. ]
  100. # list of dtypes to not add observers to
  101. _DO_NOT_OBS_DTYPE_LIST = [int, float, torch.bool, None]
  102. # note: the following default target dtype info dicts are temporary,
  103. # should be moved to the new programmable API class soon
  104. _DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO = {
  105. "input_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_fp32_placeholder_qconfig.activation,
  106. "output_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_fp32_placeholder_qconfig.activation
  107. }
  108. _DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFO = {
  109. "input_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_quint8_placeholder_qconfig.activation,
  110. "output_act_obs_or_fq_ctr": torch.ao.quantization.qconfig._default_quint8_placeholder_qconfig.activation
  111. }
  112. def _is_activation_post_process_node(node: Node, named_modules: Dict[str, torch.nn.Module]) -> bool:
  113. return isinstance(node, torch.fx.Node) and node.op == "call_module" and \
  114. _is_activation_post_process(named_modules[str(node.target)])
  115. def _get_dtype_and_is_dynamic(obs_or_fq_ctr: Optional[Callable]) -> Tuple[Optional[torch.dtype], bool]:
  116. """ Given a constructor for observer or fake quant module, returns
  117. a Tuple of dtype and is_dynamic
  118. """
  119. # TODO: instead of instantiating the instance, we can use inspect to get the default args
  120. if obs_or_fq_ctr is None:
  121. return None, False
  122. else:
  123. obs_or_fq = obs_or_fq_ctr()
  124. return obs_or_fq.dtype, getattr(obs_or_fq, "is_dynamic", False)
  125. def _is_input_arg_dtype_supported_by_backend(
  126. arg: Argument,
  127. node: Node,
  128. qconfig: QConfigAny,
  129. dtype_config: DTypeConfig,
  130. backend_config: BackendConfig,
  131. ) -> bool:
  132. """ Check if the configured qconfig for the argument
  133. is supported by the backend or not
  134. """
  135. if isinstance(arg, (list, tuple)):
  136. return all(_is_input_arg_dtype_supported_by_backend(
  137. a, node, qconfig,
  138. dtype_config, backend_config) for a in arg)
  139. if not isinstance(arg, Node):
  140. return True
  141. # TODO: support check for standalone module
  142. is_weight = node_arg_is_weight(node, arg, backend_config)
  143. is_bias = node_arg_is_bias(node, arg, backend_config)
  144. is_activation = not is_weight and not is_bias
  145. if is_activation:
  146. input_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get("input_act_obs_or_fq_ctr")
  147. qconfig_dtype, qconfig_is_dynamic = _get_dtype_and_is_dynamic(input_act_obs_or_fq_ctr)
  148. # TODO(future PR): remove the cast to bool below after figuring
  149. # out why backend_config has is_dynamic set to None in some cases.
  150. return (dtype_config.input_dtype is None) or (
  151. dtype_config.input_dtype == qconfig_dtype and
  152. bool(dtype_config.is_dynamic) == bool(qconfig_is_dynamic) and
  153. _qconfig_satisfies_dtype_config_constraints(qconfig, dtype_config.input_dtype_with_constraints)
  154. )
  155. elif is_weight:
  156. # TODO: move dtype check into `_qconfig_satisfies_dtype_config_constraints` as well
  157. weight_obs_or_fq_ctr = node.meta["target_dtype_info"].get("weight_obs_or_fq_ctr", None)
  158. qconfig_weight_dtype, _ = _get_dtype_and_is_dynamic(weight_obs_or_fq_ctr)
  159. backend_config_weight_dtype = dtype_config.weight_dtype
  160. dtype_matches = qconfig_weight_dtype == backend_config_weight_dtype
  161. qconfig_satisfies_constraints = _qconfig_satisfies_dtype_config_constraints(
  162. qconfig, dtype_config.weight_dtype_with_constraints, is_activation=False)
  163. return backend_config_weight_dtype is None or (dtype_matches and qconfig_satisfies_constraints)
  164. else: # bias
  165. # TODO: move dtype check into `_qconfig_satisfies_dtype_config_constraints` as well
  166. bias_obs_or_fq_ctr = node.meta["target_dtype_info"].get("bias_obs_or_fq_ctr", None)
  167. qconfig_bias_dtype, _ = _get_dtype_and_is_dynamic(bias_obs_or_fq_ctr)
  168. backend_config_bias_dtype = dtype_config.bias_dtype
  169. return backend_config_bias_dtype is None or qconfig_bias_dtype == backend_config_bias_dtype
  170. def _is_output_dtype_supported_by_backend(
  171. node: Node,
  172. qconfig: QConfigAny,
  173. dtype_config: DTypeConfig,
  174. ) -> bool:
  175. """ Check if the configured qconfig for the output
  176. is supported by the backend or not
  177. """
  178. # TODO: move dtype check into `_qconfig_satisfies_dtype_config_constraints` as well
  179. backend_config_output_dtype = dtype_config.output_dtype
  180. # TODO: we should check is_dynamic here as well, the code from _is_input_arg_dtype_supported_by_backend
  181. # from input activation check can be reused here
  182. qconfig_output_dtype = None
  183. output_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get("output_act_obs_or_fq_ctr")
  184. qconfig_output_dtype, qconfig_output_is_dynamic = _get_dtype_and_is_dynamic(output_act_obs_or_fq_ctr)
  185. # TODO: this is a hack because we can only specify one activation_obs_or_fq for
  186. # qconfig (qconfig.activation), and we are only supporting dynamically quantized
  187. # linear op which has fp32 output dtype, this should be removed if we generalize
  188. # the structure of qconfig in the future
  189. if qconfig_output_is_dynamic:
  190. qconfig_output_dtype = torch.float32
  191. dtype_matches = qconfig_output_dtype == backend_config_output_dtype
  192. qconfig_satisfies_constraints = _qconfig_satisfies_dtype_config_constraints(
  193. qconfig, dtype_config.output_dtype_with_constraints)
  194. return backend_config_output_dtype is None or (dtype_matches and qconfig_satisfies_constraints)
  195. def _is_observer_in_same_graph(node: Node, named_modules: Dict[str, torch.nn.Module]):
  196. """ Check if observer in same graph
  197. when the node output is not fp32 and input is 'placeholder'
  198. the input is assumed to be quantized, so it is observed
  199. in a different place rather than not observed.
  200. """
  201. node_output_dtype = _get_arg_target_dtype_as_output(node, named_modules)
  202. if len(node.args) > 0 and isinstance(node.args[0], Node):
  203. if node_output_dtype == torch.quint8 and node.args[0].op == 'placeholder':
  204. return False
  205. return True
  206. def _is_pattern_dtype_config_and_qconfig_supported_by_backend(
  207. pattern: Optional[Pattern],
  208. matched_node_pattern: Optional[List[Node]],
  209. qconfig: QConfigAny,
  210. backend_config: BackendConfig,
  211. ) -> bool:
  212. """ Check if the dtype configuration of a pattern is supported by
  213. the backend or not, and whether the qconfig satisfies constraints
  214. specified in the corresponding dtype config.
  215. """
  216. if backend_config is None or pattern is None:
  217. return True
  218. assert matched_node_pattern is not None and len(matched_node_pattern) >= 1
  219. pattern_to_dtype_configs = get_pattern_to_dtype_configs(backend_config)
  220. dtype_configs: List[DTypeConfig] = pattern_to_dtype_configs.get(pattern, [])
  221. pattern_to_root_node_getter = get_fusion_pattern_to_root_node_getter(backend_config)
  222. root_node_getter = pattern_to_root_node_getter.get(pattern, _default_root_node_getter)
  223. root_node = root_node_getter(matched_node_pattern)
  224. input_node = root_node
  225. output_node = matched_node_pattern[0]
  226. for dtype_config in dtype_configs:
  227. # check if arg dtype are supported
  228. supported = True
  229. for arg in list(input_node.args) + list(input_node.kwargs.values()):
  230. supported = supported and _is_input_arg_dtype_supported_by_backend(
  231. arg, input_node, qconfig, dtype_config, backend_config)
  232. # check if output dtype is supported
  233. supported = supported and _is_output_dtype_supported_by_backend(
  234. output_node, qconfig, dtype_config)
  235. if supported:
  236. return True
  237. return False
  238. def _get_standalone_module_configs(
  239. node: Node,
  240. named_modules: Dict[str, torch.nn.Module],
  241. prepare_custom_config: PrepareCustomConfig,
  242. parent_qconfig: QConfigAny,
  243. parent_backend_config: Optional[BackendConfig],
  244. ) -> Tuple[QConfigMapping, Tuple[Any, ...], PrepareCustomConfig, Optional[BackendConfig]]:
  245. """
  246. Returns the standalone module QConfigMapping and PrepareCustomConfig
  247. for `node`, assuming that the module pointed to by `node` is
  248. a standalone modules.
  249. """
  250. module_name = str(node.target)
  251. module_type = type(named_modules[module_name]) # type: ignore[index]
  252. # name config has precedence over type config
  253. config_entry = StandaloneModuleConfigEntry(None, (), None, None)
  254. config_entry = prepare_custom_config.standalone_module_classes.get(module_type, config_entry)
  255. config_entry = prepare_custom_config.standalone_module_names.get(module_name, config_entry)
  256. # fallback to use parent module's qconfig if user didn't specify qconfig dict
  257. qconfig_mapping = config_entry.qconfig_mapping or QConfigMapping().set_global(parent_qconfig)
  258. example_inputs = config_entry.example_inputs
  259. prepare_custom_config = config_entry.prepare_custom_config or PrepareCustomConfig()
  260. backend_config = config_entry.backend_config or parent_backend_config
  261. return (qconfig_mapping, example_inputs, prepare_custom_config, backend_config)
  262. def _qat_swap_modules(
  263. root: torch.nn.Module,
  264. module_to_qat_module: Dict[Pattern, Type[torch.nn.Module]]) -> None:
  265. convert(root, mapping=module_to_qat_module, inplace=True, remove_qconfig=False)
  266. def _add_matched_node_name_to_set(matched_node_pattern: NodePattern, s: Set[str]):
  267. if isinstance(matched_node_pattern, Node):
  268. s.add(matched_node_pattern.name)
  269. elif isinstance(matched_node_pattern, (list, tuple)):
  270. for maybe_node in matched_node_pattern:
  271. _add_matched_node_name_to_set(maybe_node, s)
  272. def _insert_observer(
  273. node: Node,
  274. observer: ObserverBase,
  275. model: torch.nn.Module,
  276. named_modules: Dict[str, torch.nn.Module],
  277. graph: Graph,
  278. ) -> Node:
  279. """
  280. Attaches `observer` to `model`, and creates a node which calls
  281. `observer` on the output of `node`.
  282. """
  283. model_device = assert_and_get_unique_device(model)
  284. if model_device:
  285. observer.to(model_device)
  286. # add observer module as attribute
  287. if is_equalization_observer(observer):
  288. prefix = node.name + '_equalization_process_'
  289. else:
  290. prefix = 'activation_post_process_'
  291. get_new_observer_name = get_new_attr_name_with_prefix(prefix)
  292. observer_name = get_new_observer_name(model)
  293. setattr(model, observer_name, observer)
  294. named_modules[observer_name] = observer
  295. with graph.inserting_after(node):
  296. new_obs = graph.create_node(
  297. 'call_module', observer_name, (node,), {})
  298. return new_obs
  299. def _set_target_dtype_info_for_matched_node_pattern(
  300. matched_node_pattern: NodePattern,
  301. last_node: Node,
  302. qconfig: QConfigAny,
  303. backend_config: BackendConfig,
  304. named_modules: Dict[str, torch.nn.Module],
  305. cache_for_no_tensor_check: Dict[Node, bool],
  306. processed_nodes: Set[Node],
  307. ) -> None:
  308. """ Sets the target_dtype_info for each node in matched_node_pattern
  309. Note: processed_nodes is used to ensure we only process each node once
  310. """
  311. if isinstance(matched_node_pattern, (list, tuple)):
  312. for node_pattern in matched_node_pattern:
  313. _set_target_dtype_info_for_matched_node_pattern(
  314. node_pattern,
  315. last_node,
  316. qconfig,
  317. backend_config,
  318. named_modules,
  319. cache_for_no_tensor_check,
  320. processed_nodes
  321. )
  322. # set target_dtype_info if matched_node_pattern is a Node
  323. # other types of matched object, e.g. int, float literals, are ignored
  324. elif isinstance(matched_node_pattern, Node):
  325. # for pyre
  326. assert isinstance(matched_node_pattern, Node)
  327. node = matched_node_pattern
  328. if node in processed_nodes:
  329. return
  330. processed_nodes.add(node)
  331. if qconfig is None:
  332. return
  333. # TODO: refactor the following code in terms of apply a qconfig to a pattern
  334. # e.g. for a pattern with op1 -> op2 -> op3, and qconfig = QConfig(input_act=obs0, output_act=obs1)
  335. # we set the input_obs_or_fq_ctr for the arguments of op1 to based on qconfig.input_act,
  336. # and set output_obs_or_fq_ctr based on qconfig.output_act
  337. # this also requires we extend the structure of QConfig to support more fine
  338. # grained configurations
  339. target_dtype_info: Dict[str, Optional[Tuple[Union[torch.dtype, type], bool]]] = (
  340. _get_target_activation_dtype_for_node(
  341. node,
  342. qconfig,
  343. named_modules,
  344. cache_for_no_tensor_check,
  345. )
  346. )
  347. node.meta["target_dtype_info"] = target_dtype_info
  348. def _get_target_activation_dtype_for_node(
  349. node: Node,
  350. qconfig: QConfigAny,
  351. named_modules: Dict[str, torch.nn.Module],
  352. cache_for_no_tensor_check: Dict[Node, bool],
  353. ) -> Dict[str, Optional[Tuple[Union[torch.dtype, type], bool]]]:
  354. """
  355. For each op attribute in the op's input activation, output activation,
  356. weight, bias - returns the settings of dtype and is_dynamic we expect
  357. for the `quantize` call in the reference model representation, or None
  358. if there is no `quantize` call needed.
  359. For example, if we have a node corresponding to `op0` in
  360. x0 -> op0 -> x1
  361. And we want a reference quantized representation to be
  362. x0 -> quant_static -> dequant -> op0 -> quant_dynamic -> dequant -> x1
  363. Then this function will return
  364. {
  365. "input_act_obs_or_fq_ctr": MinMaxObserver.with_args(dtype=torch.quint8, is_dynamic=False),
  366. "output_act_obs_or_fq_ctr": MinMaxObserver.with_args(dtype=torch.quint8, is_dynamic=False),
  367. }
  368. TODO(future PR, if needed): explicitly spell out the non-Tensor
  369. dtypes.
  370. """
  371. args_have_no_tensors = \
  372. all_node_args_have_no_tensors(
  373. node, named_modules, cache_for_no_tensor_check)
  374. if args_have_no_tensors:
  375. return {
  376. "input_act_obs_or_fq_ctr": None,
  377. "output_act_obs_or_fq_ctr": None,
  378. }
  379. # get qconfig to determine the eventual dtype of this node
  380. if qconfig is not None:
  381. act_dtype, weight_dtype, input_act_is_dynamic = \
  382. get_qconfig_dtypes(qconfig)
  383. # Currently `QConfig` only has one `activation` field.
  384. # For static quantization, it is reused for both input
  385. # and output activation. For dynamic quantization, this
  386. # field is currently only used for the input activation,
  387. # with the output activation being in fp32.
  388. # In the future this may change as we add more fields
  389. # to the `QConfig` object.
  390. output_act_dtype = act_dtype \
  391. if (not input_act_is_dynamic) else torch.float
  392. bias_dtype = torch.float16 \
  393. if (
  394. act_dtype == torch.float16
  395. and weight_dtype == torch.float16
  396. and (not input_act_is_dynamic)
  397. ) else torch.float
  398. return {
  399. "input_act_obs_or_fq_ctr": qconfig.activation,
  400. "weight_obs_or_fq_ctr": qconfig.weight,
  401. "bias_obs_or_fq_ctr": PlaceholderObserver.with_args(dtype=bias_dtype),
  402. "output_act_obs_or_fq_ctr": qconfig.activation,
  403. }
  404. return copy.copy(_DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO)
  405. def _get_arg_target_dtype_as_output(
  406. arg: Node,
  407. named_modules: Dict[str, torch.nn.Module],
  408. ) -> Optional[Union[torch.dtype, type]]:
  409. """ Get the target output activation dtype for
  410. the argument in the original graph, skipping inserted observers
  411. We are assuming that the observers are inserted correctly, and the dtype for
  412. argument in quantized graph will match what is specified by the qconfig
  413. """
  414. assert isinstance(arg, Node)
  415. # Custom module LSTM output is a tuple that we broke down into the internal nodes in order
  416. # to insert DeQuantStubs (see `_insert_dequant_stubs_for_custom_module_lstm_output`).
  417. # Since we modified the graph in this case, we must trace back from the args through
  418. # the specific nodes we added in order to reach the original LSTM node. Otherwise, we would
  419. # not be able to accurately detect whether this node is a consumer of custom module LSTM.
  420. custom_module_lstm_node = _maybe_get_custom_module_lstm_from_node_arg(arg, named_modules)
  421. output_act_obs_or_fq_ctr = None
  422. if custom_module_lstm_node is not None:
  423. output_act_obs_or_fq_ctr = custom_module_lstm_node.meta["target_dtype_info"]["output_act_obs_or_fq_ctr"]
  424. elif _is_activation_post_process_node(arg, named_modules):
  425. observed_arg = arg.args[0]
  426. assert isinstance(observed_arg, Node), "Currently we only support observing Node"
  427. output_act_obs_or_fq_ctr = observed_arg.meta["target_dtype_info"]["output_act_obs_or_fq_ctr"]
  428. else:
  429. output_act_obs_or_fq_ctr = \
  430. arg.meta["target_dtype_info"]["output_act_obs_or_fq_ctr"]
  431. output_act_dtype, _ = _get_dtype_and_is_dynamic(output_act_obs_or_fq_ctr)
  432. # TODO: should support is_dynamic here as well
  433. return output_act_dtype
  434. def _get_arg_target_dtype_as_input_to_node(
  435. arg: Node,
  436. node: Node,
  437. named_modules: Dict[str, torch.nn.Module],
  438. backend_config: BackendConfig,
  439. ) -> Optional[Union[torch.dtype, type]]:
  440. """ Get the target argument dtype for the argument `arg`, as input
  441. to node `node`
  442. """
  443. assert isinstance(arg, Node)
  444. is_weight = node_arg_is_weight(node, arg, backend_config)
  445. is_bias = node_arg_is_bias(node, arg, backend_config)
  446. is_activation = not is_weight and not is_bias
  447. if is_activation:
  448. input_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get("input_act_obs_or_fq_ctr")
  449. qconfig_dtype, _ = _get_dtype_and_is_dynamic(input_act_obs_or_fq_ctr)
  450. return qconfig_dtype
  451. elif is_weight:
  452. if node.target in NON_QUANTIZABLE_WEIGHT_OPS:
  453. return None
  454. else:
  455. weight_obs_or_fq_ctr = node.meta["target_dtype_info"].get("weight_obs_or_fq_ctr", None)
  456. qconfig_weight_dtype, _ = _get_dtype_and_is_dynamic(weight_obs_or_fq_ctr)
  457. return qconfig_weight_dtype
  458. else:
  459. bias_obs_or_fq_ctr = node.meta["target_dtype_info"].get("bias_obs_or_fq_ctr", None)
  460. qconfig_bias_dtype, _ = _get_dtype_and_is_dynamic(bias_obs_or_fq_ctr)
  461. return qconfig_bias_dtype
  462. def _get_arg_target_is_dynamic_as_input_to_node(
  463. arg: Node,
  464. node: Node,
  465. named_modules: Dict[str, torch.nn.Module],
  466. backend_config: BackendConfig,
  467. ) -> bool:
  468. """ Get the target argument dtype for the argument `arg`, as input
  469. to node `node`
  470. """
  471. assert isinstance(arg, Node)
  472. is_weight = node_arg_is_weight(node, arg, backend_config)
  473. is_bias = node_arg_is_bias(node, arg, backend_config)
  474. is_activation = not is_weight and not is_bias
  475. if is_activation and "input_act_obs_or_fq_ctr" in node.meta["target_dtype_info"]:
  476. input_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get("input_act_obs_or_fq_ctr")
  477. _, qconfig_is_dynamic = _get_dtype_and_is_dynamic(input_act_obs_or_fq_ctr)
  478. return qconfig_is_dynamic
  479. else:
  480. return False
  481. def _maybe_insert_input_observer_for_arg_or_kwarg(
  482. node: Union[Node, Any],
  483. arg: Argument,
  484. qconfig: QConfigAny,
  485. model: torch.nn.Module,
  486. named_modules: Dict[str, torch.nn.Module],
  487. graph: Graph,
  488. qhandler: Optional[QuantizeHandler],
  489. prepare_custom_config: PrepareCustomConfig,
  490. backend_config: BackendConfig,
  491. ) -> Argument:
  492. """
  493. Given a `node` and an `arg`, inserts an input observer between
  494. `node` and `arg` if necessary.
  495. """
  496. # for ops such as torch.cat([x0, x1]),
  497. # traverse through the list
  498. if isinstance(arg, (list, tuple)):
  499. new_arg_to_return = []
  500. for inner_arg in arg:
  501. new_inner_arg = _maybe_insert_input_observer_for_arg_or_kwarg(
  502. node, inner_arg, qconfig, model, named_modules,
  503. graph,
  504. qhandler,
  505. prepare_custom_config,
  506. backend_config)
  507. new_arg_to_return.append(new_inner_arg)
  508. return type(arg)(new_arg_to_return)
  509. if not isinstance(arg, Node):
  510. return arg
  511. assert isinstance(arg, Node)
  512. # default (no observer)
  513. new_arg = arg
  514. is_standalone_module = qhandler is not None and qhandler.is_standalone_module()
  515. assert qconfig is not None
  516. if not is_standalone_module:
  517. # regular flow for most nodes, except standalone modules
  518. is_weight = node_arg_is_weight(node, arg, backend_config)
  519. _is_reuse_input_qconfig_ = _is_reuse_input_qconfig(qconfig)
  520. act_post_process_ctr = qconfig.weight if is_weight else \
  521. qconfig.activation
  522. arg_as_output_target_dtype = _get_arg_target_dtype_as_output(arg, named_modules)
  523. arg_as_input_target_dtype = _get_arg_target_dtype_as_input_to_node(
  524. arg, node, named_modules, backend_config)
  525. arg_as_input_target_is_dynamic = \
  526. _get_arg_target_is_dynamic_as_input_to_node(
  527. arg, node, named_modules, backend_config) # type: ignore[arg-type]
  528. needs_obs = \
  529. (
  530. # the following code block is for static quantization
  531. (not arg_as_input_target_is_dynamic) and
  532. # if the dtypes are different, we need an observer
  533. (arg_as_output_target_dtype != arg_as_input_target_dtype) and
  534. # except if the second dtype is float, a dequant will be inserted
  535. # without an observer in convert
  536. # TODO(future PR): change this so a placeholder is inserted for
  537. # future dequants, to make the logic easier to understand
  538. (arg_as_input_target_dtype != torch.float) and
  539. # if arg output dtype is in _DO_NOT_OBS_DTYPE_LIST do not insert observer
  540. (arg_as_output_target_dtype not in _DO_NOT_OBS_DTYPE_LIST) and
  541. # if qconfig is reuse_input qconfig, we won't insert extra observer for input
  542. not _is_reuse_input_qconfig_
  543. ) or (
  544. # need to add input observer for dynamic quantization
  545. # only add observer for first input for now, we may need to extend
  546. # qconfig_dict and backend_config to support more general configurations
  547. # of dynamic quantization, e.g. dynamically quantizing second input, third
  548. # input etc.
  549. arg_as_input_target_is_dynamic and arg is node.args[0]
  550. )
  551. else:
  552. # custom flow for standalone modules
  553. _, _, sm_prepare_custom_config, _ = \
  554. _get_standalone_module_configs(
  555. node, named_modules, prepare_custom_config, qconfig, backend_config)
  556. sm_input_quantized_idxs = sm_prepare_custom_config.input_quantized_indexes
  557. # for args, this is set to the index of the current arg
  558. # for kwargs, this is left at None
  559. cur_input_idx = None
  560. for arg_idx, arg_to_check in enumerate(node.args):
  561. if arg_to_check is arg:
  562. cur_input_idx = arg_idx
  563. break
  564. if cur_input_idx is None:
  565. needs_obs = False
  566. else:
  567. arg_as_output_target_dtype = _get_arg_target_dtype_as_output(arg, named_modules)
  568. arg_as_input_target_dtype = torch.quint8 if cur_input_idx in sm_input_quantized_idxs \
  569. else torch.float
  570. needs_obs = (
  571. (arg_as_output_target_dtype != arg_as_input_target_dtype) and
  572. (arg_as_input_target_dtype != torch.float)
  573. )
  574. act_post_process_ctr = qconfig.activation
  575. if needs_obs:
  576. new_obs_mod = act_post_process_ctr()
  577. existing_obs_node = None
  578. # Before using the new observer, check if an observer
  579. # of the correct type already exists. If it does, use it.
  580. # This prevents duplicate observer insertions if a node is
  581. # used by multiple nodes.
  582. # TODO: this is looking into how the value is used in the future
  583. # we should remove this
  584. # removing this means we insert one observer for each use, even if they
  585. # have the same dtype, we can have an extra pass that removes the extra observers
  586. for maybe_obs_node, _ in arg.users.items():
  587. if maybe_obs_node.op == 'call_module':
  588. maybe_obs_mod = named_modules[maybe_obs_node.target] # type: ignore[index]
  589. if (
  590. type(maybe_obs_mod) == type(new_obs_mod) and
  591. maybe_obs_mod.dtype == arg_as_input_target_dtype
  592. ):
  593. existing_obs_node = maybe_obs_node
  594. break
  595. if existing_obs_node is None:
  596. new_obs_node = _insert_observer(
  597. arg, new_obs_mod, model, named_modules, graph)
  598. # override this arg to be the observed arg
  599. new_arg = new_obs_node
  600. else:
  601. new_arg = existing_obs_node
  602. return new_arg
  603. def _maybe_insert_input_observers_for_node(
  604. node: Node,
  605. qconfig: QConfigAny,
  606. model: torch.nn.Module,
  607. named_modules: Dict[str, torch.nn.Module],
  608. graph: Graph,
  609. qhandler: Optional[QuantizeHandler],
  610. prepare_custom_config: PrepareCustomConfig,
  611. backend_config: BackendConfig,
  612. ) -> None:
  613. """
  614. If needed, inserts observers to the input args and kwargs of `node`.
  615. Note: modifies `node` inplace.
  616. For example, if cur_node needs an observer after prev_node, we change from
  617. prev_node -> cur_node
  618. To
  619. prev_node -> obs -> cur_node
  620. """
  621. if qconfig is None:
  622. # if quantization is turned off for this node, we do not need
  623. # to insert input observers
  624. return
  625. assert qconfig is not None
  626. # Look through every input arg. If that arg's target dtype does not
  627. # match the current node's target dtype, insert an observer.
  628. new_args = []
  629. for arg in node.args:
  630. new_arg = _maybe_insert_input_observer_for_arg_or_kwarg(
  631. node, arg, qconfig, model, named_modules, graph,
  632. qhandler,
  633. prepare_custom_config,
  634. backend_config)
  635. new_args.append(new_arg)
  636. new_kwargs = {}
  637. for k, kwarg in node.kwargs.items():
  638. new_kwarg = _maybe_insert_input_observer_for_arg_or_kwarg(
  639. node, kwarg, qconfig, model, named_modules, graph,
  640. qhandler,
  641. prepare_custom_config,
  642. backend_config)
  643. new_kwargs[k] = new_kwarg
  644. # assign the new args and kwargs to the node, inplace
  645. node.args = tuple(new_args)
  646. node.kwargs = new_kwargs
  647. def _maybe_insert_input_equalization_observers_for_node(
  648. node: Node,
  649. equalization_qconfig: Any,
  650. model: torch.nn.Module,
  651. named_modules: Dict[str, torch.nn.Module],
  652. graph: Graph,
  653. is_branch: bool,
  654. backend_config: BackendConfig,
  655. ) -> None:
  656. """
  657. If `node` needs to be equalized, find the input/weight observers it needs in
  658. `equalization_qconfig`, creates them, and inserts it into `graph`.
  659. If `node` does not need an equalization observer, returns None.
  660. """
  661. if equalization_qconfig is None or not node_supports_equalization(node, named_modules):
  662. return
  663. if is_branch:
  664. warnings.warn(
  665. f"Cannot equalize {node} because it is part of a branch."
  666. )
  667. return
  668. new_args = []
  669. for arg in node.args:
  670. if not isinstance(arg, Node) or node_arg_is_bias(node, arg, backend_config):
  671. new_args.append(arg)
  672. continue
  673. is_weight = node_arg_is_weight(node, arg, backend_config)
  674. act_eq_process_ctr = equalization_qconfig.weight if is_weight else \
  675. equalization_qconfig.input_activation
  676. new_eq_obs_mod = act_eq_process_ctr()
  677. new_eq_obs_node = _insert_observer(
  678. arg, new_eq_obs_mod, model, named_modules, graph)
  679. new_args.append(new_eq_obs_node)
  680. # assign the new args and kwargs to the node, inplace
  681. node.args = tuple(new_args)
  682. def _maybe_insert_output_observer_for_node(
  683. node: Node,
  684. model: torch.nn.Module,
  685. named_modules: Dict[str, torch.nn.Module],
  686. graph: Graph,
  687. node_name_to_match_result_with_qconfig: Dict[str, _MatchResultWithQConfig],
  688. matched_pattern: Any,
  689. qhandler: Optional[QuantizeHandler],
  690. is_qat: bool,
  691. ) -> Optional[Node]:
  692. """
  693. If `node` needs an output observer, creates it, inserts it into `graph`
  694. and returns it.
  695. If `node` does not need an output observer, returns None.
  696. """
  697. root_node, _, pattern, qhandler, qconfig = node_name_to_match_result_with_qconfig.get(
  698. node.name, (None, None, None, None, None))
  699. if qhandler is None:
  700. return None
  701. assert qconfig is not None
  702. assert node.op != 'output', 'observer insertion for outputs is handled elsewhere'
  703. is_standalone_module = qhandler is not None and qhandler.is_standalone_module()
  704. output_act_obs_or_fq_ctr = node.meta["target_dtype_info"].get("output_act_obs_or_fq_ctr")
  705. qconfig_dtype, _ = _get_dtype_and_is_dynamic(output_act_obs_or_fq_ctr)
  706. should_insert_observer = qconfig_dtype not in _DO_NOT_OBS_DTYPE_LIST + [torch.float]
  707. # TODO(future PR): move the following logic to
  708. # should_insert_observer_for_output
  709. should_insert_observer = should_insert_observer and \
  710. activation_is_statically_quantized(qconfig)
  711. # we never insert observers to output of standalone module, we assume
  712. # if needed, they are inserted inside the standalone module
  713. should_insert_observer = should_insert_observer and \
  714. (not is_standalone_module)
  715. if should_insert_observer:
  716. observer = qconfig.activation()
  717. return _insert_observer(node, observer, model, named_modules, graph)
  718. else:
  719. return None
  720. def _maybe_insert_observers_before_graph_output(
  721. graph_output_node: Node,
  722. output_quantized_idxs: List[int],
  723. node_name_to_qconfig: Dict[str, QConfigAny],
  724. model: torch.nn.Module,
  725. named_modules: Dict[str, torch.nn.Module],
  726. graph: Graph,
  727. ) -> None:
  728. """
  729. If the output needs to be quantized and there are any nodes
  730. in the output which are not already observed, inserts observers
  731. for those nodes.
  732. """
  733. # TODO(future PR): update the output_quantized_idxs API to match
  734. # arbitrary data structures. There is always a single output, and
  735. # that output can have arbitrary nesting of values. List[int] is
  736. # not the right data type for this.
  737. assert output_quantized_idxs == [0] or output_quantized_idxs == [], \
  738. 'unrecognized format of output_quantized_idxs'
  739. # Currently dequants are inserted in the convert step. So, we only
  740. # have to do anything if the output is hardcoded to be quantized
  741. if output_quantized_idxs == []:
  742. return
  743. # TODO(future PR): support more dtypes in model outputs, if necessary
  744. output_target_dtype = torch.quint8
  745. def _recursive_maybe_replace_node_with_obs(
  746. maybe_node: Argument,
  747. target_dtype: torch.dtype,
  748. node_name_to_qconfig: Dict[str, QConfigAny],
  749. model: torch.nn.Module,
  750. named_modules: Dict[str, torch.nn.Module],
  751. graph: Graph,
  752. ) -> Argument:
  753. """
  754. Navigate an arbitrary data structure of lists, tuples, dicts.
  755. For each container type, recurse on all inputs. Once any Node
  756. is found, insert an observer if needed and do not recurse further.
  757. For example, given a structure of
  758. {'foo1': [[bar1]], 'foo2': {'foo3': [[[bar3]]]}}
  759. we recurse down to bar1 and bar3, observe them if necessary,
  760. and if we inserted an observer then replace the original node
  761. with its observer.
  762. Returns the data structure with all nodes needing observation being
  763. replaced by their observers.
  764. """
  765. if isinstance(maybe_node, Node):
  766. # check dtype of this node
  767. this_node_dtype = _get_arg_target_dtype_as_output(
  768. maybe_node, named_modules)
  769. if this_node_dtype != target_dtype:
  770. # insert observer
  771. qconfig = node_name_to_qconfig.get(maybe_node.name)
  772. # TODO(future PR): see if we need to allow specifying qconfig
  773. # on output nodes, to remove the restriction below.
  774. assert qconfig is not None, \
  775. 'Quantizing the output node without a qconfig is not supported'
  776. observer_mod = qconfig.activation()
  777. observer_node = _insert_observer(
  778. maybe_node, observer_mod, model, named_modules, graph)
  779. return observer_node
  780. else:
  781. return maybe_node
  782. elif isinstance(maybe_node, (list, tuple)):
  783. results = []
  784. for inner_node in maybe_node:
  785. results.append(_recursive_maybe_replace_node_with_obs(
  786. inner_node, target_dtype, node_name_to_qconfig, model, named_modules, graph))
  787. if isinstance(maybe_node, list):
  788. return results
  789. else:
  790. return tuple(results)
  791. elif isinstance(maybe_node, dict):
  792. results_dict = {}
  793. for k, inner_v in maybe_node.items():
  794. results_dict[k] = _recursive_maybe_replace_node_with_obs(
  795. inner_v, target_dtype, node_name_to_qconfig, model, named_modules, graph)
  796. return results_dict
  797. else:
  798. return results
  799. new_args = []
  800. for old_arg in graph_output_node.args:
  801. new_args.append(
  802. _recursive_maybe_replace_node_with_obs(
  803. old_arg, output_target_dtype, node_name_to_qconfig, model, named_modules, graph))
  804. graph_output_node.args = tuple(new_args) # type: ignore[assignment]
  805. def _maybe_propagate_dtype_for_node(
  806. node: Node,
  807. target_dtype: Union[torch.dtype, type],
  808. node_name_to_match_result_with_qconfig: Dict[str, _MatchResultWithQConfig],
  809. ) -> None:
  810. """
  811. Assigns `target_dtype` to `node`, setting `is_dynamic` to False. If `node`
  812. is a general tensor shape op, also call this function recursively on
  813. the first argument, to propagate the dtype to the caller.
  814. """
  815. node.meta["target_dtype_info"]["input_act_obs_or_fq_ctr"] = None
  816. node.meta["target_dtype_info"]["output_act_obs_or_fq_ctr"] = None
  817. # if this is a copy node, propagate to first arg
  818. root_node, _, pattern, qhandler, qconfig = node_name_to_match_result_with_qconfig.get(
  819. node.name, (None, None, None, None, None))
  820. # TODO: probably need to remove `is_general_tensor_value_op`
  821. if qhandler is not None and qhandler.is_general_tensor_value_op():
  822. prev_node = node.args[0]
  823. if isinstance(prev_node, Node):
  824. _maybe_propagate_dtype_for_node(
  825. prev_node, target_dtype, node_name_to_match_result_with_qconfig)
  826. def propagate_dtypes_for_known_nodes(
  827. graph: Graph,
  828. node_name_to_match_result_with_qconfig: Dict[str, _MatchResultWithQConfig],
  829. ) -> None:
  830. """
  831. Currently we assume that inputs to the graph are either `torch.float` or
  832. `torch.quint8`, which is not always correct. For ops such as
  833. `x.masked_fill(mask, value)`, we know that the dtype of `mask` is a
  834. `BoolTensor`. Propagate this information throughout the graph.
  835. Note: not all dtypes in the graph will be correct after this pass, but a
  836. higher percentage of them will be correct. Hopefully in the future we can
  837. replace this with a better way to reason about dtypes of tensors.
  838. """
  839. for node in graph.nodes:
  840. non_observable_arg_dict = get_non_observable_arg_indexes_and_types(node)
  841. for arg_type in non_observable_arg_dict:
  842. non_observable_indices = non_observable_arg_dict[arg_type](node)
  843. for index in non_observable_indices:
  844. arg = node.args[index]
  845. # when an argument is a tuple, it does not show up as another node so we need to go through
  846. # all elements of the tuple manually
  847. if isinstance(arg, (tuple, list)):
  848. arg_list = list(arg)
  849. else:
  850. arg_list = [arg]
  851. for cur_arg in arg_list:
  852. # hard coded arguments show up but aren't `Node` typed and do not need dtype propgated
  853. if isinstance(cur_arg, torch.fx.node.Node):
  854. _maybe_propagate_dtype_for_node(
  855. cur_arg, arg_type, node_name_to_match_result_with_qconfig)
  856. def _maybe_make_input_output_share_observers(
  857. node: Node,
  858. model: torch.nn.Module,
  859. named_modules: Dict[str, torch.nn.Module],
  860. ) -> bool:
  861. """
  862. Ensures that we share an observer
  863. for all input arguments as well as the output argument. In detail, given
  864. a graph of
  865. x0 -> obs0 -> op -> x2
  866. /
  867. x1 -> obs1 /
  868. where node obs0 points to observer instance observer0,
  869. obs1 points to observer1 and obs2 points to observer2, we make nodes obs1
  870. and ob2 point to observer0.
  871. Returns: whether the operation succeeded or not
  872. """
  873. first_arg = None
  874. # find the first non-Tensor arg
  875. for i in range(len(node.args)):
  876. if isinstance(node.args[i], (Node, list, tuple)):
  877. first_arg = node.args[i]
  878. break
  879. # if there is no non-Tensor arg, return directly
  880. if first_arg is None:
  881. return False
  882. if isinstance(first_arg, (list, tuple)):
  883. first_arg_arg = first_arg[0]
  884. elif isinstance(first_arg, Node):
  885. first_arg_arg = first_arg
  886. else:
  887. return False
  888. # if we have a graph such as
  889. # observed_node -> non_observed_node -> cat
  890. # we need to navigate up to the first observer
  891. iteration_guard = 0
  892. while not _is_activation_post_process_node(first_arg_arg, named_modules):
  893. if not isinstance(first_arg_arg, Node):
  894. return False
  895. # did not find an activation_post_process for the op
  896. if first_arg_arg.op == "placeholder":
  897. return False
  898. # trace back the args until we found the first Tensor/Node
  899. trace_back_node = None
  900. for i in range(len(first_arg_arg.args)):
  901. trace_back_node = first_arg_arg.args[i]
  902. if isinstance(trace_back_node, Node):
  903. break
  904. if trace_back_node is None:
  905. return False
  906. first_arg_arg = trace_back_node
  907. iteration_guard += 1
  908. if iteration_guard > 10000:
  909. raise AssertionError('Unable to find observer of previous node')
  910. assert isinstance(first_arg_arg, Node)
  911. target_to_use = first_arg_arg.target
  912. assert isinstance(target_to_use, str)
  913. obs_mod_to_use = named_modules[target_to_use]
  914. if isinstance(first_arg, (list, tuple)):
  915. # set all other input observer nodes to use that module
  916. for input_idx, input_arg in enumerate(first_arg):
  917. if input_idx == 0:
  918. continue
  919. iteration_guard = 0
  920. while not _is_activation_post_process_node(input_arg, named_modules):
  921. # failed to trace back since no input arg for the current node
  922. if len(input_arg.args) < 1:
  923. return False
  924. input_arg = input_arg.args[0]
  925. iteration_guard += 1
  926. if iteration_guard > 10000:
  927. raise AssertionError('Unable to find observer of previous node')
  928. parent_name, name = _parent_name(input_arg.target)
  929. setattr(named_modules[parent_name], name, obs_mod_to_use)
  930. # set the output observer node to use that module
  931. for output_obs_node, _ in node.users.items():
  932. assert _is_activation_post_process_node(output_obs_node, named_modules)
  933. parent_name, name = _parent_name(output_obs_node.target)
  934. setattr(named_modules[parent_name], name, obs_mod_to_use)
  935. # TODO(future PR): delete the orphaned observer modules
  936. return True
  937. def _remove_output_observer(
  938. node: Node,
  939. model: torch.nn.Module,
  940. named_modules: Dict[str, torch.nn.Module]):
  941. items = list(node.users.items())
  942. for output_obs_node, _ in items:
  943. assert _is_activation_post_process_node(output_obs_node, named_modules)
  944. output_obs_node.replace_all_uses_with(node)
  945. model.graph.erase_node(output_obs_node) # type: ignore[union-attr, operator]
  946. def _swap_custom_module_to_observed(
  947. node: Node,
  948. qconfig: QConfigAny,
  949. named_modules: Dict[str, torch.nn.Module],
  950. prepare_custom_config: PrepareCustomConfig):
  951. custom_module = named_modules[node.target] # type: ignore[index]
  952. custom_module_class_mapping = prepare_custom_config.float_to_observed_mapping
  953. observed_custom_module_class = \
  954. get_swapped_custom_module_class(
  955. custom_module, custom_module_class_mapping, qconfig)
  956. observed_custom_module = \
  957. observed_custom_module_class.from_float(custom_module)
  958. parent_name, name = _parent_name(node.target)
  959. setattr(named_modules[parent_name], name, observed_custom_module)
  960. def insert_observers_for_model(
  961. model: GraphModule,
  962. node_name_to_match_result_with_qconfig: Dict[str, _MatchResultWithQConfig],
  963. node_name_to_qconfig: Dict[str, QConfigAny],
  964. prepare_custom_config: PrepareCustomConfig,
  965. equalization_config_map: Dict[str, Any],
  966. backend_config: BackendConfig,
  967. observed_node_names: Set[str],
  968. is_qat: bool,
  969. ) -> Optional[Node]:
  970. """
  971. Inserts observers, using the following high level algorithm:
  972. For each node in the graph:
  973. 1. determine the target dtype of this node in the quantized graph, and save
  974. it for future steps
  975. 2. determine the target dtype or all args and kwargs of this node
  976. 3. if any arg or kwarg's target dtype does not match the current node's
  977. dtype, insert an observer
  978. 4. if the current node needs an output observer, insert it
  979. For example:
  980. - starting graph:
  981. x0 -> linear -> x1
  982. - observed graph after processing x0:
  983. x0(fp32)
  984. - observed graph after processing linear:
  985. x0(fp32) -> x0_obs0(int8) -> linear(int8) -> linear_obs0(int8)
  986. - observed graph after processing x1:
  987. x0(fp32) -> x0_obs0(int8) -> linear(int8) -> linear_obs0(int8) -> x1
  988. After a node is processed, the naive observer placement is guaranteed to be
  989. complete for that node and all of its predecessors. There can be future
  990. passes which optimize the graph by deduplicating observers, etc.
  991. """
  992. # node.meta["target_dtype_info"] stores the target dtype information
  993. # that's derived from qconfig for the Node, for example, if we have
  994. # a conv2d node that has a qconfig
  995. # qconfig = QConfig(activation=..., weight=...)
  996. # # information for input and bias node omitted
  997. # # for getattr node
  998. # # weight = getattr(self, 'weight')
  999. # weight.meta["target_dtype_info"] = {
  1000. # 'output_act_obs_or_fq_ctr': qconfig.weight,
  1001. # }
  1002. # # for conv2d node
  1003. # # conv2d = call_function[target=torch.nn.functional.conv2d](
  1004. # # args=(input, weight, bias))
  1005. # conv2d.meta["target_dtype_info"] = {
  1006. # 'input_act_obs_or_fq_ctr': qconfig.activation
  1007. # 'weight_obs_or_fq_ctr': qconfig.weight,
  1008. # 'bias_obs_or_fq_ctr': PlaceholderObserver.with_args(dtype=torch.float32),
  1009. # 'output_act_obs_or_fq_ctr': qconfig.activation,
  1010. # }
  1011. #
  1012. cache_for_no_tensor_check: Dict[Node, bool] = {}
  1013. # first, populate the dtype map based only on qconfig and qhandler
  1014. # this assumes:
  1015. # graph inputs are fp32 by default, and int8 where overriden
  1016. # other nodes output dtype is specified by the qconfig
  1017. named_modules = dict(model.named_modules(remove_duplicate=False))
  1018. input_quantized_idxs: List[int] = prepare_custom_config.input_quantized_indexes
  1019. output_quantized_idxs: List[int] = prepare_custom_config.output_quantized_indexes
  1020. processed_nodes: Set[Node] = set()
  1021. # initalize target_dtype_info
  1022. for node in model.graph.nodes:
  1023. node.meta["target_dtype_info"] = copy.copy(_DEFAULT_FP32_QCONFIG_FOR_TARGET_DTYPE_INFO)
  1024. inputs_seen_counter = 0
  1025. outputs_seen_counter = 0
  1026. placeholder_node_to_input_index: Dict[Node, int] = {}
  1027. # TODO: we probably don't need this counter since each graph will only have
  1028. # one output node?
  1029. output_node_to_output_index: Dict[Node, int] = {}
  1030. for node in model.graph.nodes:
  1031. if node.op == "placeholder":
  1032. placeholder_node_to_input_index[node] = inputs_seen_counter
  1033. inputs_seen_counter += 1
  1034. if node.op == "output":
  1035. output_node_to_output_index[node] = outputs_seen_counter
  1036. outputs_seen_counter += 1
  1037. # Step 1, set the observer or fake quantize module constructor for each node in the
  1038. # matched_node_pattern
  1039. for node_name, match_res_with_qconfig in node_name_to_match_result_with_qconfig.items():
  1040. last_node, matched_node_pattern, pattern, qhandler, qconfig = match_res_with_qconfig
  1041. assert qhandler is not None
  1042. _set_target_dtype_info_for_matched_node_pattern(
  1043. matched_node_pattern,
  1044. last_node,
  1045. qconfig,
  1046. backend_config,
  1047. named_modules,
  1048. cache_for_no_tensor_check,
  1049. processed_nodes
  1050. )
  1051. # Step 2. Special cases for some operators, we might be able to remove them
  1052. # in the future if we know dtype information of each node better
  1053. # Step 2.1. some settings are not based on patterns, we need to process each node
  1054. # instead
  1055. for node in model.graph.nodes:
  1056. if node.op == "placeholder" and placeholder_node_to_input_index[node] in input_quantized_idxs:
  1057. # users are not supposed to call calculate_qparams on PlaceholderObserver, and
  1058. # this is OK because we are using this as a way to encode the dtypes of input
  1059. # tensor, we won't actually insert these observers in the graph and won't
  1060. # actually call calculate_qparams
  1061. node.meta["target_dtype_info"] = copy.copy(_DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFO)
  1062. elif node.op in ("call_module", "call_method", "call_function"):
  1063. args_have_no_tensors = \
  1064. all_node_args_have_no_tensors(
  1065. node, named_modules, cache_for_no_tensor_check)
  1066. if args_have_no_tensors:
  1067. node.meta["target_dtype_info"] = {
  1068. "input_act_obs_or_fq_ctr": None,
  1069. "output_act_obs_or_fq_ctr": None,
  1070. }
  1071. elif node.op == "output" and output_node_to_output_index[node] in output_quantized_idxs:
  1072. node.meta["target_dtype_info"] = copy.copy(_DEFAULT_QUINT8_QCONFIG_FOR_TARGET_DTYPE_INFO)
  1073. # Step 2.2, for nodes with known input dtypes, propagate them throughout the
  1074. # graph. For example, if there is a call such as
  1075. # x1 = x0.masked_fill(mask, 1)
  1076. # we propagate the type of mask to be torch.bool
  1077. propagate_dtypes_for_known_nodes(model.graph, node_name_to_match_result_with_qconfig)
  1078. # Step 3, check if the requested target_dtype_info is supported by backend or not
  1079. # if not, we'll reset the target_dtye_info to use the default (float Tensor)
  1080. # reset the counters and set of processed_nodes
  1081. processed_nodes = set()
  1082. for node_name, match_res_with_qconfig in node_name_to_match_result_with_qconfig.items():
  1083. last_node, matched_node_pattern, pattern, qhandler, qconfig = match_res_with_qconfig
  1084. is_supported_by_backend = _is_pattern_dtype_config_and_qconfig_supported_by_backend(
  1085. pattern, matched_node_pattern, qconfig, backend_config)
  1086. assert qhandler is not None
  1087. # get output_act_dtype so that we don't also reset the special typed nodes
  1088. # TODO: we might want to handle these more uniformly with the default path
  1089. # this can be improved if we can use node.meta["val"]
  1090. output_act_dtype, _ = _get_dtype_and_is_dynamic(node.meta["target_dtype_info"]["output_act_obs_or_fq_ctr"])
  1091. if not is_supported_by_backend and output_act_dtype not in [None, int, float, torch.bool]:
  1092. # restore target_dtype_info to default if it is not supported by backend
  1093. _set_target_dtype_info_for_matched_node_pattern(
  1094. matched_node_pattern,
  1095. last_node,
  1096. torch.ao.quantization.qconfig._default_fp32_placeholder_qconfig,
  1097. backend_config,
  1098. named_modules,
  1099. cache_for_no_tensor_check,
  1100. processed_nodes
  1101. )
  1102. # After this point, the current node and all of its arguments
  1103. # have a target_dtype_info assigned. Now, we insert observers for inputs
  1104. # of this node (if needed for this node), and the output of this node
  1105. # (if needed for this node).
  1106. # Since we are mutating the graph as we go, we iterate over the original
  1107. # nodes before observer insertion, instead of model.graph.nodes.
  1108. nodes_before_observation = list(model.graph.nodes)
  1109. # Avoid duplicates custom module swaps for multiple nodes with same target.
  1110. custom_module_names_already_swapped: Set[str] = set()
  1111. # TODO: reuse placeholder_node_to_input_index and output_node_to_output_index
  1112. # reset inputs/outputs counters
  1113. inputs_seen_counter = 0
  1114. outputs_seen_counter = 0
  1115. results_node = None
  1116. # TODO: change this to insert obs/fq by pattern instead of by node
  1117. for node in nodes_before_observation:
  1118. if node.op == 'placeholder':
  1119. # if a graph input is in fp32, it does not need observation
  1120. # if a graph input is in int8, we assume the observation happens
  1121. # outside of the graph, and no additional observation is needed
  1122. pass
  1123. elif node.op in ('call_module', 'call_method', 'call_function', 'output'):
  1124. # check for matches
  1125. last_node, matched_node_pattern, pattern, qhandler, qconfig = (
  1126. node_name_to_match_result_with_qconfig.get(node.name, (None, None, None, None, None)) # type: ignore[assignment]
  1127. )
  1128. equalization_qconfig = equalization_config_map.get(node.name, None)
  1129. this_node_dtype_info = node.meta["target_dtype_info"]
  1130. if "val" in node.meta:
  1131. output_is_a_tensor = (
  1132. this_node_dtype_info is not None and
  1133. isinstance(node.meta["val"], FakeTensor)
  1134. )
  1135. else:
  1136. output_is_a_tensor = this_node_dtype_info is not None
  1137. skip_inserting_observers = (
  1138. (qconfig is None) or
  1139. not output_is_a_tensor
  1140. ) and (
  1141. not node.op == 'output'
  1142. )
  1143. # TODO: take a closer look to see if we can remove this check
  1144. # right now it is here because of `observed_node_names`, we are using
  1145. # it as an indicator for swapping the modules to reference modules in
  1146. # convert
  1147. is_supported_by_backend = _is_pattern_dtype_config_and_qconfig_supported_by_backend(
  1148. pattern, matched_node_pattern, qconfig, backend_config)
  1149. if not skip_inserting_observers and is_supported_by_backend:
  1150. named_modules = dict(model.named_modules(remove_duplicate=False))
  1151. if node.op != 'output':
  1152. assert matched_node_pattern is not None
  1153. # add matched nodes to the observed node name set
  1154. _add_matched_node_name_to_set(matched_node_pattern, observed_node_names)
  1155. # This is currently only used for equalization.
  1156. # Checks if the current node is in a branch in which the two
  1157. # first layers are both being quantized.
  1158. #
  1159. # ex. conv2
  1160. # /
  1161. # x -> conv1
  1162. #
  1163. # If this is the case, we will not apply equalization to the
  1164. # initial two layers.
  1165. is_quantized_branch = False
  1166. if (
  1167. len(node.args) > 0 and
  1168. isinstance(node.args[0], Node) and
  1169. len(node.args[0].users) > 1
  1170. ):
  1171. for user in node.args[0].users:
  1172. # Checks if there exists another user being quantized
  1173. is_user_quantized = (
  1174. node_name_to_qconfig.get(user.name, None) is not None or
  1175. (user.op == 'call_module' and isinstance(named_modules[str(user.target)], ObserverBase))
  1176. )
  1177. if user != node and is_user_quantized:
  1178. is_quantized_branch = True
  1179. pattern_to_root_node_getter = get_fusion_pattern_to_root_node_getter(backend_config)
  1180. root_node_getter = pattern_to_root_node_getter.get(pattern, _default_root_node_getter)
  1181. root_node = root_node_getter(matched_node_pattern)
  1182. is_input_node_of_the_pattern = node is root_node
  1183. if is_input_node_of_the_pattern:
  1184. # this modifies node inplace
  1185. _maybe_insert_input_observers_for_node(
  1186. node, qconfig, model, named_modules, model.graph,
  1187. qhandler,
  1188. prepare_custom_config,
  1189. backend_config)
  1190. # insert equalization input observers if needed
  1191. _maybe_insert_input_equalization_observers_for_node(
  1192. node, equalization_qconfig, model, named_modules, model.graph,
  1193. is_quantized_branch, backend_config)
  1194. is_last_node_of_pattern = node is last_node
  1195. is_general_tensor_value_op = \
  1196. (qhandler is not None and qhandler.is_general_tensor_value_op())
  1197. _is_reuse_input_qconfig_ = _is_reuse_input_qconfig(qconfig)
  1198. if is_last_node_of_pattern:
  1199. if _is_custom_module_lstm(node, named_modules, qconfig, qhandler):
  1200. # Currently custom module outputs are assumed to be already quantized,
  1201. # so we need to insert a DeQuantStub after the output. For custom module
  1202. # LSTM specifically, the outputs are also a nested tuple, so we must first
  1203. # break down the tuple to insert DeQuantStubs after the internal nodes.
  1204. # TODO: This currently diverges from how custom modules are handled today,
  1205. # where we insert observers after the output instead of DeQuantStubs, and
  1206. # replace these observers with "dequantize" nodes during convert. Conceptually,
  1207. # these output observers are the same as DeQuantStubs. In the future, we
  1208. # should resolve this inconsistency by inserting DeQuantStubs for all custom
  1209. # modules, not just for LSTM.
  1210. _insert_dequant_stubs_for_custom_module_lstm_output(node, model, named_modules, model.graph)
  1211. if(node.target not in custom_module_names_already_swapped):
  1212. custom_module_names_already_swapped.add(node.target)
  1213. _swap_custom_module_to_observed(node, qconfig, named_modules, prepare_custom_config)
  1214. else:
  1215. # this returns the new observer node if it was needed
  1216. maybe_output_obs_node = _maybe_insert_output_observer_for_node(
  1217. node, model, named_modules, model.graph, node_name_to_match_result_with_qconfig,
  1218. pattern, qhandler, is_qat)
  1219. if maybe_output_obs_node is not None:
  1220. # Update users of original node to use the output observer
  1221. # instead. For example, change
  1222. #
  1223. # next_node
  1224. # /
  1225. # cur_node -> obs
  1226. #
  1227. # to
  1228. #
  1229. # next_node
  1230. # /
  1231. # cur_node -> obs
  1232. #
  1233. # We need to save orig users before updating uses because
  1234. # the list of users will change as we update uses
  1235. orig_users = list(node.users.keys())
  1236. for user_node in orig_users:
  1237. if user_node is maybe_output_obs_node:
  1238. continue
  1239. user_node.replace_input_with(node, maybe_output_obs_node)
  1240. _is_observer_in_same_graph_ = _is_observer_in_same_graph(
  1241. node, named_modules)
  1242. # for general tensor value ops, we modify the graph
  1243. # to make all inputs and outputs use the first input's
  1244. # observer
  1245. if (is_general_tensor_value_op and _is_observer_in_same_graph_) or \
  1246. _is_reuse_input_qconfig_:
  1247. if not _maybe_make_input_output_share_observers(node, model, named_modules):
  1248. _remove_output_observer(node, model, named_modules)
  1249. if qhandler is not None and qhandler.is_custom_module():
  1250. if(node.target not in custom_module_names_already_swapped):
  1251. custom_module_names_already_swapped.add(node.target)
  1252. _swap_custom_module_to_observed(node, qconfig, named_modules, prepare_custom_config)
  1253. else: # output
  1254. _maybe_insert_observers_before_graph_output(
  1255. node, output_quantized_idxs,
  1256. node_name_to_qconfig,
  1257. model, named_modules, model.graph)
  1258. #
  1259. # After this point, the current node has input and output observers
  1260. # that it needs for itself inserted.
  1261. #
  1262. # increment the counters, so future inputs and outputs are assigned
  1263. # correct dtypes
  1264. if node.op == 'placeholder':
  1265. inputs_seen_counter += 1
  1266. elif node.op == 'output':
  1267. outputs_seen_counter += 1
  1268. results_node = node
  1269. return results_node
  1270. def _run_prepare_fx_on_standalone_modules(
  1271. model: torch.nn.Module,
  1272. is_qat: bool,
  1273. named_modules: Dict[str, torch.nn.Module],
  1274. node_name_to_match_result_with_qconfig: Any,
  1275. prepare_custom_config: PrepareCustomConfig,
  1276. backend_config: BackendConfig,
  1277. ) -> None:
  1278. """
  1279. Runs prepare_fx on each standalone module. Note: this does
  1280. not modify the graph, it just replaces the unobserved modules with
  1281. their observed versions.
  1282. """
  1283. for (
  1284. node_name,
  1285. (root_node, _, pattern, qhandler, qconfig),
  1286. ) in node_name_to_match_result_with_qconfig.items():
  1287. if qhandler is None:
  1288. continue
  1289. elif not qhandler.is_standalone_module():
  1290. continue
  1291. sm_qconfig_mapping, sm_example_inputs, sm_prepare_custom_config, \
  1292. sm_backend_config = _get_standalone_module_configs(
  1293. root_node, named_modules, prepare_custom_config, qconfig, backend_config)
  1294. standalone_module = named_modules[root_node.target]
  1295. prepare = \
  1296. torch.ao.quantization.quantize_fx._prepare_standalone_module_fx # type: ignore[attr-defined]
  1297. observed_standalone_module = \
  1298. prepare(
  1299. standalone_module,
  1300. sm_qconfig_mapping,
  1301. is_qat,
  1302. example_inputs=sm_example_inputs,
  1303. prepare_custom_config=sm_prepare_custom_config,
  1304. backend_config=sm_backend_config)
  1305. parent_name, name = _parent_name(root_node.target)
  1306. setattr(named_modules[parent_name], name, observed_standalone_module)
  1307. named_modules[root_node.target] = observed_standalone_module
  1308. def _save_state(
  1309. observed: GraphModule,
  1310. node_name_to_qconfig: Dict[str, QConfigAny],
  1311. node_name_to_scope: Dict[str, Tuple[str, type]],
  1312. prepare_custom_config: PrepareCustomConfig,
  1313. equalization_node_name_to_qconfig: Dict[str, Any],
  1314. qconfig_mapping: QConfigMapping,
  1315. is_qat: bool,
  1316. observed_node_names: Set[str],
  1317. ) -> None:
  1318. observed.meta["_observed_graph_module_attrs"] = (
  1319. ObservedGraphModuleAttrs(
  1320. node_name_to_qconfig=node_name_to_qconfig,
  1321. node_name_to_scope=node_name_to_scope,
  1322. prepare_custom_config=prepare_custom_config,
  1323. equalization_node_name_to_qconfig=equalization_node_name_to_qconfig,
  1324. qconfig_mapping=qconfig_mapping,
  1325. is_qat=is_qat,
  1326. observed_node_names=observed_node_names,
  1327. )
  1328. )
  1329. def prepare(
  1330. model: GraphModule,
  1331. qconfig_mapping: Union[QConfigMapping, Dict[str, Any]],
  1332. is_qat: bool,
  1333. node_name_to_scope: Dict[str, Tuple[str, type]],
  1334. example_inputs: Tuple[Any, ...],
  1335. prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None,
  1336. _equalization_config: Union[QConfigMapping, Dict[str, Any], None] = None,
  1337. backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
  1338. is_standalone_module: bool = False) -> GraphModule:
  1339. """ standalone_module means it a submodule that is not inlined in
  1340. parent module, and will be quantized separately as one unit.
  1341. How the standalone module is observed is specified by `input_quantized_idxs` and
  1342. `output_quantized_idxs` in the prepare_custom_config for the standalone module
  1343. Args:
  1344. node_name_to_scope: mapping from node name to the scope of the module which contains the node.
  1345. The scope is a tuple of fully qualified path of the module and the type of the module
  1346. Returns:
  1347. model(GraphModule): prepared standalone module
  1348. attributes related to standalone module
  1349. in model.meta["_observed_graph_module_attrs"]:
  1350. is_observed_standalone_module (bool): boolean value that shows whether the
  1351. current model is a observed standalone module or not
  1352. standalone_module_input_quantized_idxs(List[Int]): a list of
  1353. indexes for the graph input that is expected to be quantized,
  1354. same as input_quantized_idxs configuration provided
  1355. for the standalone module
  1356. standalone_module_output_quantized_idxs(List[Int]): a list of
  1357. indexs for the graph output that is quantized
  1358. same as input_quantized_idxs configuration provided
  1359. for the standalone module
  1360. """
  1361. if prepare_custom_config is None:
  1362. prepare_custom_config = PrepareCustomConfig()
  1363. if _equalization_config is None:
  1364. _equalization_config = QConfigMapping()
  1365. if isinstance(qconfig_mapping, Dict):
  1366. warnings.warn(
  1367. "Passing a QConfig dictionary to prepare is deprecated and will not be supported "
  1368. "in a future version. Please pass in a QConfigMapping instead.")
  1369. qconfig_mapping = QConfigMapping.from_dict(qconfig_mapping)
  1370. if isinstance(_equalization_config, Dict):
  1371. warnings.warn(
  1372. "Passing a QConfig dictionary to prepare for equalization is deprecated and will not "
  1373. "be supported in a future version. Please pass in a QConfigMapping instead.")
  1374. _equalization_config = QConfigMapping.from_dict(_equalization_config)
  1375. if isinstance(prepare_custom_config, Dict):
  1376. warnings.warn(
  1377. "Passing a prepare_custom_config_dict to prepare is deprecated and will not be supported "
  1378. "in a future version. Please pass in a PrepareCustomConfig instead.")
  1379. prepare_custom_config = PrepareCustomConfig.from_dict(prepare_custom_config)
  1380. if isinstance(backend_config, Dict):
  1381. warnings.warn(
  1382. "Passing a backend_config_dict to prepare is deprecated and will not be supported "
  1383. "in a future version. Please pass in a BackendConfig instead.")
  1384. backend_config = BackendConfig.from_dict(backend_config)
  1385. assert(isinstance(qconfig_mapping, QConfigMapping))
  1386. assert(isinstance(_equalization_config, QConfigMapping))
  1387. qconfig_mapping = copy.deepcopy(qconfig_mapping)
  1388. _equalization_config = copy.deepcopy(_equalization_config)
  1389. # mapping from a tuple of nodes in reverse order to uninitialized
  1390. # QuantizeHandler subclass. For example,
  1391. # {
  1392. # # match a single node
  1393. # (<class 'torch.nn.modules.conv.Conv3d'>:
  1394. # <class 'torch.ao.quantization.fx.quantize.ConvRelu'>),
  1395. # # match multiple nodes in reverse order
  1396. # ((<function relu at 0x7f766a7360d0>, <built-in function add>):
  1397. # <class 'torch.ao.quantization.fx.quantize.Add'>),
  1398. # }
  1399. pattern_to_quantize_handler: Dict[Pattern, QuantizeHandler] = {}
  1400. if backend_config is None:
  1401. backend_config = get_native_backend_config()
  1402. pattern_to_quantize_handler = _get_pattern_to_quantize_handlers(backend_config)
  1403. pattern_to_quantize_handler = _sorted_patterns_dict(pattern_to_quantize_handler)
  1404. root_node_getter_mapping = \
  1405. get_fusion_pattern_to_root_node_getter(backend_config)
  1406. _update_qconfig_for_fusion(model, qconfig_mapping)
  1407. _update_qconfig_for_fusion(model, _equalization_config)
  1408. flattened_qconfig_dict = _get_flattened_qconfig_dict(qconfig_mapping)
  1409. # TODO: support regex as well
  1410. propagate_qconfig_(model, flattened_qconfig_dict, prepare_custom_config.to_dict())
  1411. if is_qat:
  1412. module_to_qat_module = get_module_to_qat_module(backend_config)
  1413. _qat_swap_modules(model, module_to_qat_module)
  1414. _update_qconfig_for_qat(qconfig_mapping, backend_config)
  1415. # mapping from fully qualified module name to module instance
  1416. # for example,
  1417. # {
  1418. # '': Model(...),
  1419. # 'linear': Linear(...),
  1420. # 'linear.weight_fake_quant': PerChannelMinMaxObserver(...),
  1421. # }
  1422. named_modules = dict(model.named_modules(remove_duplicate=False))
  1423. # fill node_name_to_qconfig, a map from node name to qconfig, used in _find_matches
  1424. equalization_node_name_to_qconfig = _generate_node_name_to_qconfig(
  1425. model, named_modules, model.graph, _equalization_config, node_name_to_scope)
  1426. node_name_to_qconfig = _generate_node_name_to_qconfig(model, named_modules, model.graph, qconfig_mapping, node_name_to_scope)
  1427. # match the patterns that will get quantized
  1428. standalone_module_names = list(prepare_custom_config.standalone_module_names.keys())
  1429. standalone_module_classes = list(prepare_custom_config.standalone_module_classes.keys())
  1430. custom_module_classes = get_custom_module_class_keys(prepare_custom_config.float_to_observed_mapping)
  1431. matches_without_qconfig = _find_matches(
  1432. model.graph, named_modules, pattern_to_quantize_handler, root_node_getter_mapping,
  1433. standalone_module_names, standalone_module_classes, custom_module_classes)
  1434. # map qconfig instances to matches
  1435. node_name_to_match_result_with_qconfig = {}
  1436. for node_name, match_without_qconfig in matches_without_qconfig.items():
  1437. match_with_qconfig = (*match_without_qconfig, node_name_to_qconfig[node_name])
  1438. node_name_to_match_result_with_qconfig[node_name] = match_with_qconfig
  1439. _run_prepare_fx_on_standalone_modules(
  1440. model, is_qat, named_modules, node_name_to_match_result_with_qconfig, prepare_custom_config, backend_config)
  1441. # record names for the set of observed node, so that in convert step
  1442. # we know whether we need to convert a floating point module to reference
  1443. # quantized module or not
  1444. observed_node_names: Set[str] = set()
  1445. result_node = insert_observers_for_model(
  1446. model,
  1447. node_name_to_match_result_with_qconfig,
  1448. node_name_to_qconfig,
  1449. prepare_custom_config,
  1450. equalization_node_name_to_qconfig,
  1451. backend_config,
  1452. observed_node_names,
  1453. is_qat
  1454. )
  1455. model = GraphModule(model, model.graph)
  1456. _save_state(model, node_name_to_qconfig, node_name_to_scope,
  1457. prepare_custom_config, equalization_node_name_to_qconfig,
  1458. qconfig_mapping, is_qat, observed_node_names)
  1459. if is_standalone_module:
  1460. assert result_node is not None
  1461. assert isinstance(result_node.args[0], Node), \
  1462. "standalone module only supports returning simple value currently"\
  1463. "(not tuple, dict etc.)"
  1464. # these inputs are observed in parent
  1465. # converting List[int] to Tensor since module attribute is
  1466. # Union[Tensor, Module]
  1467. input_quantized_idxs: List[int] = prepare_custom_config.input_quantized_indexes
  1468. output_quantized_idxs: List[int] = prepare_custom_config.output_quantized_indexes
  1469. observed_graph_module_attrs = model.meta["_observed_graph_module_attrs"]
  1470. # inplace modification
  1471. observed_graph_module_attrs.is_observed_standalone_module = True
  1472. observed_graph_module_attrs.standalone_module_input_quantized_idxs = \
  1473. input_quantized_idxs
  1474. observed_graph_module_attrs.standalone_module_output_quantized_idxs = \
  1475. output_quantized_idxs
  1476. return model